diff --git a/.gitignore b/.gitignore index 173d3bd6..7496b0e4 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,6 @@ /Makefile.orig /MINFO /TABLE -/*.a /*.pc /rehash.time /inc.* @@ -32,6 +31,13 @@ Makefile /openssl/include/opensslconf.h /util/domd +# error code files +/crypto/err/openssl.txt.old +/engines/e_afalg.txt.old +/engines/e_capi.txt.old +/engines/e_dasync.txt.old +/engines/e_ossltest.txt.old + # Executables /apps/openssl /test/sha256t @@ -51,6 +57,7 @@ Makefile /test/ssltest_old /test/x509aux /test/v3ext +/test/ossl_shim/ossl_shim # Certain files that get created by tests on the fly /test/test-runs @@ -73,8 +80,8 @@ Makefile /util/shlib_wrap.sh /tags /TAGS -/crypto.map -/ssl.map +/libcrypto.map +/libssl.map # Windows (legacy) /tmp32 @@ -143,7 +150,8 @@ Makefile # Certificate symbolic links *.0 -# All kinds of executables +# All kinds of libraries and executables +*.a *.so *.so.* *.dylib @@ -172,9 +180,4 @@ pod2htmd.tmp # Windows manifest files *.manifest - -# Ignore -*.orig -*.rej -*.patch - +doc-nits diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..af32ea61 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,11 @@ +[submodule "boringssl"] + path = boringssl + url = https://boringssl.googlesource.com/boringssl + +[submodule "pyca.cryptography"] + path = pyca-cryptography + url = https://github.com/pyca/cryptography.git + +[submodule "krb5"] + path = krb5 + url = https://github.com/krb5/krb5 diff --git a/.travis.yml b/.travis.yml index b5fc4431..0586fb3e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,65 +3,98 @@ sudo: required language: c cache: ccache +git: + submodules: false before_install: - if [ -n "$COVERALLS" ]; then pip install --user cpp-coveralls; fi; + - if expr "$CONFIG_OPTS" ":" ".*enable-external-tests" > /dev/null; then + git submodule update --init --recursive; + fi; addons: apt: packages: - ccache + - golang-1.6 os: - linux + - osx compiler: - clang - gcc env: - - CONFIG_OPTS="" DESTDIR="_install" - - CONFIG_OPTS="--debug no-shared enable-crypto-mdebug enable-rc5 enable-md2" - - CONFIG_OPTS="no-pic --strict-warnings" BUILDONLY="yes" - - CONFIG_OPTS="no-engine no-shared --strict-warnings" BUILDONLY="yes" - - CONFIG_OPTS="no-stdio --strict-warnings" BUILDONLY="yes" - - CONFIG_OPTS="no-ec" BUILDONLY="yes" + - CONFIG_OPTS="" DESTDIR="_install" TESTS="-test_fuzz" + - CONFIG_OPTS="no-asm -Werror --debug no-afalgeng no-shared enable-crypto-mdebug enable-rc5 enable-md2" TESTS="-test_fuzz" - CONFIG_OPTS="no-asm --strict-warnings" BUILDONLY="yes" CHECKDOCS="yes" matrix: include: + - os: linux + addons: + apt: + packages: + - gcc-5 + - g++-5 + sources: + - ubuntu-toolchain-r-test + compiler: gcc-5 + env: CONFIG_OPTS="--strict-warnings" TESTS="-test_fuzz" COMMENT="Move to the BORINGTEST build when interoperable" - os: linux compiler: clang-3.9 env: CONFIG_OPTS="--strict-warnings no-deprecated" BUILDONLY="yes" - os: linux - compiler: gcc - env: CONFIG_OPTS="--debug --coverage no-asm enable-rc5 enable-md2 enable-ec_nistp_64_gcc_128 enable-ssl3 enable-ssl3-method enable-weak-ssl-ciphers" COVERALLS="yes" - - os: linux - compiler: clang-3.9 - env: CONFIG_OPTS="enable-asan" - - os: linux - compiler: clang-3.9 - env: CONFIG_OPTS="enable-msan" - - os: linux - compiler: clang-3.9 - env: CONFIG_OPTS="no-asm enable-ubsan enable-rc5 enable-md2 enable-ssl3 enable-ssl3-method -fno-sanitize=alignment" - - os: linux - compiler: clang-3.9 - env: CONFIG_OPTS="no-asm enable-asan enable-rc5 enable-md2" - - os: linux - compiler: clang-3.9 - env: CONFIG_OPTS="no-stdio" + addons: + apt: + packages: + - binutils-mingw-w64 + - gcc-mingw-w64 + compiler: i686-w64-mingw32-gcc + env: CONFIG_OPTS="no-stdio" BUILDONLY="yes" - os: linux addons: apt: packages: - gcc-5 + - g++-5 sources: - ubuntu-toolchain-r-test compiler: gcc-5 - env: CONFIG_OPTS="no-asm enable-ubsan enable-rc5 enable-md2 -DPEDANTIC" + env: EXTENDED_TEST="yes" CONFIG_OPTS="--debug --coverage no-asm enable-rc5 enable-md2 enable-ec_nistp_64_gcc_128 enable-ssl3 enable-ssl3-method enable-nextprotoneg enable-weak-ssl-ciphers no-shared -DPEDANTIC -DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION" COVERALLS="yes" BORINGSSL_TESTS="yes" CXX="g++-5" + - os: linux + addons: + apt: + packages: + - gcc-5 + - g++-5 + sources: + - ubuntu-toolchain-r-test + compiler: gcc-5 + env: EXTENDED_TEST="yes" CONFIG_OPTS="--debug enable-ssl3 enable-ssl3-method enable-weak-ssl-ciphers enable-external-tests" BORINGSSL_TESTS="yes" CXX="g++-5" TESTS=95 + - os: linux + compiler: clang-3.9 + env: EXTENDED_TEST="yes" CONFIG_OPTS="enable-msan" + - os: linux + compiler: clang-3.9 + env: EXTENDED_TEST="yes" CONFIG_OPTS="no-asm enable-ubsan enable-rc5 enable-md2 enable-ssl3 enable-ssl3-method enable-nextprotoneg -fno-sanitize=alignment no-shared -DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION" + - os: linux + compiler: clang-3.9 + env: EXTENDED_TEST="yes" CONFIG_OPTS="no-asm enable-asan enable-rc5 enable-md2 no-shared -DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION" + - os: linux + addons: + apt: + packages: + - gcc-5 + - g++-5 + sources: + - ubuntu-toolchain-r-test + compiler: gcc-5 + env: EXTENDED_TEST="yes" CONFIG_OPTS="--debug no-asm enable-ubsan enable-rc5 enable-md2 -DPEDANTIC" OPENSSL_TEST_RAND_ORDER=0 - os: linux addons: apt: @@ -69,15 +102,7 @@ matrix: - binutils-mingw-w64 - gcc-mingw-w64 compiler: i686-w64-mingw32-gcc - env: CONFIG_OPTS="no-pic" TESTS="-test_fuzz" - - os: linux - addons: - apt: - packages: - - binutils-mingw-w64 - - gcc-mingw-w64 - compiler: i686-w64-mingw32-gcc - env: CONFIG_OPTS="no-stdio" BUILDONLY="yes" + env: EXTENDED_TEST="yes" CONFIG_OPTS="no-pic" TESTS="-test_fuzz" - os: linux addons: apt: @@ -85,15 +110,7 @@ matrix: - binutils-mingw-w64 - gcc-mingw-w64 compiler: x86_64-w64-mingw32-gcc - env: CONFIG_OPTS="no-pic" TESTS="-test_fuzz" - - os: linux - addons: - apt: - packages: - - binutils-mingw-w64 - - gcc-mingw-w64 - compiler: x86_64-w64-mingw32-gcc - env: CONFIG_OPTS="no-stdio" BUILDONLY="yes" + env: EXTENDED_TEST="yes" CONFIG_OPTS="no-pic" TESTS="-test_fuzz" exclude: - os: linux compiler: clang @@ -101,6 +118,10 @@ matrix: compiler: gcc before_script: + - env + - if [ "$TRAVIS_PULL_REQUEST" != "false" -a -n "$EXTENDED_TEST" ]; then + (git log -1 $TRAVIS_COMMIT_RANGE | grep '\[extended tests\]' > /dev/null) || exit 0; + fi - if [ -n "$DESTDIR" ]; then sh .travis-create-release.sh $TRAVIS_OS_NAME; tar -xvzf _srcdist.tar.gz; @@ -131,14 +152,7 @@ before_script: fi; $srcdir/config -v $CONFIG_OPTS; fi - - if [ -z "$BUILDONLY" ]; then - if [ -n "$CROSS_COMPILE" ]; then - if [ "$TRAVIS_OS_NAME" == "linux" ]; then - sudo dpkg --add-architecture i386; - sudo apt-get update; - fi; - fi; - fi + - ./configdata.pm --dump - cd $top script: @@ -147,11 +161,9 @@ script: else make="make"; fi + - top=${PWD} - if [ -n "$DESTDIR" ]; then cd _build; - top=..; - else - top=.; fi - if $make update; then echo -e '+\057 MAKE UPDATE OK'; @@ -166,37 +178,46 @@ script: echo -e '+\057\057 MAKE DOC-NITS FAILED'; false; fi; fi - - if $make ; then + - if $make; then echo -e '+\057\057\057 MAKE OK'; else echo -e '+\057\057\057 MAKE FAILED'; false; fi; - if [ -z "$BUILDONLY" ]; then if [ -n "$CROSS_COMPILE" ]; then - sudo apt-get -yq install wine; + sudo dpkg --add-architecture i386; + sudo apt-get update; + sudo apt-get -yq --no-install-suggests --no-install-recommends --force-yes install wine; export EXE_SHELL="wine" WINEPREFIX=`pwd`; fi; - HARNESS_VERBOSE=yes make test; + if [ -e krb5/src ]; then + sudo apt-get -yq install bison dejagnu gettext keyutils ldap-utils libldap2-dev libkeyutils-dev python-cjson python-paste python-pyrad slapd tcl-dev tcsh; + fi; + if HARNESS_VERBOSE=yes BORING_RUNNER_DIR=$top/boringssl/ssl/test/runner make test; then + echo -e '+\057\057\057\057 MAKE TEST OK'; + else + echo -e '+\057\057\057\057 MAKE TEST FAILED'; false; + fi; else if $make build_tests; then - echo -e '+\057\057\075 MAKE BUILD_TESTS OK'; + echo -e '+\057\057\057\057\057 MAKE BUILD_TESTS OK'; else - echo -e '+\057\057\075 MAKE BUILD_TESTS FAILEd'; false; + echo -e '+\057\057\057\057\057 MAKE BUILD_TESTS FAILED'; false; fi; fi - if [ -n "$DESTDIR" ]; then - mkdir "../$DESTDIR"; - if $make install install_docs DESTDIR="../$DESTDIR"; then - echo -e '+\057\057\057\057\057 MAKE INSTALL_DOCS OK'; + mkdir "$top/$DESTDIR"; + if $make install install_docs DESTDIR="$top/$DESTDIR"; then + echo -e '+\057\057\057\057\057\057 MAKE INSTALL OK'; else - echo -e '+\057\057\057\057\057 MAKE INSTALL_DOCS FAILED'; false; + echo -e '+\057\057\057\057\057\057 MAKE INSTALL FAILED'; false; fi; fi - cd $top after_success: - if [ -n "$COVERALLS" ]; then - coveralls -b . --gcov-options '\-lp'; + coveralls -b . --gcov gcov-5 --gcov-options '\-lpbc'; fi; notifications: diff --git a/CHANGES b/CHANGES index 0ea1ad55..e08644a5 100644 --- a/CHANGES +++ b/CHANGES @@ -7,54 +7,261 @@ https://github.com/openssl/openssl/commits/ and pick the appropriate release branch. - Changes between 1.1.0g and 1.1.0h [27 Mar 2018] + Changes between 1.1.0g and 1.1.1 [xx XXX xxxx] - *) Constructed ASN.1 types with a recursive definition could exceed the stack + *) Extend OSSL_STORE with capabilities to search and to narrow the set of + objects loaded. This adds the functions OSSL_STORE_expect() and + OSSL_STORE_find() as well as needed tools to construct searches and + get the search data out of them. + [Richard Levitte] - 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. + *) Support for TLSv1.3 added. Note that users upgrading from an earlier + version of OpenSSL should review their configuration settings to ensure + that they are still appropriate for TLSv1.3. In particular if no TLSv1.3 + ciphersuites are enabled then OpenSSL will refuse to make a connection + unless (1) TLSv1.3 is explicitly disabled or (2) the ciphersuite + configuration is updated to include suitable ciphersuites. The DEFAULT + ciphersuite configuration does include TLSv1.3 ciphersuites. For further + information on this and other related issues please see: + https://www.openssl.org/blog/blog/2018/02/08/tlsv1.3/ - This issue was reported to OpenSSL on 4th January 2018 by the OSS-fuzz - project. - (CVE-2018-0739) + NOTE: In this pre-release of OpenSSL a draft version of the + TLSv1.3 standard has been implemented. Implementations of different draft + versions of the standard do not inter-operate, and this version will not + inter-operate with an implementation of the final standard when it is + eventually published. Different pre-release versions may implement + different versions of the draft. The final version of OpenSSL 1.1.1 will + implement the final version of the standard. + TODO(TLS1.3): Remove the above note before final release [Matt Caswell] - *) Incorrect CRYPTO_memcmp on HP-UX PA-RISC + *) Grand redesign of the OpenSSL random generator - Because of an implementation bug the PA-RISC CRYPTO_memcmp function is - effectively reduced to only comparing the least significant bit of each - byte. This allows an attacker to forge messages that would be considered as - authenticated in an amount of tries lower than that guaranteed by the - security claims of the scheme. The module can only be compiled by the - HP-UX assembler, so that only HP-UX PA-RISC targets are affected. + The default RAND method now utilizes an AES-CTR DRBG according to + NIST standard SP 800-90Ar1. The new random generator is essentially + a port of the default random generator from the OpenSSL FIPS 2.0 + object module. It is a hybrid deterministic random bit generator + using an AES-CTR bit stream and which seeds and reseeds itself + automatically using trusted system entropy sources. - This issue was reported to OpenSSL on 2nd March 2018 by Peter Waltenberg - (IBM). - (CVE-2018-0733) + Some of its new features are: + o Support for multiple DRBG instances with seed chaining. + o Add a public DRBG instance for the default RAND method. + o Add a dedicated DRBG instance for generating long term private keys. + o Make the DRBG instances fork-safe. + o Keep all global DRBG instances on the secure heap if it is enabled. + o Add a DRBG instance to every SSL instance for lock free operation + and to increase unpredictability. + [Paul Dale, Benjamin Kaduk, Kurt Roeckx, Rich Salz, Matthias St. Pierre] + + *) Changed Configure so it only says what it does and doesn't dump + so much data. Instead, ./configdata.pm should be used as a script + to display all sorts of configuration data. + [Richard Levitte] + + *) Added processing of "make variables" to Configure. + [Richard Levitte] + + *) Added SHA512/224 and SHA512/256 algorithm support. + [Paul Dale] + + *) The last traces of Netware support, first removed in 1.1.0, have + now been removed. + [Rich Salz] + + *) Get rid of Makefile.shared, and in the process, make the processing + of certain files (rc.obj, or the .def/.map/.opt files produced from + the ordinal files) more visible and hopefully easier to trace and + debug (or make silent). + [Richard Levitte] + + *) Make it possible to have environment variable assignments as + arguments to config / Configure. + [Richard Levitte] + + *) Add multi-prime RSA (RFC 8017) support. + [Paul Yang] + + *) Add SM3 implemented according to GB/T 32905-2016 + [ Jack Lloyd , + Ronald Tse , + Erick Borsboom ] + + *) Add 'Maximum Fragment Length' TLS extension negotiation and support + as documented in RFC6066. + Based on a patch from Tomasz Moń + [Filipe Raimundo da Silva] + + *) Add SM4 implemented according to GB/T 32907-2016. + [ Jack Lloyd , + Ronald Tse , + Erick Borsboom ] + + *) Reimplement -newreq-nodes and ERR_error_string_n; the + original author does not agree with the license change. + [Rich Salz] + + *) Add ARIA AEAD TLS support. + [Jon Spillett] + + *) Some macro definitions to support VS6 have been removed. Visual + Studio 6 has not worked since 1.1.0 + [Rich Salz] + + *) Add ERR_clear_last_mark(), to allow callers to clear the last mark + without clearing the errors. + [Richard Levitte] + + *) Add "atfork" functions. If building on a system that without + pthreads, see doc/man3/OPENSSL_fork_prepare.pod for application + requirements. The RAND facility now uses/requires this. + [Rich Salz] + + *) Add SHA3. [Andy Polyakov] + *) The UI API becomes a permanent and integral part of libcrypto, i.e. + not possible to disable entirely. However, it's still possible to + disable the console reading UI method, UI_OpenSSL() (use UI_null() + as a fallback). + + To disable, configure with 'no-ui-console'. 'no-ui' is still + possible to use as an alias. Check at compile time with the + macro OPENSSL_NO_UI_CONSOLE. The macro OPENSSL_NO_UI is still + possible to check and is an alias for OPENSSL_NO_UI_CONSOLE. + [Richard Levitte] + + *) Add a STORE module, which implements a uniform and URI based reader of + stores that can contain keys, certificates, CRLs and numerous other + objects. The main API is loosely based on a few stdio functions, + and includes OSSL_STORE_open, OSSL_STORE_load, OSSL_STORE_eof, + OSSL_STORE_error and OSSL_STORE_close. + The implementation uses backends called "loaders" to implement arbitrary + URI schemes. There is one built in "loader" for the 'file' scheme. + [Richard Levitte] + + *) Add devcrypto engine. This has been implemented against cryptodev-linux, + then adjusted to work on FreeBSD 8.4 as well. + Enable by configuring with 'enable-devcryptoeng'. This is done by default + on BSD implementations, as cryptodev.h is assumed to exist on all of them. + [Richard Levitte] + + *) Module names can prefixed with OSSL_ or OPENSSL_. This affects + util/mkerr.pl, which is adapted to allow those prefixes, leading to + error code calls like this: + + OSSL_FOOerr(OSSL_FOO_F_SOMETHING, OSSL_FOO_R_WHATEVER); + + With this change, we claim the namespaces OSSL and OPENSSL in a manner + that can be encoded in C. For the foreseeable future, this will only + affect new modules. + [Richard Levitte and Tim Hudson] + + *) Removed BSD cryptodev engine. + [Rich Salz] + *) Add a build target 'build_all_generated', to build all generated files and only that. This can be used to prepare everything that requires things like perl for a system that lacks perl and then move everything to that system and do the rest of the build there. [Richard Levitte] - *) Backport SSL_OP_NO_RENGOTIATION + *) In the UI interface, make it possible to duplicate the user data. This + can be used by engines that need to retain the data for a longer time + than just the call where this user data is passed. + [Richard Levitte] - OpenSSL 1.0.2 and below had the ability to disable renegotiation using the - (undocumented) SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS flag. Due to the opacity - changes this is no longer possible in 1.1.0. Therefore the new - SSL_OP_NO_RENEGOTIATION option from 1.1.1-dev has been backported to - 1.1.0 to provide equivalent functionality. + *) Ignore the '-named_curve auto' value for compatibility of applications + with OpenSSL 1.0.2. + [Tomas Mraz ] - Note that if an application built against 1.1.0h headers (or above) is run - using an older version of 1.1.0 (prior to 1.1.0h) then the option will be - accepted but nothing will happen, i.e. renegotiation will not be prevented. + *) Fragmented SSL/TLS alerts are no longer accepted. An alert message is 2 + bytes long. In theory it is permissible in SSLv3 - TLSv1.2 to fragment such + alerts across multiple records (some of which could be empty). In practice + it make no sense to send an empty alert record, or to fragment one. TLSv1.3 + prohibts this altogether and other libraries (BoringSSL, NSS) do not + support this at all. Supporting it adds significant complexity to the + record layer, and its removal is unlikely to cause inter-operability + issues. [Matt Caswell] + *) Add the ASN.1 types INT32, UINT32, INT64, UINT64 and variants prefixed + with Z. These are meant to replace LONG and ZLONG and to be size safe. + The use of LONG and ZLONG is discouraged and scheduled for deprecation + in OpenSSL 1.2.0. + [Richard Levitte] + + *) Add the 'z' and 'j' modifiers to BIO_printf() et al formatting string, + 'z' is to be used for [s]size_t, and 'j' - with [u]int64_t. + [Richard Levitte, Andy Polyakov] + + *) Add EC_KEY_get0_engine(), which does for EC_KEY what RSA_get0_engine() + does for RSA, etc. + [Richard Levitte] + + *) Have 'config' recognise 64-bit mingw and choose 'mingw64' as the target + platform rather than 'mingw'. + [Richard Levitte] + + *) The functions X509_STORE_add_cert and X509_STORE_add_crl return + success if they are asked to add an object which already exists + in the store. This change cascades to other functions which load + certificates and CRLs. + [Paul Dale] + + *) x86_64 assembly pack: annotate code with DWARF CFI directives to + facilitate stack unwinding even from assembly subroutines. + [Andy Polyakov] + + *) Remove VAX C specific definitions of OPENSSL_EXPORT, OPENSSL_EXTERN. + Also remove OPENSSL_GLOBAL entirely, as it became a no-op. + [Richard Levitte] + + *) Remove the VMS-specific reimplementation of gmtime from crypto/o_times.c. + VMS C's RTL has a fully up to date gmtime() and gmtime_r() since V7.1, + which is the minimum version we support. + [Richard Levitte] + + *) Certificate time validation (X509_cmp_time) enforces stricter + compliance with RFC 5280. Fractional seconds and timezone offsets + are no longer allowed. + [Emilia Käsper] + + *) Add support for ARIA + [Paul Dale] + + *) s_client will now send the Server Name Indication (SNI) extension by + default unless the new "-noservername" option is used. The server name is + based on the host provided to the "-connect" option unless overridden by + using "-servername". + [Matt Caswell] + + *) Add support for SipHash + [Todd Short] + + *) OpenSSL now fails if it receives an unrecognised record type in TLS1.0 + or TLS1.1. Previously this only happened in SSLv3 and TLS1.2. This is to + prevent issues where no progress is being made and the peer continually + sends unrecognised record types, using up resources processing them. + [Matt Caswell] + + *) 'openssl passwd' can now produce SHA256 and SHA512 based output, + using the algorithm defined in + https://www.akkadia.org/drepper/SHA-crypt.txt + [Richard Levitte] + + *) Heartbeat support has been removed; the ABI is changed for now. + [Richard Levitte, Rich Salz] + + *) Support for SSL_OP_NO_ENCRYPT_THEN_MAC in SSL_CONF_cmd. + [Emilia Käsper] + + *) The RSA "null" method, which was partially supported to avoid patent + issues, has been replaced to always returns NULL. + [Rich Salz] + + Changes between 1.1.0g and 1.1.0h [xx XXX xxxx] + *) Removed the OS390-Unix config target. It relied on a script that doesn't exist. [Rich Salz] @@ -113,13 +320,6 @@ (CVE-2017-3735) [Rich Salz] - *) Ignore the '-named_curve auto' value for compatibility of applications - with OpenSSL 1.0.2. - [Tomas Mraz ] - - *) Support for SSL_OP_NO_ENCRYPT_THEN_MAC in SSL_CONF_cmd. - [Emilia Käsper] - Changes between 1.1.0e and 1.1.0f [25 May 2017] *) Have 'config' recognise 64-bit mingw and choose 'mingw64' as the target @@ -235,12 +435,6 @@ (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] - *) Removed automatic addition of RPATH in shared libraries and executables, as this was a remainder from OpenSSL 1.0.x and isn't needed any more. [Richard Levitte] @@ -794,7 +988,7 @@ *) Add support for setting the minimum and maximum supported protocol. It can bet set via the SSL_set_min_proto_version() and SSL_set_max_proto_version(), or via the SSL_CONF's MinProtocol and - MaxProtcol. It's recommended to use the new APIs to disable + MaxProtocol. It's recommended to use the new APIs to disable protocols instead of disabling individual protocols using SSL_set_options() or SSL_CONF's Protocol. This change also removes support for disabling TLS 1.2 in the OpenSSL TLS @@ -1144,13 +1338,13 @@ [Steve Henson] *) Experimental encrypt-then-mac support. - + Experimental support for encrypt then mac from draft-gutmann-tls-encrypt-then-mac-02.txt To enable it set the appropriate extension number (0x42 for the test server) using e.g. -DTLSEXT_TYPE_encrypt_then_mac=0x42 - + For non-compliant peers (i.e. just about everything) this should have no effect. @@ -1201,7 +1395,7 @@ *) Use separate DRBG fields for internal and external flags. New function FIPS_drbg_health_check() to perform on demand health checking. Add - generation tests to fips_test_suite with reduced health check interval to + generation tests to fips_test_suite with reduced health check interval to demonstrate periodic health checking. Add "nodh" option to fips_test_suite to skip very slow DH test. [Steve Henson] @@ -1215,7 +1409,7 @@ combination: call this in fips_test_suite. [Steve Henson] - *) Add support for canonical generation of DSA parameter 'g'. See + *) Add support for canonical generation of DSA parameter 'g'. See FIPS 186-3 A.2.3. *) Add support for HMAC DRBG from SP800-90. Update DRBG algorithm test and @@ -1239,7 +1433,7 @@ requested amount of entropy. [Steve Henson] - *) Add PRNG security strength checks to RSA, DSA and ECDSA using + *) Add PRNG security strength checks to RSA, DSA and ECDSA using information in FIPS186-3, SP800-57 and SP800-131A. [Steve Henson] @@ -1331,7 +1525,7 @@ can be set or retrieved with a ctrl. The IV length is by default 12 bytes (96 bits) but can be set to an alternative value. If the IV length exceeds the maximum IV length (currently 16 bytes) it cannot be - set before the key. + set before the key. [Steve Henson] *) New flag in ciphers: EVP_CIPH_FLAG_CUSTOM_CIPHER. This means the @@ -1374,7 +1568,7 @@ Add CMAC pkey methods. [Steve Henson] - *) Experimental renegotiation in s_server -www mode. If the client + *) Experimental renegotiation in s_server -www mode. If the client browses /reneg connection is renegotiated. If /renegcert it is renegotiated requesting a certificate. [Steve Henson] @@ -1394,7 +1588,7 @@ *) New macro __owur for "OpenSSL Warn Unused Result". This makes use of a gcc attribute to warn if the result of a function is ignored. This is enable if DEBUG_UNUSED is set. Add to several functions in evp.h - whose return value is often ignored. + whose return value is often ignored. [Steve Henson] *) New -noct, -requestct, -requirect and -ctlogfile options for s_client. @@ -2199,7 +2393,7 @@ [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 + 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. @@ -2242,7 +2436,7 @@ *) Fix OCSP checking. [Rob Stradling and Ben Laurie] - *) Initial experimental support for explicitly trusted non-root CAs. + *) 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 @@ -2293,7 +2487,7 @@ to set list of supported curves. [Steve Henson] - *) New ctrls to retrieve supported signature algorithms and + *) 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] @@ -2498,7 +2692,7 @@ [Adam Langley, Bodo Moeller] *) Add additional DigestInfo checks. - + Re-encode DigestInto in DER and check against the original when verifying RSA signature: this will reject any improperly encoded DigestInfo structures. @@ -2668,7 +2862,7 @@ Changes between 1.0.1e and 1.0.1f [6 Jan 2014] - *) Fix for TLS record tampering bug. A carefully crafted invalid + *) 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) @@ -2696,9 +2890,9 @@ *) Make the decoding of SSLv3, TLS and DTLS CBC records constant time. - This addresses the flaw in CBC record processing discovered by + 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/ + 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 @@ -2758,7 +2952,7 @@ *) 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 + SSL_OP_ALL would also set SSL_OP_NO_TLSv1_1, unintentionally disabling TLS 1.1 also. Fix this by changing the value of SSL_OP_NO_TLSv1_1 to 0x10000000L Any application which was previously compiled against OpenSSL 1.0.1 or 1.0.1a headers and which cares about SSL_OP_NO_TLSv1_1 @@ -2767,7 +2961,7 @@ 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 + *) In order to ensure interoperability SSL_OP_NO_protocolX does not disable just protocol X, but all protocols above X *if* there are protocols *below* X still enabled. In more practical terms it means that if application wants to disable TLS1.0 in favor of TLS1.1 and @@ -2796,12 +2990,12 @@ 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 + 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. + TLS 1.2 client support entirely. [Steve Henson] *) Fix SEGV in Vector Permutation AES module observed in OpenSSH. @@ -2816,7 +3010,7 @@ *) 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 + 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] @@ -2838,12 +3032,12 @@ *) 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; + - 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] @@ -2889,7 +3083,7 @@ *) New -sigopt option to the ca, req and x509 utilities. Additional signature parameters can be passed using this option and in - particular PSS. + particular PSS. [Steve Henson] *) Add RSA PSS signing function. This will generate and set the @@ -2914,7 +3108,7 @@ [Steve Henson, Martin Kaiser ] *) Add algorithm specific signature printing. An individual ASN1 method - can now print out signatures instead of the standard hex dump. + 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 @@ -2951,7 +3145,7 @@ *) 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 + portions. This adds all GCM ciphersuites supported by RFC5288 and RFC5289. Generalise some AES* cipherstrings to include GCM and add a special AESGCM string for GCM only. [Steve Henson] @@ -3005,10 +3199,10 @@ to use them can use the private_* version instead. [Steve Henson] - *) Redirect cipher operations to FIPS module for FIPS builds. + *) Redirect cipher operations to FIPS module for FIPS builds. [Steve Henson] - *) Redirect digest operations to FIPS module for FIPS builds. + *) Redirect digest operations to FIPS module for FIPS builds. [Steve Henson] *) Update build system to add "fips" flag which will link in fipscanister.o @@ -3020,7 +3214,7 @@ This should be configurable so applications can judge speed vs strength. [Steve Henson] - *) Add TLS v1.2 server support for client authentication. + *) Add TLS v1.2 server support for client authentication. [Steve Henson] *) Add support for FIPS mode in ssl library: disable SSLv3, non-FIPS ciphers @@ -3062,11 +3256,8 @@ to work with OPENSSL_NO_SSL_INTERN defined. [Steve Henson] - *) A long standing patch to add support for SRP from EdelWeb (Peter - Sylvester and Christophe Renou) was integrated. - [Christophe Renou , Peter Sylvester - , Tom Wu , and - Ben Laurie] + *) Add SRP support. + [Tom Wu and Ben Laurie] *) Add functions to copy EVP_PKEY_METHOD and retrieve flags and id. [Steve Henson] @@ -3106,7 +3297,7 @@ this issue. (CVE-2012-0884) [Steve Henson] - *) Fix CVE-2011-4619: make sure we really are receiving a + *) Fix CVE-2011-4619: make sure we really are receiving a client hello before rejecting multiple SGC restarts. Thanks to Ivan Nestlerode for discovering this bug. [Steve Henson] @@ -3199,7 +3390,7 @@ *) 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 + http://eprint.iacr.org/2011/232.pdf [Billy Bob Brumley and Nicola Tuveri] @@ -3233,12 +3424,12 @@ [Steve Henson] *) Fix WIN32 build system to correctly link an ENGINE directory into - a DLL. + 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 + *) Check return value of int_rsa_verify in pkey_rsa_verifyrecover (CVE-2010-1633) [Steve Henson, Peter-Michael Hager ] @@ -3307,7 +3498,7 @@ 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 + registered digests in the dgst usage message instead of manually attempting to work them out. [Steve Henson] @@ -3341,7 +3532,7 @@ *) Update Gost ENGINE to support parameter files. [Victor B. Wagner ] - *) Support GeneralizedTime in ca utility. + *) Support GeneralizedTime in ca utility. [Oliver Martin , Steve Henson] *) Enhance the hash format used for certificate directory links. The new @@ -3538,7 +3729,7 @@ 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 + an internal copy of the length-'len' string at 'src', and will return non-zero for success. To get more control and flexibility, provide a callback function @@ -3579,7 +3770,7 @@ [Bodo Moeller] *) Update ssl code to support digests other than SHA1+MD5 for handshake - MAC. + MAC. [Victor B. Wagner ] @@ -3591,7 +3782,7 @@ 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. @@ -3628,7 +3819,7 @@ *) New option -sigopt to dgst utility. Update dgst to use EVP_Digest{Sign,Verify}*. These two changes make it possible to use - alternative signing parameters such as X9.31 or PSS in the dgst + alternative signing parameters such as X9.31 or PSS in the dgst utility. [Steve Henson] @@ -3648,8 +3839,8 @@ 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 + functionality) such that between otherwise identical + ciphersuites, ephemeral ECDH is preferred over ephemeral DH in the default order. [Bodo Moeller] @@ -3699,14 +3890,14 @@ *) 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. + 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 + 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] @@ -3740,7 +3931,7 @@ *) 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 + a function that just compares CRL issuer names. Cache several CRL extensions in X509_CRL structure and cache CRLDP in X509. [Steve Henson] @@ -3749,7 +3940,7 @@ Name comparison can then be performed rapidly using memcmp(). [Steve Henson] - *) Non-blocking OCSP request processing. Add -timeout option to ocsp + *) Non-blocking OCSP request processing. Add -timeout option to ocsp utility. [Steve Henson] @@ -3828,7 +4019,7 @@ functional reference processing. [Steve Henson] - *) New functions EVP_Digest{Sign,Verify)*. These are enchance versions of + *) New functions EVP_Digest{Sign,Verify)*. These are enhanced versions of EVP_{Sign,Verify}* which allow an application to customise the signature process. [Steve Henson] @@ -3875,7 +4066,7 @@ type for signing if it is not explicitly indicated. [Steve Henson] - *) Use OID cross reference table in ASN1_sign() and ASN1_verify(). New + *) 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. @@ -3884,7 +4075,7 @@ *) 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. + needed to use the correct OID to be removed. [Steve Henson] *) Remove algorithm specific dependencies when setting PKCS7_SIGNER_INFO @@ -3900,7 +4091,7 @@ [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 + 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. @@ -3921,7 +4112,7 @@ *) Add functions for main EVP_PKEY_method operations. The undocumented functions EVP_PKEY_{encrypt,decrypt} have been renamed to - EVP_PKEY_{encrypt,decrypt}_old. + EVP_PKEY_{encrypt,decrypt}_old. [Steve Henson] *) Initial definitions for EVP_PKEY_METHOD. This will be a high level public @@ -3946,7 +4137,7 @@ type. [Steve Henson] - *) Transfer public key printing routines to EVP_PKEY_ASN1_METHOD. New + *) 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. @@ -3967,11 +4158,11 @@ *) 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 @@ -4040,8 +4231,8 @@ [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 + in SSL structures. New SSL ctrl to set maximum send fragment size. + Save memory by setting the I/O buffer sizes dynamically instead of using the maximum available value. [Steve Henson] @@ -4094,13 +4285,13 @@ protection is active. (CVE-2010-0740) [Bodo Moeller, Adam Langley ] - *) Fix for CVE-2010-0433 where some kerberos enabled versions of OpenSSL + *) Fix for CVE-2010-0433 where some kerberos enabled versions of OpenSSL could be crashed if the relevant tables were not present (e.g. chrooted). [Tomas Hoger ] Changes between 0.9.8l and 0.9.8m [25 Feb 2010] - *) Always check bn_wexpend() return values for failure. (CVE-2009-3245) + *) Always check bn_wexpand() return values for failure. (CVE-2009-3245) [Martin Olsson, Neel Mehta] *) Fix X509_STORE locking: Every 'objs' access requires a lock (to @@ -4233,11 +4424,11 @@ 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 + left. Additionally every future message was buffered, even if the sequence number made no sense and would be part of another handshake. So only messages with sequence numbers less than 10 in advance will be buffered. (CVE-2009-1378) - [Robin Seggelmann, discovered by Daniel Mentz] + [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 @@ -4246,11 +4437,11 @@ memory left. This patch adds the pqueue_size() function to determine the size of a buffer and limits the record buffer to 100 entries. (CVE-2009-1377) - [Robin Seggelmann, discovered by Daniel Mentz] + [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] + [Daniel Mentz] *) Handle non-blocking I/O properly in SSL_shutdown() call. [Darryl Miles ] @@ -4285,7 +4476,7 @@ a legal length. (CVE-2009-0590) [Steve Henson] - *) Set S/MIME signing as the default purpose rather than setting it + *) 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] @@ -4417,12 +4608,12 @@ 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) + handshake which could lead to a client crash as found using the + Codenomicon TLS test suite (CVE-2008-1672) [Steve Henson, Mark Cox] *) Fix double free in TLS server name extensions which could lead to - a remote crash found by Codenomicon TLS test suite (CVE-2008-0891) + a remote crash found by Codenomicon TLS test suite (CVE-2008-0891) [Joe Orton] *) Clear error queue in SSL_CTX_use_certificate_chain_file() @@ -4523,7 +4714,7 @@ *) 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 @@ -4575,7 +4766,7 @@ (gcc 4.2 and later) reject their use. [Kurt Roeckx , Peter Hartley , Steve Henson] - + *) Add RFC4507 support to OpenSSL. This includes the corrections in RFC4507bis. The encrypted ticket format is an encrypted encoded SSL_SESSION structure, that way new session features are automatically @@ -4584,7 +4775,7 @@ 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. @@ -4764,7 +4955,7 @@ *) 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. + *) 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 @@ -4851,7 +5042,7 @@ *) 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 + necessarily true if compression is enabled and can result in false positives causing handshake failure. The actual bug test is ancient code so it is hoped that implementations will either have fixed it by now or any which still have the bug do not support compression. @@ -5044,7 +5235,7 @@ *) 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 + 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] @@ -5080,7 +5271,7 @@ we can fix the problem directly in the 'ca' utility.) [Steve Henson] - *) Reduced header interdepencies by declaring more opaque objects in + *) Reduced header interdependencies by declaring more opaque objects in ossl_typ.h. As a consequence, including some headers (eg. engine.h) will give fewer recursive includes, which could break lazy source code - so this change is covered by the OPENSSL_NO_DEPRECATED symbol. As always, @@ -5093,12 +5284,12 @@ [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 + 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 + 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 + Add EVP_CHECK_DES_KEY #define to return an error if the key is not valid (weak or incorrect parity). [Steve Henson] @@ -5211,7 +5402,7 @@ functions. [Steve Henson] - *) New function PKCS7_set0_type_other() this initializes a PKCS7 + *) New function PKCS7_set0_type_other() this initializes a PKCS7 structure of type "other". [Steve Henson] @@ -5272,16 +5463,16 @@ 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_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. + 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' @@ -5304,7 +5495,7 @@ named like the index file with '.attr' appended to the name. [Richard Levitte] - *) Generate muti valued AVAs using '+' notation in config files for + *) Generate multi-valued AVAs using '+' notation in config files for req and dirName. [Steve Henson] @@ -5420,7 +5611,7 @@ [Geoff Thorpe] *) Change the ZLIB compression method to be stateful, and make it - available to TLS with the number defined in + available to TLS with the number defined in draft-ietf-tls-compression-04.txt. [Richard Levitte] @@ -5428,8 +5619,8 @@ is defined as follows (according to X.509_4thEditionDraftV6.pdf): CertificatePair ::= SEQUENCE { - forward [0] Certificate OPTIONAL, - reverse [1] Certificate OPTIONAL, + 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 @@ -5444,7 +5635,7 @@ Makefile.shared, for Cygwin's sake. [Richard Levitte] - *) Extend the BIGNUM API by creating a function + *) 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); @@ -5597,7 +5788,7 @@ *) 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]: + used) in the following functions [macros]: BN_GF2m_add BN_GF2m_sub [= BN_GF2m_add] @@ -5690,7 +5881,7 @@ EC_METHOD_get_field_type() returns this value. [Nils Larsch ] - *) Add functions + *) Add functions EC_POINT_point2bn() EC_POINT_bn2point() EC_POINT_point2hex() @@ -5749,7 +5940,7 @@ EC_GROUP_set_curve_name() EC_GROUP_get_curve_name() [Nils Larsch ] @@ -5809,7 +6000,7 @@ *) 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. + *) 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 @@ -5845,7 +6036,7 @@ draft-ietf-tls-56-bit-ciphersuites-0[01].txt, but do not really appear there. - Also deactive the remaining ciphersuites from + 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] @@ -5863,10 +6054,10 @@ *) Fixes for VC++ 2005 build under Windows. [Steve Henson] - *) Add new Windows build target VC-32-GMAKE for VC++. This uses GNU make + *) 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. + build to use fipscanister.o from the GNU make build. [Steve Henson] Changes between 0.9.7h and 0.9.7i [14 Oct 2005] @@ -5979,7 +6170,7 @@ values. The OpenSSL team would like to thank the UK NISCC for bringing this issue - to our attention. + to our attention. [Stephen Henson, reported by UK NISCC] @@ -6024,7 +6215,7 @@ Changes between 0.9.7d and 0.9.7e [25 Oct 2004] - *) Avoid a race condition when CRLs are checked in a multi threaded + *) 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. @@ -6048,13 +6239,13 @@ 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 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] + [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 @@ -6064,7 +6255,7 @@ named like the index file with '.attr' appended to the name. [Richard Levitte] - *) X509 verify fixes. Disable broken certificate workarounds when + *) 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 @@ -6073,7 +6264,7 @@ [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 + 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. @@ -6097,7 +6288,7 @@ 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 @@ -6127,7 +6318,7 @@ blocks during encryption. [Richard Levitte] - *) Various fixes to base64 BIO and non blocking I/O. On write + *) 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 @@ -6175,7 +6366,7 @@ *) Target "mingw" now allows native Windows code to be generated in the Cygwin environment as well as with the MinGW compiler. - [Ulf Moeller] + [Ulf Moeller] Changes between 0.9.7 and 0.9.7a [19 Feb 2003] @@ -6211,7 +6402,7 @@ *) 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 + 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: @@ -6431,15 +6622,15 @@ 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 + # Place yourself outside of the OpenSSL source tree. In + # this example, the environment variable OPENSSL_SOURCE + # is assumed to contain the absolute OpenSSL source directory. + mkdir -p objtree/"`uname -s`-`uname -r`-`uname -m`" + cd objtree/"`uname -s`-`uname -r`-`uname -m`" + (cd $OPENSSL_SOURCE; find . -type f) | while read F; do + mkdir -p `dirname $F` + ln -s $OPENSSL_SOURCE/$F $F + done To be absolutely sure not to disturb the source tree, a "make clean" is a good thing. If it isn't successful, don't worry about it, @@ -6459,7 +6650,7 @@ error in AES-CFB decryption. [Richard Levitte] - *) Remove most calls to EVP_CIPHER_CTX_cleanup() in evp_enc.c, this + *) 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 @@ -6486,11 +6677,11 @@ [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 + ENGINEs. Without any "init" command the ENGINE will be initialized + after all ctrl commands have been executed on it. If init=1 the + ENGINE is initialized at that point (ctrls before that point are run on the uninitialized ENGINE and after on the initialized one). If - init=0 then the ENGINE will not be iniatialized at all. + init=0 then the ENGINE will not be initialized at all. [Steve Henson] *) Fix the 'app_verify_callback' interface so that the user-defined @@ -6528,7 +6719,7 @@ *) 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 + 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 @@ -6594,7 +6785,7 @@ 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 @@ -6711,7 +6902,7 @@ [Richard Levitte] *) Test for certificates which contain unsupported critical extensions. - If such a certificate is found during a verify operation it is + 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 @@ -6747,7 +6938,7 @@ *) 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 + of specific crypto interfaces. This change also introduces integrated support for symmetric ciphers and digest implementations - so ENGINEs can now accelerate these by providing EVP_CIPHER and EVP_MD implementations of their own. This is detailed in crypto/engine/README @@ -6934,8 +7125,8 @@ des_key_schedule ks; - des_set_key_checked(..., &ks); - des_ncbc_encrypt(..., &ks, ...); + des_set_key_checked(..., &ks); + des_ncbc_encrypt(..., &ks, ...); (Note that a later change renames 'des_...' into 'DES_...'.) [Ben Laurie] @@ -7076,7 +7267,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k [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 + 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 @@ -7141,7 +7332,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k '-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 + openssl engine chil -pre FORK_CHECK:0 -pre SO_PATH:/lib/test.so [Geoff] *) New dynamic control command support for ENGINEs. ENGINEs can now @@ -7240,7 +7431,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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. + 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. @@ -7329,16 +7520,16 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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); + 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) + 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. @@ -7428,7 +7619,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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 + 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] @@ -7453,7 +7644,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k option to ocsp utility. [Steve Henson] - *) New nonce behavior. The return value of OCSP_check_nonce() now + *) 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 @@ -7527,7 +7718,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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. + contents: this is used in various key identifiers. [Steve Henson] *) Make sk_sort() tolerate a NULL argument. @@ -7542,7 +7733,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k to data. This was previously part of the PKCS7 ASN1 code. This was causing problems with OpenSSL created PKCS#12 and PKCS#7 structures. [Steve Henson, reported by Kenneth R. Robinette - ] + ] *) Add CRYPTO_push_info() and CRYPTO_pop_info() calls to new ASN1 routines: without these tracing memory leaks is very painful. @@ -7556,7 +7747,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k and use ASN1_TIME_set() if the value is not V_ASN1_UTCTIME or V_ASN1_GENERALIZEDTIME, without this it always uses GeneralizedTime. [Steve Henson, reported by Kenneth R. Robinette - ] + ] *) Fixes to BN_to_ASN1_INTEGER when bn is zero. This would previously result in a zero length in the ASN1_INTEGER structure which was @@ -7641,10 +7832,10 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 + 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 @@ -7715,7 +7906,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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 + OCSP extension code. New simple OCSP HTTP function which can be used to send requests and parse the response. [Steve Henson] @@ -7751,7 +7942,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k [Steve Henson] *) Enhance mkdef.pl to be more accepting about spacing in C preprocessor - lines, recognice more "algorithms" that can be deselected, and make + lines, recognize more "algorithms" that can be deselected, and make it complain about algorithm deselection that isn't recognised. [Richard Levitte] @@ -7985,11 +8176,11 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Add the following functions: - ENGINE_load_cswift() - ENGINE_load_chil() - ENGINE_load_atalla() - ENGINE_load_nuron() - ENGINE_load_builtin_engines() + 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 @@ -8101,7 +8292,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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. @@ -8149,7 +8340,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 + via timing by performing a MAC computation even if incorrect block cipher padding has been found. This is a countermeasure against active attacks where the attacker has to distinguish between bad padding and a MAC verification error. (CVE-2003-0078) @@ -8180,7 +8371,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k [Zeev Lieber ] *) Undo an undocumented change introduced in 0.9.6e which caused - repeated calls to OpenSSL_add_all_ciphers() and + repeated calls to OpenSSL_add_all_ciphers() and OpenSSL_add_all_digests() to be ignored, even after calling EVP_cleanup(). [Richard Levitte] @@ -8238,8 +8429,8 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Fix ASN1 checks. Check for overflow by comparing with LONG_MAX and get fix the header length calculation. [Florian Weimer , - Alon Kantor (and others), - Steve Henson] + Alon Kantor (and others), + Steve Henson] *) Use proper error handling instead of 'assertions' in buffer overflow checks added in 0.9.6e. This prevents DoS (the @@ -8354,7 +8545,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k a generator of the order-q subgroup is just as good, if not better. [Bodo Moeller] - + *) Map new X509 verification errors to alerts. Discovered and submitted by Tom Wu . [Lutz Jaenicke] @@ -8467,7 +8658,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k [Broadcom, Nalin Dahyabhai , Mark Cox] *) [In 0.9.6c-engine release:] - Add support for SureWare crypto accelerator cards from + Add support for SureWare crypto accelerator cards from Baltimore Technologies. (Use engine 'sureware') [Baltimore Technologies and Mark Cox] @@ -8810,8 +9001,8 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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. + + *) MIPS assembler BIGNUM division bug fix. [Andy Polyakov] *) Disabled incorrect Alpha assembler code. @@ -8867,7 +9058,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 + 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] @@ -8981,7 +9172,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) rand_win.c fix for Borland C. [Ulf Möller] - + *) BN_rshift bugfix for n == 0. [Bodo Moeller] @@ -9051,7 +9242,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 ] + [Bodo Moeller; problems reported by Anders Gertz ] *) Correct util/mkdef.pl to be selective about disabled algorithms. Previously, it would create entries for disabled algorithms no @@ -9141,7 +9332,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k doc package contains the contents of the doc directory. The original openssl.spec was provided by Damien Miller . [Richard Levitte] - + *) Add a large number of documentation files for many SSL routines. [Lutz Jaenicke ] @@ -9187,19 +9378,19 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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 @@ -9209,10 +9400,10 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 @@ -9220,9 +9411,9 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 @@ -9231,15 +9422,15 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 + + *) Add new PKCS#7 signing option PKCS7_NOSMIMECAP which excludes S/MIME capabilities. [Steve Henson] @@ -9301,7 +9492,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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 + 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] @@ -9309,27 +9500,27 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Added BIO_vprintf() and BIO_vsnprintf(). [Richard Levitte] - *) Added more prefixes to parse for in the the strings written + *) Added more prefixes to parse for in the strings written through a logging bio, to cover all the levels that are available through syslog. The prefixes are now: - PANIC, EMERG, EMR => LOG_EMERG - ALERT, ALR => LOG_ALERT - CRIT, CRI => LOG_CRIT - ERROR, ERR => LOG_ERR - WARNING, WARN, WAR => LOG_WARNING - NOTICE, NOTE, NOT => LOG_NOTICE - INFO, INF => LOG_INFO - DEBUG, DBG => LOG_DEBUG + 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 + 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] @@ -9380,7 +9571,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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 + multibyte characters. Added options to the 'x509' utility to allow the various flags to be set. [Steve Henson] @@ -9458,7 +9649,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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. + consistent name changes. [Richard Levitte] *) Add BSD-style MD5-based passwords to 'openssl passwd' (option '-1'). @@ -9482,9 +9673,9 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k added extra typesafe functions: these no longer exist. [Steve Henson] - *) Reorganisation of the stack code. The macros are now all + *) Reorganisation of the stack code. The macros are now all collected in safestack.h . Each macro is defined in terms of - a "stack macro" of the form SKM_(type, a, b). The + a "stack macro" of the form SKM_(type, a, b). The DEBUG_SAFESTACK is now handled in terms of function casts, this has the advantage of retaining type safety without the use of additional functions. If DEBUG_SAFESTACK is not defined @@ -9502,7 +9693,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 + an -sgckey command line option to the rsa utility. Thanks to Adrian Peck for posting details of the modified algorithm to openssl-dev. [Steve Henson] @@ -9514,7 +9705,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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 + in the subject name and the subject alternative name extensions and omit any duplicate addresses. [Steve Henson] @@ -9746,7 +9937,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k ] *) Fix for HMAC. It wasn't zeroing the rest of the block if the key length - was larger than the MD block size. + was larger than the MD block size. [Steve Henson, pointed out by Yost William ] *) Modernise PKCS12_parse() so it uses STACK_OF(X509) for its ca argument @@ -9787,7 +9978,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k ssl_cert_dup, which is used by SSL_new, now copies DH keys in addition to parameters -- in previous versions (since OpenSSL 0.9.3) the 'default key' from SSL_CTX_set_tmp_dh would always be lost, meaning - you effectivly got SSL_OP_SINGLE_DH_USE when using this macro. + you effectively got SSL_OP_SINGLE_DH_USE when using this macro. [Bodo Moeller] *) New s_client option -ign_eof: EOF at stdin is ignored, and @@ -9881,7 +10072,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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 + 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 ] @@ -10006,7 +10197,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) ./config recognizes MacOS X now. [Andy Polyakov] - *) Bug fix for BN_div() when the first words of num and divsor are + *) Bug fix for BN_div() when the first words of num and divisor are equal (it gave wrong results if (rem=(n1-q*d0)&BN_MASK2) < d0). [Ulf Möller] @@ -10044,7 +10235,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Source code cleanups: use const where appropriate, eliminate casts, use void * instead of char * in lhash. - [Ulf Möller] + [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 @@ -10069,7 +10260,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 + candidate has passed the trial division test (when q is generated from an application-provided seed, trial division is skipped). [Bodo Moeller] @@ -10178,7 +10369,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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. + NO_RSA in ssl/s2*.c. [Kris Kennaway , modified by Ulf Möller] *) Precautions against using the PRNG uninitialized: RAND_bytes() now @@ -10220,9 +10411,9 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Honor the no-xxx Configure options when creating .DEF files. [Ulf Möller] - *) Add PKCS#10 attributes to field table: challengePassword, + *) 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 + 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 @@ -10374,9 +10565,9 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k With these changes, a new set of functions and macros have appeared: - CRYPTO_set_mem_debug_functions() [F] + CRYPTO_set_mem_debug_functions() [F] CRYPTO_get_mem_debug_functions() [F] - CRYPTO_dbg_set_options() [F] + CRYPTO_dbg_set_options() [F] CRYPTO_dbg_get_options() [F] CRYPTO_malloc_debug_init() [M] @@ -10389,7 +10580,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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. + 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 @@ -10532,7 +10723,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 + 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. @@ -10649,7 +10840,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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. + using the new 'x509' options. Current auxiliary information includes an "alias" and some trust settings. The trust settings will ultimately be used in enhanced @@ -10665,7 +10856,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k performance improvement for 1024 bit RSA signs. [Mark Cox] - *) Hack to fix PKCS#7 decryption when used with some unorthodox RC2 + *) 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 @@ -10677,7 +10868,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k the key length and effective key length are equal. [Steve Henson] - *) Add a bunch of functions that should simplify the creation of + *) 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 @@ -10710,7 +10901,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k Use the random seed file in some applications that previously did not: ca, - dsaparam -genkey (which also ignored its '-rand' option), + dsaparam -genkey (which also ignored its '-rand' option), s_client, s_server, x509 (when signing). @@ -10747,7 +10938,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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 + 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. @@ -10920,7 +11111,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 + library. Also added low level modexp hooks and CRYPTO_EX structure and associated functions. [Steve Henson] @@ -10965,7 +11156,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k [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] @@ -11054,7 +11245,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k delete an unused file. [Ulf Möller] - *) Add support for the the free Netwide assembler (NASM) under Win32, + *) Add support for the free Netwide assembler (NASM) under Win32, since not many people have MASM (ml) and it can be hard to obtain. This is currently experimental but it seems to work OK and pass all the tests. Check out INSTALL.W32 for info. @@ -11070,7 +11261,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k for verifying the consistency of RSA keys. [Ulf Moeller, Bodo Moeller] - *) Various changes to make Win32 compile work: + *) 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. @@ -11094,7 +11285,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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. + 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. @@ -11171,7 +11362,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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. + necessary function names. [Steve Henson] *) mk1mf.pl (used by Windows builds) did not properly read the @@ -11211,7 +11402,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Add initial documentation of the X509V3 functions. [Steve Henson] - *) Add a new pair of functions PEM_write_PKCS8PrivateKey() and + *) 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. @@ -11353,11 +11544,11 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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. + This also avoids the problems with SC4.2 and unpatched SC5. [Andy Polyakov ] *) New functions sk_num, sk_value and sk_set to replace the previous macros. - These are required because of the typesafe stack would otherwise break + 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 @@ -11418,7 +11609,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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+ + -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 @@ -11439,7 +11630,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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 @@ -11487,7 +11678,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Update HPUX configuration. [Anonymous] - + *) Add missing sk__unshift() function to safestack.h [Ralf S. Engelschall] @@ -11591,11 +11782,11 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Fix lots of warnings. [Richard Levitte ] - + *) In add_cert_dir() in crypto/x509/by_dir.c, break out of the loop if the directory spec didn't end with a LIST_SEPARATOR_CHAR. [Richard Levitte ] - + *) Fix problems with sizeof(long) == 8. [Andy Polyakov ] @@ -11679,7 +11870,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Bugfix: In test/testenc, don't test "openssl " for ciphers that were excluded, e.g. by -DNO_IDEA. Also, test - all available cipers including rc5, which was forgotten until now. + all available ciphers including rc5, which was forgotten until now. In order to let the testing shell script know which algorithms are available, a new (up to now undocumented) command "openssl list-cipher-commands" is used. @@ -11706,7 +11897,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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. @@ -11749,8 +11940,8 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k OAEP isn't supported when OpenSSL is built with RSAref. [Ulf Moeller ] - *) Move definitions of IS_SET/IS_SEQUENCE inside crypto/asn1/asn1.h - so they no longer are missing under -DNOPROTO. + *) Move definitions of IS_SET/IS_SEQUENCE inside crypto/asn1/asn1.h + so they no longer are missing under -DNOPROTO. [Soren S. Jorvang ] @@ -11907,14 +12098,14 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k [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), + 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 + 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. @@ -11923,7 +12114,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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. + relationship to the OpenSSL project. [Ralf S. Engelschall] *) Remove confusing variables in function signatures in files @@ -11954,7 +12145,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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] @@ -11967,12 +12158,12 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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). + (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. + 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 @@ -12119,7 +12310,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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: + If you do a: perl util/mkdef.pl crypto ssl update it will update them. [Steve Henson] @@ -12170,7 +12361,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Fixed ms/32all.bat script: `no_asm' -> `no-asm' [Rainer W. Gerling ] - + *) New program nseq to manipulate netscape certificate sequences [Steve Henson] @@ -12225,7 +12416,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Spelling mistake in C version of CAST-128. [Ben Laurie, reported by Jeremy Hylton ] - *) Changes to the error generation code. The perl script err-code.pl + *) 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 @@ -12277,7 +12468,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) 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_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] @@ -12371,7 +12562,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Fix renumbering bug in X509_NAME_delete_entry(). [Ben Laurie] - *) Enhanced the err-ins.pl script so it makes the error library number + *) 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] @@ -12379,7 +12570,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Fixed sk_insert which never worked properly. [Steve Henson] - *) Fix ASN1 macros so they can handle indefinite length constructed + *) Fix ASN1 macros so they can handle indefinite length constructed EXPLICIT tags. Some non standard certificates use these: they can now be read in. [Steve Henson] @@ -12424,10 +12615,10 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k Changes between 0.9.1b and 0.9.1c [23-Dec-1998] - *) Added OPENSSL_VERSION_NUMBER to crypto/crypto.h and + *) 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] @@ -12435,7 +12626,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k because the symlink to include/ was missing. [Ralf S. Engelschall] - *) Incorporated the popular no-RSA/DSA-only patches + *) Incorporated the popular no-RSA/DSA-only patches which allow to compile a RSA-free SSLeay. [Andrew Cooke / Interrader Ldt., Ralf S. Engelschall] @@ -12443,7 +12634,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k when "ssleay" is still not found. [Ralf S. Engelschall] - *) Added more platforms to Configure: Cray T3E, HPUX 11, + *) Added more platforms to Configure: Cray T3E, HPUX 11, [Ralf S. Engelschall, Beckmann ] *) Updated the README file. @@ -12459,13 +12650,13 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Cleaned up the top-level documents; o new files: CHANGES and LICENSE - o merged VERSION, HISTORY* and README* files a CHANGES.SSLeay + 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: + *) 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 @@ -12481,7 +12672,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k 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] @@ -12491,17 +12682,17 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Changed some BIGNUM api stuff. [Eric A. Young] - *) Various platform ports: OpenBSD, Ultrix, IRIX 64bit, NetBSD, + *) 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: + *) 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 + *) Add -strparse option to asn1pars program which parses nested + binary structures [Dr Stephen Henson ] *) Added "oid_file" to ssleay.cnf for "ca" and "req" programs. @@ -12580,7 +12771,7 @@ des-cbc 3624.96k 5258.21k 5530.91k 5624.30k 5628.26k *) Fixed various code and comment typos. [Eric A. Young] - *) A minor bug in ssl/s3_clnt.c where there would always be 4 0 + *) A minor bug in ssl/s3_clnt.c where there would always be 4 0 bytes sent in the client random. [Edward Bishop ] diff --git a/CONTRIBUTING b/CONTRIBUTING index 1eebaf37..08c607aa 100644 --- a/CONTRIBUTING +++ b/CONTRIBUTING @@ -50,5 +50,5 @@ acceptance and review process faster: test/README for information on the test framework. 6. New features or changed functionality must include - documentation. Please look at the "pod" files in doc/apps, doc/crypto - and doc/ssl for examples of our style. + documentation. Please look at the "pod" files in doc/man[1357] + for examples of our style. diff --git a/Configurations/00-base-templates.conf b/Configurations/00-base-templates.conf index 3455b3ac..0350997f 100644 --- a/Configurations/00-base-templates.conf +++ b/Configurations/00-base-templates.conf @@ -1,14 +1,18 @@ # -*- Mode: perl -*- -%targets=( +my %targets=( DEFAULTS => { template => 1, cflags => "", + cppflags => "", + lflags => "", defines => [], + includes => [], thread_scheme => "(unknown)", # Assume we don't know thread_defines => [], apps_aux_src => "", + apps_init_src => "", cpuid_asm_src => "mem_clr.c", uplink_aux_src => "", bn_asm_src => "bn_asm.c", @@ -36,12 +40,30 @@ shared_rcflag => "", shared_extension => "", - build_scheme => [ "unified", "unix" ], - build_file => "Makefile", + #### Defaults for the benefit of the config targets who don't inherit + #### a BASE and assume Unixly defaults + #### THESE WILL DISAPPEAR IN OpenSSL 1.2 + build_scheme => [ "unified", "unix" ], + build_file => "Makefile", + + ar => "ar", + arflags => "r", + cc => "cc", + hashbangperl => "/usr/bin/env perl", + ranlib => sub { which("$config{cross_compile_prefix}ranlib") + ? "ranlib" : "" }, + rc => "windres", + + #### THESE WILL BE ENABLED IN OpenSSL 1.2 + #hashbangperl => "PERL", # Only Unix actually cares }, BASE_common => { template => 1, + + enable => [], + disable => [], + defines => sub { my @defs = (); @@ -49,24 +71,32 @@ push @defs, "ZLIB_SHARED" unless $disabled{"zlib-dynamic"}; return [ @defs ]; }, + includes => + sub { + my @incs = (); + push @incs, $withargs{zlib_include} + if !$disabled{zlib} && $withargs{zlib_include}; + return [ @incs ]; + }, }, BASE_unix => { inherit_from => [ "BASE_common" ], template => 1, + ar => "ar", + arflags => "r", + cc => "cc", + lflags => + sub { $withargs{zlib_lib} ? "-L".$withargs{zlib_lib} : () }, ex_libs => - sub { - unless ($disabled{zlib}) { - if (defined($disabled{"zlib-dynamic"})) { - if (defined($withargs{zlib_lib})) { - return "-L".$withargs{zlib_lib}." -lz"; - } else { - return "-lz"; - } - } - } - return (); }, + sub { !defined($disabled{zlib}) + && defined($disabled{"zlib-dynamic"}) + ? "-lz" : () }, + hashbangperl => "/usr/bin/env perl", # Only Unix actually cares + ranlib => sub { which("$config{cross_compile_prefix}ranlib") + ? "ranlib" : "" }, + rc => "windres", build_scheme => [ "unified", "unix" ], build_file => "Makefile", @@ -107,13 +137,23 @@ inherit_from => [ "BASE_common" ], template => 1, + includes => + add(sub { + my @incs = (); + # GNV$ZLIB_INCLUDE is the standard logical name for later + # zlib incarnations. + push @incs, 'GNV$ZLIB_INCLUDE:' + if !$disabled{zlib} && !$withargs{zlib_include}; + return [ @incs ]; + }), + build_file => "descrip.mms", build_scheme => [ "unified", "VMS" ], }, uplink_common => { template => 1, - apps_aux_src => add("../ms/applink.c"), + apps_init_src => add("../ms/applink.c"), uplink_aux_src => add("../ms/uplink.c"), defines => add("OPENSSL_USE_APPLINK"), }, @@ -163,7 +203,7 @@ template => 1, cpuid_asm_src => "x86_64cpuid.s", bn_asm_src => "asm/x86_64-gcc.c x86_64-mont.s x86_64-mont5.s x86_64-gf2m.s rsaz_exp.c rsaz-x86_64.s rsaz-avx2.s", - ec_asm_src => "ecp_nistz256.c ecp_nistz256-x86_64.s", + ec_asm_src => "ecp_nistz256.c ecp_nistz256-x86_64.s x25519-x86_64.s", aes_asm_src => "aes-x86_64.s vpaes-x86_64.s bsaes-x86_64.s aesni-x86_64.s aesni-sha1-x86_64.s aesni-sha256-x86_64.s aesni-mb-x86_64.s", md5_asm_src => "md5-x86_64.s", sha1_asm_src => "sha1-x86_64.s sha256-x86_64.s sha512-x86_64.s sha1-mb-x86_64.s sha256-mb-x86_64.s", @@ -180,9 +220,7 @@ cpuid_asm_src => "ia64cpuid.s", bn_asm_src => "bn-ia64.s ia64-mont.s", aes_asm_src => "aes_core.c aes_cbc.c aes-ia64.s", - md5_asm_src => "md5-ia64.s", sha1_asm_src => "sha1-ia64.s sha256-ia64.s sha512-ia64.s", - rc4_asm_src => "rc4-ia64.s rc4_skey.c", modes_asm_src => "ghash-ia64.s", perlasm_scheme => "void" }, @@ -217,7 +255,7 @@ }, mips32_asm => { template => 1, - bn_asm_src => "bn-mips.s mips-mont.s", + bn_asm_src => "bn-mips.S mips-mont.S", aes_asm_src => "aes_cbc.c aes-mips.S", sha1_asm_src => "sha1-mips.S sha256-mips.S", }, @@ -276,18 +314,20 @@ inherit_from => [ "parisc11_asm" ], perlasm_scheme => "64", }, - ppc64_asm => { + ppc32_asm => { template => 1, cpuid_asm_src => "ppccpuid.s ppccap.c", - bn_asm_src => "bn-ppc.s ppc-mont.s ppc64-mont.s", + bn_asm_src => "bn-ppc.s ppc-mont.s", aes_asm_src => "aes_core.c aes_cbc.c aes-ppc.s vpaes-ppc.s aesp8-ppc.s", sha1_asm_src => "sha1-ppc.s sha256-ppc.s sha512-ppc.s sha256p8-ppc.s sha512p8-ppc.s", modes_asm_src => "ghashp8-ppc.s", chacha_asm_src => "chacha-ppc.s", poly1305_asm_src=> "poly1305-ppc.s poly1305-ppcfp.s", }, - ppc32_asm => { - inherit_from => [ "ppc64_asm" ], - template => 1 + ppc64_asm => { + inherit_from => [ "ppc32_asm" ], + template => 1, + ec_asm_src => "ecp_nistz256.c ecp_nistz256-ppc64.s", + }, ); diff --git a/Configurations/10-main.conf b/Configurations/10-main.conf index b49f04b5..3ee07176 100644 --- a/Configurations/10-main.conf +++ b/Configurations/10-main.conf @@ -53,14 +53,14 @@ my $vc_wince_info = {}; sub vc_wince_info { unless (%$vc_wince_info) { # sanity check - $die->('%OSVERSION% is not defined') if (!defined($ENV{'OSVERSION'})); - $die->('%PLATFORM% is not defined') if (!defined($ENV{'PLATFORM'})); - $die->('%TARGETCPU% is not defined') if (!defined($ENV{'TARGETCPU'})); + $die->('%OSVERSION% is not defined') if (!defined(env('OSVERSION'))); + $die->('%PLATFORM% is not defined') if (!defined(env('PLATFORM'))); + $die->('%TARGETCPU% is not defined') if (!defined(env('TARGETCPU'))); # # Idea behind this is to mimic flags set by eVC++ IDE... # - my $wcevers = $ENV{'OSVERSION'}; # WCENNN + my $wcevers = env('OSVERSION'); # WCENNN my $wcevernum; my $wceverdotnum; if ($wcevers =~ /^WCE([1-9])([0-9]{2})$/) { @@ -74,12 +74,12 @@ sub vc_wince_info { my $wcecdefs = "-D_WIN32_WCE=$wcevernum -DUNDER_CE=$wcevernum"; # -D_WIN32_WCE=NNN my $wcelflag = "/subsystem:windowsce,$wceverdotnum"; # ...,N.NN - my $wceplatf = $ENV{'PLATFORM'}; + my $wceplatf = env('PLATFORM'); $wceplatf =~ tr/a-z0-9 /A-Z0-9_/; $wcecdefs .= " -DWCE_PLATFORM_$wceplatf"; - my $wcetgt = $ENV{'TARGETCPU'}; # just shorter name... + my $wcetgt = env('TARGETCPU'); # just shorter name... SWITCH: for($wcetgt) { /^X86/ && do { $wcecdefs.=" -Dx86 -D_X86_ -D_i386_ -Di_386_"; $wcelflag.=" /machine:X86"; last; }; @@ -107,7 +107,7 @@ sub vc_wince_info { $wcelflag.=" /machine:$wcetgt"; last; }; } - $vc_wince_info = { cflags => $wcecdefs, + $vc_wince_info = { cppflags => $wcecdefs, lflags => $wcelflag }; } return $vc_wince_info; @@ -116,13 +116,19 @@ sub vc_wince_info { # Helper functions for the VMS configs my $vms_info = {}; sub vms_info { - unless (%$vms_info) { - my $pointer_size = shift; - my $pointer_size_str = $pointer_size == 0 ? "" : "$pointer_size"; + my $pointer_size_str = $config{target} =~ m|-p(\d+)$| ? $1 : ""; + # For the case where Configure iterate through all config targets, such + # as when listing them and their details, we reset info if the pointer + # size changes. + if (%$vms_info && $vms_info->{pointer_size} ne $pointer_size_str) { + $vms_info = {}; + } + + unless (%$vms_info) { $vms_info->{disable_warns} = [ ]; $vms_info->{pointer_size} = $pointer_size_str; - if ($pointer_size == 64) { + if ($pointer_size_str eq "64") { `PIPE CC /NOCROSS_REFERENCE /NOLIST /NOOBJECT /WARNINGS = DISABLE = ( MAYLOSEDATA3, EMPTYFILE ) NL: 2> NL:`; if ($? == 0) { push @{$vms_info->{disable_warns}}, "MAYLOSEDATA3"; @@ -140,14 +146,25 @@ sub vms_info { $vms_info->{def_zlib} =~ s|/.*$||g; } } + + if ($config{target} =~ /-ia64/) { + `PIPE ias -H 2> NL:`; + if ($? == 0) { + $vms_info->{as} = "ias"; + $vms_info->{asflags} = '-d debug "-N" vms_upcase'; + $vms_info->{asoutflag} = "-o"; + $vms_info->{perlasm_scheme} = "ias"; + } + } } return $vms_info; } -%targets = ( +my %targets = ( #### Basic configs that should work on any 32-bit box "gcc" => { + inherit_from => [ "BASE_unix" ], cc => "gcc", cflags => picker(debug => "-O0 -g", release => "-O3"), @@ -155,6 +172,7 @@ sub vms_info { bn_ops => "BN_LLONG", }, "cc" => { + inherit_from => [ "BASE_unix" ], cc => "cc", cflags => "-O", thread_scheme => "(unknown)", @@ -164,12 +182,13 @@ sub vms_info { "vos-gcc" => { inherit_from => [ "BASE_unix" ], cc => "gcc", - cflags => picker(default => "-Wall -DOPENSSL_SYS_VOS -D_POSIX_C_SOURCE=200112L -D_BSD -D_VOS_EXTENDED_NAMES -DB_ENDIAN", + cflags => picker(default => "-Wall", debug => "-O0 -g", release => "-O3"), + cppflags => "-D_POSIX_C_SOURCE=200112L -D_BSD -D_VOS_EXTENDED_NAMES -DB_ENDIAN", thread_scheme => "(unknown)", sys_id => "VOS", - lflags => "-Wl,-map", + lflags => add("-Wl,-map"), bn_ops => "BN_LLONG", shared_extension => ".so", }, @@ -178,32 +197,25 @@ sub vms_info { "solaris-common" => { inherit_from => [ "BASE_unix" ], template => 1, - cflags => "-DFILIO_H", + cppflags => "-DFILIO_H", ex_libs => add("-lsocket -lnsl -ldl"), dso_scheme => "dlfcn", thread_scheme => "pthreads", shared_target => "solaris-shared", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, #### Solaris x86 with GNU C setups "solaris-x86-gcc" => { # NB. GNU C has to be configured to use GNU assembler, and not # /usr/ccs/bin/as. Failure to comply will result in compile # failures [at least] in 32-bit build. - # [Above statement is in direct contradition with one below. - # Latter is kept, because it's formally inappropriate to - # modify compile flags in letter release.] - # -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. inherit_from => [ "solaris-common", asm("x86_elf_asm") ], cc => "gcc", - cflags => add_before(picker(default => "-Wall -DL_ENDIAN -DOPENSSL_NO_INLINE_ASM", + cflags => add_before(picker(default => "-Wall", debug => "-O0 -g", release => "-O3 -fomit-frame-pointer"), threads("-pthread")), + cppflags => add("-DL_ENDIAN"), ex_libs => add(threads("-pthread")), bn_ops => "BN_LLONG", shared_cflag => "-fPIC", @@ -217,18 +229,19 @@ sub vms_info { # 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:-) - # + # -- inherit_from => [ "solaris-common", asm("x86_64_asm") ], cc => "gcc", - cflags => add_before(picker(default => "-m64 -Wall -DL_ENDIAN", + cflags => add_before(picker(default => "-m64 -Wall", debug => "-O0 -g", release => "-O3"), threads("-pthread")), + cppflags => add("-DL_ENDIAN"), ex_libs => add(threads("-pthread")), bn_ops => "SIXTY_FOUR_BIT_LONG", perlasm_scheme => "elf", shared_cflag => "-fPIC", - shared_ldflag => "-m64 -shared -static-libgcc", + shared_ldflag => "-shared -static-libgcc", multilib => "/64", }, @@ -248,17 +261,17 @@ sub vms_info { "solaris64-x86_64-cc" => { inherit_from => [ "solaris-common", asm("x86_64_asm") ], cc => "cc", - cflags => add_before(picker(default => "-xarch=generic64 -xstrconst -Xa -DL_ENDIAN", + cflags => add_before(picker(default => "-xarch=generic64 -xstrconst -Xa", debug => "-g", - release => "-xO5 -xdepend -xbuiltin"), - threads("-D_REENTRANT")), + release => "-xO5 -xdepend -xbuiltin")), + cppflags => add("-DL_ENDIAN", threads("-D_REENTRANT")), thread_scheme => "pthreads", - lflags => add("-xarch=generic64",threads("-mt")), + lflags => add(threads("-mt")), ex_libs => add(threads("-lpthread")), bn_ops => "SIXTY_FOUR_BIT_LONG", perlasm_scheme => "elf", shared_cflag => "-KPIC", - shared_ldflag => "-xarch=generic64 -G -dy -z text", + shared_ldflag => "-G -dy -z text", multilib => "/64", }, @@ -266,10 +279,11 @@ sub vms_info { "solaris-sparcv7-gcc" => { inherit_from => [ "solaris-common" ], cc => "gcc", - cflags => add_before(picker(default => "-Wall -DB_ENDIAN -DBN_DIV2W", + cflags => add_before(picker(default => "-Wall", debug => "-O0 -g", release => "-O3"), threads("-pthread")), + cppflags => add("-DB_ENDIAN -DBN_DIV2W"), ex_libs => add(threads("-pthread")), bn_ops => "BN_LLONG RC4_CHAR", shared_cflag => "-fPIC", @@ -289,7 +303,6 @@ sub vms_info { inherit_from => [ "solaris-sparcv9-gcc" ], cflags => sub { my $f=join(" ",@_); $f =~ s/\-m32/-m64/; $f; }, bn_ops => "BN_LLONG RC4_CHAR", - shared_ldflag => "-m64 -shared", multilib => "/64", }, @@ -300,10 +313,11 @@ sub vms_info { "solaris-sparcv7-cc" => { inherit_from => [ "solaris-common" ], cc => "cc", - cflags => add_before(picker(default => "-xstrconst -Xa -DB_ENDIAN -DBN_DIV2W", + cflags => add_before(picker(default => "-xstrconst -Xa", debug => "-g", - release => "-xO5 -xdepend"), - threads("-D_REENTRANT")), + release => "-xO5 -xdepend")), + cppflags => add("-DB_ENDIAN -DBN_DIV2W", + threads("-D_REENTRANT")), lflags => add(threads("-mt")), ex_libs => add(threads("-lpthread")), bn_ops => "BN_LLONG RC4_CHAR", @@ -322,9 +336,7 @@ sub vms_info { "solaris64-sparcv9-cc" => { inherit_from => [ "solaris-sparcv7-cc", asm("sparcv9_asm") ], cflags => add_before("-xarch=v9"), - lflags => add_before("-xarch=v9"), bn_ops => "BN_LLONG RC4_CHAR", - shared_ldflag => "-xarch=v9 -G -dy -z text", multilib => "/64", }, @@ -333,9 +345,10 @@ sub vms_info { "irix-mips3-gcc" => { inherit_from => [ "BASE_unix", asm("mips64_asm") ], cc => "gcc", - cflags => combine(picker(default => "-mabi=n32 -DB_ENDIAN -DBN_DIV3W", + cflags => combine(picker(default => "-mabi=n32", debug => "-g -O0", - release => "-O3"), + release => "-O3")), + cppflags => combine("-DB_ENDIAN -DBN_DIV3W", threads("-D_SGI_MP_SOURCE")), ex_libs => add(threads("-lpthread")), bn_ops => "RC4_CHAR SIXTY_FOUR_BIT", @@ -343,16 +356,16 @@ sub vms_info { perlasm_scheme => "n32", dso_scheme => "dlfcn", shared_target => "irix-shared", - shared_ldflag => "-mabi=n32", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", multilib => "32", }, "irix-mips3-cc" => { inherit_from => [ "BASE_unix", asm("mips64_asm") ], cc => "cc", - cflags => combine(picker(default => "-n32 -mips3 -use_readonly_const -G0 -rdata_shared -DB_ENDIAN -DBN_DIV3W", + cflags => combine(picker(default => "-n32 -mips3 -use_readonly_const -G0 -rdata_shared", debug => "-g -O0", - release => "-O2"), + release => "-O2")), + cppflags => combine("-DB_ENDIAN -DBN_DIV3W", threads("-D_SGI_MP_SOURCE")), ex_libs => add(threads("-lpthread")), bn_ops => "RC4_CHAR SIXTY_FOUR_BIT", @@ -360,17 +373,17 @@ sub vms_info { perlasm_scheme => "n32", dso_scheme => "dlfcn", shared_target => "irix-shared", - shared_ldflag => "-n32", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", multilib => "32", }, # N64 ABI builds. "irix64-mips4-gcc" => { inherit_from => [ "BASE_unix", asm("mips64_asm") ], cc => "gcc", - cflags => combine(picker(default => "-mabi=64 -mips4 -DB_ENDIAN -DBN_DIV3W", + cflags => combine(picker(default => "-mabi=64 -mips4", debug => "-g -O0", - release => "-O3"), + release => "-O3")), + cppflags => combine("-DB_ENDIAN -DBN_DIV3W", threads("-D_SGI_MP_SOURCE")), ex_libs => add(threads("-lpthread")), bn_ops => "RC4_CHAR SIXTY_FOUR_BIT_LONG", @@ -378,16 +391,16 @@ sub vms_info { perlasm_scheme => "64", dso_scheme => "dlfcn", shared_target => "irix-shared", - shared_ldflag => "-mabi=64", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", multilib => "64", }, "irix64-mips4-cc" => { inherit_from => [ "BASE_unix", asm("mips64_asm") ], cc => "cc", - cflags => combine(picker(default => "-64 -mips4 -use_readonly_const -G0 -rdata_shared -DB_ENDIAN -DBN_DIV3W", + cflags => combine(picker(default => "-64 -mips4 -use_readonly_const -G0 -rdata_shared", debug => "-g -O0", - release => "-O2"), + release => "-O2")), + cppflags => combine("-DB_ENDIAN -DBN_DIV3W", threads("-D_SGI_MP_SOURCE")), ex_libs => add(threads("-lpthread")), bn_ops => "RC4_CHAR SIXTY_FOUR_BIT_LONG", @@ -395,8 +408,7 @@ sub vms_info { perlasm_scheme => "64", dso_scheme => "dlfcn", shared_target => "irix-shared", - shared_ldflag => "-64", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", multilib => "64", }, @@ -427,14 +439,13 @@ sub vms_info { # targets; b) performance-critical 32-bit assembly modules implement # even PA-RISC 2.0-specific code paths, which are chosen at run-time, # thus adequate performance is provided even with PA-RISC 1.1 build. -# "hpux-parisc-gcc" => { inherit_from => [ "BASE_unix" ], cc => "gcc", - cflags => combine(picker(default => "-DB_ENDIAN -DBN_DIV2W", - debug => "-O0 -g", + cflags => combine(picker(debug => "-O0 -g", release => "-O3"), threads("-pthread")), + cppflags => "-DB_ENDIAN -DBN_DIV2W", ex_libs => add("-Wl,+s -ldld", threads("-pthread")), bn_ops => "BN_LLONG", thread_scheme => "pthreads", @@ -442,7 +453,7 @@ sub vms_info { shared_target => "hpux-shared", shared_cflag => "-fPIC", shared_ldflag => "-shared", - shared_extension => ".sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".sl.\$(SHLIB_VERSION_NUMBER)", }, "hpux-parisc1_1-gcc" => { inherit_from => [ "hpux-parisc-gcc", asm("parisc11_asm") ], @@ -451,10 +462,9 @@ sub vms_info { "hpux64-parisc2-gcc" => { inherit_from => [ "BASE_unix", asm("parisc20_64_asm") ], cc => "gcc", - cflags => combine(picker(default => "-DB_ENDIAN", - debug => "-O0 -g", - release => "-O3"), - threads("-D_REENTRANT")), + cflags => combine(picker(debug => "-O0 -g", + release => "-O3")), + cppflags => combine("-DB_ENDIAN", threads("-D_REENTRANT")), ex_libs => add("-ldl"), bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR", thread_scheme => "pthreads", @@ -462,20 +472,18 @@ sub vms_info { shared_target => "hpux-shared", shared_cflag => "-fpic", shared_ldflag => "-shared", - shared_extension => ".sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".sl.\$(SHLIB_VERSION_NUMBER)", multilib => "/pa20_64", }, # More attempts at unified 10.X and 11.X targets for HP C compiler. - # - # Chris Ruemmler - # Kevin Steves "hpux-parisc-cc" => { inherit_from => [ "BASE_unix" ], cc => "cc", - cflags => combine(picker(default => "+Optrs_strongly_typed -Ae +ESlit -DB_ENDIAN -DBN_DIV2W -DMD32_XARRAY", + cflags => combine(picker(default => "+Optrs_strongly_typed -Ae +ESlit", debug => "+O0 +d -g", - release => "+O3"), + release => "+O3")), + cppflags => combine("-DB_ENDIAN -DBN_DIV2W -DMD32_XARRAY", threads("-D_REENTRANT")), ex_libs => add("-Wl,+s -ldld",threads("-lpthread")), bn_ops => "RC4_CHAR", @@ -484,7 +492,7 @@ sub vms_info { shared_target => "hpux-shared", shared_cflag => "+Z", shared_ldflag => "-b", - shared_extension => ".sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".sl.\$(SHLIB_VERSION_NUMBER)", }, "hpux-parisc1_1-cc" => { inherit_from => [ "hpux-parisc-cc", asm("parisc11_asm") ], @@ -494,9 +502,10 @@ sub vms_info { "hpux64-parisc2-cc" => { inherit_from => [ "BASE_unix", asm("parisc20_64_asm") ], cc => "cc", - cflags => combine(picker(default => "+DD64 +Optrs_strongly_typed -Ae +ESlit -DB_ENDIAN -DMD32_XARRAY", + cflags => combine(picker(default => "+DD64 +Optrs_strongly_typed -Ae +ESlit", debug => "+O0 +d -g", - release => "+O3"), + release => "+O3")), + cppflags => combine("-DB_ENDIAN -DMD32_XARRAY", threads("-D_REENTRANT")), ex_libs => add("-ldl",threads("-lpthread")), bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR", @@ -504,8 +513,8 @@ sub vms_info { dso_scheme => "dlfcn", shared_target => "hpux-shared", shared_cflag => "+Z", - shared_ldflag => "+DD64 -b", - shared_extension => ".sl.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_ldflag => "-b", + shared_extension => ".sl.\$(SHLIB_VERSION_NUMBER)", multilib => "/pa20_64", }, @@ -513,47 +522,45 @@ sub vms_info { "hpux-ia64-cc" => { inherit_from => [ "BASE_unix", asm("ia64_asm") ], cc => "cc", - cflags => combine(picker(default => "-Ae +DD32 +Olit=all -z -DB_ENDIAN", + cflags => combine(picker(default => "-Ae +DD32 +Olit=all -z", debug => "+O0 +d -g", - release => "+O2"), - threads("-D_REENTRANT")), + release => "+O2")), + cppflags => combine("-DB_ENDIAN", threads("-D_REENTRANT")), ex_libs => add("-ldl",threads("-lpthread")), bn_ops => "SIXTY_FOUR_BIT", thread_scheme => "pthreads", dso_scheme => "dlfcn", shared_target => "hpux-shared", shared_cflag => "+Z", - shared_ldflag => "+DD32 -b", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_ldflag => "-b", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", multilib => "/hpux32", }, - # Frank Geurts has patiently assisted - # with debugging of the following config. "hpux64-ia64-cc" => { inherit_from => [ "BASE_unix", asm("ia64_asm") ], cc => "cc", - cflags => combine(picker(default => "-Ae +DD64 +Olit=all -z -DB_ENDIAN", + cflags => combine(picker(default => "-Ae +DD64 +Olit=all -z", debug => "+O0 +d -g", - release => "+O3"), - threads("-D_REENTRANT")), + release => "+O3")), + cppflags => combine("-DB_ENDIAN", threads("-D_REENTRANT")), ex_libs => add("-ldl", threads("-lpthread")), bn_ops => "SIXTY_FOUR_BIT_LONG", thread_scheme => "pthreads", dso_scheme => "dlfcn", shared_target => "hpux-shared", shared_cflag => "+Z", - shared_ldflag => "+DD64 -b", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_ldflag => "-b", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", multilib => "/hpux64", }, # GCC builds... "hpux-ia64-gcc" => { inherit_from => [ "BASE_unix", asm("ia64_asm") ], cc => "gcc", - cflags => combine(picker(default => "-DB_ENDIAN", - debug => "-O0 -g", + cflags => combine(picker(debug => "-O0 -g", release => "-O3"), threads("-pthread")), + cppflags => "-DB_ENDIAN", ex_libs => add("-ldl", threads("-pthread")), bn_ops => "SIXTY_FOUR_BIT", thread_scheme => "pthreads", @@ -561,24 +568,25 @@ sub vms_info { shared_target => "hpux-shared", shared_cflag => "-fpic", shared_ldflag => "-shared", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", multilib => "/hpux32", }, "hpux64-ia64-gcc" => { inherit_from => [ "BASE_unix", asm("ia64_asm") ], cc => "gcc", - cflags => combine(picker(default => "-mlp64 -DB_ENDIAN", + cflags => combine(picker(default => "-mlp64", debug => "-O0 -g", release => "-O3"), threads("-pthread")), + cppflags => "-DB_ENDIAN", ex_libs => add("-ldl", threads("-pthread")), bn_ops => "SIXTY_FOUR_BIT_LONG", thread_scheme => "pthreads", dso_scheme => "dlfcn", shared_target => "hpux-shared", shared_cflag => "-fpic", - shared_ldflag => "-mlp64 -shared", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_ldflag => "-shared", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", multilib => "/hpux64", }, @@ -586,9 +594,12 @@ sub vms_info { "MPE/iX-gcc" => { inherit_from => [ "BASE_unix" ], cc => "gcc", - cflags => "-DBN_DIV2W -O3 -D_POSIX_SOURCE -D_SOCKET_SOURCE -I/SYSLOG/PUB", + cflags => "-O3", + cppflags => "-D_ENDIAN -DBN_DIV2W -D_POSIX_SOURCE -D_SOCKET_SOURCE", + includes => add("/SYSLOG/PUB"), sys_id => "MPE", - ex_libs => add("-L/SYSLOG/PUB -lsyslog -lsocket -lcurses"), + lflags => add("-L/SYSLOG/PUB"), + ex_libs => add("-lsyslog -lsocket -lcurses"), thread_scheme => "(unknown)", bn_ops => "BN_LLONG", }, @@ -600,8 +611,8 @@ sub vms_info { "tru64-alpha-gcc" => { inherit_from => [ "BASE_unix", asm("alpha_asm") ], cc => "gcc", - cflags => combine("-std=c9x -D_XOPEN_SOURCE=500 -D_OSF_SOURCE -O3", - threads("-pthread")), + cflags => combine("-std=c9x -O3", threads("-pthread")), + cppflags => "-D_XOPEN_SOURCE=500 -D_OSF_SOURCE", ex_libs => add("-lrt", threads("-pthread")), # for mlock(2) bn_ops => "SIXTY_FOUR_BIT_LONG", thread_scheme => "pthreads", @@ -612,8 +623,9 @@ sub vms_info { "tru64-alpha-cc" => { inherit_from => [ "BASE_unix", asm("alpha_asm") ], cc => "cc", - cflags => combine("-std1 -D_XOPEN_SOURCE=500 -D_OSF_SOURCE -tune host -fast -readonly_strings", + cflags => combine("-std1 -tune host -fast -readonly_strings", threads("-pthread")), + cppflags => "-D_XOPEN_SOURCE=500 -D_OSF_SOURCE", ex_libs => add("-lrt", threads("-pthread")), # for mlock(2) bn_ops => "SIXTY_FOUR_BIT_LONG", thread_scheme => "pthreads", @@ -631,18 +643,24 @@ sub vms_info { "linux-generic32" => { inherit_from => [ "BASE_unix" ], cc => "gcc", + cxx => "g++", cflags => combine(picker(default => "-Wall", debug => "-O0 -g", release => "-O3"), threads("-pthread")), + cxxflags => combine(picker(default => "-std=c++11 -Wall", + debug => "-O0 -g", + release => "-O3"), + threads("-pthread")), + cppflags => "-DOPENSSL_USE_NODELETE", ex_libs => add("-ldl", threads("-pthread")), bn_ops => "BN_LLONG RC4_CHAR", thread_scheme => "pthreads", dso_scheme => "dlfcn", shared_target => "linux-shared", - shared_cflag => "-fPIC -DOPENSSL_USE_NODELETE", + shared_cflag => "-fPIC", shared_ldflag => "-Wl,-znodelete", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, "linux-generic64" => { inherit_from => [ "linux-generic32" ], @@ -655,16 +673,16 @@ sub vms_info { }, "linux-ppc64" => { inherit_from => [ "linux-generic64", asm("ppc64_asm") ], - cflags => add("-m64 -DB_ENDIAN"), + cflags => add("-m64"), + cppflags => add("-DB_ENDIAN"), perlasm_scheme => "linux64", - shared_ldflag => add("-m64"), multilib => "64", }, "linux-ppc64le" => { inherit_from => [ "linux-generic64", asm("ppc64_asm") ], - cflags => add("-m64 -DL_ENDIAN"), + cflags => add("-m64"), + cppflags => add("-DL_ENDIAN"), perlasm_scheme => "linux64le", - shared_ldflag => add("-m64"), }, "linux-armv4" => { @@ -711,32 +729,31 @@ sub vms_info { cflags => add("-mabi=ilp32"), bn_ops => "SIXTY_FOUR_BIT RC4_CHAR", perlasm_scheme => "linux64", - shared_ldflag => add("-mabi=ilp32"), }, "linux-mips32" => { # Configure script adds minimally required -march for assembly # support, if no -march was specified at command line. inherit_from => [ "linux-generic32", asm("mips32_asm") ], - cflags => add("-mabi=32 -DBN_DIV3W"), + cflags => add("-mabi=32"), + cppflags => add("-DBN_DIV3W"), perlasm_scheme => "o32", - shared_ldflag => add("-mabi=32"), }, # mips32 and mips64 below refer to contemporary MIPS Architecture # specifications, MIPS32 and MIPS64, rather than to kernel bitness. "linux-mips64" => { inherit_from => [ "linux-generic32", asm("mips64_asm") ], - cflags => add("-mabi=n32 -DBN_DIV3W"), + cflags => add("-mabi=n32"), + cppflags => add("-DBN_DIV3W"), bn_ops => "SIXTY_FOUR_BIT RC4_CHAR", perlasm_scheme => "n32", - shared_ldflag => add("-mabi=n32"), multilib => "32", }, "linux64-mips64" => { inherit_from => [ "linux-generic64", asm("mips64_asm") ], - cflags => add("-mabi=64 -DBN_DIV3W"), + cflags => add("-mabi=64"), + cppflags => add("-DBN_DIV3W"), perlasm_scheme => "64", - shared_ldflag => add("-mabi=64"), multilib => "64", }, @@ -745,16 +762,17 @@ sub vms_info { #### machines where gcc doesn't understand -m32 and -m64 "linux-elf" => { inherit_from => [ "linux-generic32", asm("x86_elf_asm") ], - cflags => add(picker(default => "-DL_ENDIAN", - release => "-fomit-frame-pointer")), + cflags => add(picker(release => "-fomit-frame-pointer")), + cppflags => add("-DL_ENDIAN"), bn_ops => "BN_LLONG", }, "linux-aout" => { inherit_from => [ "BASE_unix", asm("x86_asm") ], cc => "gcc", - cflags => add(picker(default => "-DL_ENDIAN -Wall", + cflags => add(picker(default => "-Wall", debug => "-O0 -g", release => "-O3 -fomit-frame-pointer")), + cppflags => add("-DL_ENDIAN"), bn_ops => "BN_LLONG", thread_scheme => "(unknown)", perlasm_scheme => "a.out", @@ -763,37 +781,38 @@ sub vms_info { #### X86 / X86_64 targets "linux-x86" => { inherit_from => [ "linux-generic32", asm("x86_asm") ], - cflags => add(picker(default => "-m32 -DL_ENDIAN", + cflags => add(picker(default => "-m32", release => "-fomit-frame-pointer")), + cppflags => add("-DL_ENDIAN"), bn_ops => "BN_LLONG", perlasm_scheme => "elf", - shared_ldflag => add("-m32"), }, "linux-x86-clang" => { inherit_from => [ "linux-x86" ], cc => "clang", cxx => "clang++", - cflags => add("-Wextra -Qunused-arguments"), + cflags => add("-Wextra"), }, "linux-x86_64" => { inherit_from => [ "linux-generic64", asm("x86_64_asm") ], - cflags => add("-m64 -DL_ENDIAN"), + cflags => add("-m64"), + cppflags => add("-DL_ENDIAN"), bn_ops => "SIXTY_FOUR_BIT_LONG", perlasm_scheme => "elf", - shared_ldflag => add("-m64"), multilib => "64", }, "linux-x86_64-clang" => { inherit_from => [ "linux-x86_64" ], cc => "clang", - cflags => add("-Wextra -Qunused-arguments"), + cxx => "clang++", + cflags => add("-Wextra"), }, "linux-x32" => { inherit_from => [ "linux-generic32", asm("x86_64_asm") ], - cflags => add("-mx32 -DL_ENDIAN"), + cflags => add("-mx32"), + cppflags => add("-DL_ENDIAN"), bn_ops => "SIXTY_FOUR_BIT", perlasm_scheme => "elf32", - shared_ldflag => add("-mx32"), multilib => "x32", }, @@ -804,9 +823,9 @@ sub vms_info { "linux64-s390x" => { inherit_from => [ "linux-generic64", asm("s390x_asm") ], - cflags => add("-m64 -DB_ENDIAN"), + cflags => add("-m64"), + cppflags => add("-DB_ENDIAN"), perlasm_scheme => "64", - shared_ldflag => add("-m64"), multilib => "64", }, "linux32-s390x" => { @@ -827,46 +846,46 @@ sub vms_info { # sysdeps/s390/dl-procinfo.c affecting ldconfig and ld.so.1... # inherit_from => [ "linux-generic32", asm("s390x_asm") ], - cflags => add("-m31 -Wa,-mzarch -DB_ENDIAN"), + cflags => add("-m31 -Wa,-mzarch"), + cppflags => add("-DB_ENDIAN"), bn_asm_src => sub { my $r=join(" ",@_); $r=~s|asm/s390x\.S|bn_asm.c|; $r; }, perlasm_scheme => "31", - shared_ldflag => add("-m31"), multilib => "/highgprs", }, #### SPARC Linux setups - # Ray Miller has - # patiently assisted with debugging of following two configs. "linux-sparcv8" => { inherit_from => [ "linux-generic32", asm("sparcv8_asm") ], - cflags => add("-mcpu=v8 -DB_ENDIAN -DBN_DIV2W"), + cflags => add("-mcpu=v8"), + cppflags => add("-DB_ENDIAN -DBN_DIV2W"), }, "linux-sparcv9" => { # it's a real mess with -mcpu=ultrasparc option under Linux, # but -Wa,-Av8plus should do the trick no matter what. inherit_from => [ "linux-generic32", asm("sparcv9_asm") ], - cflags => add("-m32 -mcpu=ultrasparc -Wa,-Av8plus -DB_ENDIAN -DBN_DIV2W"), - shared_ldflag => add("-m32"), + cflags => add("-m32 -mcpu=ultrasparc -Wa,-Av8plus"), + cppflags => add("-DB_ENDIAN -DBN_DIV2W"), }, "linux64-sparcv9" => { # GCC 3.1 is a requirement inherit_from => [ "linux-generic64", asm("sparcv9_asm") ], - cflags => add("-m64 -mcpu=ultrasparc -DB_ENDIAN"), + cflags => add("-m64 -mcpu=ultrasparc"), + cppflags => add("-DB_ENDIAN"), bn_ops => "BN_LLONG RC4_CHAR", - shared_ldflag => add("-m64"), multilib => "64", }, "linux-alpha-gcc" => { inherit_from => [ "linux-generic64", asm("alpha_asm") ], - cflags => add("-DL_ENDIAN"), + cppflags => add("-DL_ENDIAN"), bn_ops => "SIXTY_FOUR_BIT_LONG", }, "linux-c64xplus" => { inherit_from => [ "BASE_unix" ], # TI_CGT_C6000_7.3.x is a requirement cc => "cl6x", - cflags => combine("--linux -ea=.s -eo=.o -mv6400+ -o2 -ox -ms -pden -DOPENSSL_SMALL_FOOTPRINT", + cflags => "--linux -ea=.s -eo=.o -mv6400+ -o2 -ox -ms -pden", + cppflags => combine("-DOPENSSL_SMALL_FOOTPRINT", threads("-D_REENTRANT")), bn_ops => "BN_LLONG", cpuid_asm_src => "c64xpluscpuid.s", @@ -883,7 +902,7 @@ sub vms_info { shared_target => "linux-shared", shared_cflag => "--pic", shared_ldflag => add("-z --sysv --shared"), - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", ranlib => "true", }, @@ -960,6 +979,23 @@ sub vms_info { inherit_from => [ "android64", asm("aarch64_asm") ], perlasm_scheme => "linux64", }, + "android64-x86_64" => { + inherit_from => [ "android64", asm("x86_64_asm") ], + perlasm_scheme => "elf", + }, + "android64-mips64" => { + ############################################################ + # You are more than likely have to specify target processor + # on ./Configure command line. Trouble is that toolchain's + # default is MIPS64r6 (at least in r10d), but there are no + # such processors around (or they are too rare to spot one). + # Actual problem is that MIPS64r6 is binary incompatible + # with previous MIPS ISA versions, in sense that unlike + # prior versions original MIPS binary code will fail. + # + inherit_from => [ "android64", asm("mips64_asm") ], + perlasm_scheme => "64", + }, #### *BSD "BSD-generic32" => { @@ -975,13 +1011,16 @@ sub vms_info { cflags => combine(picker(default => "-Wall", debug => "-O0 -g", release => "-O3"), - threads("-pthread -D_THREAD_SAFE -D_REENTRANT")), + threads("-pthread")), + cppflags => threads("-D_THREAD_SAFE -D_REENTRANT"), + ex_libs => add(threads("-pthread")), + enable => add("devcryptoeng"), bn_ops => "BN_LLONG", thread_scheme => "pthreads", dso_scheme => "dlfcn", shared_target => "bsd-gcc-shared", shared_cflag => "-fPIC", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, "BSD-generic64" => { inherit_from => [ "BSD-generic32" ], @@ -990,8 +1029,8 @@ sub vms_info { "BSD-x86" => { inherit_from => [ "BSD-generic32", asm("x86_asm") ], - cflags => add(picker(default => "-DL_ENDIAN", - release => "-fomit-frame-pointer")), + cflags => add(picker(release => "-fomit-frame-pointer")), + cppflags => add("-DL_ENDIAN"), bn_ops => "BN_LLONG", shared_target => "bsd-shared", perlasm_scheme => "a.out", @@ -1003,26 +1042,27 @@ sub vms_info { "BSD-sparcv8" => { inherit_from => [ "BSD-generic32", asm("sparcv8_asm") ], - cflags => add("-mcpu=v8 -DB_ENDIAN"), + cflags => add("-mcpu=v8"), + cppflags => add("-DB_ENDIAN"), }, "BSD-sparc64" => { # -DMD32_REG_T=int doesn't actually belong in sparc64 target, it # simply *happens* to work around a compiler bug in gcc 3.3.3, # triggered by RIPEMD160 code. inherit_from => [ "BSD-generic64", asm("sparcv9_asm") ], - cflags => add("-DB_ENDIAN -DMD32_REG_T=int"), + cppflags => add("-DB_ENDIAN -DMD32_REG_T=int"), bn_ops => "BN_LLONG", }, "BSD-ia64" => { inherit_from => [ "BSD-generic64", asm("ia64_asm") ], - cflags => add_before("-DL_ENDIAN"), + cppflags => add("-DL_ENDIAN"), bn_ops => "SIXTY_FOUR_BIT_LONG", }, "BSD-x86_64" => { inherit_from => [ "BSD-generic64", asm("x86_64_asm") ], - cflags => add_before("-DL_ENDIAN"), + cppflags => add("-DL_ENDIAN"), bn_ops => "SIXTY_FOUR_BIT_LONG", perlasm_scheme => "elf", }, @@ -1030,14 +1070,15 @@ sub vms_info { "bsdi-elf-gcc" => { inherit_from => [ "BASE_unix", asm("x86_elf_asm") ], cc => "gcc", - cflags => "-DPERL5 -DL_ENDIAN -fomit-frame-pointer -O3 -Wall", + cflags => "-fomit-frame-pointer -O3 -Wall", + cppflags => "-DPERL5 -DL_ENDIAN", ex_libs => add("-ldl"), bn_ops => "BN_LLONG", thread_scheme => "(unknown)", dso_scheme => "dlfcn", shared_target => "bsd-gcc-shared", shared_cflag => "-fPIC", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, "nextstep" => { @@ -1061,7 +1102,8 @@ sub vms_info { "qnx4" => { inherit_from => [ "BASE_unix" ], cc => "cc", - cflags => "-DL_ENDIAN -DTERMIO", + cflags => "", + cppflags => "-DL_ENDIAN -DTERMIO", thread_scheme => "(unknown)", }, "QNX6" => { @@ -1071,17 +1113,18 @@ sub vms_info { dso_scheme => "dlfcn", shared_target => "bsd-gcc-shared", shared_cflag => "-fPIC", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, "QNX6-i386" => { inherit_from => [ "BASE_unix", asm("x86_elf_asm") ], cc => "gcc", - cflags => "-DL_ENDIAN -O2 -Wall", + cflags => "-O2 -Wall", + cppflags => "-DL_ENDIAN", ex_libs => add("-lsocket"), dso_scheme => "dlfcn", shared_target => "bsd-gcc-shared", shared_cflag => "-fPIC", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, #### SCO/Caldera targets. @@ -1092,31 +1135,30 @@ sub vms_info { # 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 has -# patiently assisted to debug most of it. +# compiler drivers and assemblers. # # UnixWare 2.0x fails destest with -O. "unixware-2.0" => { inherit_from => [ "BASE_unix" ], cc => "cc", - cflags => combine("-DFILIO_H -DNO_STRINGS_H", - threads("-Kthread")), + cflags => combine(threads("-Kthread")), + cppflags => "-DFILIO_H -DNO_STRINGS_H", ex_libs => add("-lsocket -lnsl -lresolv -lx"), thread_scheme => "uithreads", }, "unixware-2.1" => { inherit_from => [ "BASE_unix" ], cc => "cc", - cflags => combine("-O -DFILIO_H", - threads("-Kthread")), + cflags => combine("-O", threads("-Kthread")), + cppflags => "-DFILIO_H", ex_libs => add("-lsocket -lnsl -lresolv -lx"), thread_scheme => "uithreads", }, "unixware-7" => { inherit_from => [ "BASE_unix", asm("x86_elf_asm") ], cc => "cc", - cflags => combine("-O -DFILIO_H -Kalloca", - threads("-Kthread")), + cflags => combine("-O -Kalloca", threads("-Kthread")), + cppflags => "-DFILIO_H", ex_libs => add("-lsocket -lnsl"), thread_scheme => "uithreads", bn_ops => "BN_LLONG", @@ -1124,13 +1166,14 @@ sub vms_info { dso_scheme => "dlfcn", shared_target => "svr5-shared", shared_cflag => "-Kpic", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, "unixware-7-gcc" => { inherit_from => [ "BASE_unix", asm("x86_elf_asm") ], cc => "gcc", - cflags => combine("-DL_ENDIAN -DFILIO_H -O3 -fomit-frame-pointer -Wall", - threads("-D_REENTRANT")), + cflags => combine("-O3 -fomit-frame-pointer -Wall"), + cppflags => add("-DL_ENDIAN -DFILIO_H", + threads("-D_REENTRANT")), ex_libs => add("-lsocket -lnsl"), bn_ops => "BN_LLONG", thread_scheme => "pthreads", @@ -1138,9 +1181,9 @@ sub vms_info { dso_scheme => "dlfcn", shared_target => "gnu-shared", shared_cflag => "-fPIC", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, -# SCO 5 - Ben Laurie says the -O breaks the SCO cc. +# SCO 5 - Ben Laurie says the -O breaks the SCO cc. "sco5-cc" => { inherit_from => [ "BASE_unix", asm("x86_elf_asm") ], cc => "cc", @@ -1151,7 +1194,7 @@ sub vms_info { dso_scheme => "dlfcn", shared_target => "svr3-shared", shared_cflag => "-Kpic", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, "sco5-gcc" => { inherit_from => [ "BASE_unix", asm("x86_elf_asm") ], @@ -1164,7 +1207,7 @@ sub vms_info { dso_scheme => "dlfcn", shared_target => "svr3-shared", shared_cflag => "-fPIC", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, #### IBM's AIX. @@ -1176,10 +1219,10 @@ sub vms_info { "aix-gcc" => { inherit_from => [ "BASE_unix", asm("ppc32_asm") ], cc => "gcc", - cflags => combine(picker(default => "-DB_ENDIAN", - debug => "-O0 -g", + cflags => combine(picker(debug => "-O0 -g", release => "-O"), threads("-pthread")), + cppflags => "-DB_ENDIAN", ex_libs => add(threads("-pthread")), sys_id => "AIX", bn_ops => "BN_LLONG RC4_CHAR", @@ -1188,16 +1231,17 @@ sub vms_info { dso_scheme => "dlfcn", shared_target => "aix-shared", shared_ldflag => "-shared -static-libgcc -Wl,-G", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", - arflags => "-X32", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", + arflags => "-X32 r", }, "aix64-gcc" => { inherit_from => [ "BASE_unix", asm("ppc64_asm") ], cc => "gcc", - cflags => combine(picker(default => "-maix64 -DB_ENDIAN", + cflags => combine(picker(default => "-maix64", debug => "-O0 -g", release => "-O"), threads("-pthread")), + cppflags => "-DB_ENDIAN", ex_libs => add(threads("-pthread")), sys_id => "AIX", bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR", @@ -1205,17 +1249,18 @@ sub vms_info { perlasm_scheme => "aix64", dso_scheme => "dlfcn", shared_target => "aix-shared", - shared_ldflag => "-maix64 -shared -static-libgcc -Wl,-G", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", - arflags => "-X64", + shared_ldflag => "-shared -static-libgcc -Wl,-G", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", + arflags => "-X64 r", }, "aix-cc" => { inherit_from => [ "BASE_unix", asm("ppc32_asm") ], cc => "cc", - cflags => combine(picker(default => "-q32 -DB_ENDIAN -qmaxmem=16384 -qro -qroconst", + cflags => combine(picker(default => "-q32 -qmaxmem=16384 -qro -qroconst", debug => "-O0 -g", release => "-O"), - threads("-qthreaded -D_THREAD_SAFE")), + threads("-qthreaded")), + cppflags => combine("-DB_ENDIAN", threads("-D_THREAD_SAFE")), sys_id => "AIX", bn_ops => "BN_LLONG RC4_CHAR", thread_scheme => "pthreads", @@ -1223,17 +1268,18 @@ sub vms_info { perlasm_scheme => "aix32", dso_scheme => "dlfcn", shared_target => "aix-shared", - shared_ldflag => "-q32 -G", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", - arflags => "-X 32", + shared_ldflag => "-G", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", + arflags => "-X32 r", }, "aix64-cc" => { inherit_from => [ "BASE_unix", asm("ppc64_asm") ], cc => "cc", - cflags => combine(picker(default => "-q64 -DB_ENDIAN -qmaxmem=16384 -qro -qroconst", + cflags => combine(picker(default => "-q64 -qmaxmem=16384 -qro -qroconst", debug => "-O0 -g", release => "-O"), - threads("-qthreaded -D_THREAD_SAFE")), + threads("-qthreaded")), + cppflags => combine("-DB_ENDIAN", threads("-D_THREAD_SAFE")), sys_id => "AIX", bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR", thread_scheme => "pthreads", @@ -1241,16 +1287,17 @@ sub vms_info { perlasm_scheme => "aix64", dso_scheme => "dlfcn", shared_target => "aix-shared", - shared_ldflag => "-q64 -G", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", - arflags => "-X 64", + shared_ldflag => "-G", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", + arflags => "-X64 r", }, # SIEMENS BS2000/OSD: an EBCDIC-based mainframe "BS2000-OSD" => { inherit_from => [ "BASE_unix" ], cc => "c89", - cflags => "-O -XLLML -XLLMK -XL -DB_ENDIAN -DCHARSET_EBCDIC", + cflags => "-O -XLLML -XLLMK -XL", + cppflags => "-DB_ENDIAN -DCHARSET_EBCDIC", ex_libs => add("-lsocket -lnsl"), bn_ops => "THIRTY_TWO_BIT RC4_CHAR", thread_scheme => "(unknown)", @@ -1271,8 +1318,12 @@ sub vms_info { inherit_from => [ "BASE_Windows" ], template => 1, cc => "cl", - cflags => "-W3 -wd4090 -Gs0 -GF -Gy -nologo -DOPENSSL_SYS_WIN32 -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -D_CRT_SECURE_NO_DEPRECATE", - defines => add(sub { my @defs = (); + cpp => '$(CC) /EP /C', + cflags => "-W3 -wd4090 -Gs0 -GF -Gy -nologo", + defines => add("OPENSSL_SYS_WIN32", "WIN32_LEAN_AND_MEAN", + "L_ENDIAN", "_CRT_SECURE_NO_DEPRECATE", + "_WINSOCK_DEPRECATED_NO_WARNINGS", + sub { my @defs = (); unless ($disabled{"zlib-dynamic"}) { my $zlib = $withargs{zlib_lib} // "ZLIB1"; @@ -1281,7 +1332,7 @@ sub vms_info { 'LIBZ="' . $zlib . '"'); } return [ @defs ]; - }), + }), coutflag => "/Fo", lib_cflags => add("/Zi /Fdossl_static"), dso_cflags => "/Zi /Fddso", @@ -1296,17 +1347,18 @@ sub vms_info { "VC-noCE-common" => { inherit_from => [ "VC-common" ], template => 1, - cflags => add(picker(default => "-DUNICODE -D_UNICODE", - debug => + cflags => add(picker(debug => sub { ($disabled{shared} ? "" : "/MDd") - ." /Od -DDEBUG -D_DEBUG"; + ." /Od"; }, release => sub { ($disabled{shared} ? "" : "/MD") ." /O2"; })), + defines => add(picker(default => [ "UNICODE", "_UNICODE" ], + debug => [ "DEBUG", "_DEBUG" ])), lib_cflags => add(sub { $disabled{shared} ? "/MT /Zl" : () }), # Following might/should appears controversial, i.e. defining # /MDd without evaluating $disabled{shared}. It works in @@ -1370,6 +1422,7 @@ sub vms_info { # configure with 'perl Configure VC-WIN32 -DUNICODE -D_UNICODE' inherit_from => [ "VC-noCE-common", asm("x86_asm"), sub { $disabled{shared} ? () : "uplink_common" } ], + cflags => add("-WX"), as => sub { vc_win32_info()->{as} }, asflags => sub { vc_win32_info()->{asflags} }, asoutflag => sub { vc_win32_info()->{asoutflag} }, @@ -1378,7 +1431,7 @@ sub vms_info { # WIN32 UNICODE build gets linked with unicows.lib for # backward compatibility with Win9x. push @ex_libs, 'unicows.lib' - if (grep { $_ eq "UNICODE" } @user_defines); + if (grep { $_ eq "UNICODE" } @{$user{CPPDEFINES}}); return join(" ", @ex_libs, @_); }), sys_id => "WIN32", @@ -1394,30 +1447,38 @@ sub vms_info { cc => "cl", cflags => picker(default => - combine('/W3 /WX /GF /Gy /nologo -DUNICODE -D_UNICODE -DOPENSSL_SYS_WINCE -DWIN32_LEAN_AND_MEAN -DL_ENDIAN -DDSO_WIN32 -DNO_CHMOD -DOPENSSL_SMALL_FOOTPRINT', + combine('/W3 /WX /GF /Gy /nologo', sub { vc_wince_info()->{cflags}; }, - sub { defined($ENV{'WCECOMPAT'}) - ? '-I$(WCECOMPAT)/include' : (); }, - sub { defined($ENV{'PORTSDK_LIBPATH'}) - ? '-I$(PORTSDK_LIBPATH)/../../include' : (); }, sub { `cl 2>&1` =~ /Version ([0-9]+)\./ && $1>=14 ? ($disabled{shared} ? " /MT" : " /MD") : " /MC"; }), - debug => "/Od -DDEBUG -D_DEBUG", + debug => "/Od", release => "/O1i"), - lflags => combine("/nologo /opt:ref", - sub { vc_wince_info()->{lflags}; }, - sub { defined($ENV{PORTSDK_LIBPATH}) - ? "/entry:mainCRTstartup" : (); }), + cppflags => sub { vc_wince_info()->{cppflags}; }, + defines => + picker(default => [ "UNICODE", "_UNICODE", "OPENSSL_SYS_WINCE", + "WIN32_LEAN_AND_MEAN", "L_ENDIAN", "DSO_WIN32", + "NO_CHMOD", "OPENSSL_SMALL_FOOTPRINT" ], + debug => [ "DEBUG", "_DEBUG" ]), + includes => + add(combine(sub { defined(env('WCECOMPAT')) + ? '$(WCECOMPAT)/include' : (); }, + sub { defined(env('PORTSDK_LIBPATH')) + ? '$(PORTSDK_LIBPATH)/../../include' + : (); })), + lflags => add(combine("/nologo /opt:ref", + sub { vc_wince_info()->{lflags}; }, + sub { defined(env('PORTSDK_LIBPATH')) + ? "/entry:mainCRTstartup" : (); })), sys_id => "WINCE", bn_ops => "BN_LLONG EXPORT_VAR_AS_FN", ex_libs => add(sub { my @ex_libs = (); push @ex_libs, 'ws2.lib' unless $disabled{sock}; push @ex_libs, 'crypt32.lib'; - if (defined($ENV{WCECOMPAT})) { + if (defined(env('WCECOMPAT'))) { my $x = '$(WCECOMPAT)/lib'; - if (-f "$x/$ENV{TARGETCPU}/wcecompatex.lib") { + if (-f "$x/env('TARGETCPU')/wcecompatex.lib") { $x .= '/$(TARGETCPU)/wcecompatex.lib'; } else { $x .= '/wcecompatex.lib'; @@ -1425,9 +1486,9 @@ sub vms_info { push @ex_libs, $x; } push @ex_libs, '$(PORTSDK_LIBPATH)/portlib.lib' - if (defined($ENV{'PORTSDK_LIBPATH'})); + if (defined(env('PORTSDK_LIBPATH'))); push @ex_libs, ' /nodefaultlib coredll.lib corelibc.lib' - if ($ENV{'TARGETCPU'} eq "X86"); + if (env('TARGETCPU') eq "X86"); return @ex_libs; }), build_scheme => add("VC-WCE", { separator => undef }), @@ -1438,10 +1499,11 @@ sub vms_info { inherit_from => [ "BASE_unix", asm("x86_asm"), sub { $disabled{shared} ? () : "x86_uplink" } ], cc => "gcc", - cflags => combine(picker(default => "-DL_ENDIAN -DWIN32_LEAN_AND_MEAN -DUNICODE -D_UNICODE -m32 -Wall", - debug => "-g -O0", - release => "-O3 -fomit-frame-pointer"), - threads("-D_MT")), + cflags => picker(default => "-m32 -Wall", + debug => "-g -O0", + release => "-O3 -fomit-frame-pointer"), + cppflags => combine("-DL_ENDIAN -DWIN32_LEAN_AND_MEAN", + "-DUNICODE -D_UNICODE", threads("-D_MT")), sys_id => "MINGW32", ex_libs => add("-lws2_32 -lgdi32 -lcrypt32"), bn_ops => "BN_LLONG EXPORT_VAR_AS_FN", @@ -1449,7 +1511,7 @@ sub vms_info { perlasm_scheme => "coff", dso_scheme => "win32", shared_target => "mingw-shared", - shared_cflag => add("-D_WINDLL"), + shared_cppflags => add("_WINDLL"), shared_ldflag => "-static-libgcc", shared_rcflag => "--target=pe-i386", shared_extension => ".dll", @@ -1467,10 +1529,11 @@ sub vms_info { # Applink is never engaged and can as well be omitted. inherit_from => [ "BASE_unix", asm("x86_64_asm") ], cc => "gcc", - cflags => combine(picker(default => "-DL_ENDIAN -DWIN32_LEAN_AND_MEAN -DUNICODE -D_UNICODE -m64 -Wall", - debug => "-g -O0", - release => "-O3"), - threads("-D_MT")), + cflags => picker(default => "-m64 -Wall", + debug => "-g -O0", + release => "-O3"), + cppflags => combine("-DL_ENDIAN -DWIN32_LEAN_AND_MEAN", + "-DUNICODE -D_UNICODE", threads("-D_MT")), sys_id => "MINGW64", ex_libs => add("-lws2_32 -lgdi32 -lcrypt32"), bn_ops => "SIXTY_FOUR_BIT EXPORT_VAR_AS_FN", @@ -1478,7 +1541,7 @@ sub vms_info { perlasm_scheme => "mingw64", dso_scheme => "win32", shared_target => "mingw-shared", - shared_cflag => add("-D_WINDLL"), + shared_cppflags => add("_WINDLL"), shared_ldflag => "-static-libgcc", shared_rcflag => "--target=pe-x86-64", shared_extension => ".dll", @@ -1490,7 +1553,8 @@ sub vms_info { "UEFI" => { inherit_from => [ "BASE_unix" ], cc => "cc", - cflags => "-DL_ENDIAN -O", + cflags => "-O", + cppflags => "-DL_ENDIAN", sys_id => "UEFI", }, @@ -1498,7 +1562,8 @@ sub vms_info { "UWIN" => { inherit_from => [ "BASE_unix" ], cc => "cc", - cflags => "-DTERMIOS -DL_ENDIAN -O -Wall", + cflags => "-O -Wall", + cppflags => "-DTERMIOS -DL_ENDIAN", sys_id => "UWIN", bn_ops => "BN_LLONG", dso_scheme => "win32", @@ -1508,33 +1573,33 @@ sub vms_info { "Cygwin-x86" => { inherit_from => [ "BASE_unix", asm("x86_asm") ], cc => "gcc", - cflags => picker(default => "-DTERMIOS -DL_ENDIAN -Wall", + cflags => picker(default => "-Wall", debug => "-g -O0", release => "-O3 -fomit-frame-pointer"), + cppflags => "-DTERMIOS -DL_ENDIAN", sys_id => "CYGWIN", bn_ops => "BN_LLONG", thread_scheme => "pthread", perlasm_scheme => "coff", dso_scheme => "dlfcn", shared_target => "cygwin-shared", - shared_cflag => "-D_WINDLL", - shared_ldflag => "-shared", + shared_cppflags => "-D_WINDLL", shared_extension => ".dll", }, "Cygwin-x86_64" => { inherit_from => [ "BASE_unix", asm("x86_64_asm") ], cc => "gcc", - cflags => picker(default => "-DTERMIOS -DL_ENDIAN -Wall", + cflags => picker(default => "-Wall", debug => "-g -O0", release => "-O3"), + cppflags => "-DTERMIOS -DL_ENDIAN", sys_id => "CYGWIN", bn_ops => "SIXTY_FOUR_BIT_LONG", thread_scheme => "pthread", perlasm_scheme => "mingw64", dso_scheme => "dlfcn", shared_target => "cygwin-shared", - shared_cflag => "-D_WINDLL", - shared_ldflag => "-shared", + shared_cppflags => "-D_WINDLL", shared_extension => ".dll", }, # Backward compatibility for those using this target @@ -1560,10 +1625,10 @@ sub vms_info { inherit_from => [ "BASE_unix" ], template => 1, cc => "cc", - cflags => combine(picker(default => "", - debug => "-g -O0", - release => "-O3"), - threads("-D_REENTRANT")), + cflags => picker(default => "", + debug => "-g -O0", + release => "-O3"), + cppflags => threads("-D_REENTRANT"), sys_id => "MACOSX", plib_lflags => "-Wl,-search_paths_first", bn_ops => "BN_LLONG RC4_CHAR", @@ -1573,40 +1638,38 @@ sub vms_info { ranlib => "ranlib -c", shared_target => "darwin-shared", shared_cflag => "-fPIC", - shared_ldflag => "-dynamiclib", - shared_extension => ".\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", + shared_extension => ".\$(SHLIB_VERSION_NUMBER).dylib", }, # Option "freeze" such as -std=gnu9x can't negatively interfere # with future defaults for below two targets, because MacOS X # for PPC has no future, it was discontinued by vendor in 2009. "darwin-ppc-cc" => { inherit_from => [ "darwin-common", asm("ppc32_asm") ], - cflags => add("-arch ppc -std=gnu9x -DB_ENDIAN -Wa,-force_cpusubtype_ALL"), + cflags => add("-arch ppc -std=gnu9x -Wa,-force_cpusubtype_ALL"), + cppflags => add("-DB_ENDIAN"), perlasm_scheme => "osx32", - shared_cflag => add("-fno-common"), - shared_ldflag => "-arch ppc -dynamiclib", }, "darwin64-ppc-cc" => { inherit_from => [ "darwin-common", asm("ppc64_asm") ], - cflags => add("-arch ppc64 -std=gnu9x -DB_ENDIAN"), + cflags => add("-arch ppc64 -std=gnu9x"), + cppflags => add("-DB_ENDIAN"), bn_ops => "SIXTY_FOUR_BIT_LONG RC4_CHAR", perlasm_scheme => "osx64", - shared_ldflag => "-arch ppc64 -dynamiclib", }, "darwin-i386-cc" => { inherit_from => [ "darwin-common", asm("x86_asm") ], - cflags => add(picker(default => "-arch i386 -DL_ENDIAN", + cflags => add(picker(default => "-arch i386", release => "-fomit-frame-pointer")), + cppflags => add("-DL_ENDIAN"), bn_ops => "BN_LLONG RC4_INT", perlasm_scheme => "macosx", - shared_ldflag => "-arch i386 -dynamiclib", }, "darwin64-x86_64-cc" => { inherit_from => [ "darwin-common", asm("x86_64_asm") ], - cflags => add("-arch x86_64 -DL_ENDIAN -Wall"), + cflags => add("-arch x86_64 -Wall"), + cppflags => add("-DL_ENDIAN"), bn_ops => "SIXTY_FOUR_BIT_LONG", perlasm_scheme => "macosx", - shared_ldflag => "-arch x86_64 -dynamiclib", }, #### iPhoneOS/iOS @@ -1651,75 +1714,109 @@ sub vms_info { inherit_from => [ "BASE_unix" ], inherit_from => [ asm("x86_elf_asm") ], cc => "gcc", - cflags => combine("-DL_ENDIAN -O3 -fomit-frame-pointer -Wall", + cflags => combine("-O3 -fomit-frame-pointer -Wall", threads("-pthread")), + cppflags => "-DL_ENDIAN", ex_libs => add("-ldl", threads("-pthread")), bn_ops => "BN_LLONG", thread_scheme => "pthreads", dso_scheme => "dlfcn", shared_target => "linux-shared", shared_cflag => "-fPIC", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, ##### VxWorks for various targets "vxworks-ppc60x" => { inherit_from => [ "BASE_unix" ], cc => "ccppc", - cflags => "-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", + cflags => "-mrtp -mhard-float -mstrict-align -fno-implicit-fp -O2 -fstrength-reduce -fno-builtin -fno-strict-aliasing -Wall", + cppflags => combine("-D_REENTRANT -DPPC32_fp60x -DCPU=PPC32", + "_DTOOL_FAMILY=gnu -DTOOL=gnu", + "-I\$(WIND_BASE)/target/usr/h", + "-I\$(WIND_BASE)/target/usr/h/wrn/coreip"), sys_id => "VXWORKS", - ex_libs => add("-Wl,--defsym,__wrs_rtp_base=0xe0000000 -L \$(WIND_BASE)/target/usr/lib/ppc/PPC32/common"), + lflags => add("-L \$(WIND_BASE)/target/usr/lib/ppc/PPC32/common"), + ex_libs => add("-Wl,--defsym,__wrs_rtp_base=0xe0000000"), }, "vxworks-ppcgen" => { inherit_from => [ "BASE_unix" ], cc => "ccppc", - cflags => "-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", + cflags => "-mrtp -msoft-float -mstrict-align -O1 -fno-builtin -fno-strict-aliasing -Wall", + cppflags => combine("-D_REENTRANT -DPPC32 -DCPU=PPC32", + "-DTOOL_FAMILY=gnu -DTOOL=gnu", + "-I\$(WIND_BASE)/target/usr/h", + "-I\$(WIND_BASE)/target/usr/h/wrn/coreip"), sys_id => "VXWORKS", - ex_libs => add("-Wl,--defsym,__wrs_rtp_base=0xe0000000 -L \$(WIND_BASE)/target/usr/lib/ppc/PPC32/sfcommon"), + lflags => add("-L \$(WIND_BASE)/target/usr/lib/ppc/PPC32/sfcommon"), + ex_libs => add("-Wl,--defsym,__wrs_rtp_base=0xe0000000"), }, "vxworks-ppc405" => { inherit_from => [ "BASE_unix" ], cc => "ccppc", - cflags => "-g -msoft-float -mlongcall -DCPU=PPC405 -I\$(WIND_BASE)/target/h", + cflags => "-g -msoft-float -mlongcall", + cppflags => combine("-D_REENTRANT -DPPC32 -DCPU=PPC405", + "-DTOOL_FAMILY=gnu -DTOOL=gnu", + "-I\$(WIND_BASE)/target/h"), sys_id => "VXWORKS", - lflags => "-r", + lflags => add("-r"), }, "vxworks-ppc750" => { inherit_from => [ "BASE_unix" ], cc => "ccppc", - cflags => "-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)", + cflags => "-ansi -nostdinc -fvolatile -fno-builtin -fno-for-scope -fsigned-char -Wall -msoft-float -mlongcall \$(DEBUG_FLAG)", + cppflags => combine("-DPPC750 -D_REENTRANT -DCPU=PPC604", + "-I\$(WIND_BASE)/target/h"), sys_id => "VXWORKS", - lflags => "-r", + lflags => add("-r"), }, "vxworks-ppc750-debug" => { inherit_from => [ "BASE_unix" ], cc => "ccppc", - cflags => "-ansi -nostdinc -DPPC750 -D_REENTRANT -fvolatile -fno-builtin -fno-for-scope -fsigned-char -Wall -msoft-float -mlongcall -DCPU=PPC604 -I\$(WIND_BASE)/target/h -DPEDANTIC -DDEBUG -g", + cflags => "-ansi -nostdinc -fvolatile -fno-builtin -fno-for-scope -fsigned-char -Wall -msoft-float -mlongcall -g", + cppflags => combine("-DPPC750 -D_REENTRANT -DCPU=PPC604", + "-DPEDANTIC -DDEBUG", + "-I\$(WIND_BASE)/target/h"), sys_id => "VXWORKS", - lflags => "-r", + lflags => add("-r"), }, "vxworks-ppc860" => { inherit_from => [ "BASE_unix" ], cc => "ccppc", - cflags => "-nostdinc -msoft-float -DCPU=PPC860 -DNO_STRINGS_H -I\$(WIND_BASE)/target/h", + cflags => "-nostdinc -msoft-float", + cppflags => combine("-DCPU=PPC860 -DNO_STRINGS_H", + "-I\$(WIND_BASE)/target/h"), sys_id => "VXWORKS", - lflags => "-r", + lflags => add("-r"), }, "vxworks-simlinux" => { inherit_from => [ "BASE_unix" ], cc => "ccpentium", - cflags => "-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", + cflags => "-B\$(WIND_BASE)/host/\$(WIND_HOST_TYPE)/lib/gcc-lib/ -fno-builtin -fno-defer-pop", + cppflags => combine("-D_VSB_CONFIG_FILE=\"\$(WIND_BASE)/target/lib/h/config/vsbConfig.h\"", + "-DL_ENDIAN -DCPU=SIMLINUX -DNO_STRINGS_H", + "-DTOOL_FAMILY=gnu -DTOOL=gnu", + "-DOPENSSL_NO_HW_PADLOCK", + "-I\$(WIND_BASE)/target/h", + "-I\$(WIND_BASE)/target/h/wrn/coreip"), sys_id => "VXWORKS", - lflags => "-r", + lflags => add("-r"), ranlib => "ranlibpentium", }, "vxworks-mips" => { inherit_from => [ "BASE_unix", asm("mips32_asm") ], cc => "ccmips", - cflags => combine("-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", - threads("-D_REENTRANT")), + cflags => "-mrtp -mips2 -O -G 0 -B\$(WIND_BASE)/host/\$(WIND_HOST_TYPE)/lib/gcc-lib/ -msoft-float -mno-branch-likely -fno-builtin -fno-defer-pop", + cppflags => combine("-D_VSB_CONFIG_FILE=\"\$(WIND_BASE)/target/lib/h/config/vsbConfig.h\"", + "-DCPU=MIPS32 -DNO_STRINGS_H", + "-DTOOL_FAMILY=gnu -DTOOL=gnu", + "-DOPENSSL_NO_HW_PADLOCK", + threads("-D_REENTRANT"), + "-I\$(WIND_BASE)/target/h", + "-I\$(WIND_BASE)/target/h/wrn/coreip"), sys_id => "VXWORKS", - ex_libs => add("-Wl,--defsym,__wrs_rtp_base=0xe0000000 -L \$(WIND_BASE)/target/usr/lib/mips/MIPSI32/sfcommon"), + lflags => add("-L \$(WIND_BASE)/target/usr/lib/mips/MIPSI32/sfcommon"), + ex_libs => add("-Wl,--defsym,__wrs_rtp_base=0xe0000000"), thread_scheme => "pthreads", perlasm_scheme => "o32", ranlib => "ranlibmips", @@ -1728,157 +1825,123 @@ sub vms_info { #### uClinux "uClinux-dist" => { inherit_from => [ "BASE_unix" ], - cc => "$ENV{'CC'}", - cflags => combine(threads("-D_REENTRANT")), + cc => sub { env('CC') }, + cppflags => threads("-D_REENTRANT"), ex_libs => add("\$(LDLIBS)"), bn_ops => "BN_LLONG", thread_scheme => "pthreads", - dso_scheme => "$ENV{'LIBSSL_dlfcn'}", + dso_scheme => sub { env('LIBSSL_dlfcn') }, shared_target => "linux-shared", shared_cflag => "-fPIC", - shared_ldflag => "-shared", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", - ranlib => "$ENV{'RANLIB'}", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", + ranlib => sub { env('RANLIB') }, }, "uClinux-dist64" => { inherit_from => [ "BASE_unix" ], - cc => "$ENV{'CC'}", - cflags => combine(threads("-D_REENTRANT")), + cc => sub { env('CC') }, + cppflags => threads("-D_REENTRANT"), ex_libs => add("\$(LDLIBS)"), bn_ops => "SIXTY_FOUR_BIT_LONG", thread_scheme => "pthreads", - dso_scheme => "$ENV{'LIBSSL_dlfcn'}", + dso_scheme => sub { env('LIBSSL_dlfcn') }, shared_target => "linux-shared", shared_cflag => "-fPIC", - shared_ldflag => "-shared", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", - ranlib => "$ENV{'RANLIB'}", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", + ranlib => sub { env('RANLIB') }, }, ##### VMS + # Most things happen in vms-generic. + # Note that vms_info extracts the pointer size from the end of + # the target name, and will assume that anything matching /-p\d+$/ + # indicates the pointer size setting for the desired target. "vms-generic" => { inherit_from => [ "BASE_VMS" ], template => 1, cc => "CC/DECC", - cflags => picker(default => "/STANDARD=(ISOC94,RELAXED)/NOLIST/PREFIX=ALL", - debug => "/NOOPTIMIZE/DEBUG", - release => "/OPTIMIZE/NODEBUG"), - defines => add("OPENSSL_USE_NODELETE"), - lflags => picker(default => "/MAP", + cpp => '$(CC)/PREPROCESS_ONLY=SYS$OUTPUT:', + cflags => + combine(picker(default => "/STANDARD=(ISOC94,RELAXED)/NOLIST/PREFIX=ALL", + debug => "/NOOPTIMIZE/DEBUG", + release => "/OPTIMIZE/NODEBUG"), + sub { my @warnings = + @{vms_info()->{disable_warns}}; + @warnings + ? "/WARNINGS=DISABLE=(".join(",",@warnings).")" : (); }), + defines => + add("OPENSSL_USE_NODELETE", + sub { + return vms_info()->{def_zlib} + ? "LIBZ=\"\"\"".vms_info()->{def_zlib}."\"\"\"" : (); + }), + lflags => picker(default => "/MAP='F\$PARSE(\".MAP\",\"\$\@\")'", debug => "/DEBUG/TRACEBACK", release => "/NODEBUG/NOTRACEBACK"), lib_cflags => add("/NAMES=(AS_IS,SHORTENED)/EXTERN_MODEL=STRICT_REFDEF"), - dso_cflags => add("/NAMES=(AS_IS,SHORTENED)"), + # no_inst_lib_cflags is used instead of lib_cflags by descrip.mms.tmpl + # for object files belonging to selected internal libraries + no_inst_lib_cflags => "", + ex_libs => add(sub { return vms_info()->{zlib} || (); }), shared_target => "vms-shared", dso_scheme => "vms", thread_scheme => "pthreads", - apps_aux_src => "vms_decc_init.c vms_term_sock.c", + as => sub { vms_info()->{as} }, + asflags => sub { vms_info()->{asflags} }, + asoutflag => sub { vms_info()->{asoutflag} }, + perlasm_scheme => sub { vms_info()->{perlasm_scheme} }, + + apps_aux_src => "vms_term_sock.c", + apps_init_src => "vms_decc_init.c", }, + # From HELP CC/POINTER_SIZE: + # + # ---------- + # LONG[=ARGV] The compiler assumes 64-bit pointers. If the ARGV option to + # LONG or 64 is present, the main argument argv will be an + # array of long pointers instead of an array of short pointers. + # + # 64[=ARGV] Same as LONG. + # ---------- + # + # We don't want the hassle of dealing with 32-bit pointers with argv, so + # we force it to have 64-bit pointers, see the added cflags in the -p64 + # config targets below. + "vms-alpha" => { inherit_from => [ "vms-generic" ], - cflags => add(sub { my @warnings = - @{vms_info(0)->{disable_warns}}; - @warnings - ? "/WARNINGS=DISABLE=(".join(",",@warnings).")" : (); }), - defines => - add(sub { - return vms_info(0)->{def_zlib} - ? "LIBZ=\"\"\"".vms_info(0)->{def_zlib}."\"\"\"" : (); - }), - ex_libs => add(sub { return vms_info(0)->{zlib} || (); }), - pointer_size => sub { return vms_info(0)->{pointer_size} }, - #as => "???", - #debug_aflags => "/NOOPTIMIZE/DEBUG", - #release_aflags => "/OPTIMIZE/NODEBUG", - bn_opts => "SIXTY_FOUR_BIT RC4_INT", + bn_ops => "SIXTY_FOUR_BIT RC4_INT", + pointer_size => "", }, "vms-alpha-p32" => { - inherit_from => [ "vms-generic" ], - cflags => - add("/POINTER_SIZE=32", - sub { my @warnings = - @{vms_info(32)->{disable_warns}}; - @warnings - ? "/WARNINGS=DISABLE=(".join(",",@warnings).")" : (); - } ), - defines => - add(sub { - return vms_info(32)->{def_zlib} - ? "LIBZ=\"\"\"".vms_info(32)->{def_zlib}."\"\"\"" : (); - }), - ex_libs => add(sub { return vms_info(32)->{zlib} || (); }), - pointer_size => sub { return vms_info(32)->{pointer_size} }, + inherit_from => [ "vms-alpha" ], + cflags => add("/POINTER_SIZE=32"), + pointer_size => "32", }, "vms-alpha-p64" => { - inherit_from => [ "vms-generic" ], - cflags => - add("/POINTER_SIZE=64=ARGV", - sub { my @warnings = - @{vms_info(64)->{disable_warns}}; - @warnings - ? "/WARNINGS=DISABLE=(".join(",",@warnings).")" : (); - } ), - defines => - add(sub { - return vms_info(64)->{def_zlib} - ? "LIBZ=\"\"\"".vms_info(64)->{def_zlib}."\"\"\"" : (); - }), - ex_libs => add(sub { return vms_info(64)->{zlib} || (); }), - pointer_size => sub { return vms_info(64)->{pointer_size} }, + inherit_from => [ "vms-alpha" ], + cflags => add("/POINTER_SIZE=64=ARGV"), + pointer_size => "64", }, "vms-ia64" => { - inherit_from => [ "vms-generic" ], - cflags => add(sub { my @warnings = - @{vms_info(0)->{disable_warns}}; - @warnings - ? "/WARNINGS=DISABLE=(".join(",",@warnings).")" : (); }), - defines => - add(sub { - return vms_info(0)->{def_zlib} - ? "LIBZ=\"\"\"".vms_info(0)->{def_zlib}."\"\"\"" : (); - }), - ex_libs => add(sub { return vms_info(0)->{zlib} || (); }), - pointer_size => sub { return vms_info(0)->{pointer_size} }, - #as => "I4S", - #debug_aflags => "/NOOPTIMIZE/DEBUG", - #release_aflags => "/OPTIMIZE/NODEBUG", - bn_opts => "SIXTY_FOUR_BIT RC4_INT", + inherit_from => [ "vms-generic", + sub { vms_info()->{as} + ? asm("ia64_asm")->() : () } ], + bn_ops => "SIXTY_FOUR_BIT RC4_INT", + pointer_size => "", + + modes_asm_src => "", # Because ghash-ia64.s doesn't work on VMS }, "vms-ia64-p32" => { - inherit_from => [ "vms-generic" ], - cflags => - add("/POINTER_SIZE=32", - sub { my @warnings = - @{vms_info(32)->{disable_warns}}; - @warnings - ? "/WARNINGS=DISABLE=(".join(",",@warnings).")" : (); - } ), - defines => - add(sub { - return vms_info(32)->{def_zlib} - ? "LIBZ=\"\"\"".vms_info(32)->{def_zlib}."\"\"\"" : (); - }), - ex_libs => add(sub { return vms_info(32)->{zlib} || (); }), - pointer_size => sub { return vms_info(32)->{pointer_size} }, + inherit_from => [ "vms-ia64" ], + cflags => add("/POINTER_SIZE=32"), + pointer_size => "32", }, "vms-ia64-p64" => { - inherit_from => [ "vms-generic" ], - cflags => - add("/POINTER_SIZE=64=ARGV", - sub { my @warnings = - @{vms_info(64)->{disable_warns}}; - @warnings - ? "/WARNINGS=DISABLE=(".join(",",@warnings).")" : (); - } ), - defines => - add(sub { - return vms_info(64)->{def_zlib} - ? "LIBZ=\"\"\"".vms_info(64)->{def_zlib}."\"\"\"" : (); - }), - ex_libs => add(sub { return vms_info(64)->{zlib} || (); }), - pointer_size => sub { return vms_info(64)->{pointer_size} }, + inherit_from => [ "vms-ia64" ], + cflags => add("/POINTER_SIZE=64=ARGV"), + pointer_size => "64", }, ); diff --git a/Configurations/50-djgpp.conf b/Configurations/50-djgpp.conf index f532bd16..b4d19e20 100644 --- a/Configurations/50-djgpp.conf +++ b/Configurations/50-djgpp.conf @@ -2,13 +2,14 @@ # and rely entirely on the OpenSSL community to help is fine # tune and test. -%targets = ( +my %targets = ( "DJGPP" => { inherit_from => [ asm("x86_asm") ], cc => "gcc", cflags => "-I/dev/env/WATT_ROOT/inc -DTERMIOS -DL_ENDIAN -fomit-frame-pointer -O2 -Wall", sys_id => "MSDOS", - ex_libs => add("-L/dev/env/WATT_ROOT/lib -lwatt"), + lflags => add("-L/dev/env/WATT_ROOT/lib"), + ex_libs => add("-lwatt"), bn_ops => "BN_LLONG", perlasm_scheme => "a.out", }, diff --git a/Configurations/50-haiku.conf b/Configurations/50-haiku.conf index f1146666..b57e1487 100644 --- a/Configurations/50-haiku.conf +++ b/Configurations/50-haiku.conf @@ -1,4 +1,4 @@ -%targets = ( +my %targets = ( "haiku-common" => { template => 1, cc => "cc", @@ -14,7 +14,7 @@ shared_target => "gnu-shared", shared_cflag => "-fPIC", shared_ldflag => "-shared", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, "haiku-x86" => { inherit_from => [ "haiku-common", asm("x86_elf_asm") ], diff --git a/Configurations/50-masm.conf b/Configurations/50-masm.conf index 60a55072..e2b54e34 100644 --- a/Configurations/50-masm.conf +++ b/Configurations/50-masm.conf @@ -7,11 +7,16 @@ # proven to be daunting task. This is experimental target, for # production builds stick with [up-to-date version of] nasm. -%targets = ( +my %targets = ( "VC-WIN64A-masm" => { - inherit_from => [ "VC-WIN64A" ], + inherit_from => [ "VC-WIN64-common", asm("x86_64_asm"), + sub { $disabled{shared} ? () : "x86_64_uplink" } ], as => "ml64", - asflags => "/c /Cp /Cx /Zi", + asflags => "/nologo /c /Cp /Cx /Zi", asoutflag => "/Fo", + sys_id => "WIN64A", + bn_asm_src => sub { return undef unless @_; + my $r=join(" ",@_); $r=~s|asm/x86_64-gcc|bn_asm|; $r; }, + perlasm_scheme => "masm", }, ); diff --git a/Configurations/90-team.conf b/Configurations/90-team.conf index 0a83c22a..31382182 100644 --- a/Configurations/90-team.conf +++ b/Configurations/90-team.conf @@ -1,20 +1,22 @@ ## -*- mode: perl; -*- ## Build configuration targets for openssl-team members -%targets = ( +my %targets = ( "purify" => { + inherit_from => [ 'BASE_unix' ], cc => "purify gcc", cflags => "-g -Wall", thread_scheme => "(unknown)", ex_libs => add(" ","-lsocket -lnsl"), }, "debug" => { + inherit_from => [ 'BASE_unix' ], cc => "gcc", cflags => "-DBN_DEBUG -DREF_DEBUG -DCONF_DEBUG -DBN_CTX_DEBUG -DOPENSSL_NO_ASM -ggdb -g2 -Wformat -Wshadow -Wmissing-prototypes -Wmissing-declarations -Werror", thread_scheme => "(unknown)", }, "debug-erbridge" => { - inherit_from => [ "x86_64_asm" ], + inherit_from => [ 'BASE_unix', "x86_64_asm" ], cc => "gcc", cflags => combine("$gcc_devteam_warn -DBN_DEBUG -DCONF_DEBUG -m64 -DL_ENDIAN -DTERMIO -g", threads("-D_REENTRANT")), @@ -26,11 +28,11 @@ shared_target => "linux-shared", shared_cflag => "-fPIC", shared_ldflag => "-m64", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", multilib => "64", }, "debug-linux-pentium" => { - inherit_from => [ "x86_elf_asm" ], + inherit_from => [ 'BASE_unix', "x86_elf_asm" ], cc => "gcc", cflags => combine("-DBN_DEBUG -DREF_DEBUG -DCONF_DEBUG -DBN_CTX_DEBUG -DL_ENDIAN -g -mcpu=pentium -Wall", threads("-D_REENTRANT")), @@ -40,7 +42,7 @@ dso_scheme => "dlfcn", }, "debug-linux-ppro" => { - inherit_from => [ "x86_elf_asm" ], + inherit_from => [ 'BASE_unix', "x86_elf_asm" ], cc => "gcc", cflags => combine("-DBN_DEBUG -DREF_DEBUG -DCONF_DEBUG -DBN_CTX_DEBUG -DL_ENDIAN -g -mcpu=pentiumpro -Wall", threads("-D_REENTRANT")), @@ -50,6 +52,7 @@ dso_scheme => "dlfcn", }, "debug-linux-ia32-aes" => { + inherit_from => [ 'BASE_unix' ], cc => "gcc", cflags => combine("-DL_ENDIAN -O3 -fomit-frame-pointer -Wall", threads("-D_REENTRANT")), @@ -74,15 +77,16 @@ dso_scheme => "dlfcn", shared_target => "linux-shared", shared_cflag => "-fPIC", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, "dist" => { + inherit_from => [ 'BASE_unix' ], cc => "cc", cflags => "-O", thread_scheme => "(unknown)", }, "debug-test-64-clang" => { - inherit_from => [ "x86_64_asm" ], + inherit_from => [ 'BASE_unix', "x86_64_asm" ], cc => "clang", cflags => combine("$gcc_devteam_warn -Wno-error=overlength-strings -Wno-error=extended-offsetof -Wno-error=language-extension-token -Wno-error=unused-const-variable -Wstrict-overflow -Qunused-arguments -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -g3 -O3 -pipe", threads("${BSDthreads}")), @@ -92,10 +96,10 @@ dso_scheme => "dlfcn", shared_target => "bsd-gcc-shared", shared_cflag => "-fPIC", - shared_extension => ".so.\$(SHLIB_MAJOR).\$(SHLIB_MINOR)", + shared_extension => ".so.\$(SHLIB_VERSION_NUMBER)", }, "darwin64-debug-test-64-clang" => { - inherit_from => [ "x86_64_asm" ], + inherit_from => [ 'BASE_unix', "x86_64_asm" ], cc => "clang", cflags => combine("-arch x86_64 -DL_ENDIAN $gcc_devteam_warn -Wno-error=overlength-strings -Wno-error=extended-offsetof -Wno-error=language-extension-token -Wno-error=unused-const-variable -Wstrict-overflow -Qunused-arguments -DBN_DEBUG -DCONF_DEBUG -DDEBUG_SAFESTACK -DDEBUG_UNUSED -g3 -O3 -pipe", threads("${BSDthreads}")), @@ -107,6 +111,6 @@ shared_target => "darwin-shared", shared_cflag => "-fPIC -fno-common", shared_ldflag => "-arch x86_64 -dynamiclib", - shared_extension => ".\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", + shared_extension => ".\$(SHLIB_VERSION_NUMBER).dylib", }, ); diff --git a/Configurations/README b/Configurations/README index 6e136454..8d32a254 100644 --- a/Configurations/README +++ b/Configurations/README @@ -38,17 +38,40 @@ In each table entry, the following keys are significant: sys_id => System identity for systems where that is difficult to determine automatically. - cc => The compiler command, usually one of "cc", - "gcc" or "clang". This command is normally - also used to link object files and - libraries into the final program. - cflags => Flags that are used at all times when - compiling. + enable => Enable specific configuration features. + This MUST be an array of words. + disable => Disable specific configuration features. + This MUST be an array of words. + Note: if the same feature is both enabled + and disabled, disable wins. + + cpp => The C preprocessor command, normally not + given, as the build file defaults are + usually good enough. + cppflags => The C preprocessor flags. defines => As an alternative, macro definitions may be - present here instead of in `cflags'. If + given here instead of in `cppflags'. If given here, they MUST be as an array of the string such as "MACRO=value", or just "MACRO" for definitions without value. + includes => As an alternative, inclusion directories + may be given here instead of in `cppflags'. + If given here, the MUST be an array of + strings, one directory specification each. + cc => The C compiler command, usually one of "cc", + "gcc" or "clang". This command is normally + also used to link object files and + libraries into the final program. + cxx => The C++ compiler command, usually one of + "c++", "g++" or "clang++". This command is + also used when linking a program where at + least one of the object file is made from + C++ source. + cflags => Flags that are used at all times when + compiling C object files. + cxxflags => Flags that are used at all times when + compiling C++ object files. If unset, it + gets the same value as cflags. shared_cflag => Extra compilation flags used when compiling for shared libraries, typically something like "-fPIC". @@ -72,7 +95,8 @@ In each table entry, the following keys are significant: (NOTE: this is here for future use, it's not implemented yet) arflags => Flags to be used with the library archive - command. + command. On Unix, this includes the + command letter, 'r' by default. ranlib => The library archive indexing command, the default is 'ranlib' it it exists. @@ -189,8 +213,14 @@ In each table entry, the following keys are significant: export vars as accessor functions. - apps_extra_src => Extra source to build apps/openssl, as - needed by the target. + apps_aux_src => Extra source to build apps/openssl and other + apps, as needed by the target and that can be + collected in a library. + apps_init_src => Init source to build apps/openssl and other + apps, as needed by the target. This code + cannot be placed in a library, as the rest + of the code isn't expected to link to it + explicitely. cpuid_asm_src => assembler implementation of cpuid code as well as OPENSSL_cleanse(). Default to mem_clr.c @@ -377,14 +407,16 @@ source as well. However, the files given through SOURCE are expected to be located in the source tree while files given through DEPEND are expected to be located in the build tree) -For some libraries, we maintain files with public symbols and their -slot in a transfer vector (important on some platforms). It can be -declared like this: +It's also possible to depend on static libraries explicitly: - ORDINALS[libcrypto]=crypto + DEPEND[foo]=libsomething.a + DEPEND[libbar]=libsomethingelse.a -The value is not the name of the file in question, but rather the -argument to util/mkdef.pl that indicates which file to use. +This should be rarely used, and care should be taken to make sure it's +only used when supported. For example, native Windows build doesn't +support build static libraries and DLLs at the same time, so using +static libraries on Windows can only be done when configured +'no-shared'. One some platforms, shared libraries come with a name that's different from their static counterpart. That's declared as follows: @@ -420,8 +452,8 @@ others, that's done as follows: GENERATE[bar.s]=asm/bar.S The value of each GENERATE line is a command line or part of it. -Configure places no rules on the command line, except the the first -item muct be the generator file. It is, however, entirely up to the +Configure places no rules on the command line, except that the first +item must be the generator file. It is, however, entirely up to the build file template to define exactly how those command lines should be handled, how the output is captured and so on. @@ -623,8 +655,7 @@ They are all expected to return a string with the lines they produce. libobj2shlib(shlib => "PATH/TO/shlibfile", lib => "PATH/TO/libfile", objs => [ "PATH/TO/objectfile", ... ], - deps => [ "PATH/TO/otherlibfile", ... ], - ordinals => [ "word", "/PATH/TO/ordfile" ]); + deps => [ "PATH/TO/otherlibfile", ... ]); 'lib' has the intended library file name *without* extension, libobj2shlib is expected to add that. @@ -633,11 +664,7 @@ They are all expected to return a string with the lines they produce. libraries (also *without* extension) this library needs to be linked with. 'objs' has the list of object files (also *without* extension) to build - this library. 'ordinals' MAY be present, and when - it is, its value is an array where the word is - "crypto" or "ssl" and the file is one of the ordinal - files util/libeay.num or util/ssleay.num in the - source directory. + this library. This function has a choice; it can use the corresponding static library as input to make the diff --git a/Configurations/README.design b/Configurations/README.design index bea9790a..cae08fc2 100644 --- a/Configurations/README.design +++ b/Configurations/README.design @@ -41,10 +41,9 @@ end products. There are variants for them with '_NO_INST' as suffix (PROGRAM_NO_INST etc) to specify end products that shouldn't get installed. -The variables SOURCE, DEPEND, INCLUDE and ORDINALS are indexed by a -produced file, and their values are the source used to produce that -particular produced file, extra dependencies, include directories -needed, and ordinal files (explained further below. +The variables SOURCE, DEPEND and INCLUDE are indexed by a produced +file, and their values are the source used to produce that particular +produced file, extra dependencies, and include directories needed. All their values in all the build.info throughout the source tree are collected together and form a set of programs, libraries, engines and @@ -57,18 +56,15 @@ dependencies. # build.info LIBS=libcrypto libssl - ORDINALS[libcrypto]=crypto - ORDINALS[libssl]=ssl INCLUDE[libcrypto]=include INCLUDE[libssl]=include DEPEND[libssl]=libcrypto This is the top directory build.info file, and it tells us that two -libraries are to be built, there are some ordinals to be used to -declare what symbols in those libraries are seen as public, the -include directory 'include/' shall be used throughout when building -anything that will end up in each library, and that the library -'libssl' depend on the library 'libcrypto' to function properly. +libraries are to be built, the include directory 'include/' shall be +used throughout when building anything that will end up in each +library, and that the library 'libssl' depend on the library +'libcrypto' to function properly. # apps/build.info PROGRAMS=openssl @@ -133,7 +129,7 @@ library 'libssl' is built from the source file 'ssl/tls.c'. ENGINES_NO_INST=ossltest SOURCE[ossltest]=e_ossltest.c - DEPEND[ossltest]=../libcrypto + DEPEND[ossltest]=../libcrypto.a INCLUDE[ossltest]=../include This is the build.info file in 'engines/', telling us that two engines @@ -142,18 +138,17 @@ dasync's source is 'engines/e_dasync.c' and ossltest's source is 'engines/e_ossltest.c' and that the include directory 'include/' may be used when building anything that will be part of these engines. Also, both engines depend on the library 'libcrypto' to function -properly. Finally, only dasync is being installed, as ossltest is -only for internal testing. +properly. ossltest is explicitly linked with the static variant of +the library 'libcrypto'. Finally, only dasync is being installed, as +ossltest is only for internal testing. When Configure digests these build.info files, the accumulated information comes down to this: LIBS=libcrypto libssl - ORDINALS[libcrypto]=crypto SOURCE[libcrypto]=crypto/aes.c crypto/evp.c crypto/cversion.c DEPEND[crypto/cversion.o]=crypto/buildinf.h INCLUDE[libcrypto]=include - ORDINALS[libssl]=ssl SOURCE[libssl]=ssl/tls.c INCLUDE[libssl]=include DEPEND[libssl]=libcrypto @@ -170,7 +165,7 @@ information comes down to this: ENGINES_NO_INST=engines/ossltest SOURCE[engines/ossltest]=engines/e_ossltest.c - DEPEND[engines/ossltest]=libcrypto + DEPEND[engines/ossltest]=libcrypto.a INCLUDE[engines/ossltest]=include GENERATE[crypto/buildinf.h]=util/mkbuildinf.pl "$(CC) $(CFLAGS)" "$(PLATFORM)" @@ -186,9 +181,9 @@ PROGRAMS may be used to declare programs only. ENGINES may be used to declare engines only. -The indexes for SOURCE and ORDINALS must only be end product files, -such as libraries, programs or engines. The values of SOURCE -variables must only be source files (possibly generated) +The indexes for SOURCE must only be end product files, such as +libraries, programs or engines. The values of SOURCE variables must +only be source files (possibly generated). INCLUDE and DEPEND shows a relationship between different files (usually produced files) or between files and directories, such as a @@ -235,12 +230,6 @@ indexes: libraries => a list of libraries. These are directly inferred from the LIBS variable in build.info files. - ordinals => a hash table containing 'file' => [ 'word', 'ordfile' ] - pairs. 'file' and 'word' are directly inferred from - the ORDINALS variables in build.info files, while the - file 'ofile' comes from internal knowledge in - Configure. - programs => a list of programs. These are directly inferred from the PROGRAMS variable in build.info files. @@ -281,10 +270,14 @@ section above would be digested into a %unified_info table: [ "crypto/buildinf.h", ], - "engines/ossltest" => + "engines/dasync" => [ "libcrypto", ], + "engines/ossltest" => + [ + "libcrypto.a", + ], "libssl" => [ "libcrypto", @@ -354,19 +347,6 @@ section above would be digested into a %unified_info table: "libcrypto", "libssl", ], - "ordinals" => - { - "libcrypto" => - [ - "crypto", - "util/libcrypto.num", - ], - "libssl" => - [ - "ssl", - "util/libssl.num", - ], - }, "programs" => [ "apps/openssl", @@ -396,6 +376,14 @@ section above would be digested into a %unified_info table: [ "crypto/evp.c", ], + "engines/e_dasync.o" => + [ + "engines/e_dasync.c", + ], + "engines/dasync" => + [ + "engines/e_dasync.o", + ], "engines/e_ossltest.o" => [ "engines/e_ossltest.c", @@ -517,8 +505,7 @@ etc. libobj2shlib(shlib => "PATH/TO/shlibfile", lib => "PATH/TO/libfile", objs => [ "PATH/TO/objectfile", ... ], - deps => [ "PATH/TO/otherlibfile", ... ], - ordinals => [ "word", "/PATH/TO/ordfile" ]); + deps => [ "PATH/TO/otherlibfile", ... ]); 'lib' has the intended library file name *without* extension, libobj2shlib is expected to add that. @@ -527,11 +514,7 @@ etc. libraries (also *without* extension) this library needs to be linked with. 'objs' has the list of object files (also *without* extension) to build - this library. 'ordinals' MAY be present, and when - it is, its value is an array where the word is - "crypto" or "ssl" and the file is one of the ordinal - files util/libcrypto.num or util/libssl.num in the - source directory. + this library. This function has a choice; it can use the corresponding static library as input to make the @@ -604,8 +587,7 @@ following calls: libobj2shlib(shlib => "libcrypto", lib => "libcrypto", objs => [ "crypto/aes", "crypto/evp", "crypto/cversion" ], - deps => [ ] - ordinals => [ "crypto", "util/libcrypto.num" ]); + deps => [ ]); obj2lib(lib => "libcrypto" objs => [ "crypto/aes", "crypto/evp", "crypto/cversion" ]); diff --git a/Configurations/common.tmpl b/Configurations/common.tmpl index 13ffe948..180621e7 100644 --- a/Configurations/common.tmpl +++ b/Configurations/common.tmpl @@ -9,15 +9,23 @@ # there are no duplicate dependencies and that they are in the # right order. This is especially used to sort the list of # libraries that a build depends on. + sub extensionlesslib { + my @result = map { $_ =~ /(\.a)?$/; $` } @_; + return @result if wantarray; + return $result[0]; + } sub resolvedepends { my $thing = shift; + my $extensionlessthing = extensionlesslib($thing); my @listsofar = @_; # to check if we're looping - my @list = @{$unified_info{depends}->{$thing}}; + my @list = @{$unified_info{depends}->{$thing} // + $unified_info{depends}->{$extensionlessthing}}; my @newlist = (); if (scalar @list) { foreach my $item (@list) { + my $extensionlessitem = extensionlesslib($item); # It's time to break off when the dependency list starts looping - next if grep { $_ eq $item } @listsofar; + next if grep { extensionlesslib($_) eq $extensionlessitem } @listsofar; push @newlist, $item, resolvedepends($item, @listsofar, $item); } } @@ -26,12 +34,34 @@ sub reducedepends { my @list = @_; my @newlist = (); + my %replace = (); while (@list) { my $item = shift @list; - push @newlist, $item - unless grep { $item eq $_ } @list; + my $extensionlessitem = extensionlesslib($item); + if (grep { $extensionlessitem eq extensionlesslib($_) } @list) { + if ($item ne $extensionlessitem) { + # If this instance of the library is explicitly static, we + # prefer that to any shared library name, since it must have + # been done on purpose. + $replace{$extensionlessitem} = $item; + } + } else { + push @newlist, $item; + } } - @newlist; + map { $replace{$_} // $_; } @newlist; + } + + # is_installed checks if a given file will be installed (i.e. they are + # not defined _NO_INST in build.info) + sub is_installed { + my $product = shift; + if (grep { $product eq $_ } + map { (@{$unified_info{install}->{$_}}) } + keys %{$unified_info{install}}) { + return 1; + } + return 0; } # dogenerate is responsible for producing all the recipes that build @@ -66,11 +96,11 @@ sub doobj { my $obj = shift; return "" if $cache{$obj}; - (my $obj_no_o = $obj) =~ s|\.o$||; my $bin = shift; my %opts = @_; if (@{$unified_info{sources}->{$obj}}) { - $OUT .= src2obj(obj => $obj_no_o, + $OUT .= src2obj(obj => $obj, + product => $bin, srcs => $unified_info{sources}->{$obj}, deps => $unified_info{depends}->{$obj}, incs => $unified_info{includes}->{$obj}, @@ -90,26 +120,28 @@ sub dolib { my $lib = shift; return "" if $cache{$lib}; - unless ($disabled{shared}) { - my %ordinals = - $unified_info{ordinals}->{$lib} - ? (ordinals => $unified_info{ordinals}->{$lib}) : (); + unless ($disabled{shared} || $lib =~ /\.a$/) { $OUT .= libobj2shlib(shlib => $unified_info{sharednames}->{$lib}, lib => $lib, - objs => [ map { (my $x = $_) =~ s|\.o$||; $x } - (@{$unified_info{sources}->{$lib}}, - @{$unified_info{shared_sources}->{$lib}}) ], + objs => [ @{$unified_info{shared_sources}->{$lib}}, + @{$unified_info{sources}->{$lib}} ], deps => [ reducedepends(resolvedepends($lib)) ], - %ordinals); - foreach (@{$unified_info{shared_sources}->{$lib}}) { - doobj($_, $lib, intent => "lib"); + installed => is_installed($lib)); + foreach ((@{$unified_info{shared_sources}->{$lib}}, + @{$unified_info{sources}->{$lib}})) { + # If this is somehow a compiled object, take care of it that way + # Otherwise, it might simply be generated + if (defined $unified_info{sources}->{$_}) { + doobj($_, $lib, intent => "lib", installed => is_installed($lib)); + } else { + dogenerate($_, undef, undef, intent => "lib"); + } } } $OUT .= obj2lib(lib => $lib, - objs => [ map { (my $x = $_) =~ s|\.o$||; $x } - @{$unified_info{sources}->{$lib}} ]); + objs => [ @{$unified_info{sources}->{$lib}} ]); foreach (@{$unified_info{sources}->{$lib}}) { - doobj($_, $lib, intent => "lib"); + doobj($_, $lib, intent => "lib", installed => is_installed($lib)); } $cache{$lib} = 1; } @@ -121,13 +153,13 @@ my $lib = shift; return "" if $cache{$lib}; $OUT .= obj2dso(lib => $lib, - objs => [ map { (my $x = $_) =~ s|\.o$||; $x } - (@{$unified_info{sources}->{$lib}}, - @{$unified_info{shared_sources}->{$lib}}) ], - deps => [ resolvedepends($lib) ]); + objs => [ @{$unified_info{sources}->{$lib}}, + @{$unified_info{shared_sources}->{$lib}} ], + deps => [ resolvedepends($lib) ], + installed => is_installed($lib)); foreach ((@{$unified_info{sources}->{$lib}}, @{$unified_info{shared_sources}->{$lib}})) { - doobj($_, $lib, intent => "dso"); + doobj($_, $lib, intent => "dso", installed => is_installed($lib)); } $cache{$lib} = 1; } @@ -139,11 +171,11 @@ return "" if $cache{$bin}; my $deps = [ reducedepends(resolvedepends($bin)) ]; $OUT .= obj2bin(bin => $bin, - objs => [ map { (my $x = $_) =~ s|\.o$||; $x } - @{$unified_info{sources}->{$bin}} ], - deps => $deps); + objs => [ @{$unified_info{sources}->{$bin}} ], + deps => $deps, + installed => is_installed($bin)); foreach (@{$unified_info{sources}->{$bin}}) { - doobj($_, $bin, intent => "bin"); + doobj($_, $bin, intent => "bin", installed => is_installed($bin)); } $cache{$bin} = 1; } @@ -154,7 +186,8 @@ my $script = shift; return "" if $cache{$script}; $OUT .= in2script(script => $script, - sources => $unified_info{sources}->{$script}); + sources => $unified_info{sources}->{$script}, + installed => is_installed($script)); $cache{$script} = 1; } diff --git a/Configurations/descrip.mms.tmpl b/Configurations/descrip.mms.tmpl index 7e3356f1..2364644b 100644 --- a/Configurations/descrip.mms.tmpl +++ b/Configurations/descrip.mms.tmpl @@ -9,7 +9,7 @@ our $osslprefix = 'OSSL$'; (our $osslprefix_q = $osslprefix) =~ s/\$/\\\$/; - our $sover = sprintf "%02d%02d", $config{shlib_major}, $config{shlib_minor}; + our $sover_dirname = sprintf "%02d%02d", split(/\./, $config{shlib_version_number}); our $osslver = sprintf "%02d%02d", split(/\./, $config{version}); our $sourcedir = $config{sourcedir}; @@ -42,9 +42,19 @@ # Because we need to make two computations of these data, # we store them in arrays for reuse - our @shlibs = map { $unified_info{sharednames}->{$_} || () } @{$unified_info{libraries}}; - our @install_shlibs = map { $unified_info{sharednames}->{$_} || () } @{$unified_info{install}->{libraries}}; - our @generated = ( ( map { (my $x = $_) =~ s|\.S$|\.s|; $x } + our @libs = + map { (my $x = $_) =~ s/\.a$//; $x } + @{$unified_info{libraries}}; + our @shlibs = + map { $unified_info{sharednames}->{$_} || () } + grep(!/\.a$/, @{$unified_info{libraries}}); + our @install_libs = + map { (my $x = $_) =~ s/\.a$//; $x } + @{$unified_info{install}->{libraries}}; + our @install_shlibs = + map { $unified_info{sharednames}->{$_} || () } + grep(!/\.a$/, @{$unified_info{install}->{libraries}}); + our @generated = ( ( map { (my $x = $_) =~ s|\.[sS]$|\.asm|; $x } grep { defined $unified_info{generate}->{$_} } map { @{$unified_info{sources}->{$_}} } grep { /\.o$/ } keys %{$unified_info{sources}} ), @@ -63,17 +73,9 @@ } my $sd1 = sourcedir("ssl","record"); my $sd2 = sourcedir("ssl","statem"); - $unified_info{before}->{"[.test]heartbeat_test.OBJ"} - = $unified_info{before}->{"[.test]ssltest_old.OBJ"} - = qq(record_include = F\$PARSE("$sd1","A.;",,,"SYNTAX_ONLY") - "A.;" - define record 'record_include' - statem_include = F\$PARSE("$sd2","A.;",,,"SYNTAX_ONLY") - "A.;" - define statem 'statem_include'); - $unified_info{after}->{"[.test]heartbeat_test.OBJ"} - = $unified_info{after}->{"[.test]ssltest.OBJ"} - = qq(deassign statem - deassign record); - foreach (grep /^\[\.ssl\.(?:record|statem)\].*\.o$/, keys %{$unified_info{sources}}) { + my @ssl_locl_users = grep(/^\[\.(?:ssl\.(?:record|statem)|test)\].*\.o$/, + keys %{$unified_info{sources}}); + foreach (@ssl_locl_users) { (my $x = $_) =~ s|\.o$|.OBJ|; $unified_info{before}->{$x} = qq(record_include = F\$PARSE("$sd1","A.;",,,"SYNTAX_ONLY") - "A.;" @@ -121,7 +123,7 @@ SHLIB_EXT=.EXE OBJ_EXT=.OBJ DEP_EXT=.D -LIBS={- join(", ", map { "-\n\t".$_.".OLB" } @{$unified_info{libraries}}) -} +LIBS={- join(", ", map { "-\n\t".$_.".OLB" } @libs) -} SHLIBS={- join(", ", map { "-\n\t".$_.".EXE" } @shlibs) -} ENGINES={- join(", ", map { "-\n\t".$_.".EXE" } @{$unified_info{engines}}) -} PROGRAMS={- join(", ", map { "-\n\t".$_.".EXE" } @{$unified_info{programs}}) -} @@ -135,7 +137,7 @@ DEPS={- our @deps = map { (my $x = $_) =~ s|\.o$|\$(DEP_EXT)|; $x; } GENERATED_MANDATORY={- join(", ", map { "-\n\t".$_ } @{$unified_info{depends}->{""}} ) -} GENERATED={- join(", ", map { "-\n\t".$_ } @generated) -} -INSTALL_LIBS={- join(", ", map { "-\n\t".$_.".OLB" } @{$unified_info{install}->{libraries}}) -} +INSTALL_LIBS={- join(", ", map { "-\n\t".$_.".OLB" } @install_libs) -} INSTALL_SHLIBS={- join(", ", map { "-\n\t".$_.".EXE" } @install_shlibs) -} INSTALL_ENGINES={- join(", ", map { "-\n\t".$_.".EXE" } @{$unified_info{install}->{engines}}) -} INSTALL_PROGRAMS={- join(", ", map { "-\n\t".$_.".EXE" } @{$unified_info{install}->{programs}}) -} @@ -167,27 +169,52 @@ OPENSSLDIR={- catdir($config{openssldir}) or # The same, but for C OPENSSLDIR_C={- $osslprefix -}DATAROOT:[000000] # Where installed engines reside, for C -ENGINESDIR_C={- $osslprefix -}ENGINES{- $sover.$target{pointer_size} -}: +ENGINESDIR_C={- $osslprefix -}ENGINES{- $sover_dirname.$target{pointer_size} -}: -CC= {- $target{cc} -} -CFLAGS= /DEFINE=({- join(",", @{$target{defines}}, @{$config{defines}},"OPENSSLDIR=\"\"\"\$(OPENSSLDIR_C)\"\"\"","ENGINESDIR=\"\"\"\$(ENGINESDIR_C)\"\"\"") -}) {- $target{cflags} -} {- $config{cflags} -} -CFLAGS_Q=$(CFLAGS) -DEPFLAG= /DEFINE=({- join(",", @{$config{depdefines}}) -}) -LDFLAGS= {- $target{lflags} -} -EX_LIBS= {- $target{ex_libs} ? ",".$target{ex_libs} : "" -}{- $config{ex_libs} ? ",".$config{ex_libs} : "" -} -LIB_CFLAGS={- $target{lib_cflags} || "" -} -DSO_CFLAGS={- $target{dso_cflags} || "" -} -BIN_CFLAGS={- $target{bin_cflags} || "" -} +CC= {- $config{cc} -} +CPP= {- $config{cpp} -} +DEFINES={- our $defines = join(",", + '__dummy', # To make comma processing easier + @{$config{defines}}) -} +INCLUDES={- our $includes = join(',', @{$config{includes}}) -} +CPPFLAGS='qual_includes'{- our $cppflags = join('', @{$config{cppflags}}) -} +CPPFLAGS_Q={- (my $x = $cppflags) =~ s|"|""|g; + (my $d = $defines) =~ s|"|""|g; + $x .= "/INCLUDE=($includes)" if $includes; + $x .= "/DEFINE=($d)"; + $x; -} +CFLAGS={- join('', @{$config{cflags}}) -} +LDFLAGS= {- join('', @{$config{lflags}}) -} +EX_LIBS= {- join('', map { ','.$_ } @{$config{ex_libs}}) -} + +LIB_DEFINES=$(DEFINES){- join("", (map { ",$_" } + @{$target{shared_defines}}, + 'OPENSSLDIR="""$(OPENSSLDIR_C)"""', + 'ENGINESDIR="""$(ENGINESDIR_C)"""')) -} +LIB_CPPFLAGS=$(CPPFLAGS)/DEFINE=($(LIB_DEFINES)) +LIB_CFLAGS=$(CFLAGS){- $target{lib_cflags} // "" -} +DSO_DEFINES=$(DEFINES){- join("", (map { ",$_" } @{$target{dso_defines}})) -} +DSO_CPPFLAGS=$(CPPFLAGS)/DEFINE=($(DSO_DEFINES)) +DSO_CFLAGS=$(CFLAGS){- $target{dso_cflags} // "" -} +BIN_DEFINES=$(DEFINES){- join("", (map { ",$_" } @{$target{bin_defines}})) -} +BIN_CPPFLAGS=$(CPPFLAGS)/DEFINE=($(BIN_DEFINES)) +BIN_CFLAGS=$(CFLAGS){- $target{bin_cflags} // "" -} +NO_INST_LIB_CFLAGS=$(CFLAGS){- $target{no_inst_lib_cflags} + // $target{lib_cflags} + // "" -} +NO_INST_DSO_CFLAGS=$(CFLAGS){- $target{no_inst_dso_cflags} + // $target{dso_cflags} + // "" -} +NO_INST_BIN_CFLAGS=$(CFLAGS){- $target{no_inst_bin_cflags} + // $target{bin_cflags} + // "" -} PERL={- $config{perl} -} -# 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={- $target{as} -} -ASFLAG={- $target{asflags} -} +AS={- $config{as} -} +ASFLAGS={- join(' ', @{$config{asflags}}) -} +ASOUTFLAG={- $target{asoutflag} -}$(OSSL_EMPTY) +PERLASM_SCHEME={- $target{perlasm_scheme} -} # .FIRST and .LAST are special targets with MMS and MMK. # The defines in there are for C. includes that look like @@ -238,10 +265,10 @@ NODEBUG=@ $(NODEBUG) ! Set up logical names for the libraries, so LINK and $(NODEBUG) ! running programs can use them. $(NODEBUG) ! - $(NODEBUG) {- join("\n\t\$(NODEBUG) ", map { "DEFINE ".uc($_)." 'F\$ENV(\"DEFAULT\")'".uc($_)."\$(SHLIB_EXT)" } map { $unified_info{sharednames}->{$_} || () } @{$unified_info{libraries}}) || "!" -} + $(NODEBUG) {- join("\n\t\$(NODEBUG) ", map { "DEFINE ".uc($_)." 'F\$ENV(\"DEFAULT\")'".uc($_)."\$(SHLIB_EXT)" } @shlibs) || "!" -} .LAST : - $(NODEBUG) {- join("\n\t\$(NODEBUG) ", map { "DEASSIGN ".uc($_) } map { $unified_info{sharednames}->{$_} || () } @{$unified_info{libraries}}) || "!" -} + $(NODEBUG) {- join("\n\t\$(NODEBUG) ", map { "DEASSIGN ".uc($_) } @shlibs) || "!" -} $(NODEBUG) DEASSIGN ossl_dataroot $(NODEBUG) DEASSIGN ossl_installroot $(NODEBUG) DEASSIGN internal @@ -331,8 +358,8 @@ uninstall : uninstall_docs uninstall_sw # Because VMS wants the generation number (or *) to delete files, we can't # use $(LIBS), $(PROGRAMS), $(GENERATED) and $(ENGINES)directly. libclean : - {- join("\n\t", map { "- DELETE $_.OLB;*" } @{$unified_info{libraries}}) || "@ !" -} - {- join("\n\t", map { "- DELETE $_.EXE;*,$_.MAP;*,$_.OPT;*" } @shlibs) || "@ !" -} + {- join("\n\t", map { "- DELETE $_.OLB;*" } @libs) || "@ !" -} + {- join("\n\t", map { "- DELETE $_.EXE;*,$_.MAP;*" } @shlibs) || "@ !" -} clean : libclean {- join("\n\t", map { "- DELETE $_.EXE;*,$_.OPT;*" } @{$unified_info{programs}}) || "@ !" -} @@ -395,6 +422,12 @@ install_ssldirs : check_INSTALLTOP IF F$SEARCH("OSSL_DATAROOT:[000000]openssl.cnf") .EQS. "" THEN - COPY/PROT=W:R {- sourcefile("apps", "openssl-vms.cnf") -} - ossl_dataroot:[000000]openssl.cnf + @ ! Install CTLOG configuration file + COPY/PROT=W:R {- sourcefile("apps", "ct_log_list.cnf") -} - + ossl_dataroot:[000000]ct_log_list.cnf-dist + IF F$SEARCH("OSSL_DATAROOT:[000000]ct_log_list.cnf") .EQS. "" THEN - + COPY/PROT=W:R {- sourcefile("apps", "ct_log_list.cnf") -} - + ossl_dataroot:[000000]ct_log_list.cnf install_shared : check_INSTALLTOP @ {- output_off() if $disabled{shared}; "" -} ! @@ -415,7 +448,7 @@ _install_dev_ns : check_INSTALLTOP - CREATE/DIR ossl_installroot:[LIB.'arch'] {- join("\n ", map { "COPY/PROT=W:R $_.OLB ossl_installroot:[LIB.'arch']" } - @{$unified_info{install}->{libraries}}) -} + @install_libs) -} install_dev : install_shared _install_dev_ns @@ -433,9 +466,9 @@ install_runtime : install_shared _install_runtime_ns install_engines : check_INSTALLTOP @ {- output_off() unless scalar @{$unified_info{engines}}; "" -} ! @ WRITE SYS$OUTPUT "*** Installing engines" - - CREATE/DIR ossl_installroot:[ENGINES{- $sover.$target{pointer_size} -}.'arch'] + - CREATE/DIR ossl_installroot:[ENGINES{- $sover_dirname.$target{pointer_size} -}.'arch'] {- join("\n ", - map { "COPY/PROT=W:RE $_.EXE ossl_installroot:[ENGINES$sover$target{pointer_size}.'arch']" } + map { "COPY/PROT=W:RE $_.EXE ossl_installroot:[ENGINES$sover_dirname$target{pointer_size}.'arch']" } @{$unified_info{install}->{engines}}) -} @ {- output_on() unless scalar @{$unified_info{engines}}; "" -} ! @@ -488,6 +521,7 @@ vmsconfig.pm : configdata.pm WRITE CONFIG "our %config = (" WRITE CONFIG " target => '","{- $config{target} -}","'," WRITE CONFIG " version => '","{- $config{version} -}","'," + WRITE CONFIG " shlib_version_number => '","{- $config{shlib_version_number} -}","'," WRITE CONFIG " shlib_major => '","{- $config{shlib_major} -}","'," WRITE CONFIG " shlib_minor => '","{- $config{shlib_minor} -}","'," WRITE CONFIG " no_shared => '","{- $disabled{shared} -}","'," @@ -524,8 +558,7 @@ debug_logicals : # Building targets ################################################### configdata.pm : $(SRCDIR)Configure $(SRCDIR)config.com {- join(" ", @{$config{build_file_templates}}, @{$config{build_infos}}, @{$config{conf_files}}) -} - @ WRITE SYS$OUTPUT "Reconfiguring..." - perl $(SRCDIR)Configure reconf + perl configdata.pm -r @ WRITE SYS$OUTPUT "*************************************************" @ WRITE SYS$OUTPUT "*** ***" @ WRITE SYS$OUTPUT "*** Please run the same mms command again ***" @@ -533,41 +566,148 @@ configdata.pm : $(SRCDIR)Configure $(SRCDIR)config.com {- join(" ", @{$config{bu @ WRITE SYS$OUTPUT "*************************************************" @ PIPE ( EXIT %X10000000 ) +reconfigure reconf : + perl configdata.pm -r + {- use File::Basename; use File::Spec::Functions qw/abs2rel rel2abs catfile catdir/; + # Helper function to figure out dependencies on libraries + # It takes a list of library names and outputs a list of dependencies + sub compute_lib_depends { + if ($disabled{shared}) { + return map { $_ =~ /\.a$/ ? $`.".OLB" : $_.".OLB" } @_; + } + return map { $_ =~ /\.a$/ + ? $`.".OLB" + : $unified_info{sharednames}->{$_}.".EXE" } @_; + } + + # Helper function to deal with inclusion directory specs. + # We have to deal with two things: + # 1. comma separation and no possibility of trailing comma + # 2. no inclusion directories given at all + # 3. long compiler command lines + # To resolve 1, we need to iterate through the sources of inclusion + # directories, and only add a comma when needed. + # To resolve 2, we need to have a variable that will hold the whole + # inclusion qualifier, or be the empty string if there are no inclusion + # directories. That's the symbol 'qual_includes' that's used in CPPFLAGS + # To resolve 3, we creata a logical name TMP_INCLUDES: to hold the list + # of inclusion directories. + # + # This function returns a list of two lists, one being the collection of + # commands to execute before the compiler is called, and the other being + # the collection of commands to execute after. It takes as arguments the + # collection of strings to include as directory specs. + sub includes { + my @stuff = ( @_ ); + my @before = ( + 'qual_includes :=', + ); + my @after = ( + 'DELETE/SYMBOL/LOCAL qual_includes', + ); + + if (scalar @stuff > 0) { + push @before, 'tmp_includes := '.shift(@stuff); + while (@stuff) { + push @before, 'tmp_add := '.shift(@stuff); + push @before, 'IF tmp_includes .NES. "" .AND. tmp_add .NES. "" THEN tmp_includes = tmp_includes + ","'; + push @before, 'tmp_includes = tmp_includes + tmp_add'; + } + push @before, "IF tmp_includes .NES. \"\" THEN DEFINE tmp_includes 'tmp_includes'"; + push @before, 'IF tmp_includes .NES. "" THEN qual_includes := /INCLUDE=(tmp_includes:)'; + push @before, 'DELETE/SYMBOL/LOCAL tmp_includes'; + push @before, 'DELETE/SYMBOL/LOCAL tmp_add'; + push @after, 'DEASSIGN tmp_includes:' + } + return ([ @before ], [ @after ]); + } + sub generatesrc { my %args = @_; + (my $target = $args{src}) =~ s/\.[sS]$/.asm/; my $generator = join(" ", @{$args{generator}}); my $generator_incs = join("", map { ' "-I'.$_.'"' } @{$args{generator_incs}}); my $deps = join(", -\n\t\t", @{$args{generator_deps}}, @{$args{deps}}); - if ($args{src} !~ /\.[sS]$/) { + if ($target !~ /\.asm$/) { if ($args{generator}->[0] =~ m|^.*\.in$|) { my $dofile = abs2rel(rel2abs(catfile($config{sourcedir}, "util", "dofile.pl")), rel2abs($config{builddir})); return <<"EOF"; -$args{src} : $args{generator}->[0] $deps +$target : $args{generator}->[0] $deps \$(PERL) "-I\$(BLDDIR)" "-Mconfigdata" $dofile \\ - "-o$target{build_file}" $generator > \$@ + "-o$target{build_file}" $generator > \$\@ EOF } else { return <<"EOF"; -$args{src} : $args{generator}->[0] $deps - \$(PERL)$generator_incs $generator > \$@ +$target : $args{generator}->[0] $deps + \$(PERL)$generator_incs $generator > \$\@ EOF } } else { - die "No method to generate assembler source present.\n"; + if ($args{generator}->[0] =~ /\.pl$/) { + $generator = '$(PERL)'.$generator_incs.' '.$generator; + } elsif ($args{generator}->[0] =~ /\.S$/) { + $generator = undef; + } else { + die "Generator type for $src unknown: $generator\n"; + } + + my $cppflags = { + lib => '$(LIB_CFLAGS) $(LIB_CPPFLAGS)', + dso => '$(DSO_CFLAGS) $(DSO_CPPFLAGS)', + bin => '$(BIN_CFLAGS) $(BIN_CPPFLAGS)' + } -> {$args{intent}}; + my @incs_cmds = includes({ lib => '$(LIB_INCLUDES)', + dso => '$(DSO_INCLUDES)', + bin => '$(BIN_INCLUDES)' } -> {$args{intent}}, + '$(INCLUDES)', + @{$args{incs}}); + my $incs_on = join("\n\t\@ ", @{$incs_cmds[0]}) || '!'; + my $incs_off = join("\n\t\@ ", @{$incs_cmds[1]}) || '!'; + if (defined($generator)) { + # If the target is named foo.S in build.info, we want to + # end up generating foo.s in two steps. + if ($args{src} =~ /\.S$/) { + return <<"EOF"; +$target : $args{generator}->[0] $deps + $generator \$\@-S + \@ $incs_on + PIPE \$(CPP) $cppflags \$\@-S | - + \$(PERL) -ne "/^#(\\s*line)?\\s*[0-9]+\\s+""/ or print" > \$\@-i + \@ $incs_off + RENAME \$\@-i \$\@ + DELETE \$\@-S +EOF + } + # Otherwise.... + return <<"EOF"; +$target : $args{generator}->[0] $deps + $generator \$\@ +EOF + } + return <<"EOF"; +$target : $args{generator}->[0] $deps + \@ $incs_on + SHOW SYMBOL qual_includes + PIPE \$(CPP) $cppflags $args{generator}->[0] | - + \$(PERL) "-ne" "/^#(\\s*line)?\\s*[0-9]+\\s+""/ or print" > \$\@ + \@ $incs_off +EOF } } sub src2obj { my %args = @_; - my $obj = $args{obj}; - my $deps = join(", -\n\t\t", @{$args{srcs}}, @{$args{deps}}); + my @srcs = map { (my $x = $_) =~ s/\.s$/.asm/; $x + } ( @{$args{srcs}} ); + (my $obj = $args{obj}) =~ s|\.o$||; + my $deps = join(", -\n\t\t", @srcs, @{$args{deps}}); # Because VMS C isn't very good at combining a /INCLUDE path with # #includes having a relative directory (like '#include "../foo.h"), @@ -580,50 +720,64 @@ EOF my $objd = abs2rel(rel2abs(dirname($obj)), rel2abs($forward)); my $objn = basename($obj); my $srcs = - join(", ", - map { abs2rel(rel2abs($_), rel2abs($forward)) } @{$args{srcs}}); - my $ecflags = { lib => '$(LIB_CFLAGS)', - dso => '$(DSO_CFLAGS)', - bin => '$(BIN_CFLAGS)' } -> {$args{intent}}; - my $incs_on = "\@ !"; - my $incs_off = "\@ !"; - my $incs = ""; - my @incs = (); - push @incs, @{$args{incs}} if @{$args{incs}}; - unless ($disabled{zlib}) { - # GNV$ZLIB_INCLUDE is the standard logical name for later zlib - # incarnations. - push @incs, ($withargs{zlib_include} || 'GNV$ZLIB_INCLUDE:'); - } - if (@incs) { - $incs_on = - "DEFINE tmp_includes " - .join(",-\n\t\t\t", map { - file_name_is_absolute($_) - ? $_ : catdir($backward,$_) - } @incs); - $incs_off = "DEASSIGN tmp_includes"; - $incs = " /INCLUDE=(tmp_includes:)"; - } + join(", ", map { abs2rel(rel2abs($_), rel2abs($forward)) } @srcs); my $before = $unified_info{before}->{$obj.".OBJ"} || "\@ !"; my $after = $unified_info{after}->{$obj.".OBJ"} || "\@ !"; - my $depbuild = $disabled{makedepend} ? "" - : " /MMS=(FILE=${objd}${objn}.tmp-D,TARGET=$obj.OBJ)"; - return <<"EOF"; + if ($srcs[0] =~ /\.asm$/) { + return <<"EOF"; $obj.OBJ : $deps ${before} SET DEFAULT $forward - $incs_on - \$(CC) \$(CFLAGS)${ecflags}${incs}${depbuild} /OBJECT=${objd}${objn}.OBJ /REPOSITORY=$backward $srcs - $incs_off + \$(AS) \$(ASFLAGS) \$(ASOUTFLAG)${objd}${objn}.OBJ $srcs + SET DEFAULT $backward +EOF + } + + my $cflags; + if ($args{installed}) { + $cflags = { lib => '$(LIB_CFLAGS)', + dso => '$(DSO_CFLAGS)', + bin => '$(BIN_CFLAGS)' } -> {$args{intent}}; + } else { + $cflags = { lib => '$(NO_INST_LIB_CFLAGS)', + dso => '$(NO_INST_DSO_CFLAGS)', + bin => '$(NO_INST_BIN_CFLAGS)' } -> {$args{intent}}; + } + $cflags .= { lib => '$(LIB_CPPFLAGS)', + dso => '$(DSO_CPPFLAGS)', + bin => '$(BIN_CPPFLAGS)' } -> {$args{intent}}; + + my @incs_cmds = includes({ lib => '$(LIB_INCLUDES)', + dso => '$(DSO_INCLUDES)', + bin => '$(BIN_INCLUDES)' } -> {$args{intent}}, + '$(INCLUDES)', + map { + file_name_is_absolute($_) + ? $_ : catdir($backward,$_) + } @{$args{incs}}); + my $incs_on = join("\n\t\@ ", @{$incs_cmds[0]}) || '!'; + my $incs_off = join("\n\t\@ ", @{$incs_cmds[1]}) || '!'; + my $depbuild = $disabled{makedepend} ? "" + : " /MMS=(FILE=${objd}${objn}.tmp-D,TARGET=$obj.OBJ)"; + + return <<"EOF" +$obj.OBJ : $deps + ${before} + SET DEFAULT $forward + \@ $incs_on + \$(CC) ${cflags}${depbuild} /OBJECT=${objd}${objn}.OBJ /REPOSITORY=$backward $srcs + \@ $incs_off SET DEFAULT $backward ${after} + - PURGE $obj.OBJ +EOF + . ($disabled{makedepend} ? "" : <<"EOF" \@ PIPE ( \$(PERL) -e "use File::Compare qw/compare_text/; my \$x = compare_text(""$obj.D"",""$obj.tmp-D""); exit(0x10000000 + (\$x == 0));" || - RENAME $obj.tmp-D $obj.d ) \@ IF F\$SEARCH("$obj.tmp-D") .NES. "" THEN DELETE $obj.tmp-D;* - - PURGE $obj.OBJ EOF + ); } sub libobj2shlib { my %args = @_; @@ -631,19 +785,14 @@ EOF my $shlib = $args{shlib}; my $libd = dirname($lib); my $libn = basename($lib); - (my $mkdef_key = $libn) =~ s/^${osslprefix_q}lib([^0-9]*)\d*/$1/i; - my @deps = map { - $disabled{shared} ? $_.".OLB" - : $unified_info{sharednames}->{$_}.".EXE"; } @{$args{deps}}; - my $deps = join(", -\n\t\t", @deps); + my @objs = map { (my $x = $_) =~ s|\.o$|.OBJ|; $x } + grep { $_ =~ m|\.o$| } + @{$args{objs}}; + my @defs = grep { $_ =~ /\.opt$/ } @{$args{objs}}; + my @deps = compute_lib_depends(@{$args{deps}}); + die "More than one symbol vector" if scalar @defs > 1; + my $deps = join(", -\n\t\t", @defs, @deps); my $shlib_target = $disabled{shared} ? "" : $target{shared_target}; - my $ordinalsfile = defined($args{ordinals}) ? $args{ordinals}->[1] : ""; - my $engine_opt = abs2rel(rel2abs(catfile($config{sourcedir}, - "VMS", "engine.opt")), - rel2abs($config{builddir})); - my $mkdef_pl = abs2rel(rel2abs(catfile($config{sourcedir}, - "util", "mkdef.pl")), - rel2abs($config{builddir})); my $translatesyms_pl = abs2rel(rel2abs(catfile($config{sourcedir}, "VMS", "translatesyms.pl")), rel2abs($config{builddir})); @@ -651,27 +800,32 @@ EOF # previous line's file spec as default, so if no directory spec # is present in the current line and the previous line has one that # doesn't apply, you're in for a surprise. - my $write_opt = + my $write_opt1 = + join(",-\"\n\t", map { my $x = $_ =~ /\[/ ? $_ : "[]".$_; + "WRITE OPT_FILE \"$x" } @objs). + "\""; + my $write_opt2 = join("\n\t", map { my $x = $_ =~ /\[/ ? $_ : "[]".$_; $x =~ s|(\.EXE)|$1/SHARE|; $x =~ s|(\.OLB)|$1/LIB|; "WRITE OPT_FILE \"$x\"" } @deps) || "\@ !"; - return <<"EOF"; -$shlib.EXE : $lib.OLB $deps $ordinalsfile - \$(PERL) $mkdef_pl "$mkdef_key" "VMS" > $shlib.SYMVEC-tmp - \$(PERL) $translatesyms_pl \$(BLDDIR)CXX\$DEMANGLER_DB. < $shlib.SYMVEC-tmp > $shlib.SYMVEC - DELETE $shlib.SYMVEC-tmp;* - OPEN/WRITE/SHARE=READ OPT_FILE $shlib.OPT - WRITE OPT_FILE "IDENTIFICATION=""V$config{version}""" - TYPE $shlib.SYMVEC /OUTPUT=OPT_FILE: - WRITE OPT_FILE "$lib.OLB/LIBRARY" - $write_opt + return <<"EOF" +$shlib.EXE : $lib.OLB $deps + \$(PERL) $translatesyms_pl \$(BLDDIR)CXX\$DEMANGLER_DB. < $defs[0] > $defs[0]-translated + OPEN/WRITE/SHARE=READ OPT_FILE $lib-components.OPT + $write_opt1 + $write_opt2 CLOSE OPT_FILE - LINK /MAP=$shlib.MAP /FULL/SHARE=$shlib.EXE $shlib.OPT/OPT \$(EX_LIBS) - DELETE $shlib.SYMVEC;* - PURGE $shlib.EXE,$shlib.OPT,$shlib.MAP + LINK \$(LDFLAGS)/SHARE=\$\@ $defs[0]-translated/OPT,- + $lib-components.OPT/OPT \$(EX_LIBS) + DELETE $defs[0]-translated;*,$lib-components.OPT;* + PURGE $shlib.EXE,$shlib.MAP EOF + . ($config{target} =~ m|alpha| ? "" : <<"EOF" + SET IMAGE/FLAGS=(NOCALL_DEBUG) \$\@ +EOF + ); } sub obj2dso { my %args = @_; @@ -679,10 +833,8 @@ EOF my $libd = dirname($lib); my $libn = basename($lib); (my $libn_nolib = $libn) =~ s/^lib//; - my @objs = map { "$_.OBJ" } @{$args{objs}}; - my @deps = map { - $disabled{shared} ? $_.".OLB" - : $unified_info{sharednames}->{$_}.".EXE"; } @{$args{deps}}; + my @objs = map { (my $x = $_) =~ s|\.o$|.OBJ|; $x } @{$args{objs}}; + my @deps = compute_lib_depends(@{$args{deps}}); my $deps = join(", -\n\t\t", @objs, @deps); my $shlib_target = $disabled{shared} ? "" : $target{shared_target}; my $engine_opt = abs2rel(rel2abs(catfile($config{sourcedir}, @@ -702,23 +854,28 @@ EOF $x =~ s|(\.OLB)|$1/LIB|; "WRITE OPT_FILE \"$x\"" } @deps) || "\@ !"; - return <<"EOF"; + return <<"EOF" $lib.EXE : $deps OPEN/WRITE/SHARE=READ OPT_FILE $lib.OPT TYPE $engine_opt /OUTPUT=OPT_FILE: $write_opt1 $write_opt2 CLOSE OPT_FILE - LINK /MAP=$lib.MAP /FULL/SHARE=$lib.EXE $lib.OPT/OPT \$(EX_LIBS) + LINK \$(LDFLAGS)/SHARE=\$\@ $lib.OPT/OPT \$(EX_LIBS) - PURGE $lib.EXE,$lib.OPT,$lib.MAP EOF + . ($config{target} =~ m|alpha| ? "" : <<"EOF" + SET IMAGE/FLAGS=(NOCALL_DEBUG) \$\@ +EOF + ); } sub obj2lib { my %args = @_; - my $lib = $args{lib}; - my $objs = join(", -\n\t\t", map { $_.".OBJ" } (@{$args{objs}})); - my $fill_lib = join("\n\t", (map { "LIBRARY/REPLACE $lib.OLB $_.OBJ" } - @{$args{objs}})); + (my $lib = $args{lib}) =~ s/\.a$//; + my @objs = map { (my $x = $_) =~ s|\.o$|.OBJ|; $x } @{$args{objs}}; + my $objs = join(", -\n\t\t", @objs); + my $fill_lib = join("\n\t", (map { "LIBRARY/REPLACE $lib.OLB $_" } + @objs)); return <<"EOF"; $lib.OLB : $objs LIBRARY/CREATE/OBJECT $lib.OLB @@ -731,34 +888,91 @@ EOF my $bin = $args{bin}; my $bind = dirname($bin); my $binn = basename($bin); - my @objs = map { "$_.OBJ" } @{$args{objs}}; - my @deps = map { - $disabled{shared} ? $_.".OLB" - : $unified_info{sharednames}->{$_}.".EXE"; } @{$args{deps}}; + my @objs = map { (my $x = $_) =~ s|\.o$|.OBJ|; $x } @{$args{objs}}; + my $objs = join(",", @objs); + my @deps = compute_lib_depends(@{$args{deps}}); my $deps = join(", -\n\t\t", @objs, @deps); + + my $olb_count = scalar grep(m|\.OLB$|, @deps); + my $analyse_objs = "@ !"; + if ($olb_count > 0) { + my $analyse_quals = + $config{target} =~ m|alpha| ? "/GSD" : "/SECTIONS=SYMTAB"; + $analyse_objs = "- pipe ANALYSE/OBJECT$analyse_quals $objs | SEARCH SYS\$INPUT \"\"\"main\"\"\" ; nomain = \$severity .NE. 1" + } # The "[]" hack is because in .OPT files, each line inherits the # previous line's file spec as default, so if no directory spec # is present in the current line and the previous line has one that # doesn't apply, you're in for a surprise. my $write_opt1 = join(",-\"\n\t", map { my $x = $_ =~ /\[/ ? $_ : "[]".$_; - "WRITE OPT_FILE \"$x" } @objs). + "\@ WRITE OPT_FILE \"$x" } @objs). "\""; my $write_opt2 = - join("\n\t", map { my $x = $_ =~ /\[/ ? $_ : "[]".$_; - $x =~ s|(\.EXE)|$1/SHARE|; - $x =~ s|(\.OLB)|$1/LIB|; - "WRITE OPT_FILE \"$x\"" } @deps) + join("\n\t", map { my @lines = (); + my $x = $_ =~ /\[/ ? $_ : "[]".$_; + if ($x =~ m|\.EXE$|) { + push @lines, "\@ WRITE OPT_FILE \"$x/SHARE\""; + } elsif ($x =~ m|\.OLB$|) { + (my $l = $x) =~ s/\W/_/g; + push @lines, + "\@ IF nomain THEN WRITE OPT_FILE \"$x/LIB\$(INCLUDE_MAIN_$l)\"", + "\@ IF .NOT. nomain THEN WRITE OPT_FILE \"$x/LIB\"" + } + @lines + } @deps) || "\@ !"; - return <<"EOF"; + # The linking commands looks a bit complex, but it's for good reason. + # When you link, say, foo.obj, bar.obj and libsomething.exe/share, and + # bar.obj happens to have a symbol that also exists in libsomething.exe, + # the linker will warn about it, loudly, and will then choose to pick + # the first copy encountered (the one in bar.obj in this example). + # On Unix and on Windows, the corresponding maneuvre goes through + # silently with the same effect. + # With some test programs, made for checking the internals of OpenSSL, + # we do this kind of linking deliberately, picking a few specific object + # files from within [.crypto] or [.ssl] so we can reach symbols that are + # otherwise unreachable (since the shareable images only exports the + # symbols listed in [.util]*.num), and then with the shared libraries + # themselves. So we need to silence the warning about multiply defined + # symbols, to mimic the way linking work on Unix and Windows, and so + # the build isn't interrupted (MMS stops when warnings are signaled, + # by default), and so someone building doesn't have to worry where it + # isn't necessary. If there are other warnings, however, we show them + # and let it break the build. + return <<"EOF" $bin.EXE : $deps - OPEN/WRITE/SHARE=READ OPT_FILE $bin.OPT + $analyse_objs + @ OPEN/WRITE/SHARE=READ OPT_FILE $bin.OPT $write_opt1 $write_opt2 - CLOSE OPT_FILE - LINK/EXEC=$bin.EXE \$(LDFLAGS) $bin.OPT/OPT \$(EX_LIBS) + @ CLOSE OPT_FILE + TYPE $bin.opt ! For debugging + - pipe SPAWN/WAIT/NOLOG/OUT=$bin.LINKLOG - + LINK \$(LDFLAGS)/EXEC=\$\@ $bin.OPT/OPT \$(EX_LIBS) ; - + link_status = \$status ; link_severity = link_status .AND. 7 + @ search_severity = 1 + -@ IF link_severity .EQ. 0 THEN - + pipe SEARCH $bin.LINKLOG "%","-"/MATCH=AND | - + SPAWN/WAIT/NOLOG/OUT=NLA0: - + SEARCH SYS\$INPUT: "-W-MULDEF,"/MATCH=NOR ; - + search_severity = \$severity + @ ! search_severity is 3 when the last search didn't find any matching + @ ! string: %SEARCH-I-NOMATCHES, no strings matched + @ ! If that was the result, we pretend linking got through without + @ ! fault or warning. + @ IF search_severity .EQ. 3 THEN link_severity = 1 + @ ! At this point, if link_severity shows that there was a fault + @ ! or warning, make sure to restore the linking status. + -@ IF .NOT. link_severity THEN TYPE $bin.LINKLOG + -@ DELETE $bin.LINKLOG;* + @ IF .NOT. link_severity THEN SPAWN/WAIT/NOLOG EXIT 'link_status' - PURGE $bin.EXE,$bin.OPT EOF + . ($config{target} =~ m|alpha| ? "" : <<"EOF" + SET IMAGE/FLAGS=(NOCALL_DEBUG) \$\@ +EOF + ); } sub in2script { my %args = @_; diff --git a/Configurations/shared-info.pl b/Configurations/shared-info.pl new file mode 100644 index 00000000..97163488 --- /dev/null +++ b/Configurations/shared-info.pl @@ -0,0 +1,102 @@ +#! /usr/bin/env perl +# -*- mode: perl; -*- +# Copyright 2016-2018 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 + +# This is a collection of extra attributes to be used as input for creating +# shared libraries, currently on any Unix variant, including Unix like +# environments on Windows. + +sub detect_gnu_ld { + my @lines = + `$config{cross_compile_prefix}$config{cc} -Wl,-V /dev/null 2>&1`; + return grep /^GNU ld/, @lines; +} +sub detect_gnu_cc { + my @lines = + `$config{cross_compile_prefix}$config{cc} -v 2>&1`; + return grep /gcc/, @lines; +} + +my %shared_info; +%shared_info = ( + 'gnu-shared' => { + shared_ldflag => '-shared -Wl,-Bsymbolic', + shared_sonameflag => '-Wl,-soname=', + }, + 'linux-shared' => sub { + return { + %{$shared_info{'gnu-shared'}}, + shared_defflag => '-Wl,--version-script=', + }; + }, + 'bsd-gcc-shared' => sub { return $shared_info{'linux-shared'}; }, + 'bsd-shared' => sub { + return $shared_info{'gnu-shared'} if detect_gnu_ld(); + return { + shared_ldflag => '-shared -nostdlib', + }; + }, + 'darwin-shared' => { + dso_lflags => '-bundle', + shared_ldflag => '-dynamiclib -current_version $(SHLIB_VERSION_NUMBER) -compatibility_version $(SHLIB_VERSION_NUMBER)', + shared_sonameflag => '-install_name $(INSTALLTOP)/$(LIBDIR)/', + }, + 'cygwin-shared' => { + shared_ldflag => '-shared -Wl,--enable-auto-image-base', + shared_impflag => '-Wl,--out-implib=', + }, + 'mingw-shared' => sub { + return { + %{$shared_info{'cygwin-shared'}}, + # def_flag made to empty string so it still generates + # something + shared_defflag => '', + }; + }, + 'alpha-osf1-shared' => sub { + return $shared_info{'gnu-shared'} if detect_gnu_ld(); + return { + dso_lflags => '-shared -Wl,-Bsymbolic', + shared_ldflag => '-shared -Wl,-Bsymbolic -set_version $(SHLIB_VERSION_NUMBER)', + }; + }, + 'solaris-shared' => { + shared_ldflag => '-Wl,-Bsymbolic', + shared_defflag => '-Wl,-M,', + }, + 'svr3-shared' => sub { + return $shared_info{'gnu-shared'} if detect_gnu_ld(); + return { + shared_ldflag => '-G', + shared_sonameflag => '-h ', + }; + }, + 'svr5-shared' => sub { + return $shared_info{'gnu-shared'} if detect_gnu_ld(); + return { + shared_ldflag => detect_gnu_cc() ? '-shared' : '-G', + shared_sonameflag => '-h ', + }; + }, + 'irix-shared' => sub { + return $shared_info{'gnu-shared'} if detect_gnu_ld(); + return { + shared_ldflag => '-shared -Wl,-Bsymbolic', + shared_sonameflag => '-Wl,-soname=', + }; + }, + 'hpux-shared' => { + bin_lflags => '-Wl,+s,+cdp,../:,+cdp,./:', + shared_ldflag => '-Wl,-B,symbolic,+vnocompatwarnings,-z,+s,+cdp,../:,+cdp,./:', + shared_sonameflag => '-Wl,+h,', + }, + 'aix-shared' => { + bin_lflags => '-Wl,-bsvr4', + shared_ldflag => '-Wl,-bexpall,-bnolibpath,-bM:SRE', + }, +); diff --git a/Configurations/unix-Makefile.tmpl b/Configurations/unix-Makefile.tmpl index 40cf2c3d..78b1a5e5 100644 --- a/Configurations/unix-Makefile.tmpl +++ b/Configurations/unix-Makefile.tmpl @@ -15,9 +15,9 @@ sub windowsdll { $config{target} =~ /^(?:Cygwin|mingw)/ } - our $sover = $config{target} =~ /^mingw/ - ? $config{shlib_major}."_".$config{shlib_minor} - : $config{shlib_major}.".".$config{shlib_minor}; + our $sover_dirname = $config{shlib_version_number}; + $sover_dirname =~ s|\.|_|g + if $config{target} =~ /^mingw/; # shlib and shlib_simple both take a static library name and figure # out what the shlib name should be. @@ -39,18 +39,24 @@ # removed. On some systems, they may therefore return the exact same # string. sub shlib { - return () if $disabled{shared}; my $lib = shift; - return $unified_info{sharednames}->{$lib}. $shlibvariant. $shlibext; + return () if $disabled{shared} || $lib =~ /\.a$/; + return $unified_info{sharednames}->{$lib}. $shlibvariant. '$(SHLIB_EXT)'; } sub shlib_simple { - return () if $disabled{shared}; - my $lib = shift; + return () if $disabled{shared} || $lib =~ /\.a$/; + if (windowsdll()) { - return $lib . $shlibextimport; + return $lib . '$(SHLIB_EXT_IMPORT)'; } - return $lib . $shlibextsimple; + return $lib . '$(SHLIB_EXT_SIMPLE)'; + } + + # Easy fixing of static library names + sub lib { + (my $lib = shift) =~ s/\.a$//; + return $lib . $libext; } # dso is a complement to shlib / shlib_simple that returns the @@ -84,8 +90,11 @@ SHLIB_VERSION_HISTORY={- $config{shlib_version_history} -} SHLIB_MAJOR={- $config{shlib_major} -} SHLIB_MINOR={- $config{shlib_minor} -} SHLIB_TARGET={- $target{shared_target} -} +SHLIB_EXT={- $shlibext -} +SHLIB_EXT_SIMPLE={- $shlibextsimple -} +SHLIB_EXT_IMPORT={- $shlibextimport -} -LIBS={- join(" ", map { $_.$libext } @{$unified_info{libraries}}) -} +LIBS={- join(" ", map { lib($_) } @{$unified_info{libraries}}) -} SHLIBS={- join(" ", map { shlib($_) } @{$unified_info{libraries}}) -} SHLIB_INFO={- join(" ", map { "\"".shlib($_).";".shlib_simple($_)."\"" } @{$unified_info{libraries}}) -} ENGINES={- join(" ", map { dso($_) } @{$unified_info{engines}}) -} @@ -98,12 +107,13 @@ DEPS={- join(" ", map { (my $x = $_) =~ s|\.o$|$depext|; $x; } {- output_on() if $disabled{makedepend}; "" -} GENERATED_MANDATORY={- join(" ", @{$unified_info{depends}->{""}} ) -} GENERATED={- join(" ", - ( grep { defined $unified_info{generate}->{$_} } + ( map { (my $x = $_) =~ s|\.S$|\.s|; $x } + grep { defined $unified_info{generate}->{$_} } map { @{$unified_info{sources}->{$_}} } grep { /\.o$/ } keys %{$unified_info{sources}} ), ( grep { /\.h$/ } keys %{$unified_info{generate}} )) -} -INSTALL_LIBS={- join(" ", map { $_.$libext } @{$unified_info{install}->{libraries}}) -} +INSTALL_LIBS={- join(" ", map { lib($_) } @{$unified_info{install}->{libraries}}) -} INSTALL_SHLIBS={- join(" ", map { shlib($_) } @{$unified_info{install}->{libraries}}) -} INSTALL_SHLIB_INFO={- join(" ", map { "\"".shlib($_).";".shlib_simple($_)."\"" } @{$unified_info{install}->{libraries}}) -} INSTALL_ENGINES={- join(" ", map { dso($_) } @{$unified_info{install}->{engines}}) -} @@ -144,21 +154,26 @@ OPENSSLDIR={- # : catdir($prefix, $config{openssldir})) : catdir($prefix, "ssl"); $openssldir -} -LIBDIR={- # - # if $prefix/lib$target{multilib} is not an existing - # directory, then assume that it's not searched by linker - # automatically, in which case adding $target{multilib} suffix - # causes more grief than we're ready to tolerate, so don't... - our $multilib = - -d "$prefix/lib$target{multilib}" ? $target{multilib} : ""; - our $libdir = $config{libdir} || "lib$multilib"; - $libdir -} -ENGINESDIR={- use File::Spec::Functions; - catdir($prefix,$libdir,"engines-$sover") -} +LIBDIR={- our $libdir = $config{libdir}; + unless ($libdir) { + # + # if $prefix/lib$target{multilib} is not an existing + # directory, then assume that it's not searched by linker + # automatically, in which case adding $target{multilib} suffix + # causes more grief than we're ready to tolerate, so don't... + our $multilib = + -d "$prefix/lib$target{multilib}" ? $target{multilib} : ""; + $libdir = "lib$multilib"; + } + file_name_is_absolute($libdir) ? "" : $libdir -} +# $(libdir) is chosen to be compatible with the GNU coding standards +libdir={- file_name_is_absolute($libdir) + ? $libdir : '$(INSTALLTOP)/$(LIBDIR)' -} +ENGINESDIR=$(libdir)/engines-{- $sover_dirname -} # Convenience variable for those who want to set the rpath in shared # libraries and applications -LIBRPATH=$(INSTALLTOP)/$(LIBDIR) +LIBRPATH=$(libdir) MANDIR=$(INSTALLTOP)/share/man DOCDIR=$(INSTALLTOP)/share/doc/$(BASENAME) @@ -170,29 +185,47 @@ HTMLDIR=$(DOCDIR)/html MANSUFFIX= HTMLSUFFIX=html - +# For "optional" echo messages, to get "real" silence +ECHO = echo CROSS_COMPILE= {- $config{cross_compile_prefix} -} -CC= $(CROSS_COMPILE){- $target{cc} -} -CFLAGS={- our $cflags2 = join(" ",(map { "-D".$_} @{$target{defines}}, @{$config{defines}}),"-DOPENSSLDIR=\"\\\"\$(OPENSSLDIR)\\\"\"","-DENGINESDIR=\"\\\"\$(ENGINESDIR)\\\"\"") -} {- $target{cflags} -} {- $config{cflags} -} -CFLAGS_Q={- $cflags2 =~ s|([\\"])|\\$1|g; $cflags2 -} {- $config{cflags} -} -LDFLAGS= {- $target{lflags} -} -PLIB_LDFLAGS= {- $target{plib_lflags} -} -EX_LIBS= {- $target{ex_libs} -} {- $config{ex_libs} -} -LIB_CFLAGS={- $target{shared_cflag} || "" -} -LIB_LDFLAGS={- $target{shared_ldflag}." ".$config{shared_ldflag} -} -DSO_CFLAGS={- $target{shared_cflag} || "" -} -DSO_LDFLAGS=$(LIB_LDFLAGS) -BIN_CFLAGS={- $target{bin_cflags} -} +CPPFLAGS={- our $cppflags = join(" ", + (map { "-D".$_} @{$config{defines}}), + (map { "-I".$_} @{$config{includes}}), + @{$config{cppflags}}) -} +CPPFLAGS_Q={- $cppflags =~ s|([\\"])|\\$1|g; $cppflags -} +CC= $(CROSS_COMPILE){- $config{cc} -} +CFLAGS={- join(' ', @{$config{cflags}}) -} +CXX={- $config{cxx} ? "\$(CROSS_COMPILE)$config{cxx}" : '' -} +CXXFLAGS={- join(' ', @{$config{cxxflags}}) -} +LDFLAGS= {- join(' ', @{$config{lflags}}) -} +PLIB_LDFLAGS= {- join(' ', @{$config{plib_lflags}}) -} +EX_LIBS= {- join(' ', @{$config{ex_libs}}) -} + +LIB_CPPFLAGS={- join(' ', '$(CPPFLAGS)', + $target{shared_cppflag} || (), + (map { '-D'.$_ } + ('OPENSSLDIR="\"$(OPENSSLDIR)\""', + 'ENGINESDIR="\"$(ENGINESDIR)\""'))) -} +LIB_CFLAGS={- join(' ', '$(CFLAGS)', $target{shared_cflag} || ()) -} +LIB_CXXFLAGS={- join(' ', '$(CXXFLAGS)', $target{shared_cxxflag} || ()) -} +LIB_LDFLAGS={- join(' ', '$(LDFLAGS)', $target{shared_ldflag} || (), $config{shared_ldflag} || ()) -} +DSO_CPPFLAGS={- join(' ', '$(CPPFLAGS)', $target{dso_cppflags} || ()) -} +DSO_CFLAGS={- join(' ', '$(CFLAGS)', $target{dso_cflags} || ()) -} +DSO_CXXFLAGS={- join(' ', '$(CXXFLAGS)', $target{dso_cxxflags} || ()) -} +DSO_LDFLAGS={- join(' ', '$(LDFLAGS)', $target{dso_lflags} || ()) -} +BIN_CPPFLAGS={- join(' ', '$(CPPFLAGS)', $target{bin_cppflags} || ()) -} +BIN_CFLAGS={- join(' ', '$(CFLAGS)', $target{bin_cflags} || ()) -} +BIN_CXXFLAGS={- join(' ', '$(CXXFLAGS)', $target{bin_cxxflags} || ()) -} +BIN_LDFLAGS={- join(' ', '$(LDFLAGS)', $target{bin_lflags} || ()) -} PERL={- $config{perl} -} -ARFLAGS= {- $target{arflags} -} -AR=$(CROSS_COMPILE){- $target{ar} || "ar" -} $(ARFLAGS) r -RANLIB= {- $target{ranlib} -} -NM= $(CROSS_COMPILE){- $target{nm} || "nm" -} -RCFLAGS={- $target{shared_rcflag} -} +AR=$(CROSS_COMPILE){- $config{ar} -} +ARFLAGS= {- join(' ', @{$config{arflags}}) -} +RANLIB={- $config{ranlib} ? "\$(CROSS_COMPILE)$config{ranlib}" : "true"; -} RC= $(CROSS_COMPILE){- $target{rc} || "windres" -} +RCFLAGS={- join(' ', @{$config{rcflags}}) -} {- $target{shared_rcflag} -} RM= rm -f RMDIR= rmdir TAR= {- $target{tar} || "tar" -} @@ -207,8 +240,9 @@ TARFILE= ../$(NAME).tar # order to be excused from maintaining a separate set of architecture # dependent assembler flags. E.g. if you throw -mcpu=ultrasparc at SPARC # gcc, then the driver will automatically translate it to -xarch=v8plus -# and pass it down to assembler. In any case, we do not define AS or -# ASFLAGS for this reason. +# and pass it down to assembler. +AS={- $config{as} ? "\$(CROSS_COMPILE)$config{as}" : '$(CC) -c' -} +ASFLAGS={- join(' ', @{$config{asflags}}) || '$(CFLAGS)' -} PERLASM_SCHEME= {- $target{perlasm_scheme} -} # For x86 assembler: Set PROCESSOR to 386 if you want to support @@ -276,10 +310,10 @@ libclean: @set -e; for s in $(SHLIB_INFO); do \ s1=`echo "$$s" | cut -f1 -d";"`; \ s2=`echo "$$s" | cut -f2 -d";"`; \ - echo $(RM) $$s1; \ + $(ECHO) $(RM) $$s1; \ $(RM) $$s1; \ if [ "$$s1" != "$$s2" ]; then \ - echo $(RM) $$s2; \ + $(ECHO) $(RM) $$s2; \ $(RM) $$s2; \ fi; \ done @@ -339,47 +373,56 @@ install_ssldirs: @set -e; for x in dummy $(MISC_SCRIPTS); do \ if [ "$$x" = "dummy" ]; then continue; fi; \ fn=`basename $$x`; \ - echo "install $$x -> $(DESTDIR)$(OPENSSLDIR)/misc/$$fn"; \ + $(ECHO) "install $$x -> $(DESTDIR)$(OPENSSLDIR)/misc/$$fn"; \ cp $$x $(DESTDIR)$(OPENSSLDIR)/misc/$$fn.new; \ chmod 755 $(DESTDIR)$(OPENSSLDIR)/misc/$$fn.new; \ mv -f $(DESTDIR)$(OPENSSLDIR)/misc/$$fn.new \ $(DESTDIR)$(OPENSSLDIR)/misc/$$fn; \ done - @echo "install $(SRCDIR)/apps/openssl.cnf -> $(DESTDIR)$(OPENSSLDIR)/openssl.cnf.dist" + @$(ECHO) "install $(SRCDIR)/apps/openssl.cnf -> $(DESTDIR)$(OPENSSLDIR)/openssl.cnf.dist" @cp $(SRCDIR)/apps/openssl.cnf $(DESTDIR)$(OPENSSLDIR)/openssl.cnf.new @chmod 644 $(DESTDIR)$(OPENSSLDIR)/openssl.cnf.new @mv -f $(DESTDIR)$(OPENSSLDIR)/openssl.cnf.new $(DESTDIR)$(OPENSSLDIR)/openssl.cnf.dist - @if ! [ -f "$(DESTDIR)$(OPENSSLDIR)/openssl.cnf" ]; then \ - echo "install $(SRCDIR)/apps/openssl.cnf -> $(DESTDIR)$(OPENSSLDIR)/openssl.cnf"; \ + @if [ ! -f "$(DESTDIR)$(OPENSSLDIR)/openssl.cnf" ]; then \ + $(ECHO) "install $(SRCDIR)/apps/openssl.cnf -> $(DESTDIR)$(OPENSSLDIR)/openssl.cnf"; \ cp $(SRCDIR)/apps/openssl.cnf $(DESTDIR)$(OPENSSLDIR)/openssl.cnf; \ chmod 644 $(DESTDIR)$(OPENSSLDIR)/openssl.cnf; \ fi + @$(ECHO) "install $(SRCDIR)/apps/ct_log_list.cnf -> $(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf.dist" + @cp $(SRCDIR)/apps/ct_log_list.cnf $(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf.new + @chmod 644 $(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf.new + @mv -f $(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf.new $(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf.dist + @if [ ! -f "$(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf" ]; then \ + $(ECHO) "install $(SRCDIR)/apps/ct_log_list.cnf -> $(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf"; \ + cp $(SRCDIR)/apps/ct_log_list.cnf $(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf; \ + chmod 644 $(DESTDIR)$(OPENSSLDIR)/ct_log_list.cnf; \ + fi install_dev: @[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1) - @echo "*** Installing development files" + @$(ECHO) "*** Installing development files" @$(PERL) $(SRCDIR)/util/mkdir-p.pl $(DESTDIR)$(INSTALLTOP)/include/openssl @ : {- output_off() unless grep { $_ eq "OPENSSL_USE_APPLINK" } @{$target{defines}}; "" -} - @echo "install $(SRCDIR)/ms/applink.c -> $(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c" + @$(ECHO) "install $(SRCDIR)/ms/applink.c -> $(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c" @cp $(SRCDIR)/ms/applink.c $(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c @chmod 644 $(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c @ : {- output_on() unless grep { $_ eq "OPENSSL_USE_APPLINK" } @{$target{defines}}; "" -} @set -e; for i in $(SRCDIR)/include/openssl/*.h \ $(BLDDIR)/include/openssl/*.h; do \ fn=`basename $$i`; \ - echo "install $$i -> $(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn"; \ + $(ECHO) "install $$i -> $(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn"; \ cp $$i $(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn; \ chmod 644 $(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn; \ done - @$(PERL) $(SRCDIR)/util/mkdir-p.pl $(DESTDIR)$(INSTALLTOP)/$(LIBDIR) + @$(PERL) $(SRCDIR)/util/mkdir-p.pl $(DESTDIR)$(libdir) @set -e; for l in $(INSTALL_LIBS); do \ fn=`basename $$l`; \ - echo "install $$l -> $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn"; \ - cp $$l $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn.new; \ - $(RANLIB) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn.new; \ - chmod 644 $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn.new; \ - mv -f $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn.new \ - $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn; \ + $(ECHO) "install $$l -> $(DESTDIR)$(libdir)/$$fn"; \ + cp $$l $(DESTDIR)$(libdir)/$$fn.new; \ + $(RANLIB) $(DESTDIR)$(libdir)/$$fn.new; \ + chmod 644 $(DESTDIR)$(libdir)/$$fn.new; \ + mv -f $(DESTDIR)$(libdir)/$$fn.new \ + $(DESTDIR)$(libdir)/$$fn; \ done @ : {- output_off() if $disabled{shared}; "" -} @set -e; for s in $(INSTALL_SHLIB_INFO); do \ @@ -388,53 +431,53 @@ install_dev: fn1=`basename $$s1`; \ fn2=`basename $$s2`; \ : {- output_off() if windowsdll(); "" -}; \ - echo "install $$s1 -> $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn1"; \ - cp $$s1 $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn1.new; \ - chmod 755 $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn1.new; \ - mv -f $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn1.new \ - $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn1; \ + $(ECHO) "install $$s1 -> $(DESTDIR)$(libdir)/$$fn1"; \ + cp $$s1 $(DESTDIR)$(libdir)/$$fn1.new; \ + chmod 755 $(DESTDIR)$(libdir)/$$fn1.new; \ + mv -f $(DESTDIR)$(libdir)/$$fn1.new \ + $(DESTDIR)$(libdir)/$$fn1; \ if [ "$$fn1" != "$$fn2" ]; then \ - echo "link $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2 -> $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn1"; \ - ln -sf $$fn1 $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2; \ + $(ECHO) "link $(DESTDIR)$(libdir)/$$fn2 -> $(DESTDIR)$(libdir)/$$fn1"; \ + ln -sf $$fn1 $(DESTDIR)$(libdir)/$$fn2; \ fi; \ : {- output_on() if windowsdll(); "" -}{- output_off() unless windowsdll(); "" -}; \ - echo "install $$s2 -> $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2"; \ - cp $$s2 $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2.new; \ - chmod 755 $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2.new; \ - mv -f $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2.new \ - $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2; \ + $(ECHO) "install $$s2 -> $(DESTDIR)$(libdir)/$$fn2"; \ + cp $$s2 $(DESTDIR)$(libdir)/$$fn2.new; \ + chmod 755 $(DESTDIR)$(libdir)/$$fn2.new; \ + mv -f $(DESTDIR)$(libdir)/$$fn2.new \ + $(DESTDIR)$(libdir)/$$fn2; \ : {- output_on() unless windowsdll(); "" -}; \ done @ : {- output_on() if $disabled{shared}; "" -} - @$(PERL) $(SRCDIR)/util/mkdir-p.pl $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig - @echo "install libcrypto.pc -> $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libcrypto.pc" - @cp libcrypto.pc $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig - @chmod 644 $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libcrypto.pc - @echo "install libssl.pc -> $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libssl.pc" - @cp libssl.pc $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig - @chmod 644 $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libssl.pc - @echo "install openssl.pc -> $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/openssl.pc" - @cp openssl.pc $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig - @chmod 644 $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/openssl.pc + @$(PERL) $(SRCDIR)/util/mkdir-p.pl $(DESTDIR)$(libdir)/pkgconfig + @$(ECHO) "install libcrypto.pc -> $(DESTDIR)$(libdir)/pkgconfig/libcrypto.pc" + @cp libcrypto.pc $(DESTDIR)$(libdir)/pkgconfig + @chmod 644 $(DESTDIR)$(libdir)/pkgconfig/libcrypto.pc + @$(ECHO) "install libssl.pc -> $(DESTDIR)$(libdir)/pkgconfig/libssl.pc" + @cp libssl.pc $(DESTDIR)$(libdir)/pkgconfig + @chmod 644 $(DESTDIR)$(libdir)/pkgconfig/libssl.pc + @$(ECHO) "install openssl.pc -> $(DESTDIR)$(libdir)/pkgconfig/openssl.pc" + @cp openssl.pc $(DESTDIR)$(libdir)/pkgconfig + @chmod 644 $(DESTDIR)$(libdir)/pkgconfig/openssl.pc uninstall_dev: - @echo "*** Uninstalling development files" + @$(ECHO) "*** Uninstalling development files" @ : {- output_off() unless grep { $_ eq "OPENSSL_USE_APPLINK" } @{$target{defines}}; "" -} - @echo "$(RM) $(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c" + @$(ECHO) "$(RM) $(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c" @$(RM) $(DESTDIR)$(INSTALLTOP)/include/openssl/applink.c @ : {- output_on() unless grep { $_ eq "OPENSSL_USE_APPLINK" } @{$target{defines}}; "" -} @set -e; for i in $(SRCDIR)/include/openssl/*.h \ $(BLDDIR)/include/openssl/*.h; do \ fn=`basename $$i`; \ - echo "$(RM) $(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn"; \ + $(ECHO) "$(RM) $(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn"; \ $(RM) $(DESTDIR)$(INSTALLTOP)/include/openssl/$$fn; \ done -$(RMDIR) $(DESTDIR)$(INSTALLTOP)/include/openssl -$(RMDIR) $(DESTDIR)$(INSTALLTOP)/include @set -e; for l in $(INSTALL_LIBS); do \ fn=`basename $$l`; \ - echo "$(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn"; \ - $(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn; \ + $(ECHO) "$(RM) $(DESTDIR)$(libdir)/$$fn"; \ + $(RM) $(DESTDIR)$(libdir)/$$fn; \ done @ : {- output_off() if $disabled{shared}; "" -} @set -e; for s in $(INSTALL_SHLIB_INFO); do \ @@ -443,32 +486,32 @@ uninstall_dev: fn1=`basename $$s1`; \ fn2=`basename $$s2`; \ : {- output_off() if windowsdll(); "" -}; \ - echo "$(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn1"; \ - $(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn1; \ + $(ECHO) "$(RM) $(DESTDIR)$(libdir)/$$fn1"; \ + $(RM) $(DESTDIR)$(libdir)/$$fn1; \ if [ "$$fn1" != "$$fn2" ]; then \ - echo "$(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2"; \ - $(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2; \ + $(ECHO) "$(RM) $(DESTDIR)$(libdir)/$$fn2"; \ + $(RM) $(DESTDIR)$(libdir)/$$fn2; \ fi; \ : {- output_on() if windowsdll(); "" -}{- output_off() unless windowsdll(); "" -}; \ - echo "$(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2"; \ - $(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn2; \ + $(ECHO) "$(RM) $(DESTDIR)$(libdir)/$$fn2"; \ + $(RM) $(DESTDIR)$(libdir)/$$fn2; \ : {- output_on() unless windowsdll(); "" -}; \ done @ : {- output_on() if $disabled{shared}; "" -} - $(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libcrypto.pc - $(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/libssl.pc - $(RM) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig/openssl.pc - -$(RMDIR) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/pkgconfig - -$(RMDIR) $(DESTDIR)$(INSTALLTOP)/$(LIBDIR) + $(RM) $(DESTDIR)$(libdir)/pkgconfig/libcrypto.pc + $(RM) $(DESTDIR)$(libdir)/pkgconfig/libssl.pc + $(RM) $(DESTDIR)$(libdir)/pkgconfig/openssl.pc + -$(RMDIR) $(DESTDIR)$(libdir)/pkgconfig + -$(RMDIR) $(DESTDIR)$(libdir) install_engines: @[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1) @$(PERL) $(SRCDIR)/util/mkdir-p.pl $(DESTDIR)$(ENGINESDIR)/ - @echo "*** Installing engines" + @$(ECHO) "*** Installing engines" @set -e; for e in dummy $(INSTALL_ENGINES); do \ if [ "$$e" = "dummy" ]; then continue; fi; \ fn=`basename $$e`; \ - echo "install $$e -> $(DESTDIR)$(ENGINESDIR)/$$fn"; \ + $(ECHO) "install $$e -> $(DESTDIR)$(ENGINESDIR)/$$fn"; \ cp $$e $(DESTDIR)$(ENGINESDIR)/$$fn.new; \ chmod 755 $(DESTDIR)$(ENGINESDIR)/$$fn.new; \ mv -f $(DESTDIR)$(ENGINESDIR)/$$fn.new \ @@ -476,14 +519,14 @@ install_engines: done uninstall_engines: - @echo "*** Uninstalling engines" + @$(ECHO) "*** Uninstalling engines" @set -e; for e in dummy $(INSTALL_ENGINES); do \ if [ "$$e" = "dummy" ]; then continue; fi; \ fn=`basename $$e`; \ if [ "$$fn" = '{- dso("ossltest") -}' ]; then \ continue; \ fi; \ - echo "$(RM) $(DESTDIR)$(ENGINESDIR)/$$fn"; \ + $(ECHO) "$(RM) $(DESTDIR)$(ENGINESDIR)/$$fn"; \ $(RM) $(DESTDIR)$(ENGINESDIR)/$$fn; \ done -$(RMDIR) $(DESTDIR)$(ENGINESDIR) @@ -492,30 +535,30 @@ install_runtime: @[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1) @$(PERL) $(SRCDIR)/util/mkdir-p.pl $(DESTDIR)$(INSTALLTOP)/bin @ : {- output_off() if windowsdll(); "" -} - @$(PERL) $(SRCDIR)/util/mkdir-p.pl $(DESTDIR)$(INSTALLTOP)/$(LIBDIR) + @$(PERL) $(SRCDIR)/util/mkdir-p.pl $(DESTDIR)$(libdir) @ : {- output_on() if windowsdll(); "" -} - @echo "*** Installing runtime files" + @$(ECHO) "*** Installing runtime files" @set -e; for s in dummy $(INSTALL_SHLIBS); do \ if [ "$$s" = "dummy" ]; then continue; fi; \ fn=`basename $$s`; \ : {- output_off() unless windowsdll(); "" -}; \ - echo "install $$s -> $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ + $(ECHO) "install $$s -> $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ cp $$s $(DESTDIR)$(INSTALLTOP)/bin/$$fn.new; \ chmod 644 $(DESTDIR)$(INSTALLTOP)/bin/$$fn.new; \ mv -f $(DESTDIR)$(INSTALLTOP)/bin/$$fn.new \ $(DESTDIR)$(INSTALLTOP)/bin/$$fn; \ : {- output_on() unless windowsdll(); "" -}{- output_off() if windowsdll(); "" -}; \ - echo "install $$s -> $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn"; \ - cp $$s $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn.new; \ - chmod 755 $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn.new; \ - mv -f $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn.new \ - $(DESTDIR)$(INSTALLTOP)/$(LIBDIR)/$$fn; \ + $(ECHO) "install $$s -> $(DESTDIR)$(libdir)/$$fn"; \ + cp $$s $(DESTDIR)$(libdir)/$$fn.new; \ + chmod 755 $(DESTDIR)$(libdir)/$$fn.new; \ + mv -f $(DESTDIR)$(libdir)/$$fn.new \ + $(DESTDIR)$(libdir)/$$fn; \ : {- output_on() if windowsdll(); "" -}; \ done @set -e; for x in dummy $(INSTALL_PROGRAMS); do \ if [ "$$x" = "dummy" ]; then continue; fi; \ fn=`basename $$x`; \ - echo "install $$x -> $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ + $(ECHO) "install $$x -> $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ cp $$x $(DESTDIR)$(INSTALLTOP)/bin/$$fn.new; \ chmod 755 $(DESTDIR)$(INSTALLTOP)/bin/$$fn.new; \ mv -f $(DESTDIR)$(INSTALLTOP)/bin/$$fn.new \ @@ -524,7 +567,7 @@ install_runtime: @set -e; for x in dummy $(BIN_SCRIPTS); do \ if [ "$$x" = "dummy" ]; then continue; fi; \ fn=`basename $$x`; \ - echo "install $$x -> $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ + $(ECHO) "install $$x -> $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ cp $$x $(DESTDIR)$(INSTALLTOP)/bin/$$fn.new; \ chmod 755 $(DESTDIR)$(INSTALLTOP)/bin/$$fn.new; \ mv -f $(DESTDIR)$(INSTALLTOP)/bin/$$fn.new \ @@ -532,26 +575,26 @@ install_runtime: done uninstall_runtime: - @echo "*** Uninstalling runtime files" + @$(ECHO) "*** Uninstalling runtime files" @set -e; for x in dummy $(INSTALL_PROGRAMS); \ do \ if [ "$$x" = "dummy" ]; then continue; fi; \ fn=`basename $$x`; \ - echo "$(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ + $(ECHO) "$(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ $(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn; \ done; @set -e; for x in dummy $(BIN_SCRIPTS); \ do \ if [ "$$x" = "dummy" ]; then continue; fi; \ fn=`basename $$x`; \ - echo "$(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ + $(ECHO) "$(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ $(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn; \ done @ : {- output_off() unless windowsdll(); "" -} @set -e; for s in dummy $(INSTALL_SHLIBS); do \ if [ "$$s" = "dummy" ]; then continue; fi; \ fn=`basename $$s`; \ - echo "$(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ + $(ECHO) "$(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn"; \ $(RM) $(DESTDIR)$(INSTALLTOP)/bin/$$fn; \ done @ : {- output_on() unless windowsdll(); "" -} @@ -560,24 +603,24 @@ uninstall_runtime: install_man_docs: @[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1) - @echo "*** Installing manpages" + @$(ECHO) "*** Installing manpages" $(PERL) $(SRCDIR)/util/process_docs.pl \ --destdir=$(DESTDIR)$(MANDIR) --type=man --suffix=$(MANSUFFIX) uninstall_man_docs: - @echo "*** Uninstalling manpages" + @$(ECHO) "*** Uninstalling manpages" $(PERL) $(SRCDIR)/util/process_docs.pl \ --destdir=$(DESTDIR)$(MANDIR) --type=man --suffix=$(MANSUFFIX) \ --remove install_html_docs: @[ -n "$(INSTALLTOP)" ] || (echo INSTALLTOP should not be empty; exit 1) - @echo "*** Installing HTML manpages" + @$(ECHO) "*** Installing HTML manpages" $(PERL) $(SRCDIR)/util/process_docs.pl \ --destdir=$(DESTDIR)$(HTMLDIR) --type=html uninstall_html_docs: - @echo "*** Uninstalling manpages" + @$(ECHO) "*** Uninstalling manpages" $(PERL) $(SRCDIR)/util/process_docs.pl \ --destdir=$(DESTDIR)$(HTMLDIR) --type=html --remove @@ -587,10 +630,10 @@ uninstall_html_docs: update: generate errors ordinals generate: generate_apps generate_crypto_bn generate_crypto_objects \ - generate_crypto_conf generate_crypto_asn1 + generate_crypto_conf generate_crypto_asn1 generate_fuzz_oids doc-nits: - (cd $(SRCDIR); $(PERL) util/find-doc-nits -n ) >doc-nits + (cd $(SRCDIR); $(PERL) util/find-doc-nits -n -p ) >doc-nits if [ -s doc-nits ] ; then cat doc-nits; rm doc-nits ; exit 1; fi # Test coverage is a good idea for the future @@ -628,14 +671,22 @@ generate_crypto_asn1: ( cd $(SRCDIR); $(PERL) crypto/asn1/charmap.pl \ > crypto/asn1/charmap.h ) +generate_fuzz_oids: + ( cd $(SRCDIR); $(PERL) fuzz/mkfuzzoids.pl \ + crypto/objects/obj_dat.h \ + > fuzz/oids.txt ) + +# Set to -force to force a rebuild +ERROR_REBUILD= errors: ( cd $(SRCDIR); $(PERL) util/ck_errf.pl -strict */*.c */*/*.c ) - ( cd $(SRCDIR); $(PERL) util/mkerr.pl -recurse -write ) - ( cd $(SRCDIR)/engines; \ - for e in *.ec; do \ - $(PERL) ../util/mkerr.pl -conf $$e \ - -nostatic -staticloader -write *.c; \ - done ) + ( b=`pwd`; cd $(SRCDIR); \ + $(PERL) -I$$b util/mkerr.pl $(ERROR_REBUILD) -internal ) + ( b=`pwd`; cd $(SRCDIR)/engines; \ + for E in *.ec ; do \ + $(PERL) -I$$b ../util/mkerr.pl $(ERROR_REBUILD) -static \ + -conf $$E `basename $$E .ec`.c ; \ + done ) ordinals: ( b=`pwd`; cd $(SRCDIR); $(PERL) -I$$b util/mkdef.pl crypto update ) @@ -664,8 +715,11 @@ tar: DISTDIR=$(NAME); \ mkdir -p $$TMPDIR/$$DISTDIR; \ (cd $(SRCDIR); \ + excl_re=`git submodule status | sed -e 's/^.//' | cut -d' ' -f2`; \ + excl_re="^(fuzz/corpora|`echo $$excl_re | sed -e 's/ /$$|/g'`\$$)"; \ + echo "$$excl_re"; \ git ls-tree -r --name-only --full-tree HEAD \ - | grep -v '^fuzz/corpora' \ + | egrep -v "$$excl_re" \ | while read F; do \ mkdir -p $$TMPDIR/$$DISTDIR/`dirname $$F`; \ cp $$F $$TMPDIR/$$DISTDIR/$$F; \ @@ -681,7 +735,7 @@ tar: cd $(SRCDIR); ls -l $(TARFILE).gz dist: - @$(MAKE) PREPARE_CMD='$(PERL) ./Configure dist' tar + @$(MAKE) PREPARE_CMD='$(PERL) ./Configure dist' TARFILE="$(TARFILE)" NAME="$(NAME)" tar # Helper targets ##################################################### @@ -701,9 +755,13 @@ libcrypto.pc libssl.pc openssl.pc: configdata.pm $(LIBS) {- join(" ",map { shlib libcrypto.pc: @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ - echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ + if [ -n "$(LIBDIR)" ]; then \ + echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ + else \ + echo 'libdir=$(libdir)'; \ + fi; \ echo 'includedir=$${prefix}/include'; \ - echo 'enginesdir=$${libdir}/engines-{- $sover -}'; \ + echo 'enginesdir=$${libdir}/engines-{- $sover_dirname -}'; \ echo ''; \ echo 'Name: OpenSSL-libcrypto'; \ echo 'Description: OpenSSL cryptography library'; \ @@ -715,7 +773,11 @@ libcrypto.pc: libssl.pc: @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ - echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ + if [ -n "$(LIBDIR)" ]; then \ + echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ + else \ + echo 'libdir=$(libdir)'; \ + fi; \ echo 'includedir=$${prefix}/include'; \ echo ''; \ echo 'Name: OpenSSL-libssl'; \ @@ -728,7 +790,11 @@ libssl.pc: openssl.pc: @ ( echo 'prefix=$(INSTALLTOP)'; \ echo 'exec_prefix=$${prefix}'; \ - echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ + if [ -n "$(LIBDIR)" ]; then \ + echo 'libdir=$${exec_prefix}/$(LIBDIR)'; \ + else \ + echo 'libdir=$(libdir)'; \ + fi; \ echo 'includedir=$${prefix}/include'; \ echo ''; \ echo 'Name: OpenSSL'; \ @@ -738,8 +804,7 @@ openssl.pc: configdata.pm: $(SRCDIR)/Configure $(SRCDIR)/config {- join(" ", @{$config{build_file_templates}}, @{$config{build_infos}}, @{$config{conf_files}}) -} @echo "Detected changed: $?" - @echo "Reconfiguring..." - $(PERL) $(SRCDIR)/Configure reconf + $(PERL) configdata.pm -r @echo "**************************************************" @echo "*** ***" @echo "*** Please run the same make command again ***" @@ -747,6 +812,9 @@ configdata.pm: $(SRCDIR)/Configure $(SRCDIR)/config {- join(" ", @{$config{build @echo "**************************************************" @false +reconfigure reconf: + $(PERL) configdata.pm -r + {- use File::Basename; use File::Spec::Functions qw/:DEFAULT abs2rel rel2abs/; @@ -755,13 +823,13 @@ configdata.pm: $(SRCDIR)/Configure $(SRCDIR)/config {- join(" ", @{$config{build # It takes a list of library names and outputs a list of dependencies sub compute_lib_depends { if ($disabled{shared}) { - return map { $_.$libext } @_; + return map { lib($_) } @_; } # Depending on shared libraries: # On Windows POSIX layers, we depend on {libname}.dll.a # On Unix platforms, we depend on {shlibname}.so - return map { shlib_simple($_) } @_; + return map { $_ =~ /\.a$/ ? $`.$libext : shlib_simple($_) } @_; } sub generatesrc { @@ -798,7 +866,26 @@ EOF die "Generator type for $args{src} unknown: $generator\n"; } + my $cppflags = { + lib => '$(LIB_CFLAGS) $(LIB_CPPFLAGS)', + dso => '$(DSO_CFLAGS) $(DSO_CPPFLAGS)', + bin => '$(BIN_CFLAGS) $(BIN_CPPFLAGS)' + } -> {$args{intent}}; if (defined($generator)) { + # If the target is named foo.S in build.info, we want to + # end up generating foo.s in two steps. + if ($args{src} =~ /\.S$/) { + (my $target = $args{src}) =~ s|\.S$|.s|; + return <<"EOF"; +$target: $args{generator}->[0] $deps + ( trap "rm -f \$@.*" INT 0; \\ + $generator \$@.S; \\ + \$(CPP) $incs $cppflags \$@.S | \\ + \$(PERL) -ne '/^#(line)?\\s*[0-9]+/ or print' > \$@.i && \\ + mv -f \$@.i \$@ ) +EOF + } + # Otherwise.... return <<"EOF"; $args{src}: $args{generator}->[0] $deps $generator \$@ @@ -806,7 +893,7 @@ EOF } return <<"EOF"; $args{src}: $args{generator}->[0] $deps - \$(CC) $incs \$(CFLAGS) -E $args{generator}->[0] | \\ + \$(CPP) $incs $cppflags $args{generator}->[0] | \\ \$(PERL) -ne '/^#(line)?\\s*[0-9]+/ or print' > \$@ EOF } @@ -817,45 +904,49 @@ EOF # last in the line. We may therefore need to put back a line ending. sub src2obj { my %args = @_; - my $obj = $args{obj}; - my @srcs = @{$args{srcs}}; + (my $obj = $args{obj}) =~ s|\.o$||; + my @srcs = map { if ($unified_info{generate}->{$_}) { + (my $x = $_) =~ s/\.S$/.s/; $x + } else { + $_ + } + } ( @{$args{srcs}} ); my $srcs = join(" ", @srcs); my $deps = join(" ", @srcs, @{$args{deps}}); my $incs = join("", map { " -I".$_ } @{$args{incs}}); - unless ($disabled{zlib}) { - if ($withargs{zlib_include}) { - $incs .= " -I".$withargs{zlib_include}; - } + my $cmd; + my $cmdflags; + my $cmdcompile; + my $makedepprog = $disabled{makedepend} ? undef : $config{makedepprog}; + if (grep /\.rc$/, @srcs) { + $cmd = '$(RC)'; + $cmdflags = '$(RCFLAGS)'; + $cmdcompile = ''; + $makedepprog = undef; + } elsif (grep /\.(cc|cpp)$/, @srcs) { + $cmd = '$(CXX)'; + $cmdcompile = ' -c'; + $cmdflags = { + lib => '$(LIB_CXXFLAGS) $(LIB_CPPFLAGS)', + dso => '$(DSO_CXXFLAGS) $(DSO_CPPFLAGS)', + bin => '$(BIN_CXXFLAGS) $(BIN_CPPFLAGS)' + } -> {$args{intent}}; + } else { + $cmd = '$(CC)'; + $cmdcompile = ' -c'; + $cmdflags = { + lib => '$(LIB_CFLAGS) $(LIB_CPPFLAGS)', + dso => '$(DSO_CFLAGS) $(DSO_CPPFLAGS)', + bin => '$(BIN_CFLAGS) $(BIN_CPPFLAGS)' + } -> {$args{intent}}; } - my $ecflags = { lib => '$(LIB_CFLAGS)', - dso => '$(DSO_CFLAGS)', - bin => '$(BIN_CFLAGS)' } -> {$args{intent}}; - my $makedepprog = $config{makedepprog}; - my $recipe; - # extension-specific rules - if (grep /\.s$/, @srcs) { - $recipe .= <<"EOF"; + $cmdflags .= $cmdcompile; + my $recipe = <<"EOF"; $obj$objext: $deps - \$(CC) \$(CFLAGS) $ecflags -c -o \$\@ $srcs EOF - } elsif (grep /\.S$/, @srcs) { - # In case one wonders why not just $(CC) -c file.S. While it - # does work with contemporary compilers, there are some legacy - # ones that get it wrong. Hence the elaborate scheme... We - # don't care to maintain dependecy lists, because dependency - # is rather weak, at most one header file that lists constants - # which are assigned in ascending order. + if (defined $makedepprog && $makedepprog !~ /\/makedepend/) { $recipe .= <<"EOF"; -$obj$objext: $deps - ( trap "rm -f \$@.*" INT 0; \\ - \$(CPP) $incs \$(CFLAGS) $ecflags $srcs | \\ - \$(PERL) -ne '/^#(line)?\\s*[0-9]+/ or print' > \$@.s && \\ - \$(CC) \$(CFLAGS) $ecflags -c -o \$\@ \$@.s ) -EOF - } elsif (!$disabled{makedepend} && $makedepprog !~ /\/makedepend/) { - $recipe .= <<"EOF"; -$obj$objext: $deps - \$(CC) $incs \$(CFLAGS) $ecflags -MMD -MF $obj$depext.tmp -MT \$\@ -c -o \$\@ $srcs + $cmd $incs $cmdflags -MMD -MF $obj$depext.tmp -MT \$\@ -c -o \$\@ $srcs \@touch $obj$depext.tmp \@if cmp $obj$depext.tmp $obj$depext > /dev/null 2> /dev/null; then \\ rm -f $obj$depext.tmp; \\ @@ -865,12 +956,11 @@ $obj$objext: $deps EOF } else { $recipe .= <<"EOF"; -$obj$objext: $deps - \$(CC) $incs \$(CFLAGS) $ecflags -c -o \$\@ $srcs + $cmd $incs $cmdflags -o \$\@ $srcs EOF - if (!$disabled{makedepend} && $makedepprog =~ /\/makedepend/) { + if (defined $makedepprog && $makedepprog =~ /\/makedepend/) { $recipe .= <<"EOF"; - -\$(MAKEDEPEND) -f- -o"|\$\@" -- $incs \$(CFLAGS) $ecflags -- $srcs \\ + -\$(MAKEDEPEND) -f- -o"|\$\@" -- $incs $cmdflags -- $srcs \\ >$obj$depext.tmp 2>/dev/null -\$(PERL) -i -pe 's/^.*\\|//; s/ \\/(\\\\.|[^ ])*//; \$\$_ = undef if (/: *\$\$/ || /^(#.*| *)\$\$/); \$\$_.="\\n" unless !defined(\$\$_) or /\\R\$\$/g;' $obj$depext.tmp \@if cmp $obj$depext.tmp $obj$depext > /dev/null 2> /dev/null; then \\ @@ -893,79 +983,97 @@ EOF my $libd = dirname($lib); my $libn = basename($lib); (my $libname = $libn) =~ s/^lib//; - my $linklibs = join("", map { my $d = dirname($_); - my $f = basename($_); + my @linkdirs = (); + foreach (@{args{deps}}) { + my $d = dirname($_); + push @linkdirs, $d unless grep { $d eq $_ } @linkdirs; + } + my $linkflags = join("", map { "-L$_ " } @linkdirs); + my $linklibs = join("", map { my $f = basename($_); (my $l = $f) =~ s/^lib//; - " -L$d -l$l" } @{$args{deps}}); - my $deps = join(" ",compute_lib_depends(@{$args{deps}})); - my $shlib_target = $target{shared_target}; - my $ordinalsfile = defined($args{ordinals}) ? $args{ordinals}->[1] : ""; + " -l$l" } @{$args{deps}}); + my @objs = map { (my $x = $_) =~ s|\.o$|$objext|; $x } + grep { $_ =~ m|\.o$| } + @{$args{objs}}; + my @defs = grep { $_ =~ /\.(def|map)$/ } @{$args{objs}}; + my @deps = compute_lib_depends(@{$args{deps}}); + die "More than one exported symbol map" if scalar @defs > 1; + my $objs = join(" ", @objs); + my $deps = join(" ", @objs, @defs, @deps); my $target = shlib_simple($lib); my $target_full = shlib($lib); - return <<"EOF" -# With a build on a Windows POSIX layer (Cygwin or Mingw), we know for a fact + my $shared_soname = ""; + $shared_soname .= ' '.$target{shared_sonameflag}.basename($target_full) + if defined $target{shared_sonameflag}; + my $shared_imp = ""; + $shared_imp .= ' '.$target{shared_impflag}.basename($target) + if defined $target{shared_impflag}; + my $shared_def = join("", map { ' '.$target{shared_defflag}.$_ } @defs); + my $recipe = <<"EOF"; +# When building on a Windows POSIX layer (Cygwin or Mingw), we know for a fact # that two files get produced, {shlibname}.dll and {libname}.dll.a. # With all other Unix platforms, we often build a shared library with the # SO version built into the file name and a symlink without the SO version # It's not necessary to have both as targets. The choice falls on the -# simplest, {libname}$shlibextimport for Windows POSIX layers and -# {libname}$shlibextsimple for the Unix platforms. -$target: $lib$libext $deps $ordinalsfile - \$(MAKE) -f \$(SRCDIR)/Makefile.shared -e \\ - PLATFORM=\$(PLATFORM) \\ - PERL="\$(PERL)" SRCDIR='\$(SRCDIR)' DSTDIR="$libd" \\ - INSTALLTOP='\$(INSTALLTOP)' LIBDIR='\$(LIBDIR)' \\ - LIBDEPS='\$(PLIB_LDFLAGS) '"$linklibs"' \$(EX_LIBS)' \\ - LIBNAME=$libname SHLIBVERSION=\$(SHLIB_MAJOR).\$(SHLIB_MINOR) \\ - STLIBNAME=$lib$libext \\ - SHLIBNAME=$target SHLIBNAME_FULL=$target_full \\ - CC='\$(CC)' CFLAGS='\$(CFLAGS) \$(LIB_CFLAGS)' \\ - LDFLAGS='\$(LDFLAGS)' SHARED_LDFLAGS='\$(LIB_LDFLAGS)' \\ - RC='\$(RC)' SHARED_RCFLAGS='\$(RCFLAGS)' \\ - link_shlib.$shlib_target +# simplest, {libname}\$(SHLIB_EXT_IMPORT) for Windows POSIX layers and +# {libname}\$(SHLIB_EXT_SIMPLE) for the Unix platforms. +$target: $deps + \$(CC) \$(LIB_CFLAGS) $linkflags\$(LIB_LDFLAGS)$shared_soname$shared_imp \\ + -o $target_full$shared_def $objs \\ + \$(PLIB_LDFLAGS) $linklibs \$(EX_LIBS) EOF - . (windowsdll() ? <<"EOF" : ""); - rm -f apps/$shlib$shlibext - rm -f test/$shlib$shlibext - rm -f fuzz/$shlib$shlibext - cp -p $shlib$shlibext apps/ - cp -p $shlib$shlibext test/ - cp -p $shlib$shlibext fuzz/ + if (windowsdll()) { + $recipe .= <<"EOF"; + rm -f apps/$shlib'\$(SHLIB_EXT)' + rm -f test/$shlib'\$(SHLIB_EXT)' + rm -f fuzz/$shlib'\$(SHLIB_EXT)' + cp -p $shlib'\$(SHLIB_EXT)' apps/ + cp -p $shlib'\$(SHLIB_EXT)' test/ + cp -p $shlib'\$(SHLIB_EXT)' fuzz/ EOF + } else { + $recipe .= <<"EOF"; + if [ '$target' != '$target_full' ]; then \\ + rm -f $target; \\ + ln -s $target_full $target; \\ + fi +EOF + } } sub obj2dso { my %args = @_; my $dso = $args{lib}; my $dsod = dirname($dso); my $dson = basename($dso); - my $shlibdeps = join("", map { my $d = dirname($_); - my $f = basename($_); - (my $l = $f) =~ s/^lib//; - " -L$d -l$l" } @{$args{deps}}); - my $deps = join(" ",compute_lib_depends(@{$args{deps}})); - my $shlib_target = $target{shared_target}; - my $objs = join(" ", map { $_.$objext } @{$args{objs}}); + my @linkdirs = (); + foreach (@{args{deps}}) { + my $d = dirname($_); + push @linkdirs, $d unless grep { $d eq $_ } @linkdirs; + } + my $linkflags = join("", map { "-L$_ " } @linkdirs); + my $linklibs = join("", map { my $f = basename($_); + (my $l = $f) =~ s/^lib//; + " -l$l" } @{$args{deps}}); + my @objs = map { (my $x = $_) =~ s|\.o$|$objext|; $x } @{$args{objs}}; + my @deps = compute_lib_depends(@{$args{deps}}); + my $objs = join(" ", @objs); + my $deps = join(" ", @deps); my $target = dso($dso); return <<"EOF"; $target: $objs $deps - \$(MAKE) -f \$(SRCDIR)/Makefile.shared -e \\ - PLATFORM=\$(PLATFORM) \\ - PERL="\$(PERL)" SRCDIR='\$(SRCDIR)' DSTDIR="$dsod" \\ - LIBDEPS='\$(PLIB_LDFLAGS) '"$shlibdeps"' \$(EX_LIBS)' \\ - SHLIBNAME_FULL=$target LDFLAGS='\$(LDFLAGS)' \\ - CC='\$(CC)' CFLAGS='\$(CFLAGS) \$(DSO_CFLAGS)' \\ - SHARED_LDFLAGS='\$(DSO_LDFLAGS)' \\ - LIBEXTRAS="$objs" \\ - link_dso.$shlib_target + \$(CC) \$(DSO_CFLAGS) $linkflags\$(DSO_LDFLAGS) \\ + -o $target $objs \\ + \$(PLIB_LDFLAGS) $linklibs \$(EX_LIBS) EOF } sub obj2lib { my %args = @_; - my $lib = $args{lib}; - my $objs = join(" ", map { $_.$objext } @{$args{objs}}); + (my $lib = $args{lib}) =~ s/\.a$//; + my @objs = map { (my $x = $_) =~ s|\.o$|$objext|; $x } @{$args{objs}}; + my $objs = join(" ", @objs); return <<"EOF"; $lib$libext: $objs - \$(AR) \$\@ \$\? + \$(AR) \$(ARFLAGS) \$\@ \$\? \$(RANLIB) \$\@ || echo Never mind. EOF } @@ -974,24 +1082,36 @@ EOF my $bin = $args{bin}; my $bind = dirname($bin); my $binn = basename($bin); - my $objs = join(" ", map { $_.$objext } @{$args{objs}}); + my $objs = join(" ", map { (my $x = $_) =~ s|\.o$|$objext|; $x } + @{$args{objs}}); my $deps = join(" ",compute_lib_depends(@{$args{deps}})); - my $linklibs = join("", map { my $d = dirname($_); - my $f = basename($_); - $d = "." if $d eq $f; - (my $l = $f) =~ s/^lib//; - " -L$d -l$l" } @{$args{deps}}); - my $shlib_target = $disabled{shared} ? "" : $target{shared_target}; + my @linkdirs = (); + foreach (@{args{deps}}) { + next if $_ =~ /\.a$/; + my $d = dirname($_); + push @linkdirs, $d unless grep { $d eq $_ } @linkdirs; + } + my $linkflags = join("", map { "-L$_ " } @linkdirs); + my $linklibs = join("", map { if ($_ =~ /\.a$/) { + " $_"; + } else { + my $f = basename($_); + (my $l = $f) =~ s/^lib//; + " -l$l" + } + } @{$args{deps}}); + my $cmd = '$(CC)'; + my $cmdflags = '$(BIN_CFLAGS)'; + if (grep /_cc\.o$/, @{$args{objs}}) { + $cmd = '$(CXX)'; + $cmdflags = '$(BIN_CXXFLAGS)'; + } return <<"EOF"; $bin$exeext: $objs $deps - \$(RM) $bin$exeext - \$(MAKE) -f \$(SRCDIR)/Makefile.shared -e \\ - PERL="\$(PERL)" SRCDIR=\$(SRCDIR) \\ - APPNAME=$bin$exeext OBJECTS="$objs" \\ - LIBDEPS='\$(PLIB_LDFLAGS) '"$linklibs"' \$(EX_LIBS)' \\ - CC='\$(CC)' CFLAGS='\$(CFLAGS) \$(BIN_CFLAGS)' \\ - LDFLAGS='\$(LDFLAGS)' \\ - link_app.$shlib_target + rm -f $bin$exeext + \$\${LDCMD:-$cmd} $cmdflags $linkflags\$(BIN_LDFLAGS) \\ + -o $bin$exeext $objs \\ + \$(PLIB_LDFLAGS) $linklibs \$(EX_LIBS) EOF } sub in2script { diff --git a/Configurations/windows-checker.pm b/Configurations/windows-checker.pm index de46fbc1..4b7105df 100644 --- a/Configurations/windows-checker.pm +++ b/Configurations/windows-checker.pm @@ -6,7 +6,7 @@ use Config; # we expect for the platform use File::Spec::Functions qw(:DEFAULT rel2abs); -if (rel2abs('.') !~ m|\\|) { +if (!$ENV{CONFIGURE_INSIST} && rel2abs('.') !~ m|\\|) { die <[2] eq "VC-W32" ? @@ -31,14 +32,20 @@ $win_commonroot = $ENV{$win_commonroot}; sub shlib { - return () if $disabled{shared}; my $lib = shift; + return () if $disabled{shared} || $lib =~ /\.a$/; + return () unless defined $unified_info{sharednames}->{$lib}; return $unified_info{sharednames}->{$lib} . $shlibext; } + sub lib { + (my $lib = shift) =~ s/\.a$//; + return $lib . $libext; + } + sub shlib_import { - return () if $disabled{shared}; my $lib = shift; + return () if $disabled{shared} || $lib =~ /\.a$/; return $lib . $shlibextimport; } @@ -52,7 +59,7 @@ sub dependmagic { my $target = shift; - return "$target: build_generated\n\t\$(MAKE) depend && \$(MAKE) _$target\n_$target"; + return "$target: build_generated\n\t\$(MAKE) /\$(MAKEFLAGS) depend && \$(MAKE) /\$(MAKEFLAGS) _$target\n_$target"; } ''; -} @@ -67,7 +74,7 @@ MINOR={- $config{minor} -} SHLIB_VERSION_NUMBER={- $config{shlib_version_number} -} -LIBS={- join(" ", map { $_.$libext } @{$unified_info{libraries}}) -} +LIBS={- join(" ", map { lib($_) } @{$unified_info{libraries}}) -} SHLIBS={- join(" ", map { shlib($_) } @{$unified_info{libraries}}) -} SHLIBPDBS={- join(" ", map { local $shlibext = ".pdb"; shlib($_) } @{$unified_info{libraries}}) -} ENGINES={- join(" ", map { dso($_) } @{$unified_info{engines}}) -} @@ -88,7 +95,7 @@ GENERATED={- join(" ", grep { /\.o$/ } keys %{$unified_info{sources}} ), ( grep { /\.h$/ } keys %{$unified_info{generate}} )) -} -INSTALL_LIBS={- join(" ", map { $_.$libext } @{$unified_info{install}->{libraries}}) -} +INSTALL_LIBS={- join(" ", map { lib($_) } @{$unified_info{install}->{libraries}}) -} INSTALL_SHLIBS={- join(" ", map { shlib($_) } @{$unified_info{install}->{libraries}}) -} INSTALL_SHLIBPDBS={- join(" ", map { local $shlibext = ".pdb"; shlib($_) } @{$unified_info{install}->{libraries}}) -} INSTALL_ENGINES={- join(" ", map { dso($_) } @{$unified_info{install}->{engines}}) -} @@ -116,7 +123,7 @@ INSTALLTOP_dev={- # $prefix is used in the OPENSSLDIR perl snippet INSTALLTOP_dir={- canonpath($prefix_dir) -} OPENSSLDIR_dev={- # # The logic here is that if no --openssldir was given, - # OPENSSLDIR will get the value from $prefix plus "/ssl". + # OPENSSLDIR will get the value "$win_commonroot\\SSL". # If --openssldir was given and the value is an absolute # path, OPENSSLDIR will get its value without change. # If the value from --openssldir is a relative path, @@ -135,9 +142,9 @@ OPENSSLDIR_dev={- # $openssldir_dev -} OPENSSLDIR_dir={- canonpath($openssldir_dir) -} LIBDIR={- our $libdir = $config{libdir} || "lib"; - $libdir -} + file_name_is_absolute($libdir) ? "" : $libdir -} ENGINESDIR_dev={- use File::Spec::Functions qw(:DEFAULT splitpath); - our $enginesdir = catdir($prefix,$libdir,"engines-$sover"); + our $enginesdir = catdir($prefix,$libdir,"engines-$sover_dirname"); our ($enginesdir_dev, $enginesdir_dir, $enginesdir_file) = splitpath($enginesdir, 1); $enginesdir_dev -} @@ -152,35 +159,53 @@ OPENSSLDIR=$(OPENSSLDIR_dev)$(OPENSSLDIR_dir) ENGINESDIR=$(ENGINESDIR_dev)$(ENGINESDIR_dir) !ENDIF -CC={- $target{cc} -} -CFLAGS={- join(" ",(map { "-D".$_} @{$target{defines}}, @{$config{defines}})) -} {- join(" ", quotify_l("-DENGINESDIR=\"$enginesdir\"", "-DOPENSSLDIR=\"$openssldir\"")) -} {- $target{cflags} -} {- $config{cflags} -} +# $(libdir) is chosen to be compatible with the GNU coding standards +libdir={- file_name_is_absolute($libdir) + ? $libdir : '$(INSTALLTOP)\$(LIBDIR)' -} + +CC={- $config{cc} -} +CPP={- $config{cpp} -} +CPPFLAGS={- our $cppflags = join(" ", + (map { "-D".$_} @{$config{defines}}), + (map { " /I ".$_} @{$config{includes}}), + @{$config{cppflags}}) -} +CPPFLAGS_Q={- $cppflags =~ s|([\\"])|\\$1|g; $cppflags -} +CFLAGS={- join(' ', @{$config{cflags}}) -} COUTFLAG={- $target{coutflag} || "/Fo" -}$(OSSL_EMPTY) -RC={- $target{rc} || "rc" -} +RC={- $config{rc} -} RCOUTFLAG={- $target{rcoutflag} || "/fo" -}$(OSSL_EMPTY) -LD={- $target{ld} || "link" -} -LDFLAGS={- $target{lflags} -} +LD={- $config{ld} -} +LDFLAGS={- join(' ', @{$config{lflags}}) -} LDOUTFLAG={- $target{loutflag} || "/out:" -}$(OSSL_EMPTY) -EX_LIBS={- $target{ex_libs} -} -LIB_CFLAGS={- join(" ", $target{lib_cflags}, $target{shared_cflag}) || "" -} -LIB_LDFLAGS={- $target{shared_ldflag} || "" -} -DSO_CFLAGS={- join(" ", $target{dso_cflags}, $target{shared_cflag}) || "" -} -DSO_LDFLAGS={- join(" ", $target{dso_lflags}, $target{shared_ldflag}) || "" -} -BIN_CFLAGS={- $target{bin_cflags} -} -BIN_LDFLAGS={- $target{bin_lflags} -} +EX_LIBS={- join(' ', @{$config{ex_libs}}) -} + +LIB_CPPFLAGS={- join(' ', '$(CPPFLAGS)', + $target{shared_cppflag} || (), + (map { quotify_l("-D".$_) } + "OPENSSLDIR=\"$openssldir\"", + "ENGINESDIR=\"$enginesdir\"")) -} +LIB_CFLAGS={- join(' ', '$(CFLAGS)', $target{lib_cflags} || (), $target{shared_cflag} || ()) -} +LIB_LDFLAGS={- join(' ', '$(LDFLAGS)', $target{shared_ldflag} || (), $config{shared_ldflag} || ()) -} +DSO_CPPFLAGS={- join(' ', '$(CPPFLAGS)', $target{dso_cppflags} || ()) -} +DSO_CFLAGS={- join(' ', '$(CFLAGS)', $target{dso_cflags} || ()) -} +DSO_LDFLAGS={- join(' ', '$(LDFLAGS)', $target{dso_ldflag} || ()) -} +BIN_CPPFLAGS={- join(' ', '$(CPPFLAGS)', $target{dso_cppflags} || ()) -} +BIN_CFLAGS={- join(' ', '$(CFLAGS)', $target{bin_cflags} || ()) -} +BIN_LDFLAGS={- join(' ', '$(LDFLAGS)', $target{bin_lflags} || ()) -} PERL={- $config{perl} -} -AR={- $target{ar} -} -ARFLAGS= {- $target{arflags} -} +AR={- $config{ar} -} +ARFLAGS= {- join(' ', @{$config{arflags}}) -} AROUTFLAG={- $target{aroutflag} || "/out:" -}$(OSSL_EMPTY) -MT={- $target{mt} -} -MTFLAGS= {- $target{mtflags} -} +MT={- $config{mt} -} +MTFLAGS= {- join(' ', @{$config{mtflags}}) -} MTINFLAG={- $target{mtinflag} || "-manifest " -}$(OSSL_EMPTY) MTOUTFLAG={- $target{mtoutflag} || "-outputresource:" -}$(OSSL_EMPTY) -AS={- $target{as} -} -ASFLAGS={- $target{asflags} -} +AS={- $config{as} -} +ASFLAGS={- join(' ', @{$config{asflags}}) -} ASOUTFLAG={- $target{asoutflag} -}$(OSSL_EMPTY) PERLASM_SCHEME= {- $target{perlasm_scheme} -} @@ -248,7 +273,9 @@ clean: libclean -del /Q /S /F *.d -del /Q /S /F *.obj -del /Q /S /F *.pdb - -del /Q /S /F *.exp + -del /Q /F *.exp + -del /Q /F apps\*.exp + -del /Q /F engines\*.exp -del /Q /S /F engines\*.ilk -del /Q /S /F engines\*.lib -del /Q /S /F apps\*.lib @@ -283,25 +310,28 @@ install_ssldirs: "$(OPENSSLDIR)\openssl.cnf" @"$(PERL)" "$(SRCDIR)\util\copy.pl" $(MISC_SCRIPTS) \ "$(OPENSSLDIR)\misc" + @"$(PERL)" "$(SRCDIR)\util\copy.pl" "$(SRCDIR)\apps\ct_log_list.cnf" \ + "$(OPENSSLDIR)\ct_log_list.cnf.dist" + @IF NOT EXIST "$(OPENSSLDIR)\ct_log_list.cnf" \ + "$(PERL)" "$(SRCDIR)\util\copy.pl" "$(SRCDIR)\apps\ct_log_list.cnf" \ + "$(OPENSSLDIR)\ct_log_list.cnf" install_dev: @if "$(INSTALLTOP)"=="" ( echo INSTALLTOP should not be empty & exit 1 ) @echo *** Installing development files @"$(PERL)" "$(SRCDIR)\util\mkdir-p.pl" "$(INSTALLTOP)\include\openssl" - @rem {- output_off() unless grep { $_ eq "OPENSSL_USE_APPLINK" } @{$target{defines}}; "" -} + @rem {- output_off() unless grep { $_ eq "OPENSSL_USE_APPLINK" } @{$config{defines}}; "" -} @"$(PERL)" "$(SRCDIR)\util\copy.pl" "$(SRCDIR)\ms\applink.c" \ "$(INSTALLTOP)\include\openssl" - @rem {- output_on() unless grep { $_ eq "OPENSSL_USE_APPLINK" } @{$target{defines}}; "" -} + @rem {- output_on() unless grep { $_ eq "OPENSSL_USE_APPLINK" } @{$config{defines}}; "" -} @"$(PERL)" "$(SRCDIR)\util\copy.pl" "$(SRCDIR)\include\openssl\*.h" \ "$(INSTALLTOP)\include\openssl" @"$(PERL)" "$(SRCDIR)\util\copy.pl" $(BLDDIR)\include\openssl\*.h \ "$(INSTALLTOP)\include\openssl" - @"$(PERL)" "$(SRCDIR)\util\mkdir-p.pl" "$(INSTALLTOP)\$(LIBDIR)" - @"$(PERL)" "$(SRCDIR)\util\copy.pl" $(INSTALL_LIBS) \ - "$(INSTALLTOP)\$(LIBDIR)" + @"$(PERL)" "$(SRCDIR)\util\mkdir-p.pl" "$(libdir)" + @"$(PERL)" "$(SRCDIR)\util\copy.pl" $(INSTALL_LIBS) "$(libdir)" @if "$(SHLIBS)"=="" \ - "$(PERL)" "$(SRCDIR)\util\copy.pl" ossl_static.pdb \ - "$(INSTALLTOP)\$(LIBDIR)" + "$(PERL)" "$(SRCDIR)\util\copy.pl" ossl_static.pdb "$(libdir)" uninstall_dev: @@ -344,8 +374,7 @@ uninstall_html_docs: configdata.pm: "$(SRCDIR)\Configure" {- join(" ", map { '"'.$_.'"' } @{$config{build_file_templates}}, @{$config{build_infos}}, @{$config{conf_files}}) -} @echo "Detected changed: $?" - @echo "Reconfiguring..." - "$(PERL)" "$(SRCDIR)\Configure" reconf + "$(PERL)" configdata.pm -r @echo "**************************************************" @echo "*** ***" @echo "*** Please run the same make command again ***" @@ -353,6 +382,9 @@ configdata.pm: "$(SRCDIR)\Configure" {- join(" ", map { '"'.$_.'"' } @{$config{b @echo "**************************************************" @exit 1 +reconfigure reconf: + "$(PERL)" configdata.pm -r + {- use File::Basename; use File::Spec::Functions qw/:DEFAULT abs2rel rel2abs/; @@ -361,16 +393,20 @@ configdata.pm: "$(SRCDIR)\Configure" {- join(" ", map { '"'.$_.'"' } @{$config{b # It takes a list of library names and outputs a list of dependencies sub compute_lib_depends { if ($disabled{shared}) { - return map { $_.$libext } @_; + return map { lib($_) } @_; } - return map { shlib_import($_) } @_; + foreach (@_) { + (my $l = $_) =~ s/\.a$//; + die "Linking with static variants of shared libraries is not supported in this configuration\n" + if $l ne $_ && shlib($l); + } + return map { shlib_import($_) or lib($_) } @_; } sub generatesrc { my %args = @_; (my $target = $args{src}) =~ s/\.[sS]$/.asm/; - my ($gen0, @gens) = @{$args{generator}}; - my $generator = '"'.$gen0.'"'.join('', map { " $_" } @gens); + my $generator = '"'.join('" "', @{$args{generator}}).'"'; my $generator_incs = join("", map { " -I \"$_\"" } @{$args{generator_incs}}); my $incs = join("", map { " /I \"$_\"" } @{$args{incs}}); my $deps = @{$args{deps}} ? @@ -401,6 +437,12 @@ EOF die "Generator type for $src unknown: $generator\n"; } + my $cppflags = $incs; + $cppflags .= { + lib => ' $(LIB_CFLAGS) $(LIB_CPPFLAGS)', + dso => ' $(DSO_CFLAGS) $(DSO_CPPFLAGS)', + bin => ' $(BIN_CFLAGS) $(BIN_CPPFLAGS)' + } -> {$args{intent}}; if (defined($generator)) { # If the target is named foo.S in build.info, we want to # end up generating foo.s in two steps. @@ -409,7 +451,7 @@ EOF $target: "$args{generator}->[0]" $deps set ASM=\$(AS) $generator \$@.S - \$(CC) $incs \$(CFLAGS) /EP /C \$@.S > \$@.i && move /Y \$@.i \$@ + \$(CPP) $cppflags \$@.S > \$@.i && move /Y \$@.i \$@ del /Q \$@.S EOF } @@ -422,28 +464,33 @@ EOF } return <<"EOF"; $target: "$args{generator}->[0]" $deps - \$(CC) $incs \$(CFLAGS) /EP /C "$args{generator}->[0]" > \$@.i && move /Y \$@.i \$@ + \$(CPP) $incs $cppflags "$args{generator}->[0]" > \$@.i && move /Y \$@.i \$@ EOF } } sub src2obj { my %args = @_; - my $obj = $args{obj}; my @srcs = map { (my $x = $_) =~ s/\.s$/.asm/; $x } ( @{$args{srcs}} ); my $srcs = '"'.join('" "', @srcs).'"'; my $deps = '"'.join('" "', @srcs, @{$args{deps}}).'"'; my $incs = join("", map { ' /I "'.$_.'"' } @{$args{incs}}); - unless ($disabled{zlib}) { - if ($withargs{zlib_include}) { - $incs .= ' /I "'.$withargs{zlib_include}.'"'; - } - } - my $ecflags = { lib => '$(LIB_CFLAGS)', - dso => '$(DSO_CFLAGS)', - bin => '$(BIN_CFLAGS)' } -> {$args{intent}}; + my $cflags = { lib => ' $(LIB_CFLAGS)', + dso => ' $(DSO_CFLAGS)', + bin => ' $(BIN_CFLAGS)' } -> {$args{intent}}; + $cflags .= $incs; + $cflags .= { lib => ' $(LIB_CPPFLAGS)', + dso => ' $(DSO_CPPFLAGS)', + bin => ' $(BIN_CPPFLAGS)' } -> {$args{intent}}; my $makedepprog = $config{makedepprog}; + if ($srcs[0] =~ /\.rc$/) { + return <<"EOF"; +$args{obj}: $deps + \$(RC) \$(RCOUTFLAG)\$\@ $srcs +EOF + } + (my $obj = $args{obj}) =~ s|\.o$||; if ($srcs[0] =~ /\.asm$/) { return <<"EOF"; $obj$objext: $deps @@ -452,7 +499,7 @@ EOF } return <<"EOF" if (!$disabled{makedepend}); $obj$depext: $deps - \$(CC) \$(CFLAGS) $ecflags$inc /Zs /showIncludes $srcs 2>&1 | \\ + \$(CC) $cflags /Zs /showIncludes $srcs 2>&1 | \\ "\$(PERL)" -n << > $obj$depext chomp; s/^Note: including file: *//; @@ -460,11 +507,13 @@ s/^Note: including file: *//; END { print '$obj$objext: ',join(" ", sort keys \%collect),"\\n" } << $obj$objext: $obj$depext - \$(CC) $incs \$(CFLAGS) $ecflags -c \$(COUTFLAG)\$\@ $srcs + \$(CC) $cflags -c \$(COUTFLAG)\$\@ @<< +$srcs +<< EOF return <<"EOF" if ($disabled{makedepend}); $obj$objext: $deps - \$(CC) $incs \$(CFLAGS) $ecflags -c \$(COUTFLAG)\$\@ $srcs + \$(CC) $cflags -c \$(COUTFLAG)\$\@ $srcs EOF } @@ -475,32 +524,24 @@ EOF my %args = @_; my $lib = $args{lib}; my $shlib = $args{shlib}; - (my $mkdef_key = $lib) =~ s/^lib//i; - my $objs = join("\n", map { $_.$objext } @{$args{objs}}); - my $linklibs = join("", - map { "\n$_" } compute_lib_depends(@{$args{deps}})); - my $deps = join(" ", - (map { $_.$objext } @{$args{objs}}), - compute_lib_depends(@{$args{deps}})); - my $ordinalsfile = defined($args{ordinals}) ? $args{ordinals}->[1] : ""; - my $mkdef_pl = abs2rel(rel2abs(catfile($config{sourcedir}, - "util", "mkdef.pl")), - rel2abs($config{builddir})); - my $mkrc_pl = abs2rel(rel2abs(catfile($config{sourcedir}, - "util", "mkrc.pl")), - rel2abs($config{builddir})); + my @objs = map { (my $x = $_) =~ s|\.o$|$objext|; $x } + grep { $_ =~ m/\.(?:o|res)$/ } + @{$args{objs}}; + my @defs = grep { $_ =~ /\.def$/ } @{$args{objs}}; + my @deps = compute_lib_depends(@{$args{deps}}); + die "More than one exported symbols list" if scalar @defs > 1; + my $linklibs = join("", map { "$_\n" } @deps); + my $objs = join("\n", @objs); + my $deps = join(" ", @objs, @defs, @deps); my $target = shlib_import($lib); + my $shared_def = join("", map { " /def:$_" } @defs); return <<"EOF" -$target: $deps "$ordinalsfile" "$mkdef_pl" - "\$(PERL)" "$mkdef_pl" "$mkdef_key" 32 > $shlib.def - "\$(PERL)" -i.tmp -pe "s|^LIBRARY\\s+${mkdef_key}32|LIBRARY $shlib|;" $shlib.def - DEL $shlib.def.tmp - "\$(PERL)" "$mkrc_pl" $shlib$shlibext > $shlib.rc - \$(RC) \$(RCOUTFLAG)$shlib.res $shlib.rc +$target: $deps IF EXIST $shlib$shlibext.manifest DEL /F /Q $shlib$shlibext.manifest \$(LD) \$(LDFLAGS) \$(LIB_LDFLAGS) \\ - /implib:\$@ \$(LDOUTFLAG)$shlib$shlibext /def:$shlib.def @<< || (DEL /Q \$(\@B).* $shlib.* && EXIT 1) -$objs $shlib.res$linklibs \$(EX_LIBS) + /implib:\$@ \$(LDOUTFLAG)$shlib$shlibext$shared_def @<< || (DEL /Q \$(\@B).* $shlib.* && EXIT 1) +$objs +$linklibs\$(EX_LIBS) << IF EXIST $shlib$shlibext.manifest \\ \$(MT) \$(MTFLAGS) \$(MTINFLAG)$shlib$shlibext.manifest \$(MTOUTFLAG)$shlib$shlibext @@ -516,12 +557,11 @@ EOF my %args = @_; my $dso = $args{lib}; my $dso_n = basename($dso); - my $objs = join("\n", map { $_.$objext } @{$args{objs}}); - my $linklibs = join("", - map { "\n$_" } compute_lib_depends(@{$args{deps}})); - my $deps = join(" ", - (map { $_.$objext } @{$args{objs}}), - compute_lib_depends(@{$args{deps}})); + my @objs = map { (my $x = $_) =~ s|\.o$|$objext|; $x } @{$args{objs}}; + my @deps = compute_lib_depends(@{$args{deps}}); + my $objs = join("\n", @objs); + my $linklibs = join("", map { "$_\n" } @deps); + my $deps = join(" ", @objs, @deps); return <<"EOF"; $dso$dsoext: $deps IF EXIST $dso$dsoext.manifest DEL /F /Q $dso$dsoext.manifest @@ -531,43 +571,48 @@ EXPORTS bind_engine @1 v_check @2 << -$objs$linklibs \$(EX_LIBS) +$objs +$linklibs \$(EX_LIBS) << IF EXIST $dso$dsoext.manifest \\ \$(MT) \$(MTFLAGS) \$(MTINFLAG)$dso$dsoext.manifest \$(MTOUTFLAG)$dso$dsoext EOF } sub obj2lib { + my %args = @_; + my $lib = $args{lib}; + # Because static libs and import libs are both named the same in native # Windows, we can't have both. We skip the static lib in that case, # as the shared libs are what we use anyway. - return "" unless $disabled{"shared"}; + return "" unless $disabled{"shared"} || $lib =~ /\.a$/; - my %args = @_; - my $lib = $args{lib}; - my $objs = join("\n", map { $_.$objext } @{$args{objs}}); - my $deps = join(" ", map { $_.$objext } @{$args{objs}}); + $lib =~ s/\.a$//; + my @objs = map { (my $x = $_) =~ s|\.o$|$objext|; $x } @{$args{objs}}; + my $objs = join("\n", @objs); + my $deps = join(" ", @objs); return <<"EOF"; $lib$libext: $deps \$(AR) \$(ARFLAGS) \$(AROUTFLAG)$lib$libext @<< -\$** +$objs << EOF } sub obj2bin { my %args = @_; my $bin = $args{bin}; - my $objs = join("\n", map { $_.$objext } @{$args{objs}}); - my $linklibs = join("", - map { "\n$_" } compute_lib_depends(@{$args{deps}})); - my $deps = join(" ", - (map { $_.$objext } @{$args{objs}}), - compute_lib_depends(@{$args{deps}})); + my @objs = map { (my $x = $_) =~ s|\.o$|$objext|; $x } @{$args{objs}}; + my @deps = compute_lib_depends(@{$args{deps}}); + my $objs = join("\n", @objs); + my $linklibs = join("", map { "$_\n" } @deps); + my $deps = join(" ", @objs, @deps); return <<"EOF"; $bin$exeext: $deps IF EXIST $bin$exeext.manifest DEL /F /Q $bin$exeext.manifest \$(LD) \$(LDFLAGS) \$(BIN_LDFLAGS) \$(LDOUTFLAG)$bin$exeext @<< -$objs setargv.obj$linklibs \$(EX_LIBS) +$objs +setargv.obj +$linklibs\$(EX_LIBS) << IF EXIST $bin$exeext.manifest \\ \$(MT) \$(MTFLAGS) \$(MTINFLAG)$bin$exeext.manifest \$(MTOUTFLAG)$bin$exeext diff --git a/Configure b/Configure index c0033643..3c40a0e2 100755 --- a/Configure +++ b/Configure @@ -11,6 +11,7 @@ use 5.10.0; use strict; +use Config; use FindBin; use lib "$FindBin::Bin/util/perl"; use File::Basename; @@ -103,23 +104,25 @@ my $usage="Usage: Configure [no- ...] [enable- ...] [-Dxxx] [-lx # past these. # DEBUG_UNUSED enables __owur (warn unused result) checks. +# -DPEDANTIC complements -pedantic and is meant to mask code that +# is not strictly standard-compliant and/or implementation-specific, +# e.g. inline assembly, disregards to alignment requirements, such +# that -pedantic would complain about. Incidentally -DPEDANTIC has +# to be used even in sanitized builds, because sanitizer too is +# supposed to and does take notice of non-standard behaviour. Then +# -pedantic with pre-C9x compiler would also complain about 'long +# long' not being supported. As 64-bit algorithms are common now, +# it grew impossible to resolve this without sizeable additional +# code, so we just tell compiler to be pedantic about everything +# but 'long long' type. + my $gcc_devteam_warn = "-DDEBUG_UNUSED" - # -DPEDANTIC complements -pedantic and is meant to mask code that - # is not strictly standard-compliant and/or implementation-specific, - # e.g. inline assembly, disregards to alignment requirements, such - # that -pedantic would complain about. Incidentally -DPEDANTIC has - # to be used even in sanitized builds, because sanitizer too is - # supposed to and does take notice of non-standard behaviour. Then - # -pedantic with pre-C9x compiler would also complain about 'long - # long' not being supported. As 64-bit algorithms are common now, - # it grew impossible to resolve this without sizeable additional - # code, so we just tell compiler to be pedantic about everything - # but 'long long' type. . " -DPEDANTIC -pedantic -Wno-long-long" . " -Wall" . " -Wextra" . " -Wno-unused-parameter" . " -Wno-missing-field-initializers" + . " -Wswitch" . " -Wsign-compare" . " -Wmissing-prototypes" . " -Wshadow" @@ -132,19 +135,20 @@ my $gcc_devteam_warn = "-DDEBUG_UNUSED" # 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: -# -Wswitch-enum # -Wcast-align -# -Wunreachable-code +# -Wunreachable-code -- no, too ugly/compiler-specific # -Wlanguage-extension-token -- no, we use asm() # -Wunused-macros -- no, too tricky for BN and _XOPEN_SOURCE etc # -Wextended-offsetof -- no, needed in CMS ASN1 code my $clang_devteam_warn = "" - . " -Qunused-arguments" + . " -Wswitch-default" + . " -Wno-parentheses-equality" . " -Wno-language-extension-token" . " -Wno-extended-offsetof" . " -Wconditional-uninitialized" . " -Wincompatible-pointer-types-discards-qualifiers" . " -Wmissing-variable-declarations" + . " -Wno-unknown-warning-option" ; # This adds backtrace information to the memory leak info. Is only used @@ -207,6 +211,8 @@ $config{builddir} = abs2rel($blddir); my @argvcopy=@ARGV; if (grep /^reconf(igure)?$/, @argvcopy) { + die "reconfiguring with other arguments present isn't supported" + if scalar @argvcopy > 1; if (-f "./configdata.pm") { my $file = "./configdata.pm"; unless (my $return = do $file) { @@ -219,22 +225,7 @@ if (grep /^reconf(igure)?$/, @argvcopy) { @{$configdata::config{perlargv}} : (); die "Incorrect data to reconfigure, please do a normal configuration\n" if (grep(/^reconf/,@argvcopy)); - $ENV{CROSS_COMPILE} = $configdata::config{cross_compile_prefix} - if defined($configdata::config{cross_compile_prefix}); - $ENV{CC} = $configdata::config{cc} - if defined($configdata::config{cc}); - $ENV{BUILDFILE} = $configdata::config{build_file} - if defined($configdata::config{build_file}); - $ENV{$local_config_envname} = $configdata::config{local_config_dir} - if defined($configdata::config{local_config_dir}); - - print "Reconfiguring with: ", join(" ",@argvcopy), "\n"; - print " CROSS_COMPILE = ",$ENV{CROSS_COMPILE},"\n" - if $ENV{CROSS_COMPILE}; - print " CC = ",$ENV{CC},"\n" if $ENV{CC}; - print " BUILDFILE = ",$ENV{BUILDFILE},"\n" if $ENV{BUILDFILE}; - print " $local_config_envname = ",$ENV{$local_config_envname},"\n" - if $ENV{$local_config_envname}; + $config{perlenv} = $configdata::config{perlenv} // {}; } else { die "Insufficient data to reconfigure, please do a normal configuration\n"; } @@ -273,13 +264,13 @@ foreach (sort glob($pattern)) { &read_config($_); } -if (defined $ENV{$local_config_envname}) { +if (defined env($local_config_envname)) { if ($^O eq 'VMS') { # VMS environment variables are logical names, # which can be used as is $pattern = $local_config_envname . ':' . '*.conf'; } else { - $pattern = catfile($ENV{$local_config_envname}, '*.conf'); + $pattern = catfile(env($local_config_envname), '*.conf'); } foreach (sort glob($pattern)) { @@ -287,36 +278,35 @@ if (defined $ENV{$local_config_envname}) { } } - -print "Configuring OpenSSL version $config{version} ($config{version_num})\n"; +# Save away perl command information +$config{perl_cmd} = $^X; +$config{perl_version} = $Config{version}; +$config{perl_archname} = $Config{archname}; $config{prefix}=""; $config{openssldir}=""; $config{processor}=""; $config{libdir}=""; -$config{cross_compile_prefix}=""; -$config{fipslibdir}="/usr/local/ssl/fips-2.0/lib/"; -my $nofipscanistercheck=0; -$config{baseaddr}="0xFB00000"; my $auto_threads=1; # enable threads automatically? true by default my $default_ranlib; -$config{fips}=0; # Top level directories to build $config{dirs} = [ "crypto", "ssl", "engines", "apps", "test", "util", "tools", "fuzz" ]; # crypto/ subdirectories to build $config{sdirs} = [ "objects", - "md2", "md4", "md5", "sha", "mdc2", "hmac", "ripemd", "whrlpool", "poly1305", "blake2", - "des", "aes", "rc2", "rc4", "rc5", "idea", "bf", "cast", "camellia", "seed", "chacha", "modes", + "md2", "md4", "md5", "sha", "mdc2", "hmac", "ripemd", "whrlpool", "poly1305", "blake2", "siphash", "sm3", + "des", "aes", "rc2", "rc4", "rc5", "idea", "aria", "bf", "cast", "camellia", "seed", "sm4", "chacha", "modes", "bn", "ec", "rsa", "dsa", "dh", "dso", "engine", "buffer", "bio", "stack", "lhash", "rand", "err", "evp", "asn1", "pem", "x509", "x509v3", "conf", "txt_db", "pkcs7", "pkcs12", "comp", "ocsp", "ui", - "cms", "ts", "srp", "cmac", "ct", "async", "kdf" + "cms", "ts", "srp", "cmac", "ct", "async", "kdf", "store" ]; +# test/ subdirectories to build +$config{tdirs} = [ "ossl_shim" ]; # Known TLS and DTLS protocols -my @tls = qw(ssl3 tls1 tls1_1 tls1_2); +my @tls = qw(ssl3 tls1 tls1_1 tls1_2 tls1_3); my @dtls = qw(dtls1 dtls1_2); # Explicitly known options that are possible to disable. They can @@ -325,6 +315,7 @@ my @dtls = qw(dtls1 dtls1_2); my @disablables = ( "afalgeng", + "aria", "asan", "asm", "async", @@ -344,6 +335,7 @@ my @disablables = ( "ct", "deprecated", "des", + "devcryptoeng", "dgram", "dh", "dsa", @@ -358,6 +350,7 @@ my @disablables = ( "egd", "engine", "err", + "external-tests", "filenames", "fuzz-libfuzzer", "fuzz-afl", @@ -388,6 +381,9 @@ my @disablables = ( "sctp", "seed", "shared", + "siphash", + "sm3", + "sm4", "sock", "srp", "srtp", @@ -396,11 +392,13 @@ my @disablables = ( "ssl-trace", "static-engine", "stdio", + "tests", "threads", "tls", + "tls13downgrade", "ts", "ubsan", - "ui", + "ui-console", "unit-test", "whirlpool", "weak-ssl-ciphers", @@ -410,13 +408,14 @@ my @disablables = ( foreach my $proto ((@tls, @dtls)) { push(@disablables, $proto); - push(@disablables, "$proto-method"); + push(@disablables, "$proto-method") unless $proto eq "tls1_3"; } my %deprecated_disablables = ( "ssl2" => undef, "buf-freelists" => undef, - "ripemd" => "rmd160" + "ripemd" => "rmd160", + "ui" => "ui-console", ); # All of the following is disabled by default (RC5 was enabled before 0.9.8): @@ -425,8 +424,10 @@ our %disabled = ( # "what" => "comment" "asan" => "default", "crypto-mdebug" => "default", "crypto-mdebug-backtrace" => "default", + "devcryptoeng" => "default", "ec_nistp_64_gcc_128" => "default", "egd" => "default", + "external-tests" => "default", "fuzz-libfuzzer" => "default", "fuzz-afl" => "default", "heartbeats" => "default", @@ -438,6 +439,7 @@ our %disabled = ( # "what" => "comment" "ssl3" => "default", "ssl3-method" => "default", "ubsan" => "default", + "tls13downgrade" => "default", "unit-test" => "default", "weak-ssl-ciphers" => "default", "zlib" => "default", @@ -473,14 +475,16 @@ my @disable_cascades = ( # Without position independent code, there can be no shared libraries or DSOs "pic" => [ "shared" ], "shared" => [ "dynamic-engine" ], - "engine" => [ "afalgeng" ], + "engine" => [ "afalgeng", "devcryptoeng" ], # no-autoalginit is only useful when building non-shared "autoalginit" => [ "shared", "apps" ], "stdio" => [ "apps", "capieng", "egd" ], "apps" => [ "tests" ], - "comp" => [ "zlib" ], + "tests" => [ "external-tests" ], + "comp" => [ "zlib" ], + "ec" => [ "tls1_3" ], sub { !$disabled{"unit-test"} } => [ "heartbeats" ], sub { !$disabled{"msan"} } => [ "asm" ], @@ -510,23 +514,104 @@ while ((my $first, my $second) = (shift @list, shift @list)) { &usage if ($#ARGV < 0); -my $user_cflags=""; -my @user_defines=(); +# For the "make variables" CINCLUDES and CDEFINES, we support lists with +# platform specific list separators. Users from those platforms should +# recognise those separators from how you set up the PATH to find executables. +# The default is the Unix like separator, :, but as an exception, we also +# support the space as separator. +my $list_separator_re = + { VMS => qr/(? qr/(? {$^O} // qr/(? undef, + ARFLAGS => [], + AS => undef, + ASFLAGS => [], + CC => undef, + CFLAGS => [], + CXX => undef, + CXXFLAGS => [], + CPP => undef, + CPPFLAGS => [], # -D, -I, -Wp, + CPPDEFINES => [], # Alternative for -D + CPPINCLUDES => [], # Alternative for -I + CROSS_COMPILE => undef, + HASHBANGPERL=> undef, + LD => undef, + LDFLAGS => [], # -L, -Wl, + LDLIBS => [], # -l + MT => undef, + MTFLAGS => [], + RANLIB => undef, + RC => undef, + RCFLAGS => [], + RM => undef, + ); +# Info about what "make variables" may be prefixed with the cross compiler +# prefix. This should NEVER mention any such variable with a list for value. +my @user_crossable = qw ( AR AS CC CXX CPP LD MT RANLIB RC ); +# The same but for flags given as Configure options. These are *additional* +# input, as opposed to the VAR=string option that override the corresponding +# config target attributes +my %useradd = ( + CPPDEFINES => [], + CPPINCLUDES => [], + CPPFLAGS => [], + CFLAGS => [], + CXXFLAGS => [], + LDFLAGS => [], + LDLIBS => [], + ); + +my %user_synonyms = ( + HASHBANGPERL=> 'PERL', + RC => 'WINDRES', + ); +my %user_to_target = ( + # If not given here, the value is the lc of the key + CPPDEFINES => 'defines', + CPPINCLUDES => 'includes', + CROSS_COMPILE => 'cross_compile_prefix', + LDFLAGS => 'lflags', + LDLIBS => 'ex_libs', + ); + $config{openssl_api_defines}=[]; $config{openssl_algorithm_defines}=[]; $config{openssl_thread_defines}=[]; $config{openssl_sys_defines}=[]; $config{openssl_other_defines}=[]; -my $libs=""; -my $target=""; $config{options}=""; $config{build_type} = "release"; +my $target=""; my %unsupported_options = (); my %deprecated_options = (); +# If you change this, update apps/version.c +my @known_seed_sources = qw(getrandom devrandom os egd none rdcpu librandom); +my @seed_sources = (); while (@argvcopy) { $_ = shift @argvcopy; + + # Support env variable assignments among the options + if (m|^(\w+)=(.+)?$|) + { + $config{perlenv}->{$1} = $2; + # Every time a variable is given as a configuration argument, + # it acts as a reset if the variable. + if (exists $user{$1}) + { + $user{$1} = ref $user{$1} eq "ARRAY" ? [] : undef; + } + if (exists $useradd{$1}) + { + $useradd{$1} = []; + } + next; + } + # VMS is a case insensitive environment, and depending on settings # out of our control, we may receive options uppercased. Let's # downcase at least the part before any equal sign. @@ -644,7 +729,7 @@ while (@argvcopy) { $config{processor}=386; } elsif (/^fips$/) { - $config{fips}=1; + die "FIPS mode not supported\n"; } elsif (/^rsaref$/) { @@ -654,8 +739,7 @@ while (@argvcopy) } elsif (/^nofipscanistercheck$/) { - $config{fips} = 1; - $nofipscanistercheck = 1; + die "FIPS mode not supported\n"; } elsif (/^[-+]/) { @@ -693,25 +777,34 @@ while (@argvcopy) { $withargs{fuzzer_include}=$1; } - elsif (/^--with-fipslibdir=(.*)$/) + elsif (/^--with-rand-seed=(.*)$/) { - $config{fipslibdir}="$1/"; - } - elsif (/^--with-baseaddr=(.*)$/) - { - $config{baseaddr}="$1"; - } + foreach my $x (split(m|,|, $1)) + { + die "Unknown --with-rand-seed choice $x\n" + if ! grep { $x eq $_ } @known_seed_sources; + push @seed_sources, $x; + } + } elsif (/^--cross-compile-prefix=(.*)$/) { - $config{cross_compile_prefix}=$1; + $user{CROSS_COMPILE}=$1; } elsif (/^--config=(.*)$/) { read_config $1; } - elsif (/^-[lL](.*)$/ or /^-Wl,/) + elsif (/^-L(.*)$/) { - $libs.=$_." "; + push @{$useradd{LDFLAGS}}, $_; + } + elsif (/^-l(.*)$/ or /^-Wl,/) + { + push @{$useradd{LDLIBS}}, $_; + } + elsif (/^-framework$/) + { + push @{$useradd{LDLIBS}}, $_, shift(@argvcopy); } elsif (/^-rpath$/ or /^-R$/) # -rpath is the OSF1 rpath flag @@ -719,11 +812,11 @@ while (@argvcopy) { my $rpath = shift(@argvcopy) || ""; $rpath .= " " if $rpath ne ""; - $libs.=$_." ".$rpath; + push @{$useradd{LDFLAGS}}, $_, $rpath; } elsif (/^-static$/) { - $libs.=$_." "; + push @{$useradd{LDFLAGS}}, $_; $disabled{"dso"} = "forced"; $disabled{"pic"} = "forced"; $disabled{"shared"} = "forced"; @@ -731,12 +824,21 @@ while (@argvcopy) } elsif (/^-D(.*)$/) { - push @user_defines, $1; + push @{$useradd{CPPDEFINES}}, $1; + } + elsif (/^-I(.*)$/) + { + push @{$useradd{CPPINCLUDES}}, $1; + } + elsif (/^-Wp,$/) + { + push @{$useradd{CPPFLAGS}}, $1; } else # common if (/^[-+]/), just pass down... { $_ =~ s/%([0-9a-f]{1,2})/chr(hex($1))/gei; - $user_cflags.=" ".$_; + push @{$useradd{CFLAGS}}, $_; + push @{$useradd{CXXFLAGS}}, $_; } } else @@ -746,7 +848,7 @@ while (@argvcopy) } unless ($_ eq $target || /^no-/ || /^disable-/) { - # "no-..." follows later after implied disactivations + # "no-..." follows later after implied deactivations # have been derived. (Don't take this too seriously, # we really only write OPTIONS to the Makefile out of # nostalgia.) @@ -773,22 +875,26 @@ while (@argvcopy) } } -if ($libs =~ /(^|\s)-Wl,-rpath,/ +foreach (keys %user) { + my $value = env($_); + $value //= defined $user_synonyms{$_} ? env($user_synonyms{$_}) : undef; + + if (defined $value) { + if (ref $user{$_} eq 'ARRAY') { + $user{$_} = [ split /$list_separator_re/, $value ]; + } elsif (!defined $user{$_}) { + $user{$_} = $value; + } + } +} + +if (grep { $_ =~ /(^|\s)-Wl,-rpath,/ } ($user{LDLIBS} ? @{$user{LDLIBS}} : ()) && !$disabled{shared} && !($disabled{asan} && $disabled{msan} && $disabled{ubsan})) { die "***** Cannot simultaneously use -rpath, shared libraries, and\n", "***** any of asan, msan or ubsan\n"; } -if ($config{fips}) - { - delete $disabled{"shared"} if ($disabled{"shared"} =~ /^default/); - } -else - { - @{$config{dirs}} = grep !/^fips$/, @{$config{dirs}}; - } - my @tocheckfor = (keys %disabled); while (@tocheckfor) { my %new_tocheckfor = (); @@ -829,75 +935,25 @@ if ($target eq "HASH") { exit 0; } +print "Configuring OpenSSL version $config{version} ($config{version_num}) "; +print "for $target\n"; + +if (scalar(@seed_sources) == 0) { + print "Using os-specific seed configuration\n"; + push @seed_sources, 'os'; +} +die "Cannot seed with none and anything else" + if scalar(grep { $_ eq 'none' } @seed_sources) > 0 + && scalar(@seed_sources) > 1; +push @{$config{openssl_other_defines}}, + map { (my $x = $_) =~ tr|[\-a-z]|[_A-Z]|; "OPENSSL_RAND_SEED_$x" } + @seed_sources; + # Backward compatibility? if ($target =~ m/^CygWin32(-.*)$/) { $target = "Cygwin".$1; } -foreach (sort (keys %disabled)) - { - $config{options} .= " no-$_"; - - printf " no-%-12s %-10s", $_, "[$disabled{$_}]"; - - if (/^dso$/) - { } - elsif (/^threads$/) - { } - elsif (/^shared$/) - { } - elsif (/^pic$/) - { } - elsif (/^zlib$/) - { } - elsif (/^dynamic-engine$/) - { } - elsif (/^makedepend$/) - { } - elsif (/^zlib-dynamic$/) - { } - elsif (/^sse2$/) - { } - elsif (/^engine$/) - { - @{$config{dirs}} = grep !/^engines$/, @{$config{dirs}}; - @{$config{sdirs}} = grep !/^engine$/, @{$config{sdirs}}; - push @{$config{openssl_other_defines}}, "OPENSSL_NO_ENGINE"; - print " OPENSSL_NO_ENGINE (skip engines)"; - } - else - { - my ($WHAT, $what); - - ($WHAT = $what = $_) =~ tr/[\-a-z]/[_A-Z]/; - - # Fix up C macro end names - $WHAT = "RMD160" if $what eq "ripemd"; - - # fix-up crypto/directory name(s) - $what = "ripemd" if $what eq "rmd160"; - $what = "whrlpool" if $what eq "whirlpool"; - - if ($what ne "async" && $what ne "err" - && grep { $_ eq $what } @{$config{sdirs}}) - { - push @{$config{openssl_algorithm_defines}}, "OPENSSL_NO_$WHAT"; - @{$config{sdirs}} = grep { $_ ne $what} @{$config{sdirs}}; - - print " OPENSSL_NO_$WHAT (skip dir)"; - } - else - { - push @{$config{openssl_other_defines}}, "OPENSSL_NO_$WHAT"; - print " OPENSSL_NO_$WHAT"; - } - } - - print "\n"; - } - -print "Configuring for $target\n"; - # Support for legacy targets having a name starting with 'debug-' my ($d, $t) = $target =~ m/^(debug-)?(.*)$/; if ($d) { @@ -913,54 +969,157 @@ my %target = resolve_config($target); &usage if (!%target || $target{template}); -my %conf_files = map { $_ => 1 } (@{$target{_conf_fname_int}}); -$config{conf_files} = [ sort keys %conf_files ]; %target = ( %{$table{DEFAULTS}}, %target ); +# Make the flags to build DSOs the same as for shared libraries unless they +# are already defined +$target{dso_cflags} = $target{shared_cflag} unless defined $target{dso_cflags}; +$target{dso_cxxflags} = $target{shared_cxxflag} unless defined $target{dso_cxxflags}; +$target{dso_lflags} = $target{shared_ldflag} unless defined $target{dso_lflags}; +{ + my $shared_info_pl = + catfile(dirname($0), "Configurations", "shared-info.pl"); + my %shared_info = read_eval_file($shared_info_pl); + push @{$target{_conf_fname_int}}, $shared_info_pl; + my $si = $target{shared_target}; + while (ref $si ne "HASH") { + last if ! defined $si; + if (ref $si eq "CODE") { + $si = $si->(); + } else { + $si = $shared_info{$si}; + } + } + + # Some of the 'shared_target' values don't have any entried in + # %shared_info. That's perfectly fine, AS LONG AS the build file + # template knows how to handle this. That is currently the case for + # Windows and VMS. + if (defined $si) { + # Just as above, copy certain shared_* attributes to the corresponding + # dso_ attribute unless the latter is already defined + $si->{dso_cflags} = $si->{shared_cflag} unless defined $si->{dso_cflags}; + $si->{dso_cxxflags} = $si->{shared_cxxflag} unless defined $si->{dso_cxxflags}; + $si->{dso_lflags} = $si->{shared_ldflag} unless defined $si->{dso_lflags}; + foreach (sort keys %$si) { + $target{$_} = defined $target{$_} + ? add($si->{$_})->($target{$_}) + : $si->{$_}; + } + } +} + +my %conf_files = map { $_ => 1 } (@{$target{_conf_fname_int}}); +$config{conf_files} = [ sort keys %conf_files ]; + +foreach my $feature (@{$target{disable}}) { + if (exists $deprecated_disablables{$feature}) { + warn "***** config $target disables deprecated feature $feature\n"; + } elsif (!grep { $feature eq $_ } @disablables) { + die "***** config $target disables unknown feature $feature\n"; + } + $disabled{$feature} = 'config'; +} +foreach my $feature (@{$target{enable}}) { + if ("default" eq ($disabled{$_} // "")) { + if (exists $deprecated_disablables{$feature}) { + warn "***** config $target enables deprecated feature $feature\n"; + } elsif (!grep { $feature eq $_ } @disablables) { + die "***** config $target enables unknown feature $feature\n"; + } + delete $disabled{$_}; + } +} + +$target{cxxflags}//=$target{cflags} if $target{cxx}; $target{exe_extension}=""; $target{exe_extension}=".exe" if ($config{target} eq "DJGPP" || $config{target} =~ /^(?:Cygwin|mingw)/); $target{exe_extension}=".pm" if ($config{target} =~ /vos/); ($target{shared_extension_simple}=$target{shared_extension}) - =~ s|\.\$\(SHLIB_MAJOR\)\.\$\(SHLIB_MINOR\)||; + =~ s|\.\$\(SHLIB_VERSION_NUMBER\)||; $target{dso_extension}=$target{shared_extension_simple}; ($target{shared_import_extension}=$target{shared_extension_simple}.".a") if ($config{target} =~ /^(?:Cygwin|mingw)/); - -$config{cross_compile_prefix} = $ENV{'CROSS_COMPILE'} - if $config{cross_compile_prefix} eq ""; - # Allow overriding the names of some tools. USE WITH CARE # Note: only Unix cares about HASHBANGPERL... that explains # the default string. -$config{perl} = $ENV{'PERL'} || ($^O ne "VMS" ? $^X : "perl"); -$config{hashbangperl} = - $ENV{'HASHBANGPERL'} || $ENV{'PERL'} || "/usr/bin/env perl"; -$target{cc} = $ENV{'CC'} || $target{cc} || "cc"; -$target{ranlib} = $ENV{'RANLIB'} || $target{ranlib} || - (which("$config{cross_compile_prefix}ranlib") ? - "\$(CROSS_COMPILE)ranlib" : "true"); -$target{ar} = $ENV{'AR'} || $target{ar} || "ar"; -$target{nm} = $ENV{'NM'} || $target{nm} || "nm"; -$target{rc} = - $ENV{'RC'} || $ENV{'WINDRES'} || $target{rc} || "windres"; +$config{perl} = ($^O ne "VMS" ? $^X : "perl"); +foreach (keys %user) { + my $target_key = $user_to_target{$_} // lc $_; + my $ref_type = ref $user{$_}; + + # Temporary function. Takes an intended ref type (empty string or "ARRAY") + # and a value that's to be coerced into that type. + my $mkvalue = sub { + my $type = shift; + my $value = shift; + my $undef_p = shift; + + die "Too many arguments for \$mkvalue" if @_; + + while (ref $value eq 'CODE') { + $value = $value->(); + } + + if ($type eq 'ARRAY') { + return undef unless defined $value; + return undef if ref $value ne 'ARRAY' && !$value; + return undef if ref $value eq 'ARRAY' && !@$value; + return [ $value ] unless ref $value eq 'ARRAY'; + } + return undef unless $value; + return $value; + }; + + $config{$target_key} = + $mkvalue->($ref_type, $user{$_}) + || $mkvalue->($ref_type, $target{$target_key}); + delete $config{$target_key} unless defined $config{$target_key}; +} +$config{plib_lflags} = [ $target{plib_lflags} ]; # Allow overriding the build file name -$target{build_file} = $ENV{BUILDFILE} || $target{build_file} || "Makefile"; +$config{build_file} = env('BUILDFILE') || $target{build_file} || "Makefile"; -# Cache information necessary for reconfiguration -$config{cc} = $target{cc}; -$config{build_file} = $target{build_file}; +my %disabled_info = (); # For configdata.pm +foreach my $what (sort keys %disabled) { + $config{options} .= " no-$what"; -# For cflags, lflags, plib_lflags, ex_libs and defines, add the debug_ -# or release_ attributes. -# Do it in such a way that no spurious space is appended (hence the grep). -$config{defines} = []; -$config{cflags} = ""; -$config{ex_libs} = ""; -$config{shared_ldflag} = ""; + if (!grep { $what eq $_ } ( 'dso', 'threads', 'shared', 'pic', + 'dynamic-engine', 'makedepend', + 'zlib-dynamic', 'zlib', 'sse2' )) { + (my $WHAT = uc $what) =~ s|-|_|g; + + # Fix up C macro end names + $WHAT = "RMD160" if $what eq "ripemd"; + + # fix-up crypto/directory name(s) + $what = "ripemd" if $what eq "rmd160"; + $what = "whrlpool" if $what eq "whirlpool"; + + my $macro = $disabled_info{$what}->{macro} = "OPENSSL_NO_$WHAT"; + + if ((grep { $what eq $_ } @{$config{sdirs}}) + && $what ne 'async' && $what ne 'err') { + @{$config{sdirs}} = grep { $what ne $_} @{$config{sdirs}}; + $disabled_info{$what}->{skipped} = [ catdir('crypto', $what) ]; + + if ($what ne 'engine') { + push @{$config{openssl_algorithm_defines}}, $macro; + } else { + @{$config{dirs}} = grep !/^engines$/, @{$config{dirs}}; + push @{$disabled_info{engine}->{skipped}}, catdir('engines'); + push @{$config{openssl_other_defines}}, $macro; + } + } else { + push @{$config{openssl_other_defines}}, $macro; + } + + } +} # Make sure build_scheme is consistent. $target{build_scheme} = [ $target{build_scheme} ] @@ -990,22 +1149,24 @@ foreach my $checker (($builder_platform."-".$target{build_file}."-checker.pm", push @{$config{defines}}, "NDEBUG" if $config{build_type} eq "release"; -if ($target =~ /^mingw/ && `$target{cc} --target-help 2>&1` =~ m/-mno-cygwin/m) +if ($target =~ /^mingw/ && `$config{cc} --target-help 2>&1` =~ m/-mno-cygwin/m) { - $config{cflags} .= " -mno-cygwin"; - $config{shared_ldflag} .= " -mno-cygwin"; + push @{$config{cflags}}, "-mno-cygwin"; + push @{$config{cxxflags}}, "-mno-cygwin" if $config{cxx}; + push @{$config{shared_ldflag}}, "-mno-cygwin"; } -if ($target =~ /linux.*-mips/ && !$disabled{asm} && $user_cflags !~ /-m(ips|arch=)/) { +if ($target =~ /linux.*-mips/ && !$disabled{asm} + && !grep { $_ !~ /-m(ips|arch=)/ } (@{$user{CFLAGS}}, + @{$useradd{CFLAGS}})) { # minimally required architecture flags for assembly modules - $config{cflags}="-mips2 $config{cflags}" if ($target =~ /mips32/); - $config{cflags}="-mips3 $config{cflags}" if ($target =~ /mips64/); + my $value; + $value = '-mips2' if ($target =~ /mips32/); + $value = '-mips3' if ($target =~ /mips64/); + unshift @{$config{cflags}}, $value; + unshift @{$config{cxxflags}}, $value if $config{cxx}; } -my $no_shared_warn=0; -my $no_user_cflags=0; -my $no_user_defines=0; - # 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 @@ -1029,17 +1190,6 @@ if (!$disabled{dso} && $target{dso_scheme} ne "") } } -$config{ex_libs}="$libs$config{ex_libs}" if ($libs ne ""); - -if ($disabled{asm}) - { - if ($config{fips}) - { - @{$config{defines}} = grep !/^[BL]_ENDIAN$/, @{$config{defines}}; - @{$target{defines}} = grep !/^[BL]_ENDIAN$/, @{$target{defines}}; - } - } - # If threads aren't disabled, check how possible they are unless ($disabled{threads}) { if ($auto_threads) { @@ -1056,7 +1206,8 @@ unless ($disabled{threads}) { # system-dependent compiler options that are necessary. We # can't truly check that the given options are correct, but # we expect the user to know what [s]He is doing. - if ($no_user_cflags && $no_user_defines) { + if (!@{$user{CFLAGS}} && !@{$useradd{CFLAGS}} + && !@{$user{CPPDEFINES}} && !@{$useradd{CPPDEFINES}}) { die "You asked for multi-threading support, but didn't\n" ,"provide any system-specific compiler options\n"; } @@ -1067,9 +1218,7 @@ unless ($disabled{threads}) { # If threads still aren't disabled, add a C macro to ensure the source # code knows about it. Any other flag is taken care of by the configs. unless($disabled{threads}) { - foreach (("defines", "openssl_thread_defines")) { - push @{$config{$_}}, "OPENSSL_THREADS"; - } + push @{$config{openssl_thread_defines}}, "OPENSSL_THREADS"; } # With "deprecated" disable all deprecated features. @@ -1077,11 +1226,11 @@ if (defined($disabled{"deprecated"})) { $config{api} = $maxapi; } +my $no_shared_warn=0; if ($target{shared_target} eq "") { $no_shared_warn = 1 - if ((!$disabled{shared} || !$disabled{"dynamic-engine"}) - && !$config{fips}); + if (!$disabled{shared} || !$disabled{"dynamic-engine"}); $disabled{shared} = "no-shared-target"; $disabled{pic} = $disabled{shared} = $disabled{"dynamic-engine"} = "no-shared-target"; @@ -1095,27 +1244,28 @@ if ($disabled{"dynamic-engine"}) { $config{dynamic_engines} = 1; } -unless ($disabled{"fuzz-libfuzzer"}) { - $config{cflags} .= "-fsanitize-coverage=edge,indirect-calls "; -} - unless ($disabled{asan}) { - $config{cflags} .= "-fsanitize=address "; + push @{$config{cflags}}, "-fsanitize=address"; + push @{$config{cxxflags}}, "-fsanitize=address" if $config{cxx}; } unless ($disabled{ubsan}) { # -DPEDANTIC or -fnosanitize=alignment may also be required on some # platforms. - $config{cflags} .= "-fsanitize=undefined -fno-sanitize-recover=all "; + push @{$config{cflags}}, "-fsanitize=undefined", "-fno-sanitize-recover=all"; + push @{$config{cxxflags}}, "-fsanitize=undefined", "-fno-sanitize-recover=all" + if $config{cxx}; } unless ($disabled{msan}) { - $config{cflags} .= "-fsanitize=memory "; + push @{$config{cflags}}, "-fsanitize=memory"; + push @{$config{cxxflags}}, "-fsanitize=memory" if $config{cxx}; } unless ($disabled{"fuzz-libfuzzer"} && $disabled{"fuzz-afl"} && $disabled{asan} && $disabled{ubsan} && $disabled{msan}) { - $config{cflags} .= "-fno-omit-frame-pointer -g "; + push @{$config{cflags}}, "-fno-omit-frame-pointer", "-g"; + push @{$config{cxxflags}}, "-fno-omit-frame-pointer", "-g" if $config{cxx}; } # # Platform fix-ups @@ -1124,8 +1274,14 @@ unless ($disabled{"fuzz-libfuzzer"} && $disabled{"fuzz-afl"} # This saves the build files from having to check if ($disabled{pic}) { - $target{shared_cflag} = $target{shared_ldflag} = - $target{shared_rcflag} = ""; + foreach (qw(shared_cflag shared_cxxflag shared_cppflag + shared_defines shared_includes shared_ldflag + dso_cflags dso_cxxflags dso_cppflags + dso_defines dso_includes dso_lflags)) + { + delete $config{$_}; + $target{$_} = ""; + } } else { @@ -1139,6 +1295,8 @@ if ($target{sys_id} ne "") unless ($disabled{asm}) { $target{cpuid_asm_src}=$table{DEFAULTS}->{cpuid_asm_src} if ($config{processor} eq "386"); + push @{$config{defines}}, "OPENSSL_CPUID_OBJ" if ($target{cpuid_asm_src} ne "mem_clr.c"); + $target{bn_asm_src} =~ s/\w+-gf2m.c// if (defined($disabled{ec2m})); # bn-586 is the only one implementing bn_*_part_words @@ -1149,10 +1307,6 @@ unless ($disabled{asm}) { push @{$config{defines}}, "OPENSSL_BN_ASM_MONT5" if ($target{bn_asm_src} =~ /-mont5/); push @{$config{defines}}, "OPENSSL_BN_ASM_GF2m" if ($target{bn_asm_src} =~ /-gf2m/); - if ($config{fips}) { - push @{$config{openssl_other_defines}}, "OPENSSL_FIPS"; - } - if ($target{sha1_asm_src}) { push @{$config{defines}}, "SHA1_ASM" if ($target{sha1_asm_src} =~ /sx86/ || $target{sha1_asm_src} =~ /sha1/); push @{$config{defines}}, "SHA256_ASM" if ($target{sha1_asm_src} =~ /sha256/); @@ -1192,6 +1346,9 @@ unless ($disabled{asm}) { if ($target{ec_asm_src} =~ /ecp_nistz256/) { push @{$config{defines}}, "ECP_NISTZ256_ASM"; } + if ($target{ec_asm_src} =~ /x25519/) { + push @{$config{defines}}, "X25519_ASM"; + } if ($target{padlock_asm_src} ne $table{DEFAULTS}->{padlock_asm_src}) { push @{$config{defines}}, "PADLOCK_ASM"; } @@ -1200,33 +1357,27 @@ unless ($disabled{asm}) { } } -my %predefined; +my %predefined = compiler_predefined($config{cc}); -if ($^O ne "VMS") { - my $cc = "$config{cross_compile_prefix}$target{cc}"; - - # collect compiler pre-defines from gcc or gcc-alike... - open(PIPE, "$cc -dM -E -x c /dev/null 2>&1 |"); - while () { - m/^#define\s+(\w+(?:\(\w+\))?)(?:\s+(.+))?/ or last; - $predefined{$1} = $2 // ""; - } - close(PIPE); - - if (!$disabled{makedepend}) { - # We know that GNU C version 3 and up as well as all clang - # versions support dependency generation - if ($predefined{__GNUC__} >= 3) { - $config{makedepprog} = $cc; - } else { - $config{makedepprog} = which('makedepend'); - $disabled{makedepend} = "unavailable" unless $config{makedepprog}; - } +# Check for makedepend capabilities. +if (!$disabled{makedepend}) { + if ($config{target} =~ /^(VC|vms)-/) { + # For VC- and vms- targets, there's nothing more to do here. The + # functionality is hard coded in the corresponding build files for + # cl (Windows) and CC/DECC (VMS). + } elsif ($predefined{__GNUC__} >= 3) { + # We know that GNU C version 3 and up as well as all clang + # versions support dependency generation + $config{makedepprog} = "\$(CROSS_COMPILE)$config{cc}"; + } else { + # In all other cases, we look for 'makedepend', and disable the + # capability if not found. + $config{makedepprog} = which('makedepend'); + $disabled{makedepend} = "unavailable" unless $config{makedepprog}; } } - # Deal with bn_ops ################################################### $config{bn_ll} =0; @@ -1254,9 +1405,12 @@ die "Exactly one of SIXTY_FOUR_BIT|SIXTY_FOUR_BIT_LONG|THIRTY_TWO_BIT can be set # Hack cflags for better warnings (dev option) ####################### -# "Stringify" the C flags string. This permits it to be made part of a string -# and works as well on command lines. -$config{cflags} =~ s/([\\\"])/\\$1/g; +# "Stringify" the C and C++ flags string. This permits it to be made part of +# a string and works as well on command lines. +$config{cflags} = [ map { (my $x = $_) =~ s/([\\\"])/\\$1/g; $x } + @{$config{cflags}} ]; +$config{cxxflags} = [ map { (my $x = $_) =~ s/([\\\"])/\\$1/g; $x } + @{$config{cxxflags}} ] if $config{cxx}; if (defined($config{api})) { $config{openssl_api_defines} = [ "OPENSSL_MIN_API=".$apitable->{$config{api}} ]; @@ -1264,20 +1418,36 @@ if (defined($config{api})) { push @{$config{defines}}, $apiflag; } +if (defined($predefined{__clang__}) && !$disabled{asm}) { + push @{$config{cflags}}, "-Qunused-arguments"; + push @{$config{cxxflags}}, "-Qunused-arguments" if $config{cxx}; +} + if ($strict_warnings) { my $wopt; - die "ERROR --strict-warnings requires gcc or gcc-alike" - unless defined($predefined{__GNUC__}); + my $gccver = $predefined{__GNUC__} // -1; + + die "ERROR --strict-warnings requires gcc[>=4] or gcc-alike" + unless $gccver >= 4; + $gcc_devteam_warn .= " -Wmisleading-indentation" if $gccver >= 6; foreach $wopt (split /\s+/, $gcc_devteam_warn) { - $config{cflags} .= " $wopt" unless ($config{cflags} =~ /(?:^|\s)$wopt(?:\s|$)/) + push @{$config{cflags}}, $wopt + unless grep { $_ eq $wopt } @{$config{cflags}}; + push @{$config{cxxflags}}, $wopt + if ($config{cxx} + && !grep { $_ eq $wopt } @{$config{cxxflags}}); } if (defined($predefined{__clang__})) { foreach $wopt (split /\s+/, $clang_devteam_warn) { - $config{cflags} .= " $wopt" unless ($config{cflags} =~ /(?:^|\s)$wopt(?:\s|$)/) + push @{$config{cflags}}, $wopt + unless grep { $_ eq $wopt } @{$config{cflags}}; + push @{$config{cxxflags}}, $wopt + if ($config{cxx} + && !grep { $_ eq $wopt } @{$config{cxxflags}}); } } } @@ -1286,21 +1456,18 @@ unless ($disabled{"crypto-mdebug-backtrace"}) { foreach my $wopt (split /\s+/, $memleak_devteam_backtrace) { - $config{cflags} .= " $wopt" unless ($config{cflags} =~ /(?:^|\s)$wopt(?:\s|$)/) + push @{$config{cflags}}, $wopt + unless grep { $_ eq $wopt } @{$config{cflags}}; + push @{$config{cxxflags}}, $wopt + if ($config{cxx} + && !grep { $_ eq $wopt } @{$config{cxxflags}}); } if ($target =~ /^BSD-/) { - $config{ex_libs} .= " -lexecinfo"; + push @{$config{ex_libs}}, "-lexecinfo"; } } -if ($user_cflags ne "") { $config{cflags}="$config{cflags}$user_cflags"; } -else { $no_user_cflags=1; } -if (@user_defines) { $config{defines}=[ @{$config{defines}}, @user_defines ]; } -else { $no_user_defines=1; } - -# ALL MODIFICATIONS TO %config and %target MUST BE DONE FROM HERE ON - unless ($disabled{afalgeng}) { $config{afalgeng}=""; if ($target =~ m/^linux/) { @@ -1325,6 +1492,24 @@ unless ($disabled{afalgeng}) { push @{$config{openssl_other_defines}}, "OPENSSL_NO_AFALGENG" if ($disabled{afalgeng}); +# Finish up %config by appending things the user gave us on the command line +# apart from "make variables" +foreach (keys %useradd) { + # The must all be lists, so we assert that here + die "internal error: \$useradd{$_} isn't an ARRAY\n" + unless ref $useradd{$_} eq 'ARRAY'; + + my $target_key = $user_to_target{$_} // lc $_; + + if (defined $config{$target_key}) { + push @{$config{$target_key}}, @{$useradd{$_}}; + } else { + $config{$target_key} = [ @{$useradd{$_}} ]; + } +} + +# ALL MODIFICATIONS TO %config and %target MUST BE DONE FROM HERE ON + # If we use the unified build, collect information from build.info files my %unified_info = (); @@ -1373,7 +1558,7 @@ if ($builder eq "unified") { my @build_file_templates = (); # First, look in the user provided directory, if given - if (defined $ENV{$local_config_envname}) { + if (defined env($local_config_envname)) { @build_file_templates = map { if ($^O eq 'VMS') { @@ -1381,7 +1566,7 @@ if ($builder eq "unified") { # which can be used as is $local_config_envname . ':' . $_; } else { - catfile($ENV{$local_config_envname}, $_); + catfile(env($local_config_envname), $_); } } @build_file_template_names; @@ -1419,9 +1604,14 @@ if ($builder eq "unified") { push @build_infos, [ catdir("engines", $_), "build.info" ] if (-f catfile($srcdir, "engines", $_, "build.info")); } + foreach (@{$config{tdirs}}) { + push @build_infos, [ catdir("test", $_), "build.info" ] + if (-f catfile($srcdir, "test", $_, "build.info")); + } $config{build_infos} = [ ]; + my %ordinals = (); foreach (@build_infos) { my $sourced = catdir($srcdir, $_->[0]); my $buildd = catdir($blddir, $_->[0]); @@ -1443,7 +1633,6 @@ if ($builder eq "unified") { my @intermediates = (); my @rawlines = (); - my %ordinals = (); my %sources = (); my %shared_sources = (); my %includes = (); @@ -1452,10 +1641,6 @@ if ($builder eq "unified") { my %sharednames = (); my %generate = (); - # We want to detect configdata.pm in the source tree, so we - # don't use it if the build tree is different. - my $src_configdata = cleanfile($srcdir, "configdata.pm", $blddir); - push @{$config{build_infos}}, catfile(abs2rel($sourced, $blddir), $f); my $template = Text::Template->new(TYPE => 'FILE', @@ -1591,7 +1776,7 @@ if ($builder eq "unified") { || $target_kind eq $target{build_file}."(".$builder_platform.")"); } }, - qr/^(?:#.*|\s*)$/ => sub { }, + qr/^\s*(?:#.*)?$/ => sub { }, "OTHERWISE" => sub { die "Something wrong with this line:\n$_\nat $sourced/$f" }, "BEFORE" => sub { if ($buildinfo_debug) { @@ -1721,33 +1906,24 @@ EOF } # Additionally, we set up sharednames for libraries that don't - # have any, as themselves. - foreach (keys %{$unified_info{libraries}}) { + # have any, as themselves. Only for libraries that aren't + # explicitly static. + foreach (grep !/\.a$/, keys %{$unified_info{libraries}}) { if (!defined $unified_info{sharednames}->{$_}) { $unified_info{sharednames}->{$_} = $_ } } - } - foreach (keys %ordinals) { - my $dest = $_; - my $ddest = cleanfile($buildd, $_, $blddir); - if ($unified_info{rename}->{$ddest}) { - $ddest = $unified_info{rename}->{$ddest}; - } - foreach (@{$ordinals{$dest}}) { - my %known_ordinals = - ( - crypto => - cleanfile($sourced, catfile("util", "libcrypto.num"), $blddir), - ssl => - cleanfile($sourced, catfile("util", "libssl.num"), $blddir) - ); - my $o = $known_ordinals{$_}; - die "Ordinals for $ddest defined more than once\n" - if $unified_info{ordinals}->{$ddest}; - $unified_info{ordinals}->{$ddest} = [ $_, $o ]; + # Check that we haven't defined any library as both shared and + # explicitly static. That is forbidden. + my @doubles = (); + foreach (grep /\.a$/, keys %{$unified_info{libraries}}) { + (my $l = $_) =~ s/\.a$//; + push @doubles, $l if defined $unified_info{sharednames}->{$l}; } + die "these libraries are both explicitly static and shared:\n ", + join(" ", @doubles), "\n" + if @doubles; } foreach (keys %sources) { @@ -1761,12 +1937,14 @@ EOF # If it isn't in the source tree, we assume it's generated # in the build tree - if ($s eq $src_configdata || ! -f $s || $generate{$_}) { + if (! -f $s || $generate{$_}) { $s = cleanfile($buildd, $_, $blddir); } - # We recognise C and asm files - if ($s =~ /\.[csS]\b$/) { - (my $o = $_) =~ s/\.[csS]\b$/.o/; + # We recognise C++, C and asm files + if ($s =~ /\.(cc|cpp|c|s|S)$/) { + my $o = $_; + $o =~ s/\.[csS]$/.o/; # C and assembler + $o =~ s/\.(cc|cpp)$/_cc.o/; # C++ $o = cleanfile($buildd, $o, $blddir); $unified_info{sources}->{$ddest}->{$o} = 1; $unified_info{sources}->{$o}->{$s} = 1; @@ -1787,15 +1965,30 @@ EOF # If it isn't in the source tree, we assume it's generated # in the build tree - if ($s eq $src_configdata || ! -f $s || $generate{$_}) { + if (! -f $s || $generate{$_}) { $s = cleanfile($buildd, $_, $blddir); } - # We recognise C and asm files - if ($s =~ /\.[csS]\b$/) { - (my $o = $_) =~ s/\.[csS]\b$/.o/; + + if ($s =~ /\.(cc|cpp|c|s|S)$/) { + # We recognise C++, C and asm files + my $o = $_; + $o =~ s/\.[csS]$/.o/; # C and assembler + $o =~ s/\.(cc|cpp)$/_cc.o/; # C++ $o = cleanfile($buildd, $o, $blddir); $unified_info{shared_sources}->{$ddest}->{$o} = 1; $unified_info{sources}->{$o}->{$s} = 1; + } elsif ($s =~ /\.rc$/) { + # We also recognise resource files + my $o = $_; + $o =~ s/\.rc$/.res/; # Resource configuration + my $o = cleanfile($buildd, $o, $blddir); + $unified_info{shared_sources}->{$ddest}->{$o} = 1; + $unified_info{sources}->{$o}->{$s} = 1; + } elsif ($s =~ /\.(def|map|opt)$/) { + # We also recognise .def / .map / .opt files + # We know they are generated files + my $def = cleanfile($buildd, $s, $blddir); + $unified_info{shared_sources}->{$ddest}->{$def} = 1; } else { die "unrecognised source file type for shared library: $s\n"; } @@ -1822,7 +2015,7 @@ EOF # If the destination doesn't exist in source, it can only be # a generated file in the build tree. - if ($ddest ne "" && ($ddest eq $src_configdata || ! -f $ddest)) { + if ($ddest ne "" && ! -f $ddest) { $ddest = cleanfile($buildd, $_, $blddir); if ($unified_info{rename}->{$ddest}) { $ddest = $unified_info{rename}->{$ddest}; @@ -1836,17 +2029,23 @@ EOF # in the build tree rather than the source tree, and assume # and that there are lines to build it in a BEGINRAW..ENDRAW # section or in the Makefile template. - if ($d eq $src_configdata - || ! -f $d + if (! -f $d || (grep { $d eq $_ } map { cleanfile($srcdir, $_, $blddir) } grep { /\.h$/ } keys %{$unified_info{generate}})) { $d = cleanfile($buildd, $_, $blddir); } # Take note if the file to depend on is being renamed + # Take extra care with files ending with .a, they should + # be treated without that extension, and the extension + # should be added back after treatment. + $d =~ /(\.a)?$/; + my $e = $1 // ""; + $d = $`; if ($unified_info{rename}->{$d}) { $d = $unified_info{rename}->{$d}; } + $d .= $e; $unified_info{depends}->{$ddest}->{$d} = 1; } } @@ -1857,7 +2056,7 @@ EOF # If the destination doesn't exist in source, it can only be # a generated file in the build tree. - if ($ddest eq $src_configdata || ! -f $ddest) { + if (! -f $ddest) { $ddest = cleanfile($buildd, $_, $blddir); if ($unified_info{rename}->{$ddest}) { $ddest = $unified_info{rename}->{$ddest}; @@ -1874,6 +2073,14 @@ EOF } } + my $ordinals_text = join(', ', sort keys %ordinals); + warn <<"EOF" if $ordinals_text; + +WARNING: ORDINALS were specified for $ordinals_text +They are ignored and should be replaced with a combination of GENERATE, +DEPEND and SHARED_SOURCE. +EOF + # Massage the result # If we depend on a header file or a perl module, add an inclusion of @@ -1882,12 +2089,16 @@ EOF next if $dest eq ""; foreach my $d (keys %{$unified_info{depends}->{$dest}}) { next unless $d =~ /\.(h|pm)$/; - my $i = dirname($d); - my $spot = - $d eq "configdata.pm" || defined($unified_info{generate}->{$d}) - ? 'build' : 'source'; - push @{$unified_info{includes}->{$dest}->{$spot}}, $i - unless grep { $_ eq $i } @{$unified_info{includes}->{$dest}->{$spot}}; + if ($d eq "configdata.pm" + || defined($unified_info{generate}->{$d})) { + my $i = cleandir($blddir, dirname($d)); + push @{$unified_info{includes}->{$dest}->{build}}, $i + unless grep { $_ eq $i } @{$unified_info{includes}->{$dest}->{build}}; + } else { + my $i = cleandir($srcdir, dirname($d)); + push @{$unified_info{includes}->{$dest}->{source}}, $i + unless grep { $_ eq $i } @{$unified_info{includes}->{$dest}->{source}}; + } } } @@ -1947,13 +2158,18 @@ EOF foreach (grep /_(asm|aux)_src$/, keys %target) { my $src = $_; (my $obj = $_) =~ s/_(asm|aux)_src$/_obj/; - ($target{$obj} = $target{$src}) =~ s/\.[csS]\b/.o/g; + $target{$obj} = $target{$src}; + $target{$obj} =~ s/\.[csS]\b/.o/g; # C and assembler + $target{$obj} =~ s/\.(cc|cpp)\b/_cc.o/g; # C++ } # Write down our configuration where it fits ######################### +print "Creating configdata.pm\n"; open(OUT,">configdata.pm") || die "unable to create configdata.pm: $!\n"; print OUT <<"EOF"; +#! $config{hashbangperl} + package configdata; use strict; @@ -1971,6 +2187,22 @@ foreach (sort keys %config) { print OUT " ", $_, " => [ ", join(", ", map { quotify("perl", $_) } @{$config{$_}}), " ],\n"; + } elsif (ref($config{$_}) eq "HASH") { + print OUT " ", $_, " => {"; + if (scalar keys %{$config{$_}} > 0) { + print OUT "\n"; + foreach my $key (sort keys %{$config{$_}}) { + print OUT " ", + join(" => ", + quotify("perl", $key), + defined $config{$_}->{$key} + ? quotify("perl", $config{$_}->{$key}) + : "undef"); + print OUT ",\n"; + } + print OUT " "; + } + print OUT "},\n"; } else { print OUT " ", $_, " => ", quotify("perl", $config{$_}), ",\n" } @@ -2072,52 +2304,298 @@ if ($builder eq "unified") { EOF } -print OUT "1;\n"; +print OUT + "# The following data is only used when this files is use as a script\n"; +print OUT "my \%makevars = (\n"; +foreach (sort keys %user) { + print OUT ' ',$_,' ' x (20 - length $_),'=> ', + "'",$user_to_target{$_} || lc $_,"',\n"; +} +print OUT ");\n"; +print OUT "my \%disabled_info = (\n"; +foreach my $what (sort keys %disabled_info) { + print OUT " '$what' => {\n"; + foreach my $info (sort keys %{$disabled_info{$what}}) { + if (ref $disabled_info{$what}->{$info} eq 'ARRAY') { + print OUT " $info => [ ", + join(', ', map { "'$_'" } @{$disabled_info{$what}->{$info}}), + " ],\n"; + } else { + print OUT " $info => '", $disabled_info{$what}->{$info}, + "',\n"; + } + } + print OUT " },\n"; +} +print OUT ");\n"; +print OUT 'my @user_crossable = qw( ', join (' ', @user_crossable), " );\n"; +print OUT << 'EOF'; +# If run directly, we can give some answers, and even reconfigure +unless (caller) { + use Getopt::Long; + use File::Spec::Functions; + use File::Basename; + use Pod::Usage; + + my $here = dirname($0); + + my $dump = undef; + my $cmdline = undef; + my $options = undef; + my $target = undef; + my $envvars = undef; + my $makevars = undef; + my $buildparams = undef; + my $reconf = undef; + my $verbose = undef; + my $help = undef; + my $man = undef; + GetOptions('dump|d' => \$dump, + 'command-line|c' => \$cmdline, + 'options|o' => \$options, + 'target|t' => \$target, + 'environment|e' => \$envvars, + 'make-variables|m' => \$makevars, + 'build-parameters|b' => \$buildparams, + 'reconfigure|reconf|r' => \$reconf, + 'verbose|v' => \$verbose, + 'help' => \$help, + 'man' => \$man) + or die "Errors in command line arguments\n"; + + unless ($dump || $cmdline || $options || $target || $envvars || $makevars + || $buildparams || $reconf || $verbose || $help || $man) { + print STDERR <<"_____"; +You must give at least one option. +For more information, do '$0 --help' +_____ + exit(2); + } + + if ($help) { + pod2usage(-exitval => 0, + -verbose => 1); + } + if ($man) { + pod2usage(-exitval => 0, + -verbose => 2); + } + if ($dump || $cmdline) { + print "\nCommand line (with current working directory = $here):\n\n"; + print ' ',join(' ', + $config{perl}, + catfile($config{sourcedir}, 'Configure'), + @{$config{perlargv}}), "\n"; + print "\nPerl information:\n\n"; + print ' ',$config{perl_cmd},"\n"; + print ' ',$config{perl_version},' for ',$config{perl_archname},"\n"; + } + if ($dump || $options) { + my $longest = 0; + my $longest2 = 0; + foreach my $what (@disablables) { + $longest = length($what) if $longest < length($what); + $longest2 = length($disabled{$what}) + if $disabled{$what} && $longest2 < length($disabled{$what}); + } + print "\nEnabled features:\n\n"; + foreach my $what (@disablables) { + print " $what\n" unless $disabled{$what}; + } + print "\nDisabled features:\n\n"; + foreach my $what (@disablables) { + if ($disabled{$what}) { + print " $what", ' ' x ($longest - length($what) + 1), + "[$disabled{$what}]", ' ' x ($longest2 - length($disabled{$what}) + 1); + print $disabled_info{$what}->{macro} + if $disabled_info{$what}->{macro}; + print ' (skip ', + join(', ', @{$disabled_info{$what}->{skipped}}), + ')' + if $disabled_info{$what}->{skipped}; + print "\n"; + } + } + } + if ($dump || $target) { + print "\nConfig target attributes:\n\n"; + foreach (sort keys %target) { + next if $_ =~ m|^_| || $_ eq 'template'; + my $quotify = sub { + map { (my $x = $_) =~ s|([\\\$\@"])|\\$1|g; "\"$x\""} @_; + }; + print ' ', $_, ' => '; + if (ref($target{$_}) eq "ARRAY") { + print '[ ', join(', ', $quotify->(@{$target{$_}})), " ],\n"; + } else { + print $quotify->($target{$_}), ",\n" + } + } + } + if ($dump || $envvars) { + print "\nRecorded environment:\n\n"; + foreach (sort keys %{$config{perlenv}}) { + print ' ',$_,' = ',($config{perlenv}->{$_} || ''),"\n"; + } + } + if ($dump || $makevars) { + print "\nMakevars:\n\n"; + foreach my $var (sort keys %makevars) { + my $prefix = ''; + $prefix = $config{cross_compile_prefix} + if grep { $var eq $_ } @user_crossable; + print ' ',$var,' ' x (16 - length $var),'= ', + (ref $config{$makevars{$var}} eq 'ARRAY' + ? join(' ', @{$config{$makevars{$var}}}) + : $prefix.$config{$makevars{$var}}), + "\n" + if defined $config{$makevars{$var}}; + } + + my @buildfile = ($config{builddir}, $config{build_file}); + unshift @buildfile, $here + unless file_name_is_absolute($config{builddir}); + my $buildfile = canonpath(catdir(@buildfile)); + print <<"_____"; + +NOTE: These variables only represent the configuration view. The build file +template may have processed these variables further, please have a look at the +build file for more exact data: + $buildfile +_____ + } + if ($dump || $buildparams) { + my @buildfile = ($config{builddir}, $config{build_file}); + unshift @buildfile, $here + unless file_name_is_absolute($config{builddir}); + print "\nbuild file:\n\n"; + print " ", canonpath(catfile(@buildfile)),"\n"; + + print "\nbuild file templates:\n\n"; + foreach (@{$config{build_file_templates}}) { + my @tmpl = ($_); + unshift @tmpl, $here + unless file_name_is_absolute($config{sourcedir}); + print ' ',canonpath(catfile(@tmpl)),"\n"; + } + } + if ($reconf) { + if ($verbose) { + print 'Reconfiguring with: ', join(' ',@{$config{perlargv}}), "\n"; + foreach (sort keys %{$config{perlenv}}) { + print ' ',$_,' = ',($config{perlenv}->{$_} || ""),"\n"; + } + } + + chdir $here; + exec $^X,catfile($config{sourcedir}, 'Configure'),'reconf'; + } +} + +1; + +__END__ + +=head1 NAME + +configdata.pm - configuration data for OpenSSL builds + +=head1 SYNOPSIS + +Interactive: + + perl configdata.pm [options] + +As data bank module: + + use configdata; + +=head1 DESCRIPTION + +This module can be used in two modes, interactively and as a module containing +all the data recorded by OpenSSL's Configure script. + +When used interactively, simply run it as any perl script, with at least one +option, and you will get the information you ask for. See L below. + +When loaded as a module, you get a few databanks with useful information to +perform build related tasks. The databanks are: + + %config Configured things. + %target The OpenSSL config target with all inheritances + resolved. + %disabled The features that are disabled. + @disablables The list of features that can be disabled. + %withargs All data given through --with-THING options. + %unified_info All information that was computed from the build.info + files. + +=head1 OPTIONS + +=over 4 + +=item B<--help> + +Print a brief help message and exit. + +=item B<--man> + +Print the manual page and exit. + +=item B<--dump> | B<-d> + +Print all relevant configuration data. This is equivalent to B<--command-line> +B<--options> B<--target> B<--environment> B<--make-variables> +B<--build-parameters>. + +=item B<--command-line> | B<-c> + +Print the current configuration command line. + +=item B<--options> | B<-o> + +Print the features, both enabled and disabled, and display defined macro and +skipped directories where applicable. + +=item B<--target> | B<-t> + +Print the config attributes for this config target. + +=item B<--environment> | B<-e> + +Print the environment variables and their values at the time of configuration. + +=item B<--make-variables> | B<-m> + +Print the main make variables generated in the current configuration + +=item B<--build-parameters> | B<-b> + +Print the build parameters, i.e. build file and build file templates. + +=item B<--reconfigure> | B<--reconf> | B<-r> + +Redo the configuration. + +=item B<--verbose> | B<-v> + +Verbose output. + +=back + +=cut + +EOF close(OUT); - - -print "CC =$config{cross_compile_prefix}$target{cc}\n"; -print "CFLAG =$target{cflags} $config{cflags}\n"; -print "SHARED_CFLAG =$target{shared_cflag}\n"; -print "DEFINES =",join(" ", @{$target{defines}}, @{$config{defines}}),"\n"; -print "LFLAG =$target{lflags}\n"; -print "PLIB_LFLAG =$target{plib_lflags}\n"; -print "EX_LIBS =$target{ex_libs} $config{ex_libs}\n"; -print "APPS_OBJ =$target{apps_obj}\n"; -print "CPUID_OBJ =$target{cpuid_obj}\n"; -print "UPLINK_OBJ =$target{uplink_obj}\n"; -print "BN_ASM =$target{bn_obj}\n"; -print "EC_ASM =$target{ec_obj}\n"; -print "DES_ENC =$target{des_obj}\n"; -print "AES_ENC =$target{aes_obj}\n"; -print "BF_ENC =$target{bf_obj}\n"; -print "CAST_ENC =$target{cast_obj}\n"; -print "RC4_ENC =$target{rc4_obj}\n"; -print "RC5_ENC =$target{rc5_obj}\n"; -print "MD5_OBJ_ASM =$target{md5_obj}\n"; -print "SHA1_OBJ_ASM =$target{sha1_obj}\n"; -print "RMD160_OBJ_ASM=$target{rmd160_obj}\n"; -print "CMLL_ENC =$target{cmll_obj}\n"; -print "MODES_OBJ =$target{modes_obj}\n"; -print "PADLOCK_OBJ =$target{padlock_obj}\n"; -print "CHACHA_ENC =$target{chacha_obj}\n"; -print "POLY1305_OBJ =$target{poly1305_obj}\n"; -print "BLAKE2_OBJ =$target{blake2_obj}\n"; -print "PROCESSOR =$config{processor}\n"; -print "RANLIB =", $target{ranlib} eq '$(CROSS_COMPILE)ranlib' ? - "$config{cross_compile_prefix}ranlib" : - "$target{ranlib}", "\n"; -print "ARFLAGS =$target{arflags}\n"; -print "PERL =$config{perl}\n"; -print "\n"; -print "SIXTY_FOUR_BIT_LONG mode\n" if $config{b64l}; -print "SIXTY_FOUR_BIT mode\n" if $config{b64}; -print "THIRTY_TWO_BIT mode\n" if $config{b32}; -print "BN_LLONG mode\n" if $config{bn_ll}; -print "RC4 uses $config{rc4_int}\n" if $config{rc4_int} ne $def_int; +if ($builder_platform eq 'unix') { + my $mode = (0755 & ~umask); + chmod $mode, 'configdata.pm' + or warn sprintf("WARNING: Couldn't change mode for 'configdata.pm' to 0%03o: %s\n",$mode,$!); +} my %builders = ( unified => sub { + print 'Creating ',$target{build_file},"\n"; run_dofile(catfile($blddir, $target{build_file}), @{$config{build_file_templates}}); }, @@ -2125,11 +2603,6 @@ my %builders = ( $builders{$builder}->($builder_platform, @builder_opts); -print <<"EOF"; - -Configured for $target. -EOF - print <<"EOF" if ($disabled{threads} eq "unavailable"); The library could not be configured for supporting multi-threaded @@ -2146,6 +2619,26 @@ or position independent code, please let us know (but please first make sure you have tried with a current version of OpenSSL). EOF +print <<"EOF" if (-f catfile($srcdir, "configdata.pm") && $srcdir ne $blddir); + +WARNING: there are indications that another build was made in the source +directory. This build may have picked up artifacts from that build, the +safest course of action is to clean the source directory and redo this +configuration. +EOF + +print <<"EOF"; + +********************************************************************** +*** *** +*** If you want to report a building issue, please include the *** +*** output from this command: *** +*** *** +*** perl configdata.pm --dump *** +*** *** +********************************************************************** +EOF + exit(0); ###################################################################### @@ -2275,25 +2768,38 @@ sub add { sub { _add($separator, @_, @x) }; } +sub read_eval_file { + my $fname = shift; + my $content; + my @result; + + open F, "< $fname" or die "Can't open '$fname': $!\n"; + { + undef local $/; + $content = ; + } + close F; + { + local $@; + + @result = ( eval $content ); + warn $@ if $@; + } + return wantarray ? @result : $result[0]; +} + # configuration reader, evaluates the input file as a perl script and expects # it to fill %targets with target configurations. Those are then added to # %table. sub read_config { my $fname = shift; - open(CONFFILE, "< $fname") - or die "Can't open configuration file '$fname'!\n"; - my $x = $/; - undef $/; - my $content = ; - $/ = $x; - close(CONFFILE); - my %targets = (); + my %targets; + { # Protect certain tables from tampering - local %table = %::table; + local %table = (); - eval $content; - warn $@ if $@; + %targets = read_eval_file($fname); } my %preexisting = (); foreach (sort keys %targets) { @@ -2495,6 +3001,32 @@ sub run_dofile rename("$out.new", $out) || die "Can't rename $out.new, $!"; } +sub compiler_predefined { + state %predefined; + my $default_compiler = shift; + + return () if $^O eq 'VMS'; + + die 'compiler_predefines called without a default compiler' + unless $default_compiler; + + if (! $predefined{$default_compiler}) { + my $cc = "$config{cross_compile_prefix}$default_compiler"; + + $predefined{$default_compiler} = {}; + + # collect compiler pre-defines from gcc or gcc-alike... + open(PIPE, "$cc -dM -E -x c /dev/null 2>&1 |"); + while (my $l = ) { + $l =~ m/^#define\s+(\w+(?:\(\w+\))?)(?:\s+(.+))?/ or last; + $predefined{$default_compiler}->{$1} = $2 // ''; + } + close(PIPE); + } + + return %{$predefined{$default_compiler}}; +} + sub which { my ($name)=@_; @@ -2516,6 +3048,19 @@ sub which } } +sub env +{ + my $name = shift; + + # Note that if $ENV{$name} doesn't exist or is undefined, + # $config{perlenv}->{$name} will be created with the value + # undef. This is intentional. + + $config{perlenv}->{$name} = $ENV{$name} + if ! exists $config{perlenv}->{$name}; + return $config{perlenv}->{$name}; +} + # Configuration printer ############################################## sub print_table_entry @@ -2529,9 +3074,12 @@ sub print_table_entry my @sequence = ( "sys_id", + "cpp", + "cppflags", + "defines", + "includes", "cc", "cflags", - "defines", "unistd", "ld", "lflags", diff --git a/ECDSA-PATCH-CHANGELOG b/ECDSA-PATCH-CHANGELOG deleted file mode 100644 index d4eae753..00000000 --- a/ECDSA-PATCH-CHANGELOG +++ /dev/null @@ -1,9 +0,0 @@ -Changelog [PATCH] OpenSSL1.1h - 30-40% ECDSA performance improvement -* Sat, 6 Jan 2018 08:21:45 +0100 -- Rebuilt to host the new upstream code (6 Jan 2018). -* Fri, 5 Jan 2018 20:45:22 +0100 -- Rebuilt to host the new upstream code (5 Jan 2018). -* Wed, 1 Jan 2018 21:39:19 +0100 -- Inital packaging. -- Based on OpenSSL 1.1.1dev pull 5001. - diff --git a/INSTALL b/INSTALL index 3e21cc29..3c8548dd 100644 --- a/INSTALL +++ b/INSTALL @@ -316,6 +316,13 @@ no-err Don't compile in any error strings. + enable-external-tests + Enable building of integration with external test suites. + This is a developer option and may not work on all platforms. + The only supported external test suite at the current time is + the BoringSSL test suite. See the file test/README.external + for further details. + no-filenames Don't compile in filename and line number information (e.g. for errors and memory allocation). @@ -332,9 +339,6 @@ available if the GOST algorithms are also available through loading an externally supplied engine. - enable-heartbeats - Build support for DTLS heartbeats. - no-hw-padlock Don't build the padlock engine. @@ -415,6 +419,9 @@ the OpenSSL tests also use the command line applications the tests will also be skipped. + no-tests + Don't build test programs or run any test. + no-threads Don't try to build with support for multi-threaded applications. @@ -426,6 +433,16 @@ require additional system-dependent options! See "Note on multi-threading" below. + enable-tls13downgrade + TODO(TLS1.3): Make this enabled by default and remove the + option when TLSv1.3 is out of draft + TLSv1.3 offers a downgrade protection mechanism. This is + implemented but disabled by default. It should not typically + be enabled except for testing purposes. Otherwise this could + cause problems if a pre-RFC version of OpenSSL talks to an + RFC implementation (it will erroneously be detected as a + downgrade). + no-ts Don't build Time Stamping Authority support. @@ -467,18 +484,22 @@ no- Don't build support for negotiating the specified SSL/TLS - protocol (one of ssl, ssl3, tls, tls1, tls1_1, tls1_2, dtls, - dtls1 or dtls1_2). If "no-tls" is selected then all of tls1, - tls1_1 and tls1_2 are disabled. Similarly "no-dtls" will - disable dtls1 and dtls1_2. The "no-ssl" option is synonymous - with "no-ssl3". Note this only affects version negotiation. - OpenSSL will still provide the methods for applications to - explicitly select the individual protocol versions. + protocol (one of ssl, ssl3, tls, tls1, tls1_1, tls1_2, + tls1_3, dtls, dtls1 or dtls1_2). If "no-tls" is selected then + all of tls1, tls1_1, tls1_2 and tls1_3 are disabled. + Similarly "no-dtls" will disable dtls1 and dtls1_2. The + "no-ssl" option is synonymous with "no-ssl3". Note this only + affects version negotiation. OpenSSL will still provide the + methods for applications to explicitly select the individual + protocol versions. no--method As for no- but in addition do not build the methods for applications to explicitly select individual protocol - versions. + versions. Note that there is no "no-tls1_3-method" option + because there is no application method for TLSv1.3. Using + individual protocol methods directly is deprecated. + Applications should use TLS_method() instead. enable- Build with support for the specified algorithm, where @@ -486,13 +507,14 @@ no- Build without support for the specified algorithm, where - is one of: bf, blake2, camellia, cast, chacha, cmac, - des, dh, dsa, ecdh, ecdsa, idea, md4, mdc2, ocb, poly1305, - rc2, rc4, rmd160, scrypt, seed or whirlpool. The "ripemd" - algorithm is deprecated and if used is synonymous with rmd160. + is one of: aria, bf, blake2, camellia, cast, chacha, + cmac, des, dh, dsa, ecdh, ecdsa, idea, md4, mdc2, ocb, + poly1305, rc2, rc4, rmd160, scrypt, seed, siphash, sm3, sm4 + or whirlpool. The "ripemd" algorithm is deprecated and if + used is synonymous with rmd160. - -Dxxx, lxxx, -Lxxx, -Wl, -rpath, -R, -framework, -static - These system specific options will be recocognised and + -Dxxx, -Ixxx, -Wp, -lxxx, -Lxxx, -Wl, -rpath, -R, -framework, -static + These system specific options will be recognised and passed through to the compiler to allow you to define preprocessor symbols, specify additional libraries, library directories or other compiler options. It might be worth @@ -502,11 +524,119 @@ unsuitable for execution on other, typically older, processor. Consult your compiler documentation. + Take note of the VAR=value documentation below and how + these flags interact with those variables. + -xxx, +xxx Additional options that are not otherwise recognised are passed through as they are to the compiler as well. Again, consult your compiler documentation. + Take note of the VAR=value documentation below and how + these flags interact with those variables. + + VAR=value + Assignment if environment variable for Configure. These + work just like normal environment variable assignments, + but are supported on all platforms and are confined to + the configuration scripts only. These assignments override + the corresponding value in the inherited environment, if + there is one. + + The following variables are used as "make variables" and + can be used as an alternative to giving preprocessor, + compiler and linker options directly as configuration. + The following variables are supported: + + AR The static library archiver. + ARFLAGS Flags for the static library archiver. + AS The assembler compiler. + ASFLAGS Flags for the assembler compiler. + CC The C compiler. + CFLAGS Flags for the C compiler. + CXX The C++ compiler. + CXXFLAGS Flags for the C++ compiler. + CPP The C/C++ preprocessor. + CPPFLAGS Flags for the C/C++ preprocessor. + CPPDEFINES List of CPP macro definitions, separated + by a platform specific character (':' or + space for Unix, ';' for Windows, ',' for + VMS). This can be used in place of -D. + CPPINCLUDES List of CPP inclusion directories, separated + the same way as for CPPDEFINES. This can + be used in place of -I. + HASHBANGPERL Perl invocation to be inserted after '#!' + in public perl scripts. + LD The program linker (not used on Unix, $(CC) + is used there). + LDFLAGS Flags for the shared library, DSO and + program linker. + LDLIBS Extra libraries to use when linking. + Takes the form of a space separated list + of library specifications on Unix and + Windows, and as a comma separated list of + libraries on VMS. + RANLIB The library archive indexer. + RC The Windows resources manipulator. + RCFLAGS Flags for the Windows reources manipulator. + RM The command to remove files and directories. + + These can be mixed with flags given on the command line. + Any variable assignment resets any corresponding flags + given before it, so for example: + + ./config -DFOO CPPFLAGS=-DBAR -DCOOKIE + + Will end up having 'CPPFLAGS=-DBAR -DCOOKIE'. + + Here is how the flags documented above are collected as + augmentation of these variables: + + -Dxxx xxx is collected in CPPDEFINES + -Ixxx xxx is collected in CPPINCLUDES + -Wp,xxx collected in CPPFLAGS + -Lxxx collected in LDFLAGS + -lxxx collected in LDLIBS + -Wp,xxx collected in LDLIBS + -rpath xxx collected in LDLIBS + -R xxx collected in LDLIBS + -framework xxx collected in LDLIBS + -static collected in LDLIBS + -xxx collected in CFLAGS + +xxx collected in CFLAGS + + reconf + reconfigure + Reconfigure from earlier data. This fetches the previous + command line options and environment from data saved in + "configdata.pm", and runs the configuration process again, + using these options and environment. + Note: NO other option is permitted together with "reconf". + This means that you also MUST use "./Configure" (or + what corresponds to that on non-Unix platforms) directly + to invoke this option. + Note: The original configuration saves away values for ALL + environment variables that were used, and if they weren't + defined, they are still saved away with information that + they weren't originally defined. This information takes + precedence over environment variables that are defined + when reconfiguring. + + Displaying configuration data + ----------------------------- + + The configuration script itself will say very little, and finishes by + creating "configdata.pm". This perl module can be loaded by other scripts + to find all the configuration data, and it can also be used as a script to + display all sorts of configuration data in a human readable form. + + For more information, please do: + + $ ./configdata.pm --help # Unix + + or + + $ perl configdata.pm --help # Windows and VMS Installation in Detail ---------------------- @@ -619,22 +749,34 @@ ("openssl"). The libraries will be built in the top-level directory, and the binary will be in the "apps" subdirectory. + Troubleshooting: + If the build fails, look at the output. There may be reasons for the failure that aren't problems in OpenSSL itself (like - missing standard headers). If you are having problems you can - get help by sending an email to the openssl-users email list (see + missing standard headers). + + If the build succeeded previously, but fails after a source or + configuration change, it might be helpful to clean the build tree + before attempting another build. Use this command: + + $ make clean # Unix + $ mms clean ! (or mmk) OpenVMS + $ nmake clean # Windows + + Assembler error messages can sometimes be sidestepped by using the + "no-asm" configuration option. + + Compiling parts of OpenSSL with gcc and others with the system + compiler will result in unresolved symbols on some systems. + + If you are still having problems you can get help by sending an email + to the openssl-users email list (see https://www.openssl.org/community/mailinglists.html for details). If it is a bug with OpenSSL itself, please open an issue on GitHub, at https://github.com/openssl/openssl/issues. Please review the existing ones first; maybe the bug was already reported or has already been fixed. - (If you encounter assembler error messages, try the "no-asm" - configuration option as an immediate fix.) - - Compiling parts of OpenSSL with gcc and others with the system - compiler will result in unresolved symbols on some systems. - 3. After a successful build, the libraries should be tested. Run: $ make test # Unix @@ -682,6 +824,9 @@ To report a bug please open an issue on GitHub, at https://github.com/openssl/openssl/issues. + For more details on how the make variables TESTS can be used, + see section TESTS in Detail below. + 4. If everything tests ok, install OpenSSL with $ make install # Unix @@ -819,11 +964,14 @@ possible to create your own ".conf" and ".tmpl" files and store them locally, outside the OpenSSL source tree. This environment variable can be set to the directory where these files are held - and will have Configure to consider them in addition to the - standard ones. + and will be considered by Configure before it looks in the + standard directories. PERL The name of the Perl executable to use when building OpenSSL. + This variable is used in config script only. Configure on the + other hand imposes the interpreter by which it itself was + executed on the whole build procedure. HASHBANGPERL The command string for the Perl executable to insert in the @@ -888,12 +1036,68 @@ uninstall Uninstall all OpenSSL components. + reconfigure + reconf + Re-run the configuration process, as exactly as the last time + as possible. + update This is a developer option. If you are developing a patch for OpenSSL you may need to use this if you want to update automatically generated files; add new error codes or add new (or change the visibility of) public API functions. (Unix only). + TESTS in Detail + --------------- + + The make variable TESTS supports a versatile set of space separated tokens + with which you can specify a set of tests to be performed. With a "current + set of tests" in mind, initially being empty, here are the possible tokens: + + alltests The current set of tests becomes the whole set of available + tests (as listed when you do 'make list-tests' or similar). + xxx Adds the test 'xxx' to the current set of tests. + -xxx Removes 'xxx' from the current set of tests. If this is the + first token in the list, the current set of tests is first + assigned the whole set of available tests, effectively making + this token equivalent to TESTS="alltests -xxx". + nn Adds the test group 'nn' (which is a number) to the current + set of tests. + -nn Removes the test group 'nn' from the current set of tests. + If this is the first token in the list, the current set of + tests is first assigned the whole set of available tests, + effectively making this token equivalent to + TESTS="alltests -xxx". + + Also, all tokens except for "alltests" may have wildcards, such as *. + (on Unix and Windows, BSD style wildcards are supported, while on VMS, + it's VMS style wildcards) + + Example: All tests except for the fuzz tests: + + $ make TESTS=-test_fuzz test + + or (if you want to be explicit) + + $ make TESTS='alltests -test_fuzz' test + + Example: All tests that have a name starting with "test_ssl" but not those + starting with "test_ssl_": + + $ make TESTS='test_ssl* -test_ssl_*' test + + Example: Only test group 10: + + $ make TESTS='10' + + Example: All tests except the slow group (group 99): + + $ make TESTS='-99' + + Example: All tests in test groups 80 to 99 except for tests in group 90: + + $ make TESTS='[89]? -90' + Note on multi-threading ----------------------- diff --git a/Makefile.shared b/Makefile.shared deleted file mode 100644 index 4f9550aa..00000000 --- a/Makefile.shared +++ /dev/null @@ -1,521 +0,0 @@ -# -# Helper makefile to link shared libraries in a portable way. -# This is much simpler than libtool, and hopefully not too error-prone. -# -# The following variables need to be set on the command line to build -# properly - -# CC contains the current compiler. This one MUST be defined -CC=cc -CFLAGS=$(CFLAG) -# LDFLAGS contains flags to be used when temporary object files (when building -# shared libraries) are created, or when an application is linked. -# SHARED_LDFLAGS contains flags to be used when the shared library is created. -LDFLAGS=$(LDFLAG) -SHARED_LDFLAGS=$(SHARED_LDFLAG) - -RC=windres -# SHARED_RCFLAGS are flags used with windres, i.e. when build for Cygwin -# or Mingw. -SHARED_RCFLAGS=$(SHARED_RCFLAG) - -NM=nm - -# LIBNAME contains just the name of the library, without prefix ("lib" -# on Unix, "cyg" for certain forms under Cygwin...) or suffix (.a, .so, -# .dll, ...). This one MUST have a value when using this makefile to -# build shared libraries. -# For example, to build libfoo.so, you need to do the following: -#LIBNAME=foo -LIBNAME= - -# STLIBNAME contains the path of the static library to build the shared -# library from, for example: -#STLIBNAME=libfoo.a -STLIBNAME= - -# On most Unix platforms, SHLIBNAME contains the path of the short name of -# the shared library to build, for example -#SHLIBNAME=libfoo.so -# On Windows POSIX layers (cygwin and mingw), SHLIBNAME contains the import -# library name for the shared library to be built, for example: -#SHLIBNAME=libfoo.dll.a - -# SHLIBNAME_FULL contains the path of the full name of the shared library to -# build, for example: -#SHLIBNAME_FULL=libfoo.so.1.2 -# When building DSOs, SHLIBNAME_FULL contains path of the full DSO name, for -# example: -#SHLIBNAME_FULL=dir/dso.so -SHLIBNAME_FULL= - -# SHLIBVERSION contains the current version of the shared library (not to -# be confused with the project version) -#SHLIBVERSION=1.2 -SHLIBVERSION= - -# NOTE: to build shared libraries, LIBNAME, STLIBNAME, SHLIBNAME and -# SHLIBNAME_FULL MUST have values when using this makefile, and in some -# cases, SHLIBVERSION as well. To build DSOs, SHLIBNAME_FULL MUST have -# a value, the rest can be left alone. - - -# APPNAME contains just the name of the application, without suffix ("" -# on Unix, ".exe" on Windows, ...). This one MUST have a value when using -# this makefile to build applications. -# For example, to build foo, you need to do the following: -#APPNAME=foo -APPNAME= - -# SRCDIR is the top directory of the source tree. -SRCDIR=. - -# OBJECTS contains all the object files to link together into the application. -# This must contain at least one object file. -#OBJECTS=foo.o -OBJECTS= - -# LIBEXTRAS contains extra modules to link together with the library. -# For example, if a second library, say libbar.a needs to be linked into -# libfoo.so, you need to do the following: -#LIBEXTRAS=libbar.a -# Note that this MUST be used when using the link_dso targets, to hold the -# names of all object files that go into the target shared object. -LIBEXTRAS= - -# LIBDEPS contains all the flags necessary to cover all necessary -# dependencies to other libraries. -LIBDEPS= - -#------------------------------------------------------------------------------ -# The rest is private to this makefile. - -SET_X=: -#SET_X=set -x - -top: - echo "Trying to use this makefile interactively? Don't." - -LINK_APP= \ - ( $(SET_X); \ - LIBDEPS="$${LIBDEPS:-$(LIBDEPS)}"; \ - LDCMD="$${LDCMD:-$(CC)}"; LDFLAGS="$${LDFLAGS:-$(CFLAGS) $(LDFLAGS)}"; \ - LIBPATH=`for x in $$LIBDEPS; do echo $$x; done | sed -e 's/^ *-L//;t' -e d | uniq`; \ - LIBPATH=`echo $$LIBPATH | sed -e 's/ /:/g'`; \ - echo LD_LIBRARY_PATH=$$LIBPATH:$$LD_LIBRARY_PATH \ - $${LDCMD} $${LDFLAGS} -o $${APPNAME:=$(APPNAME)} $(OBJECTS) $${LIBDEPS}; \ - LD_LIBRARY_PATH=$$LIBPATH:$$LD_LIBRARY_PATH \ - $${LDCMD} $${LDFLAGS} -o $${APPNAME:=$(APPNAME)} $(OBJECTS) $${LIBDEPS} ) - -LINK_SO= \ - ( $(SET_X); \ - LIBDEPS="$${LIBDEPS:-$(LIBDEPS)}"; \ - SHAREDCMD="$${SHAREDCMD:-$(CC)}"; \ - SHAREDFLAGS="$${SHAREDFLAGS:-$(CFLAGS) $(SHARED_LDFLAGS)}"; \ - LIBPATH=`for x in $$LIBDEPS; do echo $$x; done | sed -e 's/^ *-L//;t' -e d | uniq`; \ - LIBPATH=`echo $$LIBPATH | sed -e 's/ /:/g'`; \ - echo LD_LIBRARY_PATH=$$LIBPATH:$$LD_LIBRARY_PATH \ - $${SHAREDCMD} $${SHAREDFLAGS} \ - -o $(SHLIBNAME_FULL) \ - $$ALLSYMSFLAGS $$SHOBJECTS $$NOALLSYMSFLAGS $$LIBDEPS; \ - LD_LIBRARY_PATH=$$LIBPATH:$$LD_LIBRARY_PATH \ - $${SHAREDCMD} $${SHAREDFLAGS} \ - -o $(SHLIBNAME_FULL) \ - $$ALLSYMSFLAGS $$SHOBJECTS $$NOALLSYMSFLAGS $$LIBDEPS \ - ) && $(SYMLINK_SO) - -SYMLINK_SO= \ - if [ -n "$$INHIBIT_SYMLINKS" ]; then :; else \ - if [ -n "$(SHLIBNAME_FULL)" -a -n "$(SHLIBNAME)" -a \ - "$(SHLIBNAME_FULL)" != "$(SHLIBNAME)" ]; then \ - ( $(SET_X); \ - rm -f $(SHLIBNAME); \ - ln -s $(SHLIBNAME_FULL) $(SHLIBNAME) ); \ - fi; \ - fi - -LINK_SO_SHLIB= SHOBJECTS="$(STLIBNAME) $(LIBEXTRAS)"; $(LINK_SO) -LINK_SO_DSO= INHIBIT_SYMLINKS=yes; SHOBJECTS="$(LIBEXTRAS)"; $(LINK_SO) - -LINK_SO_SHLIB_VIA_O= \ - SHOBJECTS=$(STLIBNAME).o; \ - ALL=$$ALLSYMSFLAGS; ALLSYMSFLAGS=; NOALLSYMSFLAGS=; \ - ( echo ld $(LDFLAGS) -r -o $$SHOBJECTS $$ALL $(STLIBNAME) $(LIBEXTRAS); \ - ld $(LDFLAGS) -r -o $$SHOBJECTS $$ALL $(STLIBNAME) $(LIBEXTRAS) ); \ - $(LINK_SO) && ( echo rm -f $$SHOBJECTS; rm -f $$SHOBJECTS ) - -LINK_SO_SHLIB_UNPACKED= \ - UNPACKDIR=link_tmp.$$$$; rm -rf $$UNPACKDIR; mkdir $$UNPACKDIR; \ - (cd $$UNPACKDIR; ar x ../$(STLIBNAME)) && \ - ([ -z "$(LIBEXTRAS)" ] || cp $(LIBEXTRAS) $$UNPACKDIR) && \ - SHOBJECTS=$$UNPACKDIR/*.o; \ - $(LINK_SO) && rm -rf $$UNPACKDIR - -DETECT_GNU_LD=($(CC) -Wl,-V /dev/null 2>&1 | grep '^GNU ld' )>/dev/null - -DO_GNU_SO_COMMON=\ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -shared -Wl,-Bsymbolic -Wl,-soname=$(SHLIBNAME_FULL)" -DO_GNU_DSO=\ - $(DO_GNU_SO_COMMON) -DO_GNU_SO=\ - ALLSYMSFLAGS='-Wl,--whole-archive'; \ - NOALLSYMSFLAGS='-Wl,--no-whole-archive'; \ - $(DO_GNU_SO_COMMON) -DO_GNU_APP=LDFLAGS="$(CFLAGS) $(LDFLAGS)" - -#This is rather special. It's a special target with which one can link -#applications without bothering with any features that have anything to -#do with shared libraries, for example when linking against static -#libraries. It's mostly here to avoid a lot of conditionals everywhere -#else... -link_app.: - $(LINK_APP) - -link_dso.gnu: - @ $(DO_GNU_DSO); $(LINK_SO_DSO) -link_shlib.gnu: - @ $(DO_GNU_SO); $(LINK_SO_SHLIB) -link_app.gnu: - @ $(DO_GNU_APP); $(LINK_APP) - -link_shlib.linux-shared: - @$(PERL) $(SRCDIR)/util/mkdef.pl $(LIBNAME) linux >$(LIBNAME).map; \ - $(DO_GNU_SO); \ - ALLSYMSFLAGS='-Wl,--whole-archive,--version-script=$(LIBNAME).map'; \ - $(LINK_SO_SHLIB) - -link_dso.bsd: - @if $(DETECT_GNU_LD); then $(DO_GNU_DSO); else \ - LIBDEPS=" "; \ - ALLSYMSFLAGS=; \ - NOALLSYMSFLAGS=; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -shared -nostdlib"; \ - fi; $(LINK_SO_DSO) -link_shlib.bsd: - @if $(DETECT_GNU_LD); then $(DO_GNU_SO); else \ - LIBDEPS=" "; \ - ALLSYMSFLAGS="-Wl,-Bforcearchive"; \ - NOALLSYMSFLAGS=; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -shared -nostdlib"; \ - fi; $(LINK_SO_SHLIB) -link_app.bsd: - @if $(DETECT_GNU_LD); then $(DO_GNU_APP); else \ - LDFLAGS="$(CFLAGS) $(LDFLAGS)"; \ - fi; $(LINK_APP) - -# For Darwin AKA Mac OS/X (dyld) -# Originally link_dso.darwin produced .so, because it was hard-coded -# in dso_dlfcn module. At later point dso_dlfcn switched to .dylib -# extension in order to allow for run-time linking with vendor- -# supplied shared libraries such as libz, so that link_dso.darwin had -# to be harmonized with it. This caused minor controversy, because -# it was believed that dlopen can't be used to dynamically load -# .dylib-s, only so called bundle modules (ones linked with -bundle -# flag). The belief seems to be originating from pre-10.4 release, -# where dlfcn functionality was emulated by dlcompat add-on. In -# 10.4 dlopen was rewritten as native part of dyld and is documented -# to be capable of loading both dynamic libraries and bundles. In -# order to provide compatibility with pre-10.4 dlopen, modules are -# linked with -bundle flag, which makes .dylib extension misleading. -# It works, because dlopen is [and always was] extension-agnostic. -# Alternative to this heuristic approach is to develop specific -# MacOS X dso module relying on whichever "native" dyld interface. -link_dso.darwin: - @ ALLSYMSFLAGS=''; \ - NOALLSYMSFLAGS=''; \ - SHAREDFLAGS="$(CFLAGS) `echo $(SHARED_LDFLAGS) | sed s/dynamiclib/bundle/`"; \ - $(LINK_SO_DSO) -link_shlib.darwin: - @ ALLSYMSFLAGS='-all_load'; \ - NOALLSYMSFLAGS=''; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -current_version $(SHLIBVERSION) -compatibility_version $(SHLIBVERSION) -install_name $(INSTALLTOP)/$(LIBDIR)/$(SHLIBNAME_FULL)"; \ - $(LINK_SO_SHLIB) -link_app.darwin: # is there run-path on darwin? - $(LINK_APP) - -link_dso.cygwin: - @ALLSYMSFLAGS=''; \ - NOALLSYMSFLAGS=''; \ - base=-Wl,--enable-auto-image-base; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -shared $$base -Wl,-Bsymbolic"; \ - $(LINK_SO_DSO) -link_shlib.cygwin: - @ INHIBIT_SYMLINKS=yes; \ - echo "$(PERL) $(SRCDIR)/util/mkrc.pl $(SHLIBNAME_FULL) |" \ - "$(RC) $(SHARED_RCFLAGS) -o rc.o"; \ - $(PERL) $(SRCDIR)/util/mkrc.pl $(SHLIBNAME_FULL) | \ - $(RC) $(SHARED_RCFLAGS) -o rc.o; \ - ALLSYMSFLAGS='-Wl,--whole-archive'; \ - NOALLSYMSFLAGS='-Wl,--no-whole-archive'; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -shared -Wl,--enable-auto-image-base -Wl,-Bsymbolic -Wl,--out-implib,$(SHLIBNAME) rc.o"; \ - $(LINK_SO_SHLIB) || exit 1; \ - rm rc.o -link_app.cygwin: - $(LINK_APP) - -# link_dso.mingw-shared and link_app.mingw-shared are mapped to the -# corresponding cygwin targets, as they do the exact same thing. -link_shlib.mingw: - @ INHIBIT_SYMLINKS=yes; \ - base=; [ $(LIBNAME) = "crypto" -a -n "$(FIPSCANLIB)" ] && base=-Wl,--image-base,0x63000000; \ - $(PERL) $(SRCDIR)/util/mkdef.pl 32 $(LIBNAME) \ - | sed -e 's|^\(LIBRARY *\)$(LIBNAME)32|\1$(SHLIBNAME_FULL)|' \ - > $(LIBNAME).def; \ - echo "$(PERL) $(SRCDIR)/util/mkrc.pl $(SHLIBNAME_FULL) |" \ - "$(RC) $(SHARED_RCFLAGS) -o rc.o"; \ - $(PERL) $(SRCDIR)/util/mkrc.pl $(SHLIBNAME_FULL) | \ - $(RC) $(SHARED_RCFLAGS) -o rc.o; \ - ALLSYMSFLAGS='-Wl,--whole-archive'; \ - NOALLSYMSFLAGS='-Wl,--no-whole-archive'; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -shared $$base -Wl,-Bsymbolic -Wl,--out-implib,$(SHLIBNAME) $(LIBNAME).def rc.o"; \ - $(LINK_SO_SHLIB) || exit 1; \ - rm $(LIBNAME).def rc.o - -link_dso.alpha-osf1: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_DSO); \ - else \ - ALLSYMSFLAGS=''; \ - NOALLSYMSFLAGS=''; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -shared -Wl,-B,symbolic"; \ - fi; \ - $(LINK_SO_DSO) -link_shlib.alpha-osf1: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_SO); \ - else \ - ALLSYMSFLAGS='-all'; \ - NOALLSYMSFLAGS='-none'; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -shared -Wl,-B,symbolic -set_version $(SHLIBVERSION)"; \ - fi; \ - $(LINK_SO_SHLIB) -link_app.alpha-osf1: - @if $(DETECT_GNU_LD); then \ - $(DO_GNU_APP); \ - else \ - LDFLAGS="$(CFLAGS) $(LDFLAGS)"; \ - fi; \ - $(LINK_APP) - -link_dso.solaris: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_DSO); \ - else \ - ALLSYMSFLAGS=""; \ - NOALLSYMSFLAGS=""; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -h $(SHLIBNAME_FULL) -Wl,-Bsymbolic"; \ - fi; \ - $(LINK_SO_DSO) -link_shlib.solaris: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_SO); \ - else \ - $(PERL) $(SRCDIR)/util/mkdef.pl $(LIBNAME) linux >$(LIBNAME).map; \ - ALLSYMSFLAGS="-Wl,-z,allextract,-M,$(LIBNAME).map"; \ - NOALLSYMSFLAGS="-Wl,-z,defaultextract"; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -h $(SHLIBNAME_FULL) -Wl,-Bsymbolic"; \ - fi; \ - $(LINK_SO_SHLIB) -link_app.solaris: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_APP); \ - else \ - LDFLAGS="$(CFLAGS) $(LDFLAGS)"; \ - fi; \ - $(LINK_APP) - -# OpenServer 5 native compilers used -link_dso.svr3: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_DSO); \ - else \ - ALLSYMSFLAGS=''; \ - NOALLSYMSFLAGS=''; \ - SHAREDFLAGS="$(CFLAGS) -G -h $(SHLIBNAME_FULL)"; \ - fi; \ - $(LINK_SO_DSO) -link_shlib.svr3: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_SO); \ - else \ - ALLSYMSFLAGS=''; \ - NOALLSYMSFLAGS=''; \ - SHAREDFLAGS="$(CFLAGS) -G -h $(SHLIBNAME_FULL)"; \ - fi; \ - $(LINK_SO_SHLIB_UNPACKED) -link_app.svr3: - @$(DETECT_GNU_LD) && $(DO_GNU_APP); \ - $(LINK_APP) - -# UnixWare 7 and OpenUNIX 8 native compilers used -link_dso.svr5: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_DSO); \ - else \ - SHARE_FLAG='-G'; \ - ($(CC) -v 2>&1 | grep gcc) > /dev/null && SHARE_FLAG='-shared'; \ - ALLSYMSFLAGS=''; \ - NOALLSYMSFLAGS=''; \ - SHAREDFLAGS="$(CFLAGS) $${SHARE_FLAG} -h $(SHLIBNAME_FULL)"; \ - fi; \ - $(LINK_SO_DSO) -link_shlib.svr5: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_SO); \ - else \ - SHARE_FLAG='-G'; \ - ($(CC) -v 2>&1 | grep gcc) > /dev/null && SHARE_FLAG='-shared'; \ - ALLSYMSFLAGS=''; \ - NOALLSYMSFLAGS=''; \ - SHAREDFLAGS="$(CFLAGS) $${SHARE_FLAG} -h $(SHLIBNAME_FULL)"; \ - fi; \ - $(LINK_SO_SHLIB_UNPACKED) -link_app.svr5: - @$(DETECT_GNU_LD) && $(DO_GNU_APP); \ - $(LINK_APP) - -link_dso.irix: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_DSO); \ - else \ - ALLSYMSFLAGS=""; \ - NOALLSYMSFLAGS=""; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -shared -Wl,-soname,$(SHLIBNAME_FULL),-B,symbolic"; \ - fi; \ - $(LINK_SO_DSO) -link_shlib.irix: - @ if $(DETECT_GNU_LD); then \ - $(DO_GNU_SO); \ - else \ - MINUSWL=""; \ - ($(CC) -v 2>&1 | grep gcc) > /dev/null && MINUSWL="-Wl,"; \ - ALLSYMSFLAGS="$${MINUSWL}-all"; \ - NOALLSYMSFLAGS="$${MINUSWL}-none"; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -shared -Wl,-soname,$(SHLIBNAME_FULL),-B,symbolic"; \ - fi; \ - $(LINK_SO_SHLIB) -link_app.irix: - @LDFLAGS="$(CFLAGS) $(LDFLAGS)"; \ - $(LINK_APP) - -# 32-bit PA-RISC HP-UX embeds the -L pathname of libs we link with, so -# we compensate for it with +cdp ../: and +cdp ./:. Yes, these rewrite -# rules imply that we can only link one level down in catalog structure, -# but that's what takes place for the moment of this writing. +cdp option -# was introduced in HP-UX 11.x and applies in 32-bit PA-RISC link -# editor context only [it's simply ignored in other cases, which are all -# ELFs by the way]. -# -link_dso.hpux: - @if $(DETECT_GNU_LD); then $(DO_GNU_DSO); else \ - ALLSYMSFLAGS=''; \ - NOALLSYMSFLAGS=''; \ - expr $(PLATFORM) : 'hpux64' > /dev/null && ALLSYMSFLAGS='-Wl,+forceload'; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -Wl,-B,symbolic,+vnocompatwarnings,-z,+s,+h,$(SHLIBNAME_FULL),+cdp,../:,+cdp,./:"; \ - fi; \ - rm -f $(SHLIBNAME_FULL) || :; \ - $(LINK_SO_DSO) && chmod a=rx $(SHLIBNAME_FULL) -link_shlib.hpux: - @if $(DETECT_GNU_LD); then $(DO_GNU_SO); else \ - ALLSYMSFLAGS='-Wl,-Fl'; \ - NOALLSYMSFLAGS=''; \ - expr $(PLATFORM) : 'hpux64' > /dev/null && ALLSYMSFLAGS='-Wl,+forceload'; \ - SHAREDFLAGS="$(CFLAGS) $(SHARED_LDFLAGS) -Wl,-B,symbolic,+vnocompatwarnings,-z,+s,+h,$(SHLIBNAME_FULL),+cdp,../:,+cdp,./:"; \ - fi; \ - rm -f $(SHLIBNAME_FULL) || :; \ - $(LINK_SO_SHLIB) && chmod a=rx $(SHLIBNAME_FULL) -link_app.hpux: - @if $(DETECT_GNU_LD); then $(DO_GNU_APP); else \ - LDFLAGS="$(CFLAGS) $(LDFLAGS) -Wl,+s,+cdp,../:,+cdp,./:"; \ - fi; \ - $(LINK_APP) - -link_dso.aix: - @OBJECT_MODE=`expr "x$(SHARED_LDFLAGS)" : 'x\-[a-z]*\(64\)'` || :; \ - OBJECT_MODE=$${OBJECT_MODE:-32}; export OBJECT_MODE; \ - ALLSYMSFLAGS=''; \ - NOALLSYMSFLAGS=''; \ - SHAREDFLAGS='$(CFLAGS) $(SHARED_LDFLAGS) -Wl,-bexpall,-bnolibpath,-bM:SRE'; \ - rm -f $(SHLIBNAME_FULL) 2>&1 > /dev/null ; \ - $(LINK_SO_DSO); -link_shlib.aix: - @ OBJECT_MODE=`expr "x$(SHARED_LDFLAGS)" : 'x\-[a-z]*\(64\)'` || : ; \ - OBJECT_MODE=$${OBJECT_MODE:-32}; export OBJECT_MODE; \ - ALLSYMSFLAGS='-bnogc'; \ - NOALLSYMSFLAGS=''; \ - SHAREDFLAGS='$(CFLAGS) $(SHARED_LDFLAGS) -Wl,-bexpall,-bnolibpath,-bM:SRE'; \ - rm -f $(SHLIBNAME_FULL) 2>&1 > /dev/null ; \ - $(LINK_SO_SHLIB_VIA_O) -link_app.aix: - LDFLAGS="$(CFLAGS) -Wl,-bsvr4 $(LDFLAGS)"; \ - $(LINK_APP) - - -# Targets to build symbolic links when needed -symlink.gnu symlink.solaris symlink.svr3 symlink.svr5 symlink.irix \ -symlink.aix: - @ $(SYMLINK_SO) -symlink.darwin: - @ $(SYMLINK_SO) -symlink.hpux: - @ $(SYMLINK_SO) -# The following lines means those specific architectures do no symlinks -symlink.cygwin symlink.alpha-osf1 symlink.tru64 symlink.tru64-rpath: - -# Compatibility targets -link_dso.bsd-gcc-shared link_dso.linux-shared link_dso.gnu-shared: link_dso.gnu -link_shlib.bsd-gcc-shared: link_shlib.linux-shared -link_shlib.gnu-shared: link_shlib.gnu -link_app.bsd-gcc-shared link_app.linux-shared link_app.gnu-shared: link_app.gnu -symlink.bsd-gcc-shared symlink.bsd-shared symlink.linux-shared symlink.gnu-shared: symlink.gnu -link_dso.bsd-shared: link_dso.bsd -link_shlib.bsd-shared: link_shlib.bsd -link_app.bsd-shared: link_app.bsd -link_dso.darwin-shared: link_dso.darwin -link_shlib.darwin-shared: link_shlib.darwin -link_app.darwin-shared: link_app.darwin -symlink.darwin-shared: symlink.darwin -link_dso.cygwin-shared: link_dso.cygwin -link_shlib.cygwin-shared: link_shlib.cygwin -link_app.cygwin-shared: link_app.cygwin -symlink.cygwin-shared: symlink.cygwin -link_dso.mingw-shared: link_dso.cygwin -link_shlib.mingw-shared: link_shlib.mingw -link_app.mingw-shared: link_app.cygwin -symlink.mingw-shared: symlink.cygwin -link_dso.alpha-osf1-shared: link_dso.alpha-osf1 -link_shlib.alpha-osf1-shared: link_shlib.alpha-osf1 -link_app.alpha-osf1-shared: link_app.alpha-osf1 -symlink.alpha-osf1-shared: symlink.alpha-osf1 -link_dso.tru64-shared: link_dso.tru64 -link_shlib.tru64-shared: link_shlib.tru64 -link_app.tru64-shared: link_app.tru64 -symlink.tru64-shared: symlink.tru64 -link_dso.tru64-shared-rpath: link_dso.tru64-rpath -link_shlib.tru64-shared-rpath: link_shlib.tru64-rpath -link_app.tru64-shared-rpath: link_app.tru64-rpath -symlink.tru64-shared-rpath: symlink.tru64-rpath -link_dso.solaris-shared: link_dso.solaris -link_shlib.solaris-shared: link_shlib.solaris -link_app.solaris-shared: link_app.solaris -symlink.solaris-shared: symlink.solaris -link_dso.svr3-shared: link_dso.svr3 -link_shlib.svr3-shared: link_shlib.svr3 -link_app.svr3-shared: link_app.svr3 -symlink.svr3-shared: symlink.svr3 -link_dso.svr5-shared: link_dso.svr5 -link_shlib.svr5-shared: link_shlib.svr5 -link_app.svr5-shared: link_app.svr5 -symlink.svr5-shared: symlink.svr5 -link_dso.irix-shared: link_dso.irix -link_shlib.irix-shared: link_shlib.irix -link_app.irix-shared: link_app.irix -symlink.irix-shared: symlink.irix -link_dso.hpux-shared: link_dso.hpux -link_shlib.hpux-shared: link_shlib.hpux -link_app.hpux-shared: link_app.hpux -symlink.hpux-shared: symlink.hpux -link_dso.aix-shared: link_dso.aix -link_shlib.aix-shared: link_shlib.aix -link_app.aix-shared: link_app.aix -symlink.aix-shared: symlink.aix diff --git a/NEWS b/NEWS index 8744fe68..c60da874 100644 --- a/NEWS +++ b/NEWS @@ -5,11 +5,25 @@ 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.1.0g and OpenSSL 1.1.0h [27 Mar 2018] + Major changes between OpenSSL 1.1.0g and OpenSSL 1.1.1 [in pre-release] + + o Support for TLSv1.3 added + o Move the display of configuration data to configdata.pm. + o Allow GNU style "make variables" to be used with Configure. + o Add a STORE module (OSSL_STORE) + o Claim the namespaces OSSL and OPENSSL, represented as symbol prefixes + o Add multi-prime RSA (RFC 8017) support + o Add SM3 implemented according to GB/T 32905-2016 + o Add SM4 implemented according to GB/T 32907-2016. + o Add 'Maximum Fragment Length' TLS extension negotiation and support + o Add ARIA support + o Add SHA3 + o Rewrite of devcrypto engine + o Add support for SipHash + o Grand redesign of the OpenSSL random generator + + Major changes between OpenSSL 1.1.0g and OpenSSL 1.1.0h [under development] - o Constructed ASN.1 types with a recursive definition could exceed the - stack (CVE-2018-0739) - o Incorrect CRYPTO_memcmp on HP-UX PA-RISC (CVE-2018-0733) o rsaz_1024_mul_avx2 overflow bug on x86_64 (CVE-2017-3738) Major changes between OpenSSL 1.1.0f and OpenSSL 1.1.0g [2 Nov 2017] @@ -367,7 +381,7 @@ o Compression memory leak fixed. o Compression session resumption fixed. o Ticket and SNI coexistence fixes. - o Many fixes to DTLS handling. + o Many fixes to DTLS handling. Major changes between OpenSSL 0.9.8k and OpenSSL 0.9.8l [5 Nov 2009]: @@ -400,7 +414,7 @@ o Add gcc 4.2 support. o Add support for AES and SSE2 assembly language optimization for VC++ build. - o Support for RFC4507bis and server name extensions if explicitly + o Support for RFC4507bis and server name extensions if explicitly selected at compile time. o DTLS improvements. o RFC4507bis support. @@ -493,7 +507,7 @@ 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 + o New X509_VERIFY_PARAM structure to support parameterisation of X.509 path validation. o Major overhaul of RC4 performance on Intel P4, IA-64 and AMD64. @@ -580,7 +594,7 @@ 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 + 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. @@ -640,7 +654,7 @@ 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. + 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). @@ -653,7 +667,7 @@ 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 + Bleichbacher's attack o Security: make RSA blinding default. o Build: shared library support fixes. @@ -765,7 +779,7 @@ 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 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 @@ -779,7 +793,7 @@ 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 New SPKAC command line utility 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 @@ -861,8 +875,7 @@ 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 Added support for RC2/64bit cipher o Extended ASN.1 parser routines - o Adjustations of the source tree for CVS + o Adjustments of the source tree for CVS o Support for various new platforms - diff --git a/NOTES.UNIX b/NOTES.UNIX index 43146e9e..32361072 100644 --- a/NOTES.UNIX +++ b/NOTES.UNIX @@ -28,3 +28,15 @@ $ ./config --prefix=/usr/local/ssl --openssldir=/usr/local/ssl \ -Wl,-rpath,'$(LIBRPATH)' + + On modern systems using GNU ld.so, a better choice may be to use the + new dtags, like this: + + $ ./config --prefix=/usr/local/ssl --openssldir=/usr/local/ssl \ + -Wl,--enable-new-dtags,-rpath,'$(LIBRPATH)' + + This sets DT_RUNPATH instead of DT_RPATH. DT_RUNPATH is considered after + the environment variable LD_LIBRARY_PATH, while DT_RPATH is considered + before that environment variable (which means that the values in that + environment variable won't matter if the library is found in the + paths given by DT_RPATH). diff --git a/NOTES.VMS b/NOTES.VMS index 3e9a57e8..98def068 100644 --- a/NOTES.VMS +++ b/NOTES.VMS @@ -56,6 +56,32 @@ to use. + About debugging + --------------- + + If you build for debugging, the default on VMS is that image + activation starts the debugger automatically, giving you a debug + prompt. Unfortunately, this disrupts all other uses, such as running + test programs in the test framework. + + Generally speaking, if you build for debugging, only use the programs + directly for debugging. Do not try to use them from a script, such + as running the test suite. + + *The following is not available on Alpha* + + As a compromise, we're turning off the flag that makes the debugger + start automatically. If there is a program that you need to debug, + you need to turn that flag back on first, for example: + + $ set image /flag=call_debug [.test]evp_test.exe + + Then just run it and you will find yourself in a debugging session. + When done, we recommend that you turn that flag back off: + + $ set image /flag=nocall_debug [.test]evp_test.exe + + Checking the distribution ------------------------- diff --git a/NOTES.WIN b/NOTES.WIN index c31aed92..ac215c36 100644 --- a/NOTES.WIN +++ b/NOTES.WIN @@ -6,7 +6,7 @@ -------------------------------------------------- In addition to the requirements and instructions listed in INSTALL, - this are required as well: + these are required as well: - You need Perl. We recommend ActiveState Perl, available from https://www.activestate.com/ActivePerl. Another viable alternative diff --git a/README b/README index 3491280e..344f1619 100644 --- a/README +++ b/README @@ -1,7 +1,7 @@ - OpenSSL 1.1.0h 27 Mar 2018 + OpenSSL 1.1.1-pre2 (alpha) 27 Feb 2018 - Copyright (c) 1998-2016 The OpenSSL Project + Copyright (c) 1998-2018 The OpenSSL Project Copyright (c) 1995-1998 Eric A. Young, Tim J. Hudson All rights reserved. @@ -62,14 +62,13 @@ - Download the latest version from the repository to see if the problem has already been addressed - Configure with no-asm - - Remove compiler optimisation flags + - Remove compiler optimization flags If you wish to report a bug then please include the following information and create an issue on GitHub: - OpenSSL version: output of 'openssl version -a' - - Any "Configure" options that you selected during compilation of the - library if applicable (see INSTALL) + - Configuration data: output of 'perl configdata.pm --dump' - OS Name, Version, Hardware platform - Compiler Details (name, version) - Application Details (name, version) diff --git a/README.ENGINE b/README.ENGINE index 530a4edd..230dc82a 100644 --- a/README.ENGINE +++ b/README.ENGINE @@ -13,7 +13,6 @@ There are currently built-in ENGINE implementations for the following crypto devices: - o Cryptodev o Microsoft CryptoAPI o VIA Padlock o nCipher CHIL diff --git a/VMS/engine.opt b/VMS/engine.opt index 1c73c800..9725023a 100644 --- a/VMS/engine.opt +++ b/VMS/engine.opt @@ -1,2 +1,3 @@ CASE_SENSITIVE=YES -SYMBOL_VECTOR=(bind_engine=PROCEDURE,v_check=PROCEDURE) +SYMBOL_VECTOR=(BIND_ENGINE=PROCEDURE,V_CHECK=PROCEDURE,- + bind_engine/BIND_ENGINE=PROCEDURE,v_check/V_CHECK=PROCEDURE) diff --git a/VMS/openssl_shutdown.com.in b/VMS/openssl_shutdown.com.in index f0df1c1c..fd4e3d50 100644 --- a/VMS/openssl_shutdown.com.in +++ b/VMS/openssl_shutdown.com.in @@ -26,7 +26,7 @@ $ ENDIF $ $ ! Abbrevs $ DEAS := DEASSIGN /NOLOG 'P1' -$ sv := {- sprintf "%02d%02d", $config{shlib_major}, $config{shlib_minor} -} +$ sv := {- sprintf "%02d%02d", split m|\.|, $config{shlib_version_number} -} $ pz := {- $config{pointer_size} -} $ $ DEAS OSSL$DATAROOT diff --git a/VMS/openssl_startup.com.in b/VMS/openssl_startup.com.in index 9c8c09ac..9e6e1c0b 100644 --- a/VMS/openssl_startup.com.in +++ b/VMS/openssl_startup.com.in @@ -88,7 +88,7 @@ $ $ ! Abbrevs $ DEFT := DEFINE /TRANSLATION=CONCEALED /NOLOG 'P1' $ DEF := DEFINE /NOLOG 'P1' -$ sv := {- sprintf "%02d%02d", $config{shlib_major}, $config{shlib_minor} -} +$ sv := {- sprintf "%02d%02d", split m|\.|, $config{shlib_version_number} -} $ pz := {- $config{pointer_size} -} $ $ DEFT OSSL$DATAROOT 'OPENSSLDIR_'] diff --git a/apps/CA.pl.in b/apps/CA.pl.in index 7277eeca..784c22f6 100644 --- a/apps/CA.pl.in +++ b/apps/CA.pl.in @@ -46,8 +46,25 @@ my $NEWCERT = "newcert.pem"; my $NEWP12 = "newcert.p12"; my $RET = 0; my $WHAT = shift @ARGV || ""; +my @OPENSSL_CMDS = ("req", "ca", "pkcs12", "x509", "verify"); +my %EXTRA = extra_args(\@ARGV, "-extra-"); my $FILE; +sub extra_args { + my ($args_ref, $arg_prefix) = @_; + my %eargs = map { + if ($_ < $#$args_ref) { + my ($arg, $value) = splice(@$args_ref, $_, 2); + $arg =~ s/$arg_prefix//; + ($arg, $value); + } else { + (); + } + } reverse grep($$args_ref[$_] =~ /$arg_prefix/, 0..$#$args_ref); + my %empty = map { ($_, "") } @OPENSSL_CMDS; + return (%empty, %eargs); +} + # See if reason for a CRL entry is valid; exit if not. sub crl_reason_ok { @@ -96,22 +113,23 @@ sub run if ( $WHAT =~ /^(-\?|-h|-help)$/ ) { - print STDERR "usage: CA -newcert|-newreq|-newreq-nodes|-newca|-sign|-signcert|-verify\n"; - print STDERR " CA -pkcs12 [certname]\n"; - print STDERR " CA -crl|-revoke cert-filename [reason]\n"; + print STDERR "usage: CA.pl -newcert | -newreq | -newreq-nodes | -xsign | -sign | -signCA | -signcert | -crl | -newca [-extra-cmd extra-params]\n"; + print STDERR " CA.pl -pkcs12 [-extra-pkcs12 extra-params] [certname]\n"; + print STDERR " CA.pl -verify [-extra-verify extra-params] certfile ...\n"; + print STDERR " CA.pl -revoke [-extra-ca extra-params] certfile [reason]\n"; exit 0; } if ($WHAT eq '-newcert' ) { # create a certificate - $RET = run("$REQ -new -x509 -keyout $NEWKEY -out $NEWCERT $DAYS"); + $RET = run("$REQ -new -x509 -keyout $NEWKEY -out $NEWCERT $DAYS $EXTRA{req}"); print "Cert is in $NEWCERT, private key is in $NEWKEY\n" if $RET == 0; -} elsif ($WHAT eq '-newreq' ) { +} elsif ($WHAT eq '-precert' ) { + # create a pre-certificate + $RET = run("$REQ -x509 -precert -keyout $NEWKEY -out $NEWCERT $DAYS"); + print "Pre-cert is in $NEWCERT, private key is in $NEWKEY\n" if $RET == 0; +} elsif ($WHAT =~ /^\-newreq(\-nodes)?$/ ) { # create a certificate request - $RET = run("$REQ -new -keyout $NEWKEY -out $NEWREQ $DAYS"); - print "Request is in $NEWREQ, private key is in $NEWKEY\n" if $RET == 0; -} elsif ($WHAT eq '-newreq-nodes' ) { - # create a certificate request - $RET = run("$REQ -new -nodes -keyout $NEWKEY -out $NEWREQ $DAYS"); + $RET = run("$REQ -new $1 -keyout $NEWKEY -out $NEWREQ $DAYS $EXTRA{req}"); print "Request is in $NEWREQ, private key is in $NEWKEY\n" if $RET == 0; } elsif ($WHAT eq '-newca' ) { # create the directory hierarchy @@ -136,11 +154,11 @@ if ($WHAT eq '-newcert' ) { print "Making CA certificate ...\n"; $RET = run("$REQ -new -keyout" . " ${CATOP}/private/$CAKEY" - . " -out ${CATOP}/$CAREQ"); + . " -out ${CATOP}/$CAREQ $EXTRA{req}"); $RET = run("$CA -create_serial" . " -out ${CATOP}/$CACERT $CADAYS -batch" . " -keyfile ${CATOP}/private/$CAKEY -selfsign" - . " -extensions v3_ca" + . " -extensions v3_ca $EXTRA{ca}" . " -infiles ${CATOP}/$CAREQ") if $RET == 0; print "CA certificate is in ${CATOP}/$CACERT\n" if $RET == 0; } @@ -150,32 +168,32 @@ if ($WHAT eq '-newcert' ) { $RET = run("$PKCS12 -in $NEWCERT -inkey $NEWKEY" . " -certfile ${CATOP}/$CACERT" . " -out $NEWP12" - . " -export -name \"$cname\""); + . " -export -name \"$cname\" $EXTRA{pkcs12}"); print "PKCS #12 file is in $NEWP12\n" if $RET == 0; } elsif ($WHAT eq '-xsign' ) { - $RET = run("$CA -policy policy_anything -infiles $NEWREQ"); + $RET = run("$CA -policy policy_anything $EXTRA{ca} -infiles $NEWREQ"); } elsif ($WHAT eq '-sign' ) { - $RET = run("$CA -policy policy_anything -out $NEWCERT -infiles $NEWREQ"); + $RET = run("$CA -policy policy_anything -out $NEWCERT $EXTRA{ca} -infiles $NEWREQ"); print "Signed certificate is in $NEWCERT\n" if $RET == 0; } elsif ($WHAT eq '-signCA' ) { $RET = run("$CA -policy policy_anything -out $NEWCERT" - . " -extensions v3_ca -infiles $NEWREQ"); + . " -extensions v3_ca $EXTRA{ca} -infiles $NEWREQ"); print "Signed CA certificate is in $NEWCERT\n" if $RET == 0; } elsif ($WHAT eq '-signcert' ) { $RET = run("$X509 -x509toreq -in $NEWREQ -signkey $NEWREQ" - . " -out tmp.pem"); + . " -out tmp.pem $EXTRA{x509}"); $RET = run("$CA -policy policy_anything -out $NEWCERT" - . " -infiles tmp.pem") if $RET == 0; + . "$EXTRA{ca} -infiles tmp.pem") if $RET == 0; print "Signed certificate is in $NEWCERT\n" if $RET == 0; } elsif ($WHAT eq '-verify' ) { my @files = @ARGV ? @ARGV : ( $NEWCERT ); my $file; foreach $file (@files) { - my $status = run("$VERIFY \"-CAfile\" ${CATOP}/$CACERT $file"); + my $status = run("$VERIFY \"-CAfile\" ${CATOP}/$CACERT $file $EXTRA{verify}"); $RET = $status if $status != 0; } } elsif ($WHAT eq '-crl' ) { - $RET = run("$CA -gencrl -out ${CATOP}/crl/$CACRL"); + $RET = run("$CA -gencrl -out ${CATOP}/crl/$CACRL $EXTRA{ca}"); print "Generated CRL is in ${CATOP}/crl/$CACRL\n" if $RET == 0; } elsif ($WHAT eq '-revoke' ) { my $cname = $ARGV[0]; @@ -186,7 +204,7 @@ if ($WHAT eq '-newcert' ) { my $reason = $ARGV[1]; $reason = " -crl_reason $reason" if defined $reason && crl_reason_ok($reason); - $RET = run("$CA -revoke \"$cname\"" . $reason); + $RET = run("$CA -revoke \"$cname\"" . $reason . $EXTRA{ca}); } else { print STDERR "Unknown arg \"$WHAT\"\n"; print STDERR "Use -help for help.\n"; diff --git a/apps/app_rand.c b/apps/app_rand.c index ff0771cb..28caad41 100644 --- a/apps/app_rand.c +++ b/apps/app_rand.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,107 +9,86 @@ #include "apps.h" #include +#include #include +#include -static int seeded = 0; -static int egdsocket = 0; +static char *save_rand_file; -int app_RAND_load_file(const char *file, int dont_warn) +void app_RAND_load_conf(CONF *c, const char *section) { - int consider_randfile = (file == NULL); - char buffer[200]; + const char *randfile = NCONF_get_string(c, section, "RANDFILE"); - if (file == NULL) - file = RAND_file_name(buffer, sizeof(buffer)); -#ifndef OPENSSL_NO_EGD - 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 (randfile == NULL) { + ERR_clear_error(); + return; } -#endif - if (file == NULL || !RAND_load_file(file, -1)) { - if (RAND_status() == 0) { - if (!dont_warn) { - BIO_printf(bio_err, "unable to load 'random state'\n"); - BIO_printf(bio_err, - "This means that the random number generator has not been seeded\n"); - BIO_printf(bio_err, "with much random data.\n"); - if (consider_randfile) { /* explanation does not apply when a - * file is explicitly named */ - BIO_printf(bio_err, - "Consider setting the RANDFILE environment variable to point at a file that\n"); - BIO_printf(bio_err, - "'random' data can be kept in (the file will be overwritten).\n"); - } - } - return 0; - } + if (RAND_load_file(randfile, -1) < 0) { + BIO_printf(bio_err, "Can't load %s into RNG\n", randfile); + ERR_print_errors(bio_err); + return; } - seeded = 1; - return 1; + if (save_rand_file == NULL) + save_rand_file = OPENSSL_strdup(randfile); } -long app_RAND_load_files(char *name) +static int loadfiles(char *name) { - char *p, *n; - int last; - long tot = 0; -#ifndef OPENSSL_NO_EGD - int egd; -#endif + char *p; + int last, ret = 1; - for (;;) { + for ( ; ; ) { last = 0; - for (p = name; ((*p != '\0') && (*p != LIST_SEPARATOR_CHAR)); p++) ; + for (p = name; *p != '\0' && *p != LIST_SEPARATOR_CHAR; p++) + continue; if (*p == '\0') last = 1; *p = '\0'; - n = name; - name = p + 1; - if (*n == '\0') - break; - -#ifndef OPENSSL_NO_EGD - egd = RAND_egd(n); - if (egd > 0) - tot += egd; - else -#endif - tot += RAND_load_file(n, -1); + if (RAND_load_file(name, -1) < 0) { + BIO_printf(bio_err, "Can't load %s into RNG\n", name); + ERR_print_errors(bio_err); + ret = 0; + } if (last) break; + name = p + 1; + if (*name == '\0') + break; } - if (tot > 512) - app_RAND_allow_write_file(); - return (tot); + return ret; } -int app_RAND_write_file(const char *file) +void app_RAND_write(void) { - char buffer[200]; + if (save_rand_file == NULL) + return; + if (RAND_write_file(save_rand_file) == -1) { + BIO_printf(bio_err, "Cannot write random bytes:\n"); + ERR_print_errors(bio_err); + } + OPENSSL_free(save_rand_file); + save_rand_file = NULL; +} - 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)); - if (file == NULL || !RAND_write_file(file)) { - BIO_printf(bio_err, "unable to write 'random state'\n"); - return 0; +/* + * See comments in opt_verify for explanation of this. + */ +enum r_range { OPT_R_ENUM }; + +int opt_rand(int opt) +{ + switch ((enum r_range)opt) { + case OPT_R__FIRST: + case OPT_R__LAST: + break; + case OPT_R_RAND: + return loadfiles(opt_arg()); + break; + case OPT_R_WRITERAND: + OPENSSL_free(save_rand_file); + save_rand_file = OPENSSL_strdup(opt_arg()); + break; } return 1; } - -void app_RAND_allow_write_file(void) -{ - seeded = 1; -} diff --git a/apps/apps.c b/apps/apps.c index 8703d0cc..0438bdb9 100644 --- a/apps/apps.c +++ b/apps/apps.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -54,9 +54,8 @@ typedef struct { unsigned long mask; } NAME_EX_TBL; -#if !defined(OPENSSL_NO_UI) || !defined(OPENSSL_NO_ENGINE) static UI_METHOD *ui_method = NULL; -#endif +static const UI_METHOD *ui_fallback_method = NULL; static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL * in_tbl); @@ -110,13 +109,13 @@ int chopup_args(ARGS *arg, char *buf) } } arg->argv[arg->argc] = NULL; - return (1); + return 1; } #ifndef APP_INIT int app_init(long mesgwin) { - return (1); + return 1; } #endif @@ -138,41 +137,55 @@ int ctx_set_verify_locations(SSL_CTX *ctx, const char *CAfile, int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path) { - if (path == NULL) { + if (path == NULL) return SSL_CTX_set_default_ctlog_list_file(ctx); - } return SSL_CTX_set_ctlog_list_file(ctx, path); } #endif +static unsigned long nmflag = 0; +static char nmflag_set = 0; + +int set_nameopt(const char *arg) +{ + int ret = set_name_ex(&nmflag, arg); + + if (ret) + nmflag_set = 1; + + return ret; +} + +unsigned long get_nameopt(void) +{ + return (nmflag_set) ? nmflag : XN_FLAG_ONELINE; +} + 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); + print_name(out, "subject=", X509_get_subject_name(x), get_nameopt()); + BIO_puts(out, "\n"); + print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt()); BIO_puts(out, "\n"); - OPENSSL_free(p); return 0; } -#ifndef OPENSSL_NO_UI static int ui_open(UI *ui) { - return UI_method_get_opener(UI_OpenSSL())(ui); + int (*opener)(UI *ui) = UI_method_get_opener(ui_fallback_method); + + if (opener) + return opener(ui); + return 1; } static int ui_read(UI *ui, UI_STRING *uis) { + int (*reader)(UI *ui, UI_STRING *uis) = NULL; + if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD && UI_get0_user_data(ui)) { switch (UI_get_string_type(uis)) { @@ -186,15 +199,25 @@ static int ui_read(UI *ui, UI_STRING *uis) return 1; } } - default: + break; + case UIT_NONE: + case UIT_BOOLEAN: + case UIT_INFO: + case UIT_ERROR: break; } } - return UI_method_get_reader(UI_OpenSSL())(ui, uis); + + reader = UI_method_get_reader(ui_fallback_method); + if (reader) + return reader(ui, uis); + return 1; } static int ui_write(UI *ui, UI_STRING *uis) { + int (*writer)(UI *ui, UI_STRING *uis) = NULL; + if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD && UI_get0_user_data(ui)) { switch (UI_get_string_type(uis)) { @@ -206,20 +229,36 @@ static int ui_write(UI *ui, UI_STRING *uis) if (password && password[0] != '\0') return 1; } - default: + break; + case UIT_NONE: + case UIT_BOOLEAN: + case UIT_INFO: + case UIT_ERROR: break; } } - return UI_method_get_writer(UI_OpenSSL())(ui, uis); + + writer = UI_method_get_writer(ui_fallback_method); + if (writer) + return writer(ui, uis); + return 1; } static int ui_close(UI *ui) { - return UI_method_get_closer(UI_OpenSSL())(ui); + int (*closer)(UI *ui) = UI_method_get_closer(ui_fallback_method); + + if (closer) + return closer(ui); + return 1; } int setup_ui_method(void) { + ui_fallback_method = UI_null(); +#ifndef OPENSSL_NO_UI_CONSOLE + ui_fallback_method = UI_OpenSSL(); +#endif 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); @@ -235,24 +274,18 @@ void destroy_ui_method(void) ui_method = NULL; } } -#endif + +const UI_METHOD *get_ui_method(void) +{ + return ui_method; +} int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp) { int res = 0; -#ifndef OPENSSL_NO_UI UI *ui = NULL; -#endif PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp; -#ifdef OPENSSL_NO_UI - if (cb_data != NULL && cb_data->password != NULL) { - res = strlen(cb_data->password); - if (res > bufsiz) - res = bufsiz; - memcpy(buf, cb_data->password, res); - } -#else ui = UI_new_method(ui_method); if (ui) { int ok = 0; @@ -276,9 +309,9 @@ int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp) /* We know that there is no previous user data to return to us */ (void)UI_add_user_data(ui, cb_data); - if (ok >= 0) - ok = UI_add_input_string(ui, prompt, ui_flags, buf, - PW_MIN_LENGTH, bufsiz - 1); + ok = UI_add_input_string(ui, prompt, ui_flags, buf, + PW_MIN_LENGTH, bufsiz - 1); + if (ok >= 0 && verify) { buff = app_malloc(bufsiz, "password buffer"); ok = UI_add_verify_string(ui, prompt, ui_flags, buff, @@ -287,8 +320,7 @@ int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp) if (ok >= 0) do { ok = UI_process(ui); - } - while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0)); + } while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0)); OPENSSL_clear_free(buff, (unsigned int)bufsiz); @@ -308,7 +340,6 @@ int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp) UI_free(ui); OPENSSL_free(prompt); } -#endif return res; } @@ -317,22 +348,24 @@ static char *app_get_pass(const char *arg, int keepbio); int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2) { int same; - if (!arg2 || !arg1 || strcmp(arg1, arg2)) + if (arg2 == NULL || arg1 == NULL || strcmp(arg1, arg2)) same = 0; else same = 1; - if (arg1) { + if (arg1 != NULL) { *pass1 = app_get_pass(arg1, same); - if (!*pass1) + if (*pass1 == NULL) return 0; - } else if (pass1) + } else if (pass1 != NULL) { *pass1 = NULL; - if (arg2) { + } + if (arg2 != NULL) { *pass2 = app_get_pass(arg2, same ? 2 : 0); - if (!*pass2) + if (*pass2 == NULL) return 0; - } else if (pass2) + } else if (pass2 != NULL) { *pass2 = NULL; + } return 1; } @@ -346,16 +379,16 @@ static char *app_get_pass(const char *arg, int keepbio) return OPENSSL_strdup(arg + 5); if (strncmp(arg, "env:", 4) == 0) { tmp = getenv(arg + 4); - if (!tmp) { + if (tmp == NULL) { BIO_printf(bio_err, "Can't read environment variable %s\n", arg + 4); return NULL; } return OPENSSL_strdup(tmp); } - if (!keepbio || !pwdbio) { + if (!keepbio || pwdbio == NULL) { if (strncmp(arg, "file:", 5) == 0) { pwdbio = BIO_new_file(arg + 5, "r"); - if (!pwdbio) { + if (pwdbio == NULL) { BIO_printf(bio_err, "Can't open file %s\n", arg + 5); return NULL; } @@ -404,12 +437,12 @@ static char *app_get_pass(const char *arg, int keepbio) return NULL; } tmp = strchr(tpass, '\n'); - if (tmp) + if (tmp != NULL) *tmp = 0; return OPENSSL_strdup(tpass); } -static CONF *app_load_config_(BIO *in, const char *filename) +CONF *app_load_config_bio(BIO *in, const char *filename) { long errorline = -1; CONF *conf; @@ -420,15 +453,21 @@ static CONF *app_load_config_(BIO *in, const char *filename) if (i > 0) return conf; - if (errorline <= 0) - BIO_printf(bio_err, "%s: Can't load config file \"%s\"\n", - opt_getprog(), filename); + if (errorline <= 0) { + BIO_printf(bio_err, "%s: Can't load ", opt_getprog()); + } else { + BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(), + errorline); + } + if (filename != NULL) + BIO_printf(bio_err, "config file \"%s\"\n", filename); else - BIO_printf(bio_err, "%s: Error on line %ld of config file \"%s\"\n", - opt_getprog(), errorline, filename); + BIO_printf(bio_err, "config input"); + NCONF_free(conf); return NULL; } + CONF *app_load_config(const char *filename) { BIO *in; @@ -438,10 +477,11 @@ CONF *app_load_config(const char *filename) if (in == NULL) return NULL; - conf = app_load_config_(in, filename); + conf = app_load_config_bio(in, filename); BIO_free(in); return conf; } + CONF *app_load_config_quiet(const char *filename) { BIO *in; @@ -451,7 +491,7 @@ CONF *app_load_config_quiet(const char *filename) if (in == NULL) return NULL; - conf = app_load_config_(in, filename); + conf = app_load_config_bio(in, filename); BIO_free(in); return conf; } @@ -515,9 +555,9 @@ static int load_pkcs12(BIO *in, const char *desc, goto die; } /* See if an empty password will do */ - if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) + if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0)) { pass = ""; - else { + } else { if (!pem_cb) pem_cb = (pem_password_cb *)password_callback; len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data); @@ -578,8 +618,7 @@ static int load_cert_crl_http(const char *url, X509 **pcert, X509_CRL **pcrl) OPENSSL_free(host); OPENSSL_free(path); OPENSSL_free(port); - if (bio) - BIO_free_all(bio); + BIO_free_all(bio); OCSP_REQ_CTX_free(rctx); if (rv != 1) { BIO_printf(bio_err, "Error loading %s from %s\n", @@ -605,17 +644,18 @@ X509 *load_cert(const char *file, int format, const char *cert_descrip) if (file == NULL) { unbuffer(stdin); cert = dup_bio_in(format); - } else + } else { cert = bio_open_default(file, 'r', format); + } if (cert == NULL) goto end; - if (format == FORMAT_ASN1) + if (format == FORMAT_ASN1) { x = d2i_X509_bio(cert, NULL); - else if (format == FORMAT_PEM) + } else if (format == FORMAT_PEM) { x = PEM_read_bio_X509_AUX(cert, NULL, (pem_password_cb *)password_callback, NULL); - else if (format == FORMAT_PKCS12) { + } else if (format == FORMAT_PKCS12) { if (!load_pkcs12(cert, cert_descrip, NULL, NULL, NULL, &x, NULL)) goto end; } else { @@ -628,7 +668,7 @@ X509 *load_cert(const char *file, int format, const char *cert_descrip) ERR_print_errors(bio_err); } BIO_free(cert); - return (x); + return x; } X509_CRL *load_crl(const char *infile, int format) @@ -646,11 +686,11 @@ X509_CRL *load_crl(const char *infile, int format) in = bio_open_default(infile, 'r', format); if (in == NULL) goto end; - if (format == FORMAT_ASN1) + if (format == FORMAT_ASN1) { x = d2i_X509_CRL_bio(in, NULL); - else if (format == FORMAT_PEM) + } else if (format == FORMAT_PEM) { x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL); - else { + } else { BIO_printf(bio_err, "bad input format specified for input crl\n"); goto end; } @@ -662,7 +702,7 @@ X509_CRL *load_crl(const char *infile, int format) end: BIO_free(in); - return (x); + return x; } EVP_PKEY *load_key(const char *file, int format, int maybe_stdin, @@ -680,9 +720,9 @@ EVP_PKEY *load_key(const char *file, int format, int maybe_stdin, goto end; } if (format == FORMAT_ENGINE) { - if (e == NULL) + if (e == NULL) { BIO_printf(bio_err, "no engine specified\n"); - else { + } else { #ifndef OPENSSL_NO_ENGINE if (ENGINE_init(e)) { pkey = ENGINE_load_private_key(e, file, ui_method, &cb_data); @@ -701,8 +741,9 @@ EVP_PKEY *load_key(const char *file, int format, int maybe_stdin, if (file == NULL && maybe_stdin) { unbuffer(stdin); key = dup_bio_in(format); - } else + } else { key = bio_open_default(file, 'r', format); + } if (key == NULL) goto end; if (format == FORMAT_ASN1) { @@ -711,21 +752,19 @@ EVP_PKEY *load_key(const char *file, int format, int maybe_stdin, pkey = PEM_read_bio_PrivateKey(key, NULL, (pem_password_cb *)password_callback, &cb_data); - } - else if (format == FORMAT_PKCS12) { + } else if (format == FORMAT_PKCS12) { if (!load_pkcs12(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) + } else if (format == FORMAT_MSBLOB) { pkey = b2i_PrivateKey_bio(key); - else if (format == FORMAT_PVK) + } else if (format == FORMAT_PVK) { pkey = b2i_PVK_bio(key, (pem_password_cb *)password_callback, &cb_data); #endif - else { + } else { BIO_printf(bio_err, "bad input format specified for key file\n"); goto end; } @@ -735,7 +774,7 @@ EVP_PKEY *load_key(const char *file, int format, int maybe_stdin, BIO_printf(bio_err, "unable to load %s\n", key_descrip); ERR_print_errors(bio_err); } - return (pkey); + return pkey; } EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin, @@ -753,9 +792,9 @@ EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin, goto end; } if (format == FORMAT_ENGINE) { - if (e == NULL) + if (e == NULL) { BIO_printf(bio_err, "no engine specified\n"); - else { + } else { #ifndef OPENSSL_NO_ENGINE pkey = ENGINE_load_public_key(e, file, ui_method, &cb_data); if (pkey == NULL) { @@ -771,14 +810,14 @@ EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin, if (file == NULL && maybe_stdin) { unbuffer(stdin); key = dup_bio_in(format); - } else + } else { key = bio_open_default(file, 'r', format); + } if (key == NULL) goto end; if (format == FORMAT_ASN1) { pkey = d2i_PUBKEY_bio(key, NULL); - } - else if (format == FORMAT_ASN1RSA) { + } else if (format == FORMAT_ASN1RSA) { #ifndef OPENSSL_NO_RSA RSA *rsa; rsa = d2i_RSAPublicKey_bio(key, NULL); @@ -808,21 +847,20 @@ EVP_PKEY *load_pubkey(const char *file, int format, int maybe_stdin, BIO_printf(bio_err, "RSA keys not supported\n"); #endif pkey = NULL; - } - else if (format == FORMAT_PEM) { + } else if (format == FORMAT_PEM) { pkey = PEM_read_bio_PUBKEY(key, NULL, (pem_password_cb *)password_callback, &cb_data); - } #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) - else if (format == FORMAT_MSBLOB) + } else if (format == FORMAT_MSBLOB) { pkey = b2i_PublicKey_bio(key); #endif + } end: BIO_free(key); if (pkey == NULL) BIO_printf(bio_err, "unable to load %s\n", key_descrip); - return (pkey); + return pkey; } static int load_certs_crls(const char *file, int format, @@ -855,36 +893,36 @@ static int load_certs_crls(const char *file, int format, BIO_free(bio); - if (pcerts && *pcerts == NULL) { + if (pcerts != NULL && *pcerts == NULL) { *pcerts = sk_X509_new_null(); - if (!*pcerts) + if (*pcerts == NULL) goto end; } - if (pcrls && *pcrls == NULL) { + if (pcrls != NULL && *pcrls == NULL) { *pcrls = sk_X509_CRL_new_null(); - if (!*pcrls) + if (*pcrls == NULL) goto end; } for (i = 0; i < sk_X509_INFO_num(xis); i++) { xi = sk_X509_INFO_value(xis, i); - if (xi->x509 && pcerts) { + if (xi->x509 != NULL && pcerts != NULL) { if (!sk_X509_push(*pcerts, xi->x509)) goto end; xi->x509 = NULL; } - if (xi->crl && pcrls) { + if (xi->crl != NULL && pcrls != NULL) { if (!sk_X509_CRL_push(*pcrls, xi->crl)) goto end; xi->crl = NULL; } } - if (pcerts && sk_X509_num(*pcerts) > 0) + if (pcerts != NULL && sk_X509_num(*pcerts) > 0) rv = 1; - if (pcrls && sk_X509_CRL_num(*pcrls) > 0) + if (pcrls != NULL && sk_X509_CRL_num(*pcrls) > 0) rv = 1; end: @@ -892,11 +930,11 @@ static int load_certs_crls(const char *file, int format, sk_X509_INFO_pop_free(xis, X509_INFO_free); if (rv == 0) { - if (pcerts) { + if (pcerts != NULL) { sk_X509_pop_free(*pcerts, X509_free); *pcerts = NULL; } - if (pcrls) { + if (pcrls != NULL) { sk_X509_CRL_pop_free(*pcrls, X509_CRL_free); *pcrls = NULL; } @@ -1101,8 +1139,9 @@ static int set_table_opts(unsigned long *flags, const char *arg, } else if (c == '+') { c = 1; arg++; - } else + } else { c = 1; + } for (ptbl = in_tbl; ptbl->name; ptbl++) { if (strcasecmp(arg, ptbl->name) == 0) { @@ -1147,9 +1186,9 @@ void print_bignum_var(BIO *out, const BIGNUM *in, const char *var, int len, unsigned char *buffer) { BIO_printf(out, " static unsigned char %s_%d[] = {", var, len); - if (BN_is_zero(in)) + if (BN_is_zero(in)) { BIO_printf(out, "\n\t0x00"); - else { + } else { int i, l; l = BN_bn2bin(in, buffer); @@ -1164,6 +1203,7 @@ void print_bignum_var(BIO *out, const BIGNUM *in, const char *var, } BIO_printf(out, "\n };\n"); } + void print_array(BIO *out, const char* title, int len, const unsigned char* d) { int i; @@ -1197,8 +1237,9 @@ X509_STORE *setup_verify(const char *CAfile, const char *CApath, int noCAfile, i BIO_printf(bio_err, "Error loading file %s\n", CAfile); goto end; } - } else + } else { X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT); + } } if (CApath != NULL || !noCApath) { @@ -1210,8 +1251,9 @@ X509_STORE *setup_verify(const char *CAfile, const char *CApath, int noCAfile, i BIO_printf(bio_err, "Error loading directory %s\n", CApath); goto end; } - } else + } else { X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT); + } } ERR_clear_error(); @@ -1242,7 +1284,7 @@ ENGINE *setup_engine(const char *engine, int debug) ENGINE *e = NULL; #ifndef OPENSSL_NO_ENGINE - if (engine) { + if (engine != NULL) { if (strcmp(engine, "auto") == 0) { BIO_printf(bio_err, "enabling auto ENGINE support\n"); ENGINE_register_all_complete(); @@ -1297,7 +1339,7 @@ static int index_serial_cmp(const OPENSSL_CSTRING *a, for (aa = a[DB_serial]; *aa == '0'; aa++) ; for (bb = b[DB_serial]; *bb == '0'; bb++) ; - return (strcmp(aa, bb)); + return strcmp(aa, bb); } static int index_name_qual(char **a) @@ -1312,7 +1354,7 @@ static unsigned long index_name_hash(const OPENSSL_CSTRING *a) int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b) { - return (strcmp(a[DB_name], b[DB_name])); + return strcmp(a[DB_name], b[DB_name]); } static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING) @@ -1363,7 +1405,7 @@ BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai) err: BIO_free(in); ASN1_INTEGER_free(ai); - return (ret); + return ret; } int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial, @@ -1413,7 +1455,7 @@ int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial err: BIO_free_all(out); ASN1_INTEGER_free(ai); - return (ret); + return ret; } int rotate_serial(const char *serialfile, const char *new_suffix, @@ -1464,15 +1506,11 @@ int rand_serial(BIGNUM *b, ASN1_INTEGER *ai) BIGNUM *btmp; int ret = 0; - if (b) - btmp = b; - else - btmp = BN_new(); - + btmp = b == NULL ? BN_new() : b; if (btmp == NULL) return 0; - if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0)) + if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY)) goto error; if (ai && !BN_to_ASN1_INTEGER(btmp, ai)) goto error; @@ -1848,8 +1886,9 @@ static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes) node = sk_X509_POLICY_NODE_value(nodes, i); X509_POLICY_NODE_print(bio_err, node, 2); } - } else + } else { BIO_puts(bio_err, " \n"); + } } void policies_print(X509_STORE_CTX *ctx) @@ -1892,10 +1931,11 @@ unsigned char *next_protos_parse(size_t *outlen, const char *in) OPENSSL_free(out); return NULL; } - out[start] = i - start; + out[start] = (unsigned char)(i - start); start = i + 1; - } else + } else { out[i + 1] = in[i]; + } } *outlen = len + 1; @@ -2118,7 +2158,7 @@ double app_tminterval(int stop, int usertime) ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7; } - return (ret); + return ret; } #elif defined(OPENSSL_SYSTEM_VXWORKS) # include @@ -2154,7 +2194,7 @@ double app_tminterval(int stop, int usertime) else ret = (now - tmstart) / (double)sysClkRateGet(); # endif - return (ret); + return ret; } #elif defined(OPENSSL_SYSTEM_VMS) @@ -2188,7 +2228,7 @@ double app_tminterval(int stop, int usertime) else ret = (now - tmstart) / (double)(CLK_TCK); - return (ret); + return ret; } #elif defined(_SC_CLK_TCK) /* by means of unistd.h */ @@ -2204,14 +2244,14 @@ double app_tminterval(int stop, int usertime) if (usertime) now = rus.tms_utime; - if (stop == TM_START) + if (stop == TM_START) { tmstart = now; - else { + } else { long int tck = sysconf(_SC_CLK_TCK); ret = (now - tmstart) / (double)tck; } - return (ret); + return ret; } #else @@ -2336,12 +2376,12 @@ int raw_read_stdin(void *buf, int siz) { DWORD n; if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL)) - return (n); + return n; else - return (-1); + return -1; } #elif defined(__VMS) -#include +# include int raw_read_stdin(void *buf, int siz) { @@ -2359,9 +2399,9 @@ int raw_write_stdout(const void *buf, int siz) { DWORD n; if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL)) - return (n); + return n; else - return (-1); + return -1; } #else int raw_write_stdout(const void *buf, int siz) @@ -2388,14 +2428,26 @@ BIO *dup_bio_in(int format) BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0)); } +static BIO_METHOD *prefix_method = NULL; + BIO *dup_bio_out(int format) { BIO *b = BIO_new_fp(stdout, BIO_NOCLOSE | (istext(format) ? BIO_FP_TEXT : 0)); + void *prefix = NULL; + #ifdef OPENSSL_SYS_VMS if (istext(format)) b = BIO_push(BIO_new(BIO_f_linebuffer()), b); #endif + + if (istext(format) && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) { + if (prefix_method == NULL) + prefix_method = apps_bf_prefix(); + b = BIO_push(BIO_new(prefix_method), b); + BIO_ctrl(b, PREFIX_CTRL_SET_PREFIX, 0, prefix); + } + return b; } @@ -2410,6 +2462,12 @@ BIO *dup_bio_err(int format) return b; } +void destroy_prefix_method() +{ + BIO_meth_free(prefix_method); + prefix_method = NULL; +} + void unbuffer(FILE *fp) { /* @@ -2636,15 +2694,23 @@ int set_cert_times(X509 *x, const char *startdate, const char *enddate, if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL) return 0; } else { - if (!ASN1_TIME_set_string(X509_getm_notBefore(x), startdate)) + if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate)) return 0; } if (enddate == NULL) { if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL) == NULL) return 0; - } else if (!ASN1_TIME_set_string(X509_getm_notAfter(x), enddate)) { + } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) { return 0; } return 1; } + +void make_uppercase(char *string) +{ + int i; + + for (i = 0; string[i] != '\0'; i++) + string[i] = toupper((unsigned char)string[i]); +} diff --git a/apps/apps.h b/apps/apps.h index f91faf8c..daaef369 100644 --- a/apps/apps.h +++ b/apps/apps.h @@ -10,17 +10,14 @@ #ifndef HEADER_APPS_H # define HEADER_APPS_H -# include "e_os.h" -# if defined(__unix) || defined(__unix__) -# include /* struct timeval for DTLS */ -# endif +# include "e_os.h" /* struct timeval for DTLS */ +# include "internal/nelem.h" # include # include # include # include # include -# include # include # include # include @@ -40,27 +37,38 @@ */ #define _UC(c) ((unsigned char)(c)) -int app_RAND_load_file(const char *file, int dont_warn); -int app_RAND_write_file(const char *file); -/* - * When `file' is NULL, use defaults. `bio_e' is for error messages. - */ -void app_RAND_allow_write_file(void); -long app_RAND_load_files(char *file); /* `file' is a list of files to read, - * separated by LIST_SEPARATOR_CHAR - * (see e_os.h). The string is - * destroyed! */ +void app_RAND_load_conf(CONF *c, const char *section); +void app_RAND_write(void); extern char *default_config_file; extern BIO *bio_in; extern BIO *bio_out; extern BIO *bio_err; +extern const unsigned char tls13_aes128gcmsha256_id[]; +extern const unsigned char tls13_aes256gcmsha384_id[]; +extern BIO_ADDR *ourpeer; + +BIO_METHOD *apps_bf_prefix(void); +/* + * The control used to set the prefix with BIO_ctrl() + * We make it high enough so the chance of ever clashing with the BIO library + * remains unlikely for the foreseeable future and beyond. + */ +#define PREFIX_CTRL_SET_PREFIX (1 << 15) +/* + * apps_bf_prefix() returns a dynamically created BIO_METHOD, which we + * need to destroy at some point. When created internally, it's stored + * in an internal pointer which can be freed with the following function + */ +void destroy_prefix_method(void); + BIO *dup_bio_in(int format); BIO *dup_bio_out(int format); BIO *dup_bio_err(int format); BIO *bio_open_owner(const char *filename, int format, int private); BIO *bio_open_default(const char *filename, char mode, int format); BIO *bio_open_default_quiet(const char *filename, char mode, int format); +CONF *app_load_config_bio(BIO *in, const char *filename); CONF *app_load_config(const char *filename); CONF *app_load_config_quiet(const char *filename); int app_load_modules(const CONF *config); @@ -175,7 +183,7 @@ int set_cert_times(X509 *x, const char *startdate, const char *enddate, case OPT_V_ALLOW_PROXY_CERTS /* - * Common "extended"? options. + * Common "extended validation" options. */ # define OPT_X_ENUM \ OPT_X__FIRST=1000, \ @@ -210,18 +218,21 @@ int set_cert_times(X509 *x, const char *startdate, const char *enddate, # define OPT_S_ENUM \ OPT_S__FIRST=3000, \ OPT_S_NOSSL3, OPT_S_NOTLS1, OPT_S_NOTLS1_1, OPT_S_NOTLS1_2, \ - OPT_S_BUGS, OPT_S_NO_COMP, OPT_S_NOTICKET, \ + OPT_S_NOTLS1_3, OPT_S_BUGS, OPT_S_NO_COMP, OPT_S_NOTICKET, \ OPT_S_SERVERPREF, OPT_S_LEGACYRENEG, OPT_S_LEGACYCONN, \ - OPT_S_ONRESUMP, OPT_S_NOLEGACYCONN, OPT_S_STRICT, OPT_S_SIGALGS, \ - OPT_S_CLIENTSIGALGS, OPT_S_CURVES, OPT_S_NAMEDCURVE, OPT_S_CIPHER, \ - OPT_S_DEBUGBROKE, OPT_S_COMP, OPT_S_MINPROTO, OPT_S_MAXPROTO, \ - OPT_S_NO_RENEGOTIATION, OPT_S__LAST + OPT_S_ONRESUMP, OPT_S_NOLEGACYCONN, OPT_S_ALLOW_NO_DHE_KEX, \ + OPT_S_PRIORITIZE_CHACHA, \ + OPT_S_STRICT, OPT_S_SIGALGS, OPT_S_CLIENTSIGALGS, OPT_S_GROUPS, \ + OPT_S_CURVES, OPT_S_NAMEDCURVE, OPT_S_CIPHER, \ + OPT_S_RECORD_PADDING, OPT_S_DEBUGBROKE, OPT_S_COMP, \ + OPT_S_NO_RENEGOTIATION, OPT_S_NO_MIDDLEBOX, OPT_S__LAST # define OPT_S_OPTIONS \ {"no_ssl3", OPT_S_NOSSL3, '-',"Just disable SSLv3" }, \ {"no_tls1", OPT_S_NOTLS1, '-', "Just disable TLSv1"}, \ {"no_tls1_1", OPT_S_NOTLS1_1, '-', "Just disable TLSv1.1" }, \ {"no_tls1_2", OPT_S_NOTLS1_2, '-', "Just disable TLSv1.2"}, \ + {"no_tls1_3", OPT_S_NOTLS1_3, '-', "Just disable TLSv1.3"}, \ {"bugs", OPT_S_BUGS, '-', "Turn on SSL bug compatibility"}, \ {"no_comp", OPT_S_NO_COMP, '-', "Disable SSL/TLS compression (default)" }, \ {"comp", OPT_S_COMP, '-', "Use SSL/TLS-level compression" }, \ @@ -238,6 +249,10 @@ int set_cert_times(X509 *x, const char *startdate, const char *enddate, "Disallow session resumption on renegotiation"}, \ {"no_legacy_server_connect", OPT_S_NOLEGACYCONN, '-', \ "Disallow initial connection to servers that don't support RI"}, \ + {"allow_no_dhe_kex", OPT_S_ALLOW_NO_DHE_KEX, '-', \ + "In TLSv1.3 allow non-(ec)dhe based key exchange on resumption"}, \ + {"prioritize_chacha", OPT_S_PRIORITIZE_CHACHA, '-', \ + "Prioritize ChaCha ciphers when preferred by clients"}, \ {"strict", OPT_S_STRICT, '-', \ "Enforce strict certificate checks as per TLS standard"}, \ {"sigalgs", OPT_S_SIGALGS, 's', \ @@ -245,15 +260,19 @@ int set_cert_times(X509 *x, const char *startdate, const char *enddate, {"client_sigalgs", OPT_S_CLIENTSIGALGS, 's', \ "Signature algorithms to support for client certificate" \ " authentication (colon-separated list)" }, \ + {"groups", OPT_S_GROUPS, 's', \ + "Groups to advertise (colon-separated list)" }, \ {"curves", OPT_S_CURVES, 's', \ - "Elliptic curves to advertise (colon-separated list)" }, \ + "Groups to advertise (colon-separated list)" }, \ {"named_curve", OPT_S_NAMEDCURVE, 's', \ "Elliptic curve used for ECDHE (server-side only)" }, \ {"cipher", OPT_S_CIPHER, 's', "Specify cipher list to be used"}, \ - {"min_protocol", OPT_S_MINPROTO, 's', "Specify the minimum protocol version to be used"}, \ - {"max_protocol", OPT_S_MAXPROTO, 's', "Specify the maximum protocol version to be used"}, \ + {"record_padding", OPT_S_RECORD_PADDING, 's', \ + "Block size to pad TLS 1.3 records to."}, \ {"debug_broken_protocol", OPT_S_DEBUGBROKE, '-', \ - "Perform all sorts of protocol violations for testing purposes"} + "Perform all sorts of protocol violations for testing purposes"}, \ + {"no_middlebox", OPT_S_NO_MIDDLEBOX, '-', "Disable TLSv1.3 middlebox compat mode" } + # define OPT_S_CASES \ OPT_S__FIRST: case OPT_S__LAST: break; \ @@ -261,6 +280,7 @@ int set_cert_times(X509 *x, const char *startdate, const char *enddate, case OPT_S_NOTLS1: \ case OPT_S_NOTLS1_1: \ case OPT_S_NOTLS1_2: \ + case OPT_S_NOTLS1_3: \ case OPT_S_BUGS: \ case OPT_S_NO_COMP: \ case OPT_S_COMP: \ @@ -270,20 +290,37 @@ int set_cert_times(X509 *x, const char *startdate, const char *enddate, case OPT_S_LEGACYCONN: \ case OPT_S_ONRESUMP: \ case OPT_S_NOLEGACYCONN: \ + case OPT_S_ALLOW_NO_DHE_KEX: \ + case OPT_S_PRIORITIZE_CHACHA: \ case OPT_S_STRICT: \ case OPT_S_SIGALGS: \ case OPT_S_CLIENTSIGALGS: \ + case OPT_S_GROUPS: \ case OPT_S_CURVES: \ case OPT_S_NAMEDCURVE: \ case OPT_S_CIPHER: \ - case OPT_S_MINPROTO: \ - case OPT_S_MAXPROTO: \ + case OPT_S_RECORD_PADDING: \ case OPT_S_NO_RENEGOTIATION: \ - case OPT_S_DEBUGBROKE + case OPT_S_DEBUGBROKE: \ + case OPT_S_NO_MIDDLEBOX #define IS_NO_PROT_FLAG(o) \ (o == OPT_S_NOSSL3 || o == OPT_S_NOTLS1 || o == OPT_S_NOTLS1_1 \ - || o == OPT_S_NOTLS1_2) + || o == OPT_S_NOTLS1_2 || o == OPT_S_NOTLS1_3) + +/* + * Random state options. + */ +# define OPT_R_ENUM \ + OPT_R__FIRST=1500, OPT_R_RAND, OPT_R_WRITERAND, OPT_R__LAST + +# define OPT_R_OPTIONS \ + {"rand", OPT_R_RAND, 's', "Load the file(s) into the random number generator"}, \ + {"writerand", OPT_R_WRITERAND, '>', "Write random data to the specified file"} + +# define OPT_R_CASES \ + OPT_R__FIRST: case OPT_R__LAST: break; \ + case OPT_R_RAND: case OPT_R_WRITERAND /* * Option parsing. @@ -296,7 +333,7 @@ typedef struct options_st { /* * value type: - no value (also the value zero), n number, p positive * number, u unsigned, l long, s string, < input file, > output file, - * f any format, F der/pem format , E der/pem/engine format identifier. + * f any format, F der/pem format, E der/pem/engine format identifier. * l, n and u include zero; p does not. */ int valtype; @@ -355,10 +392,10 @@ int opt_md(const char *name, const EVP_MD **mdp); char *opt_arg(void); char *opt_flag(void); char *opt_unknown(void); -char *opt_reset(void); char **opt_rest(void); int opt_num_rest(void); int opt_verify(int i, X509_VERIFY_PARAM *vpm); +int opt_rand(int i); void opt_help(const OPTIONS * list); int opt_format_error(const char *s, unsigned long flags); @@ -391,6 +428,7 @@ int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_data); int setup_ui_method(void); void destroy_ui_method(void); +const UI_METHOD *get_ui_method(void); int chopup_args(ARGS *arg, char *buf); # ifdef HEADER_X509_H @@ -401,6 +439,8 @@ void print_name(BIO *out, const char *title, X509_NAME *nm, void print_bignum_var(BIO *, const BIGNUM *, const char*, int, unsigned char *); void print_array(BIO *, const char *, int, const unsigned char *); +int set_nameopt(const char *arg); +unsigned long get_nameopt(void); int set_cert_ex(unsigned long *flags, const char *arg); int set_name_ex(unsigned long *flags, const char *arg); int set_ext_copy(int *copy_type, const char *arg); @@ -458,9 +498,10 @@ int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold, * disabled */ # define DB_NUMBER 6 -# define DB_TYPE_REV 'R' -# define DB_TYPE_EXP 'E' -# define DB_TYPE_VAL 'V' +# define DB_TYPE_REV 'R' /* Revoked */ +# define DB_TYPE_EXP 'E' /* Expired */ +# define DB_TYPE_VAL 'V' /* Valid ; inserted with: ca ... -valid */ +# define DB_TYPE_SUSP 'S' /* Suspended */ typedef struct db_attr_st { int unique_subject; @@ -490,8 +531,6 @@ int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b); int parse_yesno(const char *str, int def); X509_NAME *parse_name(const char *str, long chtype, int multirdn); -int args_verify(char ***pargs, int *pargc, - int *badarg, X509_VERIFY_PARAM **pm); void policies_print(X509_STORE_CTX *ctx); int bio_to_mem(unsigned char **out, int maxlen, BIO *in); int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value); @@ -503,9 +542,9 @@ int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts); int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts); -# ifndef OPENSSL_NO_PSK + extern char *psk_key; -# endif + unsigned char *next_protos_parse(size_t *outlen, const char *in); @@ -546,7 +585,12 @@ void store_setup_crl_download(X509_STORE *st); # define APP_PASS_LEN 1024 -# define SERIAL_RAND_BITS 64 +/* + * IETF RFC 5280 says serial number must be <= 20 bytes. Use 159 bits + * so that the first bit will never be one, so that the DER encoding + * rules won't force a leading octet. + */ +# define SERIAL_RAND_BITS 159 int app_isdir(const char *); int app_access(const char *, int flag); @@ -559,6 +603,8 @@ int raw_write_stdout(const void *, int); # define TM_STOP 1 double app_tminterval(int stop, int usertime); +void make_uppercase(char *string); + typedef struct verify_options_st { int depth; int quiet; @@ -568,6 +614,4 @@ typedef struct verify_options_st { extern VERIFY_CB_ARGS verify_args; -# include "progs.h" - #endif diff --git a/apps/asn1pars.c b/apps/asn1pars.c index 1ac261c7..a391e0a6 100644 --- a/apps/asn1pars.c +++ b/apps/asn1pars.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -7,28 +7,26 @@ * https://www.openssl.org/source/license.html */ -/* - * A nice addition from Dr Stephen Henson to add the - * -strparse option which parses nested binary structures - */ - #include #include #include #include "apps.h" +#include "progs.h" #include #include #include #include +#include typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_INFORM, OPT_IN, OPT_OUT, OPT_INDENT, OPT_NOOUT, OPT_OID, OPT_OFFSET, OPT_LENGTH, OPT_DUMP, OPT_DLIMIT, - OPT_STRPARSE, OPT_GENSTR, OPT_GENCONF, OPT_STRICTPEM + OPT_STRPARSE, OPT_GENSTR, OPT_GENCONF, OPT_STRICTPEM, + OPT_ITEM } OPTION_CHOICE; -OPTIONS asn1parse_options[] = { +const OPTIONS asn1parse_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'F', "input format - one of DER PEM"}, {"in", OPT_IN, '<', "input file"}, @@ -49,6 +47,7 @@ OPTIONS asn1parse_options[] = { {OPT_MORE_STR, 0, 0, "(-inform will be ignored)"}, {"strictpem", OPT_STRICTPEM, 0, "do not attempt base64 decode outside PEM markers"}, + {"item", OPT_ITEM, 's', "item to parse and print"}, {NULL} }; @@ -71,6 +70,7 @@ int asn1parse_main(int argc, char **argv) unsigned char *tmpbuf; unsigned int length = 0; OPTION_CHOICE o; + const ASN1_ITEM *it = NULL; prog = opt_init(argc, argv, asn1parse_options); @@ -134,6 +134,22 @@ int asn1parse_main(int argc, char **argv) strictpem = 1; informat = FORMAT_PEM; break; + case OPT_ITEM: + it = ASN1_ITEM_lookup(opt_arg()); + if (it == NULL) { + size_t tmp; + + BIO_printf(bio_err, "Unknown item name %s\n", opt_arg()); + BIO_puts(bio_err, "Supported types:\n"); + for (tmp = 0;; tmp++) { + it = ASN1_ITEM_get(tmp); + if (it == NULL) + break; + BIO_printf(bio_err, " %s\n", it->sname); + } + goto end; + } + break; } } argc = opt_num_rest(); @@ -174,9 +190,7 @@ int asn1parse_main(int argc, char **argv) ERR_print_errors(bio_err); goto end; } - } - - else { + } else { if (informat == FORMAT_PEM) { BIO *tmp; @@ -253,18 +267,31 @@ int asn1parse_main(int argc, char **argv) if ((length == 0) || ((long)length > num)) length = (unsigned int)num; - if (derout) { + if (derout != NULL) { if (BIO_write(derout, str + offset, length) != (int)length) { BIO_printf(bio_err, "Error writing output\n"); ERR_print_errors(bio_err); goto end; } } - if (!noout && - !ASN1_parse_dump(bio_out, &(str[offset]), length, - indent, dump)) { - ERR_print_errors(bio_err); - goto end; + if (!noout) { + const unsigned char *p = str + offset; + + if (it != NULL) { + ASN1_VALUE *value = ASN1_item_d2i(NULL, &p, length, it); + if (value == NULL) { + BIO_printf(bio_err, "Error parsing item %s\n", it->sname); + ERR_print_errors(bio_err); + goto end; + } + ASN1_item_print(bio_out, value, 0, it, NULL); + ASN1_item_free(value, it); + } else { + if (!ASN1_parse_dump(bio_out, p, length, indent, dump)) { + ERR_print_errors(bio_err); + goto end; + } + } } ret = 0; end: @@ -280,7 +307,7 @@ int asn1parse_main(int argc, char **argv) OPENSSL_free(str); ASN1_TYPE_free(at); sk_OPENSSL_STRING_free(osk); - return (ret); + return ret; } static int do_generate(char *genstr, const char *genconf, BUF_MEM *buf) @@ -290,12 +317,12 @@ static int do_generate(char *genstr, const char *genconf, BUF_MEM *buf) unsigned char *p; ASN1_TYPE *atyp = NULL; - if (genconf) { + if (genconf != NULL) { if ((cnf = app_load_config(genconf)) == NULL) goto err; - if (!genstr) + if (genstr == NULL) genstr = NCONF_get_string(cnf, "default", "asn1"); - if (!genstr) { + if (genstr == NULL) { BIO_printf(bio_err, "Can't find 'asn1' in '%s'\n", genconf); goto err; } @@ -305,7 +332,7 @@ static int do_generate(char *genstr, const char *genconf, BUF_MEM *buf) NCONF_free(cnf); cnf = NULL; - if (!atyp) + if (atyp == NULL) return -1; len = i2d_ASN1_TYPE(atyp, NULL); diff --git a/apps/bf_prefix.c b/apps/bf_prefix.c new file mode 100644 index 00000000..bae3c91b --- /dev/null +++ b/apps/bf_prefix.c @@ -0,0 +1,177 @@ +/* + * Copyright 2018 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 +#include +#include +#include +#include "apps.h" + +static int prefix_write(BIO *b, const char *out, size_t outl, + size_t *numwritten); +static int prefix_read(BIO *b, char *buf, size_t size, size_t *numread); +static int prefix_puts(BIO *b, const char *str); +static int prefix_gets(BIO *b, char *str, int size); +static long prefix_ctrl(BIO *b, int cmd, long arg1, void *arg2); +static int prefix_create(BIO *b); +static int prefix_destroy(BIO *b); +static long prefix_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp); + +static BIO_METHOD *prefix_meth = NULL; + +BIO_METHOD *apps_bf_prefix(void) +{ + if (prefix_meth == NULL) { + if ((prefix_meth = + BIO_meth_new(BIO_TYPE_FILTER, "Prefix filter")) == NULL + || !BIO_meth_set_create(prefix_meth, prefix_create) + || !BIO_meth_set_destroy(prefix_meth, prefix_destroy) + || !BIO_meth_set_write_ex(prefix_meth, prefix_write) + || !BIO_meth_set_read_ex(prefix_meth, prefix_read) + || !BIO_meth_set_puts(prefix_meth, prefix_puts) + || !BIO_meth_set_gets(prefix_meth, prefix_gets) + || !BIO_meth_set_ctrl(prefix_meth, prefix_ctrl) + || !BIO_meth_set_callback_ctrl(prefix_meth, prefix_callback_ctrl)) { + BIO_meth_free(prefix_meth); + prefix_meth = NULL; + } + } + return prefix_meth; +} + +typedef struct prefix_ctx_st { + char *prefix; + int linestart; /* flag to indicate we're at the line start */ +} PREFIX_CTX; + +static int prefix_create(BIO *b) +{ + PREFIX_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); + + if (ctx == NULL) + return 0; + + ctx->prefix = NULL; + ctx->linestart = 1; + BIO_set_data(b, ctx); + BIO_set_init(b, 1); + return 1; +} + +static int prefix_destroy(BIO *b) +{ + PREFIX_CTX *ctx = BIO_get_data(b); + + OPENSSL_free(ctx->prefix); + OPENSSL_free(ctx); + return 1; +} + +static int prefix_read(BIO *b, char *in, size_t size, size_t *numread) +{ + return BIO_read_ex(BIO_next(b), in, size, numread); +} + +static int prefix_write(BIO *b, const char *out, size_t outl, + size_t *numwritten) +{ + PREFIX_CTX *ctx = BIO_get_data(b); + + if (ctx == NULL) + return 0; + + /* If no prefix is set or if it's empty, we've got nothing to do here */ + if (ctx->prefix == NULL || *ctx->prefix == '\0') { + /* We do note if what comes next will be a new line, though */ + if (outl > 0) + ctx->linestart = (out[outl-1] == '\n'); + return BIO_write_ex(BIO_next(b), out, outl, numwritten); + } + + *numwritten = 0; + + while (outl > 0) { + size_t i; + char c; + + /* If we know that we're at the start of the line, output the prefix */ + if (ctx->linestart) { + size_t dontcare; + + if (!BIO_write_ex(BIO_next(b), ctx->prefix, strlen(ctx->prefix), + &dontcare)) + return 0; + ctx->linestart = 0; + } + + /* Now, go look for the next LF, or the end of the string */ + for (i = 0, c = '\0'; i < outl && (c = out[i]) != '\n'; i++) + continue; + if (c == '\n') + i++; + + /* Output what we found so far */ + while (i > 0) { + size_t num = 0; + + if (!BIO_write_ex(BIO_next(b), out, i, &num)) + return 0; + out += num; + outl -= num; + *numwritten += num; + i -= num; + } + + /* If we found a LF, what follows is a new line, so take note */ + if (c == '\n') + ctx->linestart = 1; + } + + return 1; +} + +static long prefix_ctrl(BIO *b, int cmd, long num, void *ptr) +{ + long ret = 0; + + switch (cmd) { + case PREFIX_CTRL_SET_PREFIX: + { + PREFIX_CTX *ctx = BIO_get_data(b); + + if (ctx == NULL) + break; + + OPENSSL_free(ctx->prefix); + ctx->prefix = OPENSSL_strdup((const char *)ptr); + ret = ctx->prefix != NULL; + } + break; + default: + if (BIO_next(b) != NULL) + ret = BIO_ctrl(BIO_next(b), cmd, num, ptr); + break; + } + return ret; +} + +static long prefix_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) +{ + return BIO_callback_ctrl(BIO_next(b), cmd, fp); +} + +static int prefix_gets(BIO *b, char *buf, int size) +{ + return BIO_gets(BIO_next(b), buf, size); +} + +static int prefix_puts(BIO *b, const char *str) +{ + return BIO_write(b, str, strlen(str)); +} diff --git a/apps/build.info b/apps/build.info index e2ddd2b5..e7243733 100644 --- a/apps/build.info +++ b/apps/build.info @@ -1,21 +1,27 @@ {- our $tsget_name = $config{target} =~ /^(VC|vms)-/ ? "tsget.pl" : "tsget"; our @apps_openssl_src = - ( qw(openssl.c - asn1pars.c ca.c ciphers.c cms.c crl.c crl2p7.c dgst.c dhparam.c - dsa.c dsaparam.c ec.c ecparam.c enc.c engine.c errstr.c gendsa.c - genpkey.c genrsa.c nseq.c ocsp.c passwd.c pkcs12.c pkcs7.c pkcs8.c - pkey.c pkeyparam.c pkeyutl.c prime.c rand.c req.c rsa.c rsautl.c - s_client.c s_server.c s_time.c sess_id.c smime.c speed.c spkac.c - srp.c ts.c verify.c version.c x509.c rehash.c - apps.c opt.c s_cb.c s_socket.c - app_rand.c), - split(/\s+/, $target{apps_aux_src}) ); + qw(openssl.c + asn1pars.c ca.c ciphers.c cms.c crl.c crl2p7.c dgst.c dhparam.c + dsa.c dsaparam.c ec.c ecparam.c enc.c engine.c errstr.c gendsa.c + genpkey.c genrsa.c nseq.c ocsp.c passwd.c pkcs12.c pkcs7.c pkcs8.c + pkey.c pkeyparam.c pkeyutl.c prime.c rand.c req.c rsa.c rsautl.c + s_client.c s_server.c s_time.c sess_id.c smime.c speed.c spkac.c + srp.c ts.c verify.c version.c x509.c rehash.c storeutl.c); + our @apps_lib_src = + ( qw(apps.c opt.c s_cb.c s_socket.c app_rand.c bf_prefix.c), + split(/\s+/, $target{apps_aux_src}) ); + our @apps_init_src = split(/\s+/, $target{apps_init_src}); "" -} IF[{- !$disabled{apps} -}] + LIBS_NO_INST=libapps.a + SOURCE[libapps.a]={- join(" ", @apps_lib_src) -} + INCLUDE[libapps.a]=.. ../include + PROGRAMS=openssl + SOURCE[openssl]={- join(" ", @apps_init_src) -} SOURCE[openssl]={- join(" ", @apps_openssl_src) -} INCLUDE[openssl]=.. ../include - DEPEND[openssl]=../libssl + DEPEND[openssl]=libapps.a ../libssl {- join("\n ", map { (my $x = $_) =~ s|\.c$|.o|; "DEPEND[$x]=progs.h" } @apps_openssl_src) -} diff --git a/apps/ca.c b/apps/ca.c index d474a2b6..2819fead 100644 --- a/apps/ca.c +++ b/apps/ca.c @@ -6,9 +6,6 @@ * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ - -/* The PPKI stuff has been donated by Jeff Barber */ - #include #include #include @@ -28,27 +25,24 @@ #ifndef W_OK # ifdef OPENSSL_SYS_VMS -# if defined(__DECC) -# include -# else -# include -# endif +# include # elif !defined(OPENSSL_SYS_VXWORKS) && !defined(OPENSSL_SYS_WINDOWS) # include # endif #endif #include "apps.h" +#include "progs.h" #ifndef W_OK # define F_OK 0 -# define X_OK 1 # define W_OK 2 # define R_OK 4 #endif -#undef BSIZE -#define BSIZE 256 +#ifndef PATH_MAX +# define PATH_MAX 4096 +#endif #define BASE_SECTION "ca" @@ -60,6 +54,7 @@ #define ENV_NEW_CERTS_DIR "new_certs_dir" #define ENV_CERTIFICATE "certificate" #define ENV_SERIAL "serial" +#define ENV_RAND_SERIAL "rand_serial" #define ENV_CRLNUMBER "crlnumber" #define ENV_PRIVATE_KEY "private_key" #define ENV_DEFAULT_DAYS "default_days" @@ -82,12 +77,14 @@ #define ENV_DATABASE "database" /* Additional revocation information types */ - -#define REV_NONE 0 /* No additional 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 */ +typedef enum { + REV_VALID = -1, /* Valid (not-revoked) status */ + REV_NONE = 0, /* No additional information */ + REV_CRL_REASON = 1, /* Value is CRL reason code */ + REV_HOLD = 2, /* Value is hold instruction */ + REV_KEY_COMPROMISE = 3, /* Value is cert key compromise time */ + REV_CA_COMPROMISE = 4 /* Value is CA key compromise time */ +} REVINFO_TYPE; static char *lookup_conf(const CONF *conf, const char *group, const char *tag); @@ -117,7 +114,6 @@ static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey, const char *enddate, long days, const 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, @@ -126,13 +122,15 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, int batch, int verbose, X509_REQ *req, const 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); +static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type, + const char *extval); +static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg); +static int make_revoked(X509_REVOKED *rev, const char *str); static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str); +static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext); static CONF *extconf = NULL; static int preserve = 0; @@ -148,11 +146,13 @@ typedef enum OPTION_choice { OPT_GENCRL, OPT_MSIE_HACK, OPT_CRLDAYS, OPT_CRLHOURS, OPT_CRLSEC, OPT_INFILES, OPT_SS_CERT, OPT_SPKAC, OPT_REVOKE, OPT_VALID, OPT_EXTENSIONS, OPT_EXTFILE, OPT_STATUS, OPT_UPDATEDB, OPT_CRLEXTS, - OPT_CRL_REASON, OPT_CRL_HOLD, OPT_CRL_COMPROMISE, - OPT_CRL_CA_COMPROMISE + OPT_RAND_SERIAL, + OPT_R_ENUM, + /* Do not change the order here; see related case statements below */ + OPT_CRL_REASON, OPT_CRL_HOLD, OPT_CRL_COMPROMISE, OPT_CRL_CA_COMPROMISE } OPTION_CHOICE; -OPTIONS ca_options[] = { +const OPTIONS ca_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"verbose", OPT_VERBOSE, '-', "Verbose output during processing"}, {"config", OPT_CONFIG, 's', "A config file"}, @@ -161,6 +161,8 @@ OPTIONS ca_options[] = { {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"}, {"create_serial", OPT_CREATE_SERIAL, '-', "If reading serial fails, create a new random serial"}, + {"rand_serial", OPT_RAND_SERIAL, '-', + "Always create a random serial; do not store it"}, {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-', "Enable support for multivalued RDNs"}, {"startdate", OPT_STARTDATE, 's', "Cert notBefore, YYMMDDHHMMSSZ"}, @@ -212,6 +214,7 @@ OPTIONS ca_options[] = { "sets compromise time to val and the revocation reason to keyCompromise"}, {"crl_CA_compromise", OPT_CRL_CA_COMPROMISE, 's', "sets compromise time to val and the revocation reason to CACompromise"}, + OPT_R_OPTIONS, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif @@ -242,18 +245,21 @@ int ca_main(int argc, char **argv) char *outdir = NULL, *outfile = NULL, *rev_arg = NULL, *ser_status = NULL; const char *serialfile = NULL, *subj = NULL; char *prog, *startdate = NULL, *enddate = NULL; - char *dbfile = NULL, *f, *randfile = NULL; - char buf[3][BSIZE]; + char *dbfile = NULL, *f; + char new_cert[PATH_MAX]; + char tmp[10 + 1] = "\0"; char *const *pp; const char *p; + size_t outdirlen = 0; int create_ser = 0, free_key = 0, total = 0, total_done = 0; int batch = 0, default_op = 1, doupdatedb = 0, ext_copy = EXT_COPY_NONE; int keyformat = FORMAT_PEM, multirdn = 0, notext = 0, output_der = 0; int ret = 1, email_dn = 1, req = 0, verbose = 0, gencrl = 0, dorevoke = 0; - int i, j, rev_type = REV_NONE, selfsign = 0; + int rand_ser = 0, i, j, selfsign = 0; long crldays = 0, crlhours = 0, crlsec = 0, days = 0; - unsigned long chtype = MBSTRING_ASC, nameopt = 0, certopt = 0; + unsigned long chtype = MBSTRING_ASC, certopt = 0; X509 *x509 = NULL, *x509p = NULL, *x = NULL; + REVINFO_TYPE rev_type = REV_NONE; X509_REVOKED *r = NULL; OPTION_CHOICE o; @@ -292,6 +298,9 @@ opthelp: case OPT_UTF8: chtype = MBSTRING_UTF8; break; + case OPT_RAND_SERIAL: + rand_ser = 1; + break; case OPT_CREATE_SERIAL: create_ser = 1; break; @@ -323,6 +332,10 @@ opthelp: case OPT_PASSIN: passinarg = opt_arg(); break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; case OPT_KEY: key = opt_arg(); break; @@ -338,8 +351,7 @@ opthelp: case OPT_SIGOPT: if (sigopts == NULL) sigopts = sk_OPENSSL_STRING_new_null(); - if (sigopts == NULL - || !sk_OPENSSL_STRING_push(sigopts, opt_arg())) + if (sigopts == NULL || !sk_OPENSSL_STRING_push(sigopts, opt_arg())) goto end; break; case OPT_NOTEXT: @@ -403,21 +415,12 @@ opthelp: case OPT_CRLEXTS: crl_ext = opt_arg(); break; - case OPT_CRL_REASON: - rev_arg = opt_arg(); - rev_type = REV_CRL_REASON; - break; + case OPT_CRL_REASON: /* := REV_CRL_REASON */ case OPT_CRL_HOLD: - rev_arg = opt_arg(); - rev_type = REV_HOLD; - break; case OPT_CRL_COMPROMISE: - rev_arg = opt_arg(); - rev_type = REV_KEY_COMPROMISE; - break; case OPT_CRL_CA_COMPROMISE: rev_arg = opt_arg(); - rev_type = REV_CA_COMPROMISE; + rev_type = (o - OPT_CRL_REASON) + REV_CRL_REASON; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); @@ -458,23 +461,20 @@ end_of_options: goto end; } - randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE"); - if (randfile == NULL) - ERR_clear_error(); - app_RAND_load_file(randfile, 0); + app_RAND_load_conf(conf, BASE_SECTION); f = NCONF_get_string(conf, section, STRING_MASK); - if (!f) + if (f == NULL) ERR_clear_error(); - if (f && !ASN1_STRING_set_default_mask_asc(f)) { + if (f != NULL && !ASN1_STRING_set_default_mask_asc(f)) { BIO_printf(bio_err, "Invalid global string mask setting %s\n", f); goto end; } if (chtype != MBSTRING_UTF8) { f = NCONF_get_string(conf, section, UTF8_IN); - if (!f) + if (f == NULL) ERR_clear_error(); else if (strcmp(f, "yes") == 0) chtype = MBSTRING_UTF8; @@ -482,9 +482,9 @@ end_of_options: db_attr.unique_subject = 1; p = NCONF_get_string(conf, section, ENV_UNIQUE_SUBJECT); - if (p) { + if (p != NULL) db_attr.unique_subject = parse_yesno(p, 1); - } else + else ERR_clear_error(); /*****************************************************************/ @@ -513,7 +513,7 @@ end_of_options: && (keyfile = lookup_conf(conf, section, ENV_PRIVATE_KEY)) == NULL) goto end; - if (!key) { + if (key == NULL) { free_key = 1; if (!app_passwd(passinarg, NULL, &key, NULL)) { BIO_printf(bio_err, "Error getting password\n"); @@ -521,12 +521,11 @@ end_of_options: } } pkey = load_key(keyfile, keyformat, 0, key, e, "CA private key"); - if (key) + if (key != NULL) OPENSSL_cleanse(key, strlen(key)); - if (pkey == NULL) { + if (pkey == NULL) /* load_key() has already printed an appropriate message */ goto end; - } /*****************************************************************/ /* we need a certificate */ @@ -561,37 +560,36 @@ end_of_options: f = NCONF_get_string(conf, section, ENV_NAMEOPT); - if (f) { - if (!set_name_ex(&nameopt, f)) { + if (f != NULL) { + if (!set_nameopt(f)) { BIO_printf(bio_err, "Invalid name options: \"%s\"\n", f); goto end; } default_op = 0; - } else { - nameopt = XN_FLAG_ONELINE; - ERR_clear_error(); } f = NCONF_get_string(conf, section, ENV_CERTOPT); - if (f) { + if (f != NULL) { if (!set_cert_ex(&certopt, f)) { BIO_printf(bio_err, "Invalid certificate options: \"%s\"\n", f); goto end; } default_op = 0; - } else + } else { ERR_clear_error(); + } f = NCONF_get_string(conf, section, ENV_EXTCOPY); - if (f) { + if (f != NULL) { if (!set_ext_copy(&ext_copy, f)) { BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", f); goto end; } - } else + } else { ERR_clear_error(); + } /*****************************************************************/ /* lookup where to write new certificates */ @@ -666,6 +664,10 @@ end_of_options: goto end; } } + if (pp[DB_name][0] == '\0') { + BIO_printf(bio_err, "entry %d: bad Subject\n", i + 1); + goto end; + } } if (verbose) { TXT_DB_write(bio_out, db->db); @@ -698,8 +700,7 @@ end_of_options: goto end; if (verbose) - BIO_printf(bio_err, - "Done. %d entries marked as expired\n", i); + BIO_printf(bio_err, "Done. %d entries marked as expired\n", i); } } @@ -731,8 +732,7 @@ end_of_options: goto end; } - if (md == NULL - && (md = lookup_conf(conf, section, ENV_DEFAULT_MD)) == NULL) + if (md == NULL && (md = lookup_conf(conf, section, ENV_DEFAULT_MD)) == NULL) goto end; if (strcmp(md, "default") == 0) { @@ -766,21 +766,25 @@ end_of_options: if (verbose) BIO_printf(bio_err, "policy is %s\n", policy); - serialfile = lookup_conf(conf, section, ENV_SERIAL); - if (serialfile == NULL) - goto end; + if (NCONF_get_string(conf, section, ENV_RAND_SERIAL) != NULL) { + rand_ser = 1; + } else { + serialfile = lookup_conf(conf, section, ENV_SERIAL); + if (serialfile == NULL) + goto end; + } - if (!extconf) { + if (extconf == NULL) { /* * no '-extfile' option, so we look for extensions in the main * configuration file */ - if (!extensions) { + if (extensions == NULL) { extensions = NCONF_get_string(conf, section, ENV_EXTENSIONS); - if (!extensions) + if (extensions == NULL) ERR_clear_error(); } - if (extensions) { + if (extensions != NULL) { /* Check syntax of file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); @@ -796,12 +800,11 @@ end_of_options: } if (startdate == NULL) { - startdate = NCONF_get_string(conf, section, - ENV_DEFAULT_STARTDATE); + startdate = NCONF_get_string(conf, section, ENV_DEFAULT_STARTDATE); if (startdate == NULL) ERR_clear_error(); } - if (startdate && !ASN1_TIME_set_string(NULL, startdate)) { + if (startdate != NULL && !ASN1_TIME_set_string_X509(NULL, startdate)) { BIO_printf(bio_err, "start date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n"); goto end; @@ -814,7 +817,7 @@ end_of_options: if (enddate == NULL) ERR_clear_error(); } - if (enddate && !ASN1_TIME_set_string(NULL, enddate)) { + if (enddate != NULL && !ASN1_TIME_set_string_X509(NULL, enddate)) { BIO_printf(bio_err, "end date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n"); goto end; @@ -824,24 +827,30 @@ end_of_options: 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"); + if (enddate == NULL && days == 0) { + BIO_printf(bio_err, "cannot lookup how many days to certify for\n"); goto end; } - if ((serial = load_serial(serialfile, create_ser, NULL)) == NULL) { - BIO_printf(bio_err, "error while loading serial number\n"); - goto end; - } - 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 end; - BIO_printf(bio_err, "next serial number is %s\n", f); - OPENSSL_free(f); + if (rand_ser) { + if ((serial = BN_new()) == NULL || !rand_serial(serial, NULL)) { + BIO_printf(bio_err, "error generating serial number\n"); + goto end; + } + } else { + if ((serial = load_serial(serialfile, create_ser, NULL)) == NULL) { + BIO_printf(bio_err, "error while loading serial number\n"); + goto end; + } + 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 end; + BIO_printf(bio_err, "next serial number is %s\n", f); + OPENSSL_free(f); + } } } @@ -859,7 +868,7 @@ end_of_options: 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, + conf, verbose, certopt, get_nameopt(), default_op, ext_copy); if (j < 0) goto end; @@ -884,7 +893,7 @@ end_of_options: attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, extensions, - conf, verbose, certopt, nameopt, default_op, + conf, verbose, certopt, get_nameopt(), default_op, ext_copy); if (j < 0) goto end; @@ -904,7 +913,7 @@ end_of_options: 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); + certopt, get_nameopt(), default_op, ext_copy, selfsign); if (j < 0) goto end; if (j > 0) { @@ -923,7 +932,7 @@ end_of_options: 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); + certopt, get_nameopt(), default_op, ext_copy, selfsign); if (j < 0) goto end; if (j > 0) { @@ -948,14 +957,13 @@ end_of_options: "\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"); + tmp[0] = '\0'; + if (fgets(tmp, sizeof(tmp), stdin) == NULL) { + BIO_printf(bio_err, "CERTIFICATION CANCELED: I/O error\n"); ret = 0; goto end; } - if ((buf[0][0] != 'y') && (buf[0][0] != 'Y')) { + if (tmp[0] != 'y' && tmp[0] != 'Y') { BIO_printf(bio_err, "CERTIFICATION CANCELED\n"); ret = 0; goto end; @@ -965,45 +973,42 @@ end_of_options: BIO_printf(bio_err, "Write out database with %d new entries\n", sk_X509_num(cert_sk)); - if (!save_serial(serialfile, "new", serial, NULL)) + if (!rand_ser + && !save_serial(serialfile, "new", serial, NULL)) goto end; if (!save_index(dbfile, "new", db)) goto end; } + outdirlen = OPENSSL_strlcpy(new_cert, outdir, sizeof(new_cert)); +#ifndef OPENSSL_SYS_VMS + outdirlen = OPENSSL_strlcat(new_cert, "/", sizeof(new_cert)); +#endif + if (verbose) BIO_printf(bio_err, "writing new certificates\n"); + for (i = 0; i < sk_X509_num(cert_sk); i++) { BIO *Cout = NULL; X509 *xi = sk_X509_value(cert_sk, i); ASN1_INTEGER *serialNumber = X509_get_serialNumber(xi); - int k; - char *n; + const unsigned char *psn = ASN1_STRING_get0_data(serialNumber); + const int snl = ASN1_STRING_length(serialNumber); + const int filen_len = 2 * (snl > 0 ? snl : 1) + sizeof(".pem"); + char *n = new_cert + outdirlen; - j = ASN1_STRING_length(serialNumber); - p = (const char *)ASN1_STRING_get0_data(serialNumber); - - if (strlen(outdir) >= (size_t)(j ? BSIZE - j * 2 - 6 : BSIZE - 8)) { + if (outdirlen + filen_len > PATH_MAX) { BIO_printf(bio_err, "certificate file name too long\n"); goto end; } - strcpy(buf[2], outdir); + if (snl > 0) { + static const char HEX_DIGITS[] = "0123456789ABCDEF"; -#ifndef OPENSSL_SYS_VMS - OPENSSL_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; + for (j = 0; j < snl; j++, psn++) { + *n++ = HEX_DIGITS[*psn >> 4]; + *n++ = HEX_DIGITS[*psn & 0x0F]; } } else { *(n++) = '0'; @@ -1013,13 +1018,13 @@ end_of_options: *(n++) = 'p'; *(n++) = 'e'; *(n++) = 'm'; - *n = '\0'; + *n = '\0'; /* closing new_cert */ if (verbose) - BIO_printf(bio_err, "writing %s\n", buf[2]); + BIO_printf(bio_err, "writing %s\n", new_cert); - Cout = BIO_new_file(buf[2], "w"); + Cout = BIO_new_file(new_cert, "w"); if (Cout == NULL) { - perror(buf[2]); + perror(new_cert); goto end; } write_new_certificate(Cout, xi, 0, notext); @@ -1042,20 +1047,19 @@ end_of_options: /*****************************************************************/ if (gencrl) { int crl_v2 = 0; - if (!crl_ext) { + if (crl_ext == NULL) { crl_ext = NCONF_get_string(conf, section, ENV_CRLEXT); - if (!crl_ext) + if (crl_ext == NULL) ERR_clear_error(); } - if (crl_ext) { + if (crl_ext != NULL) { /* 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); + "Error Loading CRL extension section %s\n", crl_ext); ret = 1; goto end; } @@ -1138,12 +1142,12 @@ end_of_options: /* Add any extensions asked for */ - if (crl_ext || crlnumberfile != NULL) { + if (crl_ext != NULL || crlnumberfile != NULL) { X509V3_CTX crlctx; X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0); X509V3_set_nconf(&crlctx, conf); - if (crl_ext) + if (crl_ext != NULL) if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx, crl_ext, crl)) goto end; if (crlnumberfile != NULL) { @@ -1157,14 +1161,15 @@ end_of_options: goto end; } } - if (crl_ext || crl_v2) { + if (crl_ext != NULL || crl_v2) { if (!X509_CRL_set_version(crl, 1)) goto end; /* version 2 CRL */ } /* we have a CRL number that need updating */ if (crlnumberfile != NULL) - if (!save_serial(crlnumberfile, "new", crlnumber, NULL)) + if (!rand_ser + && !save_serial(crlnumberfile, "new", crlnumber, NULL)) goto end; BN_free(crlnumber); @@ -1191,7 +1196,7 @@ end_of_options: if (revcert == NULL) goto end; if (dorevoke == 2) - rev_type = -1; + rev_type = REV_VALID; j = do_revoke(revcert, db, rev_type, rev_arg); if (j <= 0) goto end; @@ -1206,17 +1211,16 @@ end_of_options: BIO_printf(bio_err, "Data Base Updated\n"); } } - /*****************************************************************/ ret = 0; + end: + if (ret) + ERR_print_errors(bio_err); BIO_free_all(Sout); BIO_free_all(out); BIO_free_all(in); sk_X509_pop_free(cert_sk, X509_free); - if (ret) - ERR_print_errors(bio_err); - app_RAND_write_file(randfile); if (free_key) OPENSSL_free(key); BN_free(serial); @@ -1229,7 +1233,7 @@ end_of_options: NCONF_free(conf); NCONF_free(extconf); release_engine(e); - return (ret); + return ret; } static char *lookup_conf(const CONF *conf, const char *section, const char *tag) @@ -1266,7 +1270,7 @@ static int certify(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509, goto end; } if (verbose) - X509_REQ_print(bio_err, req); + X509_REQ_print_ex(bio_err, req, nameopt, X509_FLAG_COMPAT); BIO_printf(bio_err, "Check that the request matches the signature\n"); @@ -1294,8 +1298,9 @@ static int certify(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509, "Signature did not match the certificate request\n"); ERR_print_errors(bio_err); goto end; - } else + } 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, @@ -1305,7 +1310,7 @@ static int certify(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509, end: X509_REQ_free(req); BIO_free(in); - return (ok); + return ok; } static int certify_cert(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509, @@ -1343,8 +1348,9 @@ static int certify_cert(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x ok = 0; BIO_printf(bio_err, "Signature did not match the certificate\n"); goto end; - } else + } else { BIO_printf(bio_err, "Signature ok\n"); + } if ((rreq = X509_to_X509_REQ(req, NULL, NULL)) == NULL) goto end; @@ -1357,7 +1363,7 @@ static int certify_cert(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x end: X509_REQ_free(rreq); X509_free(req); - return (ok); + return ok; } static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, @@ -1369,13 +1375,12 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, CONF *lconf, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign) { - X509_NAME *name = NULL, *CAname = NULL, *subject = NULL; + X509_NAME *name = NULL, *CAname = NULL, *subject = NULL, *dn_subject = NULL; const ASN1_TIME *tm; ASN1_STRING *str, *str2; ASN1_OBJECT *obj; X509 *ret = NULL; - X509_NAME_ENTRY *ne; - X509_NAME_ENTRY *tne, *push; + X509_NAME_ENTRY *ne, *tne; EVP_PKEY *pktmp; int ok = -1, i, j, last, nid; const char *p; @@ -1400,49 +1405,48 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, } if (default_op) - BIO_printf(bio_err, - "The Subject's Distinguished Name is as follows\n"); + BIO_printf(bio_err, "The Subject's Distinguished Name is as follows\n"); name = X509_REQ_get_subject_name(req); + if (X509_NAME_entry_count(name) == 0) { + BIO_printf(bio_err, "Error: The supplied Subject is empty\n"); + goto end; + } 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); + nid = OBJ_obj2nid(obj); if (msie_hack) { /* assume all type should be strings */ - nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(ne)); if (str->type == V_ASN1_UNIVERSALSTRING) ASN1_UNIVERSALSTRING_to_string(str); - if ((str->type == V_ASN1_IA5STRING) && - (nid != NID_pkcs9_emailAddress)) + 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)) + 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)) + if (nid == NID_pkcs9_emailAddress && !email_dn) continue; /* check some things */ - if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) && - (str->type != V_ASN1_IA5STRING)) { + if (nid == NID_pkcs9_emailAddress && str->type != V_ASN1_IA5STRING) { BIO_printf(bio_err, "\nemailAddress type needs to be of type IA5STRING\n"); goto end; } - if ((str->type != V_ASN1_BMPSTRING) - && (str->type != V_ASN1_UTF8STRING)) { + 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))) { + 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 end; @@ -1480,6 +1484,8 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, last = -1; for (;;) { + X509_NAME_ENTRY *push = NULL; + /* lookup the object in the supplied name list */ j = X509_NAME_get_index_by_OBJ(name, obj, last); if (j < 0) { @@ -1492,7 +1498,6 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, last = j; /* depending on the 'policy', decide what to do. */ - push = NULL; if (strcmp(cv->value, "optional") == 0) { if (tne != NULL) push = tne; @@ -1502,8 +1507,9 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, "The %s field needed to be supplied and was missing\n", cv->name); goto end; - } else + } else { push = tne; + } } else if (strcmp(cv->value, "match") == 0) { int last2; @@ -1521,8 +1527,7 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, if ((j < 0) && (last2 == -1)) { BIO_printf(bio_err, "The %s field does not exist in the CA certificate,\n" - "the 'policy' is misconfigured\n", - cv->name); + "the 'policy' is misconfigured\n", cv->name); goto end; } if (j >= 0) { @@ -1568,124 +1573,25 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, goto end; } - /* We are now totally happy, lets make and sign the certificate */ - if (verbose) + if (X509_NAME_entry_count(subject) == 0) { BIO_printf(bio_err, - "Everything appears to be ok, creating and signing the certificate\n"); - - if ((ret = X509_new()) == NULL) + "Error: After applying policy the Subject is empty\n"); goto end; - -#ifdef X509_V3 - /* Make it an X509 v3 certificate. */ - if (!X509_set_version(ret, 2)) - goto end; -#endif - - if (BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(ret)) == NULL) - goto end; - if (selfsign) { - if (!X509_set_issuer_name(ret, subject)) - goto end; - } else { - if (!X509_set_issuer_name(ret, X509_get_subject_name(x509))) - goto end; - } - - if (!set_cert_times(ret, startdate, enddate, days)) - goto end; - - if (enddate != NULL) { - int tdays; - - if (!ASN1_TIME_diff(&tdays, NULL, NULL, X509_get0_notAfter(ret))) - goto end; - days = tdays; - } - - if (!X509_set_subject_name(ret, subject)) - goto end; - - pktmp = X509_REQ_get0_pubkey(req); - i = X509_set_pubkey(ret, pktmp); - if (!i) - goto end; - - /* Lets add the extensions, if there are any */ - if (ext_sect) { - X509V3_CTX ctx; - - /* 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 end; - } - 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 end; - } - - 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 end; - } - - { - const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(ret); - - if (exts != NULL && sk_X509_EXTENSION_num(exts) > 0) - /* Make it an X509 v3 certificate. */ - if (!X509_set_version(ret, 2)) - goto end; } 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; + /* + * 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. @@ -1701,18 +1607,6 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, 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 end; - } - 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 end; } if (BN_is_zero(serial)) @@ -1724,20 +1618,6 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, goto end; } - 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 end; - } - } - if (db->attributes.unique_subject) { OPENSSL_STRING *crow = row; @@ -1796,6 +1676,121 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, goto end; } + /* 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 end; + +#ifdef X509_V3 + /* Make it an X509 v3 certificate. */ + if (!X509_set_version(ret, 2)) + goto end; +#endif + + if (BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(ret)) == NULL) + goto end; + if (selfsign) { + if (!X509_set_issuer_name(ret, subject)) + goto end; + } else { + if (!X509_set_issuer_name(ret, X509_get_subject_name(x509))) + goto end; + } + + if (!set_cert_times(ret, startdate, enddate, days)) + goto end; + + if (enddate != NULL) { + int tdays; + + if (!ASN1_TIME_diff(&tdays, NULL, NULL, X509_get0_notAfter(ret))) + goto end; + days = tdays; + } + + if (!X509_set_subject_name(ret, subject)) + goto end; + + pktmp = X509_REQ_get0_pubkey(req); + i = X509_set_pubkey(ret, pktmp); + if (!i) + goto end; + + /* Lets add the extensions, if there are any */ + if (ext_sect) { + X509V3_CTX ctx; + + /* 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 != NULL) { + 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 end; + } + 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 end; + } + + 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 end; + } + + { + const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(ret); + + if (exts != NULL && sk_X509_EXTENSION_num(exts) > 0) + /* Make it an X509 v3 certificate. */ + if (!X509_set_version(ret, 2)) + goto end; + } + + /* Set the right value for the noemailDN option */ + if (email_dn == 0) { + if (!X509_set_subject_name(ret, dn_subject)) + goto end; + } + if (!default_op) { BIO_printf(bio_err, "Certificate Details:\n"); /* @@ -1816,13 +1811,13 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, BIO_printf(bio_err, "Sign the certificate? [y/n]:"); (void)BIO_flush(bio_err); buf[0] = '\0'; - if (!fgets(buf, sizeof(buf) - 1, stdin)) { + if (fgets(buf, sizeof(buf), stdin) == NULL) { BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED: I/O error\n"); ok = 0; goto end; } - if (!((buf[0] == 'y') || (buf[0] == 'Y'))) { + if (!(buf[0] == 'y' || buf[0] == 'Y')) { BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED\n"); ok = 0; goto end; @@ -1837,7 +1832,7 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, if (!do_X509_sign(ret, pkey, dgst, sigopts)) goto end; - /* We now just add it to the database */ + /* We now just add it to the database as DB_TYPE_VAL('V') */ row[DB_type] = OPENSSL_strdup("V"); tm = X509_get0_notAfter(ret); row[DB_exp_date] = app_malloc(tm->length + 1, "row expdate"); @@ -1845,6 +1840,8 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, row[DB_exp_date][tm->length] = '\0'; row[DB_rev_date] = NULL; row[DB_file] = OPENSSL_strdup("unknown"); + 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_file] == NULL) || (row[DB_name] == NULL)) { BIO_printf(bio_err, "Memory allocation failure\n"); @@ -1864,23 +1861,24 @@ static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, irow = NULL; ok = 1; end: - if (ok != 1) { + if (irow != NULL) { for (i = 0; i < DB_NUMBER; i++) OPENSSL_free(row[i]); + OPENSSL_free(irow); } - OPENSSL_free(irow); X509_NAME_free(CAname); X509_NAME_free(subject); + if (dn_subject != subject) + X509_NAME_free(dn_subject); if (ok <= 0) X509_free(ret); else *xret = ret; - return (ok); + return ok; } -static void write_new_certificate(BIO *bp, X509 *x, int output_der, - int notext) +static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext) { if (output_der) { @@ -1996,8 +1994,7 @@ static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey, * Now extract the key from the SPKI structure. */ - BIO_printf(bio_err, - "Check that the SPKAC request matches the signature\n"); + 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"); @@ -2025,7 +2022,7 @@ static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey, NETSCAPE_SPKI_free(spki); X509_NAME_ENTRY_free(ne); - return (ok); + return ok; } static int check_time_format(const char *str) @@ -2033,7 +2030,8 @@ 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) +static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type, + const char *value) { const ASN1_TIME *tm = NULL; char *row[DB_NUMBER], **rrow, **irow; @@ -2052,11 +2050,6 @@ static int do_revoke(X509 *x509, CA_DB *db, int type, char *value) 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 end; @@ -2071,7 +2064,7 @@ static int do_revoke(X509 *x509, CA_DB *db, int type, char *value) "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 */ + /* We now just add it to the database as DB_TYPE_REV('V') */ row[DB_type] = OPENSSL_strdup("V"); tm = X509_get0_notAfter(x509); row[DB_exp_date] = app_malloc(tm->length + 1, "row exp_data"); @@ -2101,32 +2094,33 @@ static int do_revoke(X509 *x509, CA_DB *db, int type, char *value) row[i] = NULL; /* Revoke Certificate */ - if (type == -1) + if (rev_type == REV_VALID) ok = 1; else - ok = do_revoke(x509, db, type, value); + /* Retry revocation after DB insertion */ + ok = do_revoke(x509, db, rev_type, value); goto end; } else if (index_name_cmp_noconst(row, rrow)) { BIO_printf(bio_err, "ERROR:name does not match %s\n", row[DB_name]); goto end; - } else if (type == -1) { + } else if (rev_type == REV_VALID) { BIO_printf(bio_err, "ERROR:Already present, serial number %s\n", row[DB_serial]); goto end; - } else if (rrow[DB_type][0] == 'R') { + } else if (rrow[DB_type][0] == DB_TYPE_REV) { BIO_printf(bio_err, "ERROR:Already revoked, serial number %s\n", row[DB_serial]); goto end; } else { BIO_printf(bio_err, "Revoking Certificate %s.\n", rrow[DB_serial]); - rev_str = make_revocation_str(type, value); + rev_str = make_revocation_str(rev_type, value); if (!rev_str) { BIO_printf(bio_err, "Error in revocation arguments\n"); goto end; } - rrow[DB_type][0] = 'R'; + rrow[DB_type][0] = DB_TYPE_REV; rrow[DB_type][1] = '\0'; rrow[DB_rev_date] = rev_str; } @@ -2134,7 +2128,7 @@ static int do_revoke(X509 *x509, CA_DB *db, int type, char *value) end: for (i = 0; i < DB_NUMBER; i++) OPENSSL_free(row[i]); - return (ok); + return ok; } static int get_certificate_status(const char *serial, CA_DB *db) @@ -2153,7 +2147,7 @@ static int get_certificate_status(const char *serial, CA_DB *db) if (serial_len % 2) { /* * Set the first char to 0 - */ ; + */ row[DB_serial][0] = '0'; /* Copy String from serial to row[DB_serial] */ @@ -2166,8 +2160,7 @@ static int get_certificate_status(const char *serial, CA_DB *db) } /* Make it Upper Case */ - for (i = 0; row[DB_serial][i] != '\0'; i++) - row[DB_serial][i] = toupper((unsigned char)row[DB_serial][i]); + make_uppercase(row[DB_serial]); ok = 1; @@ -2177,19 +2170,19 @@ static int get_certificate_status(const char *serial, CA_DB *db) BIO_printf(bio_err, "Serial %s not present in db.\n", row[DB_serial]); ok = -1; goto end; - } else if (rrow[DB_type][0] == 'V') { + } else if (rrow[DB_type][0] == DB_TYPE_VAL) { BIO_printf(bio_err, "%s=Valid (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; - } else if (rrow[DB_type][0] == 'R') { + } else if (rrow[DB_type][0] == DB_TYPE_REV) { BIO_printf(bio_err, "%s=Revoked (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; - } else if (rrow[DB_type][0] == 'E') { + } else if (rrow[DB_type][0] == DB_TYPE_EXP) { BIO_printf(bio_err, "%s=Expired (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; - } else if (rrow[DB_type][0] == 'S') { + } else if (rrow[DB_type][0] == DB_TYPE_SUSP) { BIO_printf(bio_err, "%s=Suspended (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; @@ -2202,7 +2195,7 @@ static int get_certificate_status(const char *serial, CA_DB *db) for (i = 0; i < DB_NUMBER; i++) { OPENSSL_free(row[i]); } - return (ok); + return ok; } static int do_updatedb(CA_DB *db) @@ -2234,7 +2227,7 @@ static int do_updatedb(CA_DB *db) 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') { + if (rrow[DB_type][0] == DB_TYPE_VAL) { /* ignore entries that are not valid */ if (strncmp(rrow[DB_exp_date], "49", 2) <= 0) db_y2k = 1; @@ -2244,14 +2237,14 @@ static int do_updatedb(CA_DB *db) 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][0] = DB_TYPE_EXP; 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][0] = DB_TYPE_EXP; rrow[DB_type][1] = '\0'; cnt++; @@ -2263,7 +2256,7 @@ static int do_updatedb(CA_DB *db) ASN1_UTCTIME_free(a_tm); OPENSSL_free(a_tm_s); - return (cnt); + return cnt; } static const char *crl_reasons[] = { @@ -2291,16 +2284,17 @@ static const char *crl_reasons[] = { * additional argument */ -char *make_revocation_str(int rev_type, char *rev_arg) +static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg) { char *str; - const char *other = NULL; - const char *reason = NULL; + const char *reason = NULL, *other = NULL; ASN1_OBJECT *otmp; ASN1_UTCTIME *revtm = NULL; int i; + switch (rev_type) { case REV_NONE: + case REV_VALID: break; case REV_CRL_REASON: @@ -2318,7 +2312,6 @@ char *make_revocation_str(int rev_type, char *rev_arg) case REV_HOLD: /* Argument is an OID */ - otmp = OBJ_txt2obj(rev_arg, 0); ASN1_OBJECT_free(otmp); @@ -2333,7 +2326,6 @@ char *make_revocation_str(int rev_type, char *rev_arg) 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, @@ -2348,7 +2340,6 @@ char *make_revocation_str(int rev_type, char *rev_arg) reason = "CAkeyTime"; break; - } revtm = X509_gmtime_adj(NULL, 0); @@ -2385,7 +2376,7 @@ char *make_revocation_str(int rev_type, char *rev_arg) * 2 OK and some extensions added (i.e. V2 CRL) */ -int make_revoked(X509_REVOKED *rev, const char *str) +static int make_revoked(X509_REVOKED *rev, const char *str) { char *tmp = NULL; int reason_code = -1; @@ -2535,9 +2526,9 @@ int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold, goto end; } - if (reason_code == 7) + if (reason_code == 7) { reason_code = OCSP_REVOKED_STATUS_REMOVEFROMCRL; - else if (reason_code == 8) { /* Hold instruction */ + } else if (reason_code == 8) { /* Hold instruction */ if (!arg_str) { BIO_printf(bio_err, "missing hold instruction\n"); goto end; @@ -2546,8 +2537,7 @@ int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold, hold = OBJ_txt2obj(arg_str, 0); if (!hold) { - BIO_printf(bio_err, "invalid object identifier %s\n", - arg_str); + BIO_printf(bio_err, "invalid object identifier %s\n", arg_str); goto end; } if (phold) diff --git a/apps/ciphers.c b/apps/ciphers.c index e1b5b255..4e8ffd13 100644 --- a/apps/ciphers.c +++ b/apps/ciphers.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -11,22 +11,25 @@ #include #include #include "apps.h" +#include "progs.h" #include #include typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_STDNAME, + OPT_CONVERT, OPT_SSL3, OPT_TLS1, OPT_TLS1_1, OPT_TLS1_2, + OPT_TLS1_3, OPT_PSK, OPT_SRP, OPT_V, OPT_UPPER_V, OPT_S } OPTION_CHOICE; -OPTIONS ciphers_options[] = { +const OPTIONS ciphers_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"v", OPT_V, '-', "Verbose listing of the SSL/TLS ciphers"}, {"V", OPT_UPPER_V, '-', "Even more verbose"}, @@ -43,15 +46,17 @@ OPTIONS ciphers_options[] = { #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "TLS1.2 mode"}, #endif -#ifndef OPENSSL_NO_SSL_TRACE - {"stdname", OPT_STDNAME, '-', "Show standard cipher names"}, +#ifndef OPENSSL_NO_TLS1_3 + {"tls1_3", OPT_TLS1_3, '-', "TLS1.3 mode"}, #endif + {"stdname", OPT_STDNAME, '-', "Show standard cipher names"}, #ifndef OPENSSL_NO_PSK {"psk", OPT_PSK, '-', "include ciphersuites requiring PSK"}, #endif #ifndef OPENSSL_NO_SRP {"srp", OPT_SRP, '-', "include ciphersuites requiring SRP"}, #endif + {"convert", OPT_CONVERT, 's', "Convert standard name into OpenSSL name"}, {NULL} }; @@ -78,9 +83,7 @@ int ciphers_main(int argc, char **argv) STACK_OF(SSL_CIPHER) *sk = NULL; const SSL_METHOD *meth = TLS_server_method(); int ret = 1, i, verbose = 0, Verbose = 0, use_supported = 0; -#ifndef OPENSSL_NO_SSL_TRACE int stdname = 0; -#endif #ifndef OPENSSL_NO_PSK int psk = 0; #endif @@ -88,7 +91,7 @@ int ciphers_main(int argc, char **argv) int srp = 0; #endif const char *p; - char *ciphers = NULL, *prog; + char *ciphers = NULL, *prog, *convert = NULL; char buf[512]; OPTION_CHOICE o; int min_version = 0, max_version = 0; @@ -115,9 +118,10 @@ int ciphers_main(int argc, char **argv) use_supported = 1; break; case OPT_STDNAME: -#ifndef OPENSSL_NO_SSL_TRACE stdname = verbose = 1; -#endif + break; + case OPT_CONVERT: + convert = opt_arg(); break; case OPT_SSL3: min_version = SSL3_VERSION; @@ -135,6 +139,10 @@ int ciphers_main(int argc, char **argv) min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; break; + case OPT_TLS1_3: + min_version = TLS1_3_VERSION; + max_version = TLS1_3_VERSION; + break; case OPT_PSK: #ifndef OPENSSL_NO_PSK psk = 1; @@ -155,6 +163,12 @@ int ciphers_main(int argc, char **argv) else if (argc != 0) goto opthelp; + if (convert != NULL) { + BIO_printf(bio_out, "OpenSSL cipher name: %s\n", + OPENSSL_cipher_name(convert)); + goto end; + } + ctx = SSL_CTX_new(meth); if (ctx == NULL) goto err; @@ -217,14 +231,12 @@ int ciphers_main(int argc, char **argv) else BIO_printf(bio_out, "0x%02X,0x%02X,0x%02X,0x%02X - ", id0, id1, id2, id3); /* whatever */ } -#ifndef OPENSSL_NO_SSL_TRACE if (stdname) { const char *nm = SSL_CIPHER_standard_name(c); if (nm == NULL) nm = "UNKNOWN"; BIO_printf(bio_out, "%s - ", nm); } -#endif BIO_puts(bio_out, SSL_CIPHER_description(c, buf, sizeof(buf))); } } @@ -238,5 +250,5 @@ int ciphers_main(int argc, char **argv) sk_SSL_CIPHER_free(sk); SSL_CTX_free(ctx); SSL_free(ssl); - return (ret); + return ret; } diff --git a/apps/cms.c b/apps/cms.c index 640f92eb..e9d760c9 100644 --- a/apps/cms.c +++ b/apps/cms.c @@ -12,6 +12,7 @@ #include #include #include "apps.h" +#include "progs.h" #ifndef OPENSSL_NO_CMS @@ -76,15 +77,16 @@ typedef enum OPTION_choice { OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE, OPT_CAPATH, OPT_NOCAPATH, OPT_NOCAFILE,OPT_CONTENT, OPT_PRINT, OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE, - OPT_RAND, OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, + OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM, OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP, OPT_3DES_WRAP, OPT_ENGINE, + OPT_R_ENUM, OPT_V_ENUM, OPT_CIPHER } OPTION_CHOICE; -OPTIONS cms_options[] = { +const OPTIONS cms_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] cert.pem...\n"}, {OPT_HELP_STR, 1, '-', " cert.pem... recipient certs for encryption\n"}, @@ -146,14 +148,12 @@ OPTIONS cms_options[] = { "Do not load certificates from the default certificates directory"}, {"content", OPT_CONTENT, '<', "Supply or override content for detached signature"}, - {"print", OPT_PRINT, '-', + {"print", OPT_PRINT, '-', "For the -cmsout operation print out all fields of the CMS structure"}, {"secretkey", OPT_SECRETKEY, 's'}, {"secretkeyid", OPT_SECRETKEYID, 's'}, {"pwri_password", OPT_PWRI_PASSWORD, 's'}, {"econtent_type", OPT_ECONTENT_TYPE, 's'}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"to", OPT_TO, 's', "To address"}, {"from", OPT_FROM, 's', "From address"}, @@ -169,6 +169,7 @@ OPTIONS cms_options[] = { {"receipt_request_from", OPT_RR_FROM, 's'}, {"receipt_request_to", OPT_RR_TO, 's'}, {"", OPT_CIPHER, '-', "Any supported cipher"}, + OPT_R_OPTIONS, OPT_V_OPTIONS, {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"}, {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"}, @@ -202,16 +203,13 @@ int cms_main(int argc, char **argv) const char *CAfile = NULL, *CApath = NULL; char *certsoutfile = NULL; int noCAfile = 0, noCApath = 0; - char *infile = NULL, *outfile = NULL, *rctfile = NULL, *inrand = NULL; - char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *recipfile = - NULL; + char *infile = NULL, *outfile = NULL, *rctfile = NULL; + char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *recipfile = NULL; char *to = NULL, *from = NULL, *subject = NULL, *prog; cms_key_param *key_first = NULL, *key_param = NULL; - int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = - 0; + int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0; int informat = FORMAT_SMIME, outformat = FORMAT_SMIME; - int need_rand = 0, operation = 0, ret = 1, rr_print = 0, rr_allorfirst = - -1; + int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1; int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM; size_t secret_keylen = 0, secret_keyidlen = 0; unsigned char *pwri_pass = NULL, *pwri_tmp = NULL; @@ -449,10 +447,6 @@ int cms_main(int argc, char **argv) goto opthelp; } break; - case OPT_RAND: - inrand = opt_arg(); - need_rand = 1; - break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; @@ -477,7 +471,7 @@ int cms_main(int argc, char **argv) break; case OPT_SIGNER: /* If previous -signer argument add signer to list */ - if (signerfile) { + if (signerfile != NULL) { if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; @@ -494,7 +488,7 @@ int cms_main(int argc, char **argv) break; case OPT_INKEY: /* If previous -inkey argument add signer to list */ - if (keyfile) { + if (keyfile != NULL) { if (signerfile == NULL) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto end; @@ -525,8 +519,9 @@ int cms_main(int argc, char **argv) goto end; sk_X509_push(encerts, cert); cert = NULL; - } else + } else { recipfile = opt_arg(); + } break; case OPT_CIPHER: if (!opt_cipher(opt_unknown(), &cipher)) @@ -535,12 +530,12 @@ int cms_main(int argc, char **argv) case OPT_KEYOPT: keyidx = -1; if (operation == SMIME_ENCRYPT) { - if (encerts) + if (encerts != NULL) keyidx += sk_X509_num(encerts); } else { - if (keyfile || signerfile) + if (keyfile != NULL || signerfile != NULL) keyidx++; - if (skkeys) + if (skkeys != NULL) keyidx += sk_OPENSSL_STRING_num(skkeys); } if (keyidx < 0) { @@ -567,6 +562,10 @@ int cms_main(int argc, char **argv) goto end; vpmtouched++; break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; case OPT_3DES_WRAP: # ifndef OPENSSL_NO_DES wrap_cipher = EVP_des_ede3_wrap(); @@ -586,87 +585,77 @@ int cms_main(int argc, char **argv) argc = opt_num_rest(); argv = opt_rest(); - if (((rr_allorfirst != -1) || rr_from) && !rr_to) { + if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) { BIO_puts(bio_err, "No Signed Receipts Recipients\n"); goto opthelp; } - if (!(operation & SMIME_SIGNERS) && (rr_to || rr_from)) { + if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) { BIO_puts(bio_err, "Signed receipts only allowed with -sign\n"); goto opthelp; } - if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) { + if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) { BIO_puts(bio_err, "Multiple signers or keys not allowed\n"); goto opthelp; } if (operation & SMIME_SIGNERS) { - if (keyfile && !signerfile) { + if (keyfile != NULL && signerfile == NULL) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto opthelp; } /* Check to see if any final signer needs to be appended */ - if (signerfile) { - if (!sksigners + if (signerfile != NULL) { + if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); - if (!skkeys && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) + if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; - if (!keyfile) + if (keyfile == NULL) keyfile = signerfile; sk_OPENSSL_STRING_push(skkeys, keyfile); } - if (!sksigners) { + if (sksigners == NULL) { BIO_printf(bio_err, "No signer certificate specified\n"); goto opthelp; } signerfile = NULL; keyfile = NULL; - need_rand = 1; - } - - else if (operation == SMIME_DECRYPT) { - if (!recipfile && !keyfile && !secret_key && !pwri_pass) { + } else if (operation == SMIME_DECRYPT) { + if (recipfile == NULL && keyfile == NULL + && secret_key == NULL && pwri_pass == NULL) { BIO_printf(bio_err, "No recipient certificate or key specified\n"); goto opthelp; } } else if (operation == SMIME_ENCRYPT) { - if (*argv == NULL && !secret_key && !pwri_pass && !encerts) { + if (*argv == NULL && secret_key == NULL + && pwri_pass == NULL && encerts == NULL) { BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n"); goto opthelp; } - need_rand = 1; - } else if (!operation) + } else if (!operation) { goto opthelp; + } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } - if (need_rand) { - app_RAND_load_file(NULL, (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 (!(operation & SMIME_OP)) if (flags & CMS_BINARY) outformat = FORMAT_BINARY; - } - if (!(operation & SMIME_IP)) { + if (!(operation & SMIME_IP)) if (flags & CMS_BINARY) informat = FORMAT_BINARY; - } if (operation == SMIME_ENCRYPT) { if (!cipher) { @@ -683,7 +672,7 @@ int cms_main(int argc, char **argv) goto end; } - if (*argv && !encerts) + if (*argv && encerts == NULL) if ((encerts = sk_X509_new_null()) == NULL) goto end; while (*argv) { @@ -696,7 +685,7 @@ int cms_main(int argc, char **argv) } } - if (certfile) { + if (certfile != NULL) { if (!load_certs(certfile, &other, FORMAT_PEM, NULL, "certificate file")) { ERR_print_errors(bio_err); @@ -704,7 +693,7 @@ int cms_main(int argc, char **argv) } } - if (recipfile && (operation == SMIME_DECRYPT)) { + if (recipfile != NULL && (operation == SMIME_DECRYPT)) { if ((recip = load_cert(recipfile, FORMAT_PEM, "recipient certificate file")) == NULL) { ERR_print_errors(bio_err); @@ -721,17 +710,18 @@ int cms_main(int argc, char **argv) } if (operation == SMIME_DECRYPT) { - if (!keyfile) + if (keyfile == NULL) keyfile = recipfile; } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) { - if (!keyfile) + if (keyfile == NULL) keyfile = signerfile; - } else + } else { keyfile = NULL; + } - if (keyfile) { + if (keyfile != NULL) { key = load_key(keyfile, keyform, 0, passin, e, "signing key file"); - if (!key) + if (key == NULL) goto end; } @@ -740,29 +730,29 @@ int cms_main(int argc, char **argv) goto end; if (operation & SMIME_IP) { - if (informat == FORMAT_SMIME) + if (informat == FORMAT_SMIME) { cms = SMIME_read_CMS(in, &indata); - else if (informat == FORMAT_PEM) + } else if (informat == FORMAT_PEM) { cms = PEM_read_bio_CMS(in, NULL, NULL, NULL); - else if (informat == FORMAT_ASN1) + } else if (informat == FORMAT_ASN1) { cms = d2i_CMS_bio(in, NULL); - else { + } else { BIO_printf(bio_err, "Bad input format for CMS file\n"); goto end; } - if (!cms) { + if (cms == NULL) { BIO_printf(bio_err, "Error reading S/MIME message\n"); goto end; } - if (contfile) { + if (contfile != NULL) { BIO_free(indata); if ((indata = BIO_new_file(contfile, "rb")) == NULL) { BIO_printf(bio_err, "Can't read content file %s\n", contfile); goto end; } } - if (certsoutfile) { + if (certsoutfile != NULL) { STACK_OF(X509) *allcerts; allcerts = CMS_get1_certs(cms); if (!save_certs(certsoutfile, allcerts)) { @@ -775,25 +765,25 @@ int cms_main(int argc, char **argv) } } - if (rctfile) { + if (rctfile != NULL) { char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r"; if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) { BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile); goto end; } - if (rctformat == FORMAT_SMIME) + if (rctformat == FORMAT_SMIME) { rcms = SMIME_read_CMS(rctin, NULL); - else if (rctformat == FORMAT_PEM) + } else if (rctformat == FORMAT_PEM) { rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL); - else if (rctformat == FORMAT_ASN1) + } else if (rctformat == FORMAT_ASN1) { rcms = d2i_CMS_bio(rctin, NULL); - else { + } else { BIO_printf(bio_err, "Bad input format for receipt\n"); goto end; } - if (!rcms) { + if (rcms == NULL) { BIO_printf(bio_err, "Error reading receipt\n"); goto end; } @@ -823,7 +813,7 @@ int cms_main(int argc, char **argv) int i; flags |= CMS_PARTIAL; cms = CMS_encrypt(NULL, in, cipher, flags); - if (!cms) + if (cms == NULL) goto end; for (i = 0; i < sk_X509_num(encerts); i++) { CMS_RecipientInfo *ri; @@ -837,9 +827,9 @@ int cms_main(int argc, char **argv) } } ri = CMS_add1_recipient_cert(cms, x, tflags); - if (!ri) + if (ri == NULL) goto end; - if (kparam) { + if (kparam != NULL) { EVP_PKEY_CTX *pctx; pctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (!cms_set_pkey_param(pctx, kparam->param)) @@ -853,7 +843,7 @@ int cms_main(int argc, char **argv) } } - if (secret_key) { + if (secret_key != NULL) { if (!CMS_add0_recipient_key(cms, NID_undef, secret_key, secret_keylen, secret_keyid, secret_keyidlen, @@ -863,13 +853,13 @@ int cms_main(int argc, char **argv) secret_key = NULL; secret_keyid = NULL; } - if (pwri_pass) { + if (pwri_pass != NULL) { pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass); - if (!pwri_tmp) + if (pwri_tmp == NULL) goto end; - if (!CMS_add0_recipient_password(cms, - -1, NID_undef, NID_undef, - pwri_tmp, -1, NULL)) + if (CMS_add0_recipient_password(cms, + -1, NID_undef, NID_undef, + pwri_tmp, -1, NULL) == NULL) goto end; pwri_tmp = NULL; } @@ -886,11 +876,11 @@ int cms_main(int argc, char **argv) STACK_OF(CMS_SignerInfo) *sis; CMS_SignerInfo *si; sis = CMS_get0_SignerInfos(cms); - if (!sis) + if (sis == NULL) goto end; si = sk_CMS_SignerInfo_value(sis, 0); srcms = CMS_sign_receipt(si, signer, key, other, flags); - if (!srcms) + if (srcms == NULL) goto end; CMS_ContentInfo_free(cms); cms = srcms; @@ -908,21 +898,22 @@ int cms_main(int argc, char **argv) } flags |= CMS_PARTIAL; cms = CMS_sign(NULL, NULL, other, in, flags); - if (!cms) + if (cms == NULL) goto end; - if (econtent_type) + if (econtent_type != NULL) CMS_set1_eContentType(cms, econtent_type); - if (rr_to) { + if (rr_to != NULL) { rr = make_receipt_request(rr_to, rr_allorfirst, rr_from); - if (!rr) { + if (rr == NULL) { BIO_puts(bio_err, "Signed Receipt Request Creation Error\n"); goto end; } } - } else + } else { flags |= CMS_REUSE_DIGEST; + } for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) { CMS_SignerInfo *si; cms_key_param *kparam; @@ -931,12 +922,12 @@ int cms_main(int argc, char **argv) keyfile = sk_OPENSSL_STRING_value(skkeys, i); signer = load_cert(signerfile, FORMAT_PEM, "signer certificate"); - if (!signer) { + if (signer == NULL) { ret = 2; goto end; } key = load_key(keyfile, keyform, 0, passin, e, "signing key file"); - if (!key) { + if (key == NULL) { ret = 2; goto end; } @@ -947,15 +938,15 @@ int cms_main(int argc, char **argv) } } si = CMS_add1_signer(cms, signer, key, sign_md, tflags); - if (!si) + if (si == NULL) goto end; - if (kparam) { + if (kparam != NULL) { EVP_PKEY_CTX *pctx; pctx = CMS_SignerInfo_get0_pkey_ctx(si); if (!cms_set_pkey_param(pctx, kparam->param)) goto end; } - if (rr && !CMS_add1_ReceiptRequest(si, rr)) + if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr)) goto end; X509_free(signer); signer = NULL; @@ -969,7 +960,7 @@ int cms_main(int argc, char **argv) } } - if (!cms) { + if (cms == NULL) { BIO_printf(bio_err, "Error creating CMS structure\n"); goto end; } @@ -979,7 +970,7 @@ int cms_main(int argc, char **argv) if (flags & CMS_DEBUG_DECRYPT) CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags); - if (secret_key) { + if (secret_key != NULL) { if (!CMS_decrypt_set1_key(cms, secret_key, secret_keylen, secret_keyid, secret_keyidlen)) { @@ -988,14 +979,14 @@ int cms_main(int argc, char **argv) } } - if (key) { + if (key != NULL) { 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 (pwri_pass != NULL) { if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) { BIO_puts(bio_err, "Error decrypting CMS using password\n"); goto end; @@ -1013,9 +1004,9 @@ int cms_main(int argc, char **argv) if (!CMS_uncompress(cms, indata, out, flags)) goto end; } else if (operation == SMIME_DIGEST_VERIFY) { - if (CMS_digest_verify(cms, indata, out, flags) > 0) + if (CMS_digest_verify(cms, indata, out, flags) > 0) { BIO_printf(bio_err, "Verification successful\n"); - else { + } else { BIO_printf(bio_err, "Verification failure\n"); goto end; } @@ -1024,15 +1015,15 @@ int cms_main(int argc, char **argv) indata, out, flags)) goto end; } else if (operation == SMIME_VERIFY) { - if (CMS_verify(cms, other, store, indata, out, flags) > 0) + if (CMS_verify(cms, other, store, indata, out, flags) > 0) { BIO_printf(bio_err, "Verification successful\n"); - else { + } else { BIO_printf(bio_err, "Verification failure\n"); if (verify_retcode) ret = verify_err + 32; goto end; } - if (signerfile) { + if (signerfile != NULL) { STACK_OF(X509) *signers; signers = CMS_get0_signers(cms); if (!save_certs(signerfile, signers)) { @@ -1047,9 +1038,9 @@ int cms_main(int argc, char **argv) receipt_request_print(cms); } else if (operation == SMIME_VERIFY_RECEIPT) { - if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) + if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) { BIO_printf(bio_err, "Verification successful\n"); - else { + } else { BIO_printf(bio_err, "Verification failure\n"); goto end; } @@ -1068,11 +1059,11 @@ int cms_main(int argc, char **argv) ret = SMIME_write_CMS(out, cms, indata, flags); else ret = SMIME_write_CMS(out, cms, in, flags); - } else if (outformat == FORMAT_PEM) + } else if (outformat == FORMAT_PEM) { ret = PEM_write_bio_CMS_stream(out, cms, in, flags); - else if (outformat == FORMAT_ASN1) + } else if (outformat == FORMAT_ASN1) { ret = i2d_CMS_bio_stream(out, cms, in, flags); - else { + } else { BIO_printf(bio_err, "Bad output format for CMS file\n"); goto end; } @@ -1085,8 +1076,6 @@ int cms_main(int argc, char **argv) end: if (ret) ERR_print_errors(bio_err); - if (need_rand) - app_RAND_write_file(NULL); sk_X509_pop_free(encerts, X509_free); sk_X509_pop_free(other, X509_free); X509_VERIFY_PARAM_free(vpm); @@ -1119,17 +1108,17 @@ int cms_main(int argc, char **argv) BIO_free(indata); BIO_free_all(out); OPENSSL_free(passin); - return (ret); + return ret; } static int save_certs(char *signerfile, STACK_OF(X509) *signers) { int i; BIO *tmp; - if (!signerfile) + if (signerfile == NULL) return 1; tmp = BIO_new_file(signerfile, "w"); - if (!tmp) + if (tmp == NULL) return 0; for (i = 0; i < sk_X509_num(signers); i++) PEM_write_bio_X509(tmp, sk_X509_value(signers, i)); @@ -1189,9 +1178,9 @@ static void receipt_request_print(CMS_ContentInfo *cms) 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) + if (rv == 0) { BIO_puts(bio_err, " No Receipt Request\n"); - else if (rv < 0) { + } else if (rv < 0) { BIO_puts(bio_err, " Receipt Request Parse Error\n"); ERR_print_errors(bio_err); } else { @@ -1204,15 +1193,16 @@ static void receipt_request_print(CMS_ContentInfo *cms) id = (const char *)ASN1_STRING_get0_data(scid); BIO_dump_indent(bio_err, id, idlen, 4); BIO_puts(bio_err, " Receipts From"); - if (rlist) { + if (rlist != NULL) { BIO_puts(bio_err, " List:\n"); gnames_stack_print(rlist); - } else if (allorfirst == 1) + } else if (allorfirst == 1) { BIO_puts(bio_err, ": First Tier\n"); - else if (allorfirst == 0) + } else if (allorfirst == 0) { BIO_puts(bio_err, ": All\n"); - else + } else { BIO_printf(bio_err, " Unknown (%d)\n", allorfirst); + } BIO_puts(bio_err, " Receipts To:\n"); gnames_stack_print(rto); } @@ -1227,12 +1217,12 @@ static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns) GENERAL_NAMES *gens = NULL; GENERAL_NAME *gen = NULL; ret = sk_GENERAL_NAMES_new_null(); - if (!ret) + if (ret == NULL) goto err; for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) { char *str = sk_OPENSSL_STRING_value(ns, i); gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0); - if (!gen) + if (gen == NULL) goto err; gens = GENERAL_NAMES_new(); if (gens == NULL) @@ -1261,14 +1251,15 @@ static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING) STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL; CMS_ReceiptRequest *rr; rct_to = make_names_stack(rr_to); - if (!rct_to) + if (rct_to == NULL) goto err; - if (rr_from) { + if (rr_from != NULL) { rct_from = make_names_stack(rr_from); - if (!rct_from) + if (rct_from == NULL) goto err; - } else + } else { rct_from = NULL; + } rr = CMS_ReceiptRequest_create0(NULL, -1, rr_allorfirst, rct_from, rct_to); return rr; diff --git a/apps/crl.c b/apps/crl.c index 06b6e5b9..031fada1 100644 --- a/apps/crl.c +++ b/apps/crl.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -11,6 +11,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -26,7 +27,7 @@ typedef enum OPTION_choice { OPT_NOOUT, OPT_NAMEOPT, OPT_MD } OPTION_CHOICE; -OPTIONS crl_options[] = { +const OPTIONS crl_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'F', "Input format; default PEM"}, {"in", OPT_IN, '<', "Input file - default stdin"}, @@ -69,8 +70,6 @@ int crl_main(int argc, char **argv) X509_OBJECT *xobj = NULL; EVP_PKEY *pkey; const EVP_MD *digest = EVP_sha1(); - unsigned long nmflag = 0; - char nmflag_set = 0; char *infile = NULL, *outfile = NULL, *crldiff = NULL, *keyfile = NULL; const char *CAfile = NULL, *CApath = NULL, *prog; OPTION_CHOICE o; @@ -169,8 +168,7 @@ int crl_main(int argc, char **argv) badsig = 1; break; case OPT_NAMEOPT: - nmflag_set = 1; - if (!set_name_ex(&nmflag, opt_arg())) + if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_MD: @@ -182,9 +180,6 @@ int crl_main(int argc, char **argv) if (argc != 0) goto opthelp; - if (!nmflag_set) - nmflag = XN_FLAG_ONELINE; - x = load_crl(infile, informat); if (x == NULL) goto end; @@ -260,7 +255,7 @@ int crl_main(int argc, char **argv) for (i = 1; i <= num; i++) { if (issuer == i) { print_name(bio_out, "issuer=", X509_CRL_get_issuer(x), - nmflag); + get_nameopt()); } if (crlnumber == i) { ASN1_INTEGER *crlnum; @@ -319,7 +314,7 @@ int crl_main(int argc, char **argv) goto end; if (text) - X509_CRL_print(out, x); + X509_CRL_print_ex(out, x, get_nameopt()); if (noout) { ret = 0; @@ -343,5 +338,5 @@ int crl_main(int argc, char **argv) X509_CRL_free(x); X509_STORE_CTX_free(ctx); X509_STORE_free(store); - return (ret); + return ret; } diff --git a/apps/crl2p7.c b/apps/crl2p7.c index 9c5f79f9..88fabcb2 100644 --- a/apps/crl2p7.c +++ b/apps/crl2p7.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -11,6 +11,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -25,7 +26,7 @@ typedef enum OPTION_choice { OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_NOCRL, OPT_CERTFILE } OPTION_CHOICE; -OPTIONS crl2pkcs7_options[] = { +const OPTIONS crl2pkcs7_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, @@ -131,7 +132,7 @@ int crl2pkcs7_main(int argc, char **argv) goto end; p7s->cert = cert_stack; - if (certflst) + if (certflst != NULL) for (i = 0; i < sk_OPENSSL_STRING_num(certflst); i++) { certfile = sk_OPENSSL_STRING_value(certflst, i); if (add_certs_from_file(cert_stack, certfile) < 0) { @@ -162,7 +163,7 @@ int crl2pkcs7_main(int argc, char **argv) PKCS7_free(p7); X509_CRL_free(crl); - return (ret); + return ret; } /*- @@ -212,5 +213,5 @@ static int add_certs_from_file(STACK_OF(X509) *stack, char *certfile) /* never need to OPENSSL_free x */ BIO_free(in); sk_X509_INFO_free(sk); - return (ret); + return ret; } diff --git a/apps/ct_log_list.cnf b/apps/ct_log_list.cnf index 24348745..650aa22d 100644 --- a/apps/ct_log_list.cnf +++ b/apps/ct_log_list.cnf @@ -1,34 +1,9 @@ -enabled_logs=pilot,aviator,rocketeer,digicert,certly,izempe,symantec,venafi - -[pilot] -description = Google Pilot Log -key = MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfahLEimAoz2t01p3uMziiLOl/fHTDM0YDOhBRuiBARsV4UvxG2LdNgoIGLrtCzWE0J5APC2em4JlvR8EEEFMoA== - -[aviator] -description = Google Aviator log -key = MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE1/TMabLkDpCjiupacAlP7xNi0I1JYP8bQFAHDG1xhtolSY1l4QgNRzRrvSe8liE+NPWHdjGxfx3JhTsN9x8/6Q== - -[rocketeer] -description = Google Rocketeer log -key = MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIFsYyDzBi7MxCAC/oJBXK7dHjG+1aLCOkHjpoHPqTyghLpzA9BYbqvnV16mAw04vUjyYASVGJCUoI3ctBcJAeg== - -[digicert] -description = DigiCert Log Server -key = MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEAkbFvhu7gkAW6MHSrBlpE1n4+HCFRkC5OLAjgqhkTH+/uzSfSl8ois8ZxAD2NgaTZe1M9akhYlrYkes4JECs6A== - -[certly] -description = Certly.IO log -key = MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAECyPLhWKYYUgEc+tUXfPQB4wtGS2MNvXrjwFCCnyYJifBtd2Sk7Cu+Js9DNhMTh35FftHaHu6ZrclnNBKwmbbSA== - -[izempe] -description = Izempe log -key = MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEJ2Q5DC3cUBj4IQCiDu0s6j51up+TZAkAEcQRF6tczw90rLWXkJMAW7jr9yc92bIKgV8vDXU4lDeZHvYHduDuvg== - -[symantec] -description = Symantec log -key = MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEluqsHEYMG1XcDfy1lCdGV0JwOmkY4r87xNuroPS2bMBTP01CEDPwWJePa75y9CrsHEKqAy8afig1dpkIPSEUhg== - -[venafi] -description = Venafi log -key = MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAolpIHxdSlTXLo1s6H1OCdpSj/4DyHDc8wLG9wVmLqy1lk9fz4ATVmm+/1iN2Nk8jmctUKK2MFUtlWXZBSpym97M7frGlSaQXUWyA3CqQUEuIJOmlEjKTBEiQAvpfDjCHjlV2Be4qTM6jamkJbiWtgnYPhJL6ONaGTiSPm7Byy57iaz/hbckldSOIoRhYBiMzeNoA0DiRZ9KmfSeXZ1rB8y8X5urSW+iBzf2SaOfzBvDpcoTuAaWx2DPazoOl28fP1hZ+kHUYvxbcMjttjauCFx+JII0dmuZNIwjfeG/GBb9frpSX219k1O4Wi6OEbHEr8at/XQ0y7gTikOxBn/s5wQIDAQAB +# This file specifies the Certificate Transparency logs +# that are to be trusted. +# Google's list of logs can be found here: +# www.certificate-transparency.org/known-logs +# A Python program to convert the log list to OpenSSL's format can be +# found here: +# https://github.com/google/certificate-transparency/blob/master/python/utilities/log_list/print_log_list.py +# Use the "--openssl_output" flag. diff --git a/apps/demoCA/cacert.pem b/apps/demoCA/cacert.pem deleted file mode 100644 index affbce3b..00000000 --- a/apps/demoCA/cacert.pem +++ /dev/null @@ -1,14 +0,0 @@ -subject=/C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server -issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA ------BEGIN X509 CERTIFICATE----- - -MIIBgjCCASwCAQQwDQYJKoZIhvcNAQEEBQAwODELMAkGA1UEBhMCQVUxDDAKBgNV -BAgTA1FMRDEbMBkGA1UEAxMSU1NMZWF5L3JzYSB0ZXN0IENBMB4XDTk1MTAwOTIz -MzIwNVoXDTk4MDcwNTIzMzIwNVowYDELMAkGA1UEBhMCQVUxDDAKBgNVBAgTA1FM -RDEZMBcGA1UEChMQTWluY29tIFB0eS4gTHRkLjELMAkGA1UECxMCQ1MxGzAZBgNV -BAMTElNTTGVheSBkZW1vIHNlcnZlcjBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC3 -LCXcScWua0PFLkHBLm2VejqpA1F4RQ8q0VjRiPafjx/Z/aWH3ipdMVvuJGa/wFXb -/nDFLDlfWp+oCPwhBtVPAgMBAAEwDQYJKoZIhvcNAQEEBQADQQArNFsihWIjBzb0 -DCsU0BvL2bvSwJrPEqFlkDq3F4M6EGutL9axEcANWgbbEdAvNJD1dmEmoWny27Pn -IMs6ZOZB ------END X509 CERTIFICATE----- diff --git a/apps/demoCA/index.txt b/apps/demoCA/index.txt deleted file mode 100644 index 2cdd252d..00000000 --- a/apps/demoCA/index.txt +++ /dev/null @@ -1,39 +0,0 @@ -R 980705233205Z 951009233205Z 01 certs/00000001 /CN=Eric Young -E 951009233205Z 02 certs/00000002 /CN=Duncan Young -R 980705233205Z 951201010000Z 03 certs/00000003 /CN=Tim Hudson -V 980705233205Z 04 certs/00000004 /CN=Eric Young4 -V 980705233205Z 05 certs/00000004 /CN=Eric Young5 -V 980705233205Z 06 certs/00000004 /CN=Eric Young6 -V 980705233205Z 07 certs/00000004 /CN=Eric Young7 -V 980705233205Z 08 certs/00000004 /CN=Eric Young8 -V 980705233205Z 09 certs/00000004 /CN=Eric Young9 -V 980705233205Z 0A certs/00000004 /CN=Eric YoungA -V 980705233205Z 0B certs/00000004 /CN=Eric YoungB -V 980705233205Z 0C certs/00000004 /CN=Eric YoungC -V 980705233205Z 0D certs/00000004 /CN=Eric YoungD -V 980705233205Z 0E certs/00000004 /CN=Eric YoungE -V 980705233205Z 0F certs/00000004 /CN=Eric YoungF -V 980705233205Z 10 certs/00000004 /CN=Eric Young10 -V 980705233205Z 11 certs/00000004 /CN=Eric Young11 -V 980705233205Z 12 certs/00000004 /CN=Eric Young12 -V 980705233205Z 13 certs/00000004 /CN=Eric Young13 -V 980705233205Z 14 certs/00000004 /CN=Eric Young14 -V 980705233205Z 15 certs/00000004 /CN=Eric Young15 -V 980705233205Z 16 certs/00000004 /CN=Eric Young16 -V 980705233205Z 17 certs/00000004 /CN=Eric Young17 -V 961206150305Z 010C unknown /C=AU/SP=QLD/O=Mincom Pty. Ltd./OU=MTR/CN=Eric Young/Email=eay@mincom.oz.au -V 961206153245Z 010D unknown /C=AU/SP=Queensland/O=Mincom Pty Ltd/OU=MTR/CN=Eric Young/Email=eay@mincom.oz.au -V 970322074816Z 010E unknown /CN=Eric Young/Email=eay@mincom.oz.au -V 970322075152Z 010F unknown /CN=Eric Young -V 970322075906Z 0110 unknown /CN=Eric Youngg -V 970324092238Z 0111 unknown /C=AU/SP=Queensland/CN=Eric Young -V 970324221931Z 0112 unknown /CN=Fred -V 970324224934Z 0113 unknown /C=AU/CN=eay -V 971001005237Z 0114 unknown /C=AU/SP=QLD/O=Mincom Pty Ltd/OU=MTR/CN=x509v3 test -V 971001010331Z 0115 unknown /C=AU/SP=Queensland/O=Mincom Pty Ltd/OU=MTR/CN=test again - x509v3 -V 971001013945Z 0117 unknown /C=AU/SP=Queensland/O=Mincom Pty Ltd/OU=MTR/CN=x509v3 test -V 971014225415Z 0118 unknown /C=AU/SP=Queensland/CN=test -V 971015004448Z 0119 unknown /C=AU/SP=Queensland/O=Mincom Pty Ltd/OU=MTR/CN=test2 -V 971016035001Z 011A unknown /C=AU/SP=Queensland/O=Mincom Pty Ltd/OU=MTR/CN=test64 -V 971016080129Z 011B unknown /C=FR/O=ALCATEL/OU=Alcatel Mobile Phones/CN=bourque/Email=bourque@art.alcatel.fr -V 971016224000Z 011D unknown /L=Bedford/O=Cranfield University/OU=Computer Centre/CN=Peter R Lister/Email=P.Lister@cranfield.ac.uk diff --git a/apps/demoCA/private/cakey.pem b/apps/demoCA/private/cakey.pem deleted file mode 100644 index 48fb18c7..00000000 --- a/apps/demoCA/private/cakey.pem +++ /dev/null @@ -1,24 +0,0 @@ -issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA -subject=/C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server ------BEGIN X509 CERTIFICATE----- - -MIIBgjCCASwCAQQwDQYJKoZIhvcNAQEEBQAwODELMAkGA1UEBhMCQVUxDDAKBgNV -BAgTA1FMRDEbMBkGA1UEAxMSU1NMZWF5L3JzYSB0ZXN0IENBMB4XDTk1MTAwOTIz -MzIwNVoXDTk4MDcwNTIzMzIwNVowYDELMAkGA1UEBhMCQVUxDDAKBgNVBAgTA1FM -RDEZMBcGA1UEChMQTWluY29tIFB0eS4gTHRkLjELMAkGA1UECxMCQ1MxGzAZBgNV -BAMTElNTTGVheSBkZW1vIHNlcnZlcjBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC3 -LCXcScWua0PFLkHBLm2VejqpA1F4RQ8q0VjRiPafjx/Z/aWH3ipdMVvuJGa/wFXb -/nDFLDlfWp+oCPwhBtVPAgMBAAEwDQYJKoZIhvcNAQEEBQADQQArNFsihWIjBzb0 -DCsU0BvL2bvSwJrPEqFlkDq3F4M6EGutL9axEcANWgbbEdAvNJD1dmEmoWny27Pn -IMs6ZOZB ------END X509 CERTIFICATE----- ------BEGIN RSA PRIVATE KEY----- - -MIIBPAIBAAJBALcsJdxJxa5rQ8UuQcEubZV6OqkDUXhFDyrRWNGI9p+PH9n9pYfe -Kl0xW+4kZr/AVdv+cMUsOV9an6gI/CEG1U8CAwEAAQJAXJMBZ34ZXHd1vtgL/3hZ -hexKbVTx/djZO4imXO/dxPGRzG2ylYZpHmG32/T1kaHpZlCHoEPgHoSzmxYXfxjG -sQIhAPmZ/bQOjmRUHM/VM2X5zrjjM6z18R1P6l3ObFwt9FGdAiEAu943Yh9SqMRw -tL0xHGxKmM/YJueUw1gB6sLkETN71NsCIQCeT3RhoqXfrpXDoEcEU+gwzjI1bpxq -agiNTOLfqGoA5QIhAIQFYjgzONxex7FLrsKBm16N2SFl5pXsN9SpRqqL2n63AiEA -g9VNIQ3xwpw7og3IbONifeku+J9qGMGQJMKwSTwrFtI= ------END RSA PRIVATE KEY----- diff --git a/apps/demoCA/serial b/apps/demoCA/serial deleted file mode 100644 index 69fa0ffe..00000000 --- a/apps/demoCA/serial +++ /dev/null @@ -1 +0,0 @@ -011E diff --git a/apps/dgst.c b/apps/dgst.c index 08182e2a..45745507 100644 --- a/apps/dgst.c +++ b/apps/dgst.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -11,6 +11,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -29,22 +30,21 @@ int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, - OPT_C, OPT_R, OPT_RAND, OPT_OUT, OPT_SIGN, OPT_PASSIN, OPT_VERIFY, + OPT_C, OPT_R, OPT_OUT, OPT_SIGN, OPT_PASSIN, OPT_VERIFY, OPT_PRVERIFY, OPT_SIGNATURE, OPT_KEYFORM, OPT_ENGINE, OPT_ENGINE_IMPL, OPT_HEX, OPT_BINARY, OPT_DEBUG, OPT_FIPS_FINGERPRINT, OPT_HMAC, OPT_MAC, OPT_SIGOPT, OPT_MACOPT, - OPT_DIGEST + OPT_DIGEST, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS dgst_options[] = { +const OPTIONS dgst_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [file...]\n"}, {OPT_HELP_STR, 1, '-', " file... files to digest (default is stdin)\n"}, {"help", OPT_HELP, '-', "Display this summary"}, {"c", OPT_C, '-', "Print the digest with separating colons"}, {"r", OPT_R, '-', "Print the digest in coreutils format"}, - {"rand", OPT_RAND, 's', - "Use file(s) containing random data to seed RNG or an EGD sock"}, {"out", OPT_OUT, '>', "Output to filename rather than stdout"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"sign", OPT_SIGN, 's', "Sign digest using private key"}, @@ -65,6 +65,7 @@ OPTIONS dgst_options[] = { {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"}, {"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form or key"}, {"", OPT_DIGEST, '-', "Any supported digest"}, + OPT_R_OPTIONS, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, {"engine_impl", OPT_ENGINE_IMPL, '-', @@ -84,7 +85,7 @@ int dgst_main(int argc, char **argv) char *passinarg = NULL, *passin = NULL; const EVP_MD *md = NULL, *m; const char *outfile = NULL, *keyfile = NULL, *prog = NULL; - const char *sigfile = NULL, *randfile = NULL; + const char *sigfile = NULL; OPTION_CHOICE o; int separator = 0, debug = 0, keyform = FORMAT_PEM, siglen = 0; int i, ret = 1, out_bin = -1, want_pub = 0, do_verify = 0; @@ -113,8 +114,9 @@ int dgst_main(int argc, char **argv) case OPT_R: separator = 2; break; - case OPT_RAND: - randfile = opt_arg(); + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_OUT: outfile = opt_arg(); @@ -190,7 +192,7 @@ int dgst_main(int argc, char **argv) goto end; } - if (do_verify && !sigfile) { + if (do_verify && sigfile == NULL) { BIO_printf(bio_err, "No signature to verify: use the -signature option\n"); goto end; @@ -217,30 +219,27 @@ int dgst_main(int argc, char **argv) } if (out_bin == -1) { - if (keyfile) + if (keyfile != NULL) out_bin = 1; else out_bin = 0; } - if (randfile) - app_RAND_load_file(randfile, 0); - out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT); if (out == NULL) goto end; - if ((! !mac_name + ! !keyfile + ! !hmac_key) > 1) { + if ((!(mac_name == NULL) + !(keyfile == NULL) + !(hmac_key == NULL)) > 1) { BIO_printf(bio_err, "MAC and Signing key cannot both be specified\n"); goto end; } - if (keyfile) { + if (keyfile != NULL) { if (want_pub) sigkey = load_pubkey(keyfile, keyform, 0, NULL, e, "key file"); else sigkey = load_key(keyfile, keyform, 0, passin, e, "key file"); - if (!sigkey) { + if (sigkey == NULL) { /* * load_[pub]key() has already printed an appropriate message */ @@ -248,12 +247,12 @@ int dgst_main(int argc, char **argv) } } - if (mac_name) { + if (mac_name != NULL) { EVP_PKEY_CTX *mac_ctx = NULL; int r = 0; if (!init_gen_str(&mac_ctx, mac_name, impl, 0)) goto mac_end; - if (macopts) { + if (macopts != NULL) { char *macopt; for (i = 0; i < sk_OPENSSL_STRING_num(macopts); i++) { macopt = sk_OPENSSL_STRING_value(macopts, i); @@ -277,14 +276,14 @@ int dgst_main(int argc, char **argv) goto end; } - if (hmac_key) { + if (hmac_key != NULL) { sigkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, impl, (unsigned char *)hmac_key, -1); - if (!sigkey) + if (sigkey == NULL) goto end; } - if (sigkey) { + if (sigkey != NULL) { EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX *pctx = NULL; int r; @@ -302,7 +301,7 @@ int dgst_main(int argc, char **argv) ERR_print_errors(bio_err); goto end; } - if (sigopts) { + if (sigopts != NULL) { char *sigopt; for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) { sigopt = sk_OPENSSL_STRING_value(sigopts, i); @@ -331,9 +330,9 @@ int dgst_main(int argc, char **argv) } } - if (sigfile && sigkey) { + if (sigfile != NULL && sigkey != NULL) { BIO *sigbio = BIO_new_file(sigfile, "rb"); - if (!sigbio) { + if (sigbio == NULL) { BIO_printf(bio_err, "Error opening signature file %s\n", sigfile); ERR_print_errors(bio_err); goto end; @@ -363,14 +362,14 @@ int dgst_main(int argc, char **argv) } else { const char *md_name = NULL, *sig_name = NULL; if (!out_bin) { - if (sigkey) { + if (sigkey != NULL) { 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) + if (md != NULL) md_name = EVP_MD_name(md); } ret = 0; @@ -380,9 +379,10 @@ int dgst_main(int argc, char **argv) perror(argv[i]); ret++; continue; - } else + } else { r = do_fp(out, buf, inp, separator, out_bin, sigkey, sigbuf, siglen, sig_name, md_name, argv[i]); + } if (r) ret = r; (void)BIO_reset(bmd); @@ -399,7 +399,7 @@ int dgst_main(int argc, char **argv) OPENSSL_free(sigbuf); BIO_free(bmd); release_engine(e); - return (ret); + return ret; } int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, @@ -420,13 +420,13 @@ int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, if (i == 0) break; } - if (sigin) { + if (sigin != NULL) { EVP_MD_CTX *ctx; BIO_get_md_ctx(bp, &ctx); i = EVP_DigestVerifyFinal(ctx, sigin, (unsigned int)siglen); - if (i > 0) + if (i > 0) { BIO_printf(out, "Verified OK\n"); - else if (i == 0) { + } else if (i == 0) { BIO_printf(out, "Verification Failure\n"); return 1; } else { @@ -436,7 +436,7 @@ int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, } return 0; } - if (key) { + if (key != NULL) { EVP_MD_CTX *ctx; BIO_get_md_ctx(bp, &ctx); len = BUFSIZE; @@ -453,22 +453,23 @@ int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, } } - if (binout) + if (binout) { BIO_write(out, buf, len); - else if (sep == 2) { + } 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) { + if (sig_name != NULL) { BIO_puts(out, sig_name); - if (md_name) + if (md_name != NULL) BIO_printf(out, "-%s", md_name); BIO_printf(out, "(%s)= ", file); - } else if (md_name) + } else if (md_name != NULL) { BIO_printf(out, "%s(%s)= ", md_name, file); - else + } else { BIO_printf(out, "(%s)= ", file); + } for (i = 0; i < (int)len; i++) { if (sep && (i != 0)) BIO_printf(out, ":"); diff --git a/apps/dhparam.c b/apps/dhparam.c index 94322e37..8a3a3891 100644 --- a/apps/dhparam.c +++ b/apps/dhparam.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -17,6 +17,7 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # include # include # include @@ -36,10 +37,11 @@ typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENGINE, OPT_CHECK, OPT_TEXT, OPT_NOOUT, - OPT_RAND, OPT_DSAPARAM, OPT_C, OPT_2, OPT_5 + OPT_DSAPARAM, OPT_C, OPT_2, OPT_5, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS dhparam_options[] = { +const OPTIONS dhparam_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [flags] [numbits]\n"}, {OPT_HELP_STR, 1, '-', "Valid options are:\n"}, {"help", OPT_HELP, '-', "Display this summary"}, @@ -50,8 +52,7 @@ OPTIONS dhparam_options[] = { {"check", OPT_CHECK, '-', "Check the DH parameters"}, {"text", OPT_TEXT, '-', "Print a text form of the DH parameters"}, {"noout", OPT_NOOUT, '-', "Don't output any DH parameters"}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, + OPT_R_OPTIONS, {"C", OPT_C, '-', "Print C code"}, {"2", OPT_2, '-', "Generate parameters using 2 as the generator value"}, {"5", OPT_5, '-', "Generate parameters using 5 as the generator value"}, @@ -69,7 +70,7 @@ int dhparam_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; DH *dh = NULL; - char *infile = NULL, *outfile = NULL, *prog, *inrand = NULL; + char *infile = NULL, *outfile = NULL, *prog; ENGINE *e = NULL; #ifndef OPENSSL_NO_DSA int dsaparam = 0; @@ -130,15 +131,16 @@ int dhparam_main(int argc, char **argv) case OPT_NOOUT: noout = 1; break; - case OPT_RAND: - inrand = opt_arg(); + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; } } argc = opt_num_rest(); argv = opt_rest(); - if (argv[0] && (!opt_int(argv[0], &num) || num <= 0)) + if (argv[0] != NULL && (!opt_int(argv[0], &num) || num <= 0)) goto end; if (g && !num) @@ -165,13 +167,6 @@ int dhparam_main(int argc, char **argv) } BN_GENCB_set(cb, dh_cb, bio_err); - if (!app_RAND_load_file(NULL, 1) && inrand == NULL) { - 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)); # ifndef OPENSSL_NO_DSA if (dsaparam) { @@ -211,7 +206,6 @@ int dhparam_main(int argc, char **argv) } BN_GENCB_free(cb); - app_RAND_write_file(NULL); } else { in = bio_open_default(infile, 'r', informat); @@ -354,10 +348,11 @@ int dhparam_main(int argc, char **argv) i = i2d_DHxparams_bio(out, dh); else i = i2d_DHparams_bio(out, dh); - } else if (q != NULL) + } else if (q != NULL) { i = PEM_write_bio_DHxparams(out, dh); - else + } else { i = PEM_write_bio_DHparams(out, dh); + } if (!i) { BIO_printf(bio_err, "unable to write DH parameters\n"); ERR_print_errors(bio_err); @@ -370,7 +365,7 @@ int dhparam_main(int argc, char **argv) BIO_free_all(out); DH_free(dh); release_engine(e); - return (ret); + return ret; } static int dh_cb(int p, int n, BN_GENCB *cb) diff --git a/apps/dsa.c b/apps/dsa.c index 8454b2e9..6022e64c 100644 --- a/apps/dsa.c +++ b/apps/dsa.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -17,6 +17,7 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # include # include # include @@ -34,7 +35,7 @@ typedef enum OPTION_choice { OPT_PUBOUT, OPT_CIPHER, OPT_PASSIN, OPT_PASSOUT } OPTION_CHOICE; -OPTIONS dsa_options[] = { +const OPTIONS dsa_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'f', "Input format, DER PEM PVK"}, {"outform", OPT_OUTFORM, 'f', "Output format, DER PEM PVK"}, @@ -161,7 +162,7 @@ int dsa_main(int argc, char **argv) else pkey = load_key(infile, informat, 1, passin, e, "Private Key"); - if (pkey) { + if (pkey != NULL) { dsa = EVP_PKEY_get1_DSA(pkey); EVP_PKEY_free(pkey); } @@ -199,16 +200,16 @@ int dsa_main(int argc, char **argv) } BIO_printf(bio_err, "writing DSA key\n"); if (outformat == FORMAT_ASN1) { - if (pubin || pubout) + if (pubin || pubout) { i = i2d_DSA_PUBKEY_bio(out, dsa); - else { + } else { assert(private); i = i2d_DSAPrivateKey_bio(out, dsa); } } else if (outformat == FORMAT_PEM) { - if (pubin || pubout) + if (pubin || pubout) { i = PEM_write_bio_DSA_PUBKEY(out, dsa); - else { + } else { assert(private); i = PEM_write_bio_DSAPrivateKey(out, dsa, enc, NULL, 0, NULL, passout); @@ -235,10 +236,9 @@ int dsa_main(int argc, char **argv) # else i = i2b_PVK_bio(out, pk, pvk_encr, 0, passout); # endif - } - else if (pubin || pubout) + } else if (pubin || pubout) { i = i2b_PublicKey_bio(out, pk); - else { + } else { assert(private); i = i2b_PrivateKey_bio(out, pk); } @@ -260,6 +260,6 @@ int dsa_main(int argc, char **argv) release_engine(e); OPENSSL_free(passin); OPENSSL_free(passout); - return (ret); + return ret; } #endif diff --git a/apps/dsaparam.c b/apps/dsaparam.c index 5c3c8f80..2c1cc610 100644 --- a/apps/dsaparam.c +++ b/apps/dsaparam.c @@ -17,6 +17,7 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # include # include # include @@ -24,27 +25,15 @@ NON_EMPTY_TRANSLATION_UNIT # include # include -# ifdef GENCB_TEST - -static int stop_keygen_flag = 0; - -static void timebomb_sigalarm(int foo) -{ - stop_keygen_flag = 1; -} - -# endif - static int dsa_cb(int p, int n, BN_GENCB *cb); typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_C, - OPT_NOOUT, OPT_GENKEY, OPT_RAND, OPT_ENGINE, - OPT_TIMEBOMB + OPT_NOOUT, OPT_GENKEY, OPT_ENGINE, OPT_R_ENUM } OPTION_CHOICE; -OPTIONS dsaparam_options[] = { +const OPTIONS dsaparam_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, {"in", OPT_IN, '<', "Input file"}, @@ -54,10 +43,7 @@ OPTIONS dsaparam_options[] = { {"C", OPT_C, '-', "Output C code"}, {"noout", OPT_NOOUT, '-', "No output"}, {"genkey", OPT_GENKEY, '-', "Generate a DSA key"}, - {"rand", OPT_RAND, 's', "Files to use for random number input"}, -# ifdef GENCB_TEST - {"timebomb", OPT_TIMEBOMB, 'p', "Interrupt keygen after 'pnum' seconds"}, -# endif + OPT_R_OPTIONS, # ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, # endif @@ -70,13 +56,10 @@ int dsaparam_main(int argc, char **argv) DSA *dsa = NULL; BIO *in = NULL, *out = NULL; BN_GENCB *cb = NULL; - int numbits = -1, num = 0, genkey = 0, need_rand = 0; + int numbits = -1, num = 0, genkey = 0; int informat = FORMAT_PEM, outformat = FORMAT_PEM, noout = 0, C = 0; int ret = 1, i, text = 0, private = 0; -# ifdef GENCB_TEST - int timebomb = 0; -# endif - char *infile = NULL, *outfile = NULL, *prog, *inrand = NULL; + char *infile = NULL, *outfile = NULL, *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, dsaparam_options); @@ -108,11 +91,6 @@ int dsaparam_main(int argc, char **argv) case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; - case OPT_TIMEBOMB: -# ifdef GENCB_TEST - timebomb = atoi(opt_arg()); - break; -# endif case OPT_TEXT: text = 1; break; @@ -120,11 +98,11 @@ int dsaparam_main(int argc, char **argv) C = 1; break; case OPT_GENKEY: - genkey = need_rand = 1; + genkey = 1; break; - case OPT_RAND: - inrand = opt_arg(); - need_rand = 1; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_NOOUT: noout = 1; @@ -139,7 +117,6 @@ int dsaparam_main(int argc, char **argv) goto end; /* generate a key */ numbits = num; - need_rand = 1; } private = genkey ? 1 : 0; @@ -150,13 +127,6 @@ int dsaparam_main(int argc, char **argv) if (out == NULL) goto end; - if (need_rand) { - app_RAND_load_file(NULL, (inrand != NULL)); - if (inrand != NULL) - BIO_printf(bio_err, "%ld semi-random bytes loaded\n", - app_RAND_load_files(inrand)); - } - if (numbits > 0) { cb = BN_GENCB_new(); if (cb == NULL) { @@ -164,7 +134,6 @@ int dsaparam_main(int argc, char **argv) goto end; } BN_GENCB_set(cb, dsa_cb, bio_err); - assert(need_rand); dsa = DSA_new(); if (dsa == NULL) { BIO_printf(bio_err, "Error allocating DSA object\n"); @@ -173,38 +142,16 @@ int dsaparam_main(int argc, char **argv) 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) + } else if (informat == FORMAT_ASN1) { dsa = d2i_DSAparams_bio(in, NULL); - else + } else { dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL); + } if (dsa == NULL) { BIO_printf(bio_err, "unable to load DSA parameters\n"); ERR_print_errors(bio_err); @@ -248,9 +195,6 @@ int dsaparam_main(int argc, char **argv) OPENSSL_free(data); } - if (outformat == FORMAT_ASN1 && genkey) - noout = 1; - if (!noout) { if (outformat == FORMAT_ASN1) i = i2d_DSAparams_bio(out, dsa); @@ -265,7 +209,6 @@ int dsaparam_main(int argc, char **argv) if (genkey) { DSA *dsakey; - assert(need_rand); if ((dsakey = DSAparams_dup(dsa)) == NULL) goto end; if (!DSA_generate_key(dsakey)) { @@ -281,8 +224,6 @@ int dsaparam_main(int argc, char **argv) NULL); DSA_free(dsakey); } - if (need_rand) - app_RAND_write_file(NULL); ret = 0; end: BN_GENCB_free(cb); @@ -290,7 +231,7 @@ int dsaparam_main(int argc, char **argv) BIO_free_all(out); DSA_free(dsa); release_engine(e); - return (ret); + return ret; } static int dsa_cb(int p, int n, BN_GENCB *cb) @@ -307,10 +248,6 @@ static int dsa_cb(int p, int n, BN_GENCB *cb) c = '\n'; BIO_write(BN_GENCB_get_arg(cb), &c, 1); (void)BIO_flush(BN_GENCB_get_arg(cb)); -# ifdef GENCB_TEST - if (stop_keygen_flag) - return 0; -# endif return 1; } #endif diff --git a/apps/ec.c b/apps/ec.c index 2516c032..03abb006 100644 --- a/apps/ec.c +++ b/apps/ec.c @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2002-2018 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 @@ -16,6 +16,7 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # include # include # include @@ -42,7 +43,7 @@ typedef enum OPTION_choice { OPT_NO_PUBLIC, OPT_CHECK } OPTION_CHOICE; -OPTIONS ec_options[] = { +const OPTIONS ec_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, 's', "Input file"}, {"inform", OPT_INFORM, 'f', "Input format - DER or PEM"}, @@ -185,7 +186,7 @@ int ec_main(int argc, char **argv) } else if (informat == FORMAT_ENGINE) { EVP_PKEY *pkey; if (pubin) - pkey = load_pubkey(infile, informat , 1, passin, e, "Public Key"); + pkey = load_pubkey(infile, informat, 1, passin, e, "Public Key"); else pkey = load_key(infile, informat, 1, passin, e, "Private Key"); if (pkey != NULL) { @@ -244,20 +245,20 @@ int ec_main(int argc, char **argv) BIO_printf(bio_err, "writing EC key\n"); if (outformat == FORMAT_ASN1) { - if (param_out) + if (param_out) { i = i2d_ECPKParameters_bio(out, group); - else if (pubin || pubout) + } else if (pubin || pubout) { i = i2d_EC_PUBKEY_bio(out, eckey); - else { + } else { assert(private); i = i2d_ECPrivateKey_bio(out, eckey); } } else { - if (param_out) + if (param_out) { i = PEM_write_bio_ECPKParameters(out, group); - else if (pubin || pubout) + } else if (pubin || pubout) { i = PEM_write_bio_EC_PUBKEY(out, eckey); - else { + } else { assert(private); i = PEM_write_bio_ECPrivateKey(out, eckey, enc, NULL, 0, NULL, passout); @@ -267,8 +268,9 @@ int ec_main(int argc, char **argv) if (!i) { BIO_printf(bio_err, "unable to write private key\n"); ERR_print_errors(bio_err); - } else + } else { ret = 0; + } end: BIO_free(in); BIO_free_all(out); @@ -276,6 +278,6 @@ int ec_main(int argc, char **argv) release_engine(e); OPENSSL_free(passin); OPENSSL_free(passout); - return (ret); + return ret; } #endif diff --git a/apps/ecparam.c b/apps/ecparam.c index 999f7487..51877f59 100644 --- a/apps/ecparam.c +++ b/apps/ecparam.c @@ -1,5 +1,6 @@ /* * Copyright 2002-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,20 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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 #ifdef OPENSSL_NO_EC NON_EMPTY_TRANSLATION_UNIT @@ -31,6 +18,7 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # include # include # include @@ -42,10 +30,11 @@ typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_C, OPT_CHECK, OPT_LIST_CURVES, OPT_NO_SEED, OPT_NOOUT, OPT_NAME, - OPT_CONV_FORM, OPT_PARAM_ENC, OPT_GENKEY, OPT_RAND, OPT_ENGINE + OPT_CONV_FORM, OPT_PARAM_ENC, OPT_GENKEY, OPT_ENGINE, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS ecparam_options[] = { +const OPTIONS ecparam_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'F', "Input format - default PEM (DER or PEM)"}, {"outform", OPT_OUTFORM, 'F', "Output format - default PEM"}, @@ -65,7 +54,7 @@ OPTIONS ecparam_options[] = { {"param_enc", OPT_PARAM_ENC, 's', "Specifies the way the ec parameters are encoded"}, {"genkey", OPT_GENKEY, '-', "Generate ec key"}, - {"rand", OPT_RAND, 's', "Files to use for random number input"}, + OPT_R_OPTIONS, # ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, # endif @@ -93,7 +82,7 @@ int ecparam_main(int argc, char **argv) BIO *in = NULL, *out = NULL; EC_GROUP *group = NULL; point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED; - char *curve_name = NULL, *inrand = NULL; + char *curve_name = NULL; char *infile = NULL, *outfile = NULL, *prog; unsigned char *buffer = NULL; OPTION_CHOICE o; @@ -101,7 +90,7 @@ int ecparam_main(int argc, char **argv) int informat = FORMAT_PEM, outformat = FORMAT_PEM, noout = 0, C = 0; int ret = 1, private = 0; int list_curves = 0, no_seed = 0, check = 0, new_form = 0; - int text = 0, i, need_rand = 0, genkey = 0; + int text = 0, i, genkey = 0; prog = opt_init(argc, argv, ecparam_options); while ((o = opt_next()) != OPT_EOF) { @@ -162,11 +151,11 @@ int ecparam_main(int argc, char **argv) new_asn1_flag = 1; break; case OPT_GENKEY: - genkey = need_rand = 1; + genkey = 1; break; - case OPT_RAND: - inrand = opt_arg(); - need_rand = 1; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); @@ -232,8 +221,9 @@ int ecparam_main(int argc, char **argv) BIO_printf(bio_err, "using curve name prime256v1 " "instead of secp256r1\n"); nid = NID_X9_62_prime256v1; - } else + } else { nid = OBJ_sn2nid(curve_name); + } if (nid == 0) nid = EC_curve_nist2nid(curve_name); @@ -250,10 +240,11 @@ int ecparam_main(int argc, char **argv) } EC_GROUP_set_asn1_flag(group, asn1_flag); EC_GROUP_set_point_conversion_form(group, form); - } else if (informat == FORMAT_ASN1) + } else if (informat == FORMAT_ASN1) { group = d2i_ECPKParameters_bio(in, NULL); - else + } else { group = PEM_read_bio_ECPKParameters(in, NULL, NULL, NULL); + } if (group == NULL) { BIO_printf(bio_err, "unable to load elliptic curve parameters\n"); ERR_print_errors(bio_err); @@ -393,9 +384,6 @@ int ecparam_main(int argc, char **argv) "}\n"); } - if (outformat == FORMAT_ASN1 && genkey) - noout = 1; - if (!noout) { if (outformat == FORMAT_ASN1) i = i2d_ECPKParameters_bio(out, group); @@ -409,21 +397,12 @@ int ecparam_main(int argc, char **argv) } } - if (need_rand) { - app_RAND_load_file(NULL, (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) { BIO_printf(bio_err, "unable to set group when generating key\n"); EC_KEY_free(eckey); @@ -431,9 +410,6 @@ int ecparam_main(int argc, char **argv) goto end; } - if (new_form) - EC_KEY_set_conv_form(eckey, form); - if (!EC_KEY_generate_key(eckey)) { BIO_printf(bio_err, "unable to generate key\n"); EC_KEY_free(eckey); @@ -449,9 +425,6 @@ int ecparam_main(int argc, char **argv) EC_KEY_free(eckey); } - if (need_rand) - app_RAND_write_file(NULL); - ret = 0; end: BN_free(ec_p); @@ -465,7 +438,7 @@ int ecparam_main(int argc, char **argv) release_engine(e); BIO_free(in); BIO_free_all(out); - return (ret); + return ret; } #endif diff --git a/apps/enc.c b/apps/enc.c index df553811..8e5a57d3 100644 --- a/apps/enc.c +++ b/apps/enc.c @@ -12,6 +12,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -29,7 +30,7 @@ #define SIZE (512) #define BSIZE (8*1024) -static int set_hex(char *in, unsigned char *out, int size); +static int set_hex(const char *in, unsigned char *out, int size); static void show_ciphers(const OBJ_NAME *name, void *bio_); struct doall_enc_ciphers { @@ -43,10 +44,11 @@ typedef enum OPTION_choice { OPT_E, OPT_IN, OPT_OUT, OPT_PASS, OPT_ENGINE, OPT_D, OPT_P, OPT_V, OPT_NOPAD, OPT_SALT, OPT_NOSALT, OPT_DEBUG, OPT_UPPER_P, OPT_UPPER_A, OPT_A, OPT_Z, OPT_BUFSIZE, OPT_K, OPT_KFILE, OPT_UPPER_K, OPT_NONE, - OPT_UPPER_S, OPT_IV, OPT_MD, OPT_CIPHER + OPT_UPPER_S, OPT_IV, OPT_MD, OPT_ITER, OPT_PBKDF2, OPT_CIPHER, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS enc_options[] = { +const OPTIONS enc_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"ciphers", OPT_LIST, '-', "List ciphers"}, {"in", OPT_IN, '<', "Input file"}, @@ -72,8 +74,11 @@ OPTIONS enc_options[] = { {"S", OPT_UPPER_S, 's', "Salt, in hex"}, {"iv", OPT_IV, 's', "IV in hex"}, {"md", OPT_MD, 's', "Use specified digest to create a key from the passphrase"}, + {"iter", OPT_ITER, 'p', "Specify the iteration count and force use of PBKDF2"}, + {"pbkdf2", OPT_PBKDF2, '-', "Use password-based key derivation function 2"}, {"none", OPT_NONE, '-', "Don't encrypt"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, + OPT_R_OPTIONS, #ifdef ZLIB {"z", OPT_Z, '-', "Use zlib as the 'encryption'"}, #endif @@ -104,6 +109,8 @@ int enc_main(int argc, char **argv) int ret = 1, inl, nopad = 0; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char *buff = NULL, salt[PKCS5_SALT_LEN]; + int pbkdf2 = 0; + int iter = 0; long n; struct doall_enc_ciphers dec; #ifdef ZLIB @@ -113,13 +120,13 @@ int enc_main(int argc, char **argv) /* first check the program name */ prog = opt_progname(argv[0]); - if (strcmp(prog, "base64") == 0) + if (strcmp(prog, "base64") == 0) { base64 = 1; #ifdef ZLIB - else if (strcmp(prog, "zlib") == 0) + } else if (strcmp(prog, "zlib") == 0) { do_zlib = 1; #endif - else { + } else { cipher = EVP_get_cipherbyname(prog); if (cipher == NULL && strcmp(prog, "enc") != 0) { BIO_printf(bio_err, "%s is not a known cipher\n", prog); @@ -252,9 +259,23 @@ int enc_main(int argc, char **argv) goto opthelp; cipher = c; break; + case OPT_ITER: + if (!opt_int(opt_arg(), &iter)) + goto opthelp; + pbkdf2 = 1; + break; + case OPT_PBKDF2: + pbkdf2 = 1; + if (iter == 0) /* do not overwrite a chosen value */ + iter = 10000; + break; case OPT_NONE: cipher = NULL; break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; } } if (opt_num_rest() != 0) { @@ -275,6 +296,9 @@ int enc_main(int argc, char **argv) if (dgst == NULL) dgst = EVP_sha256(); + if (iter == 0) + iter = 1; + /* It must be large enough for a base64 encoded line */ if (base64 && bsize < 80) bsize = 80; @@ -296,12 +320,13 @@ int enc_main(int argc, char **argv) if (infile == NULL) { in = dup_bio_in(informat); - } else + } else { in = bio_open_default(infile, 'r', informat); + } if (in == NULL) goto end; - if (!str && passarg) { + if (str == NULL && passarg != NULL) { if (!app_passwd(passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; @@ -311,13 +336,13 @@ int enc_main(int argc, char **argv) if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) { if (1) { -#ifndef OPENSSL_NO_UI +#ifndef OPENSSL_NO_UI_CONSOLE for (;;) { char prompt[200]; BIO_snprintf(prompt, sizeof(prompt), "enter %s %s password:", - OBJ_nid2ln(EVP_CIPHER_nid(cipher)), - (enc) ? "encryption" : "decryption"); + OBJ_nid2ln(EVP_CIPHER_nid(cipher)), + (enc) ? "encryption" : "decryption"); strbuf[0] = '\0'; i = EVP_read_pw_string((char *)strbuf, SIZE, prompt, enc); if (i == 0) { @@ -397,17 +422,18 @@ int enc_main(int argc, char **argv) unsigned char *sptr; size_t str_len = strlen(str); - if (nosalt) + if (nosalt) { sptr = NULL; - else { + } else { if (enc) { if (hsalt) { 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 */ @@ -430,19 +456,41 @@ int enc_main(int argc, char **argv) BIO_printf(bio_err, "bad magic number\n"); goto end; } - sptr = salt; } - if (!EVP_BytesToKey(cipher, dgst, sptr, - (unsigned char *)str, - str_len, 1, key, iv)) { - BIO_printf(bio_err, "EVP_BytesToKey failed\n"); - goto end; + if (pbkdf2 == 1) { + /* + * derive key and default iv + * concatenated into a temporary buffer + */ + unsigned char tmpkeyiv[EVP_MAX_KEY_LENGTH + EVP_MAX_IV_LENGTH]; + int iklen = EVP_CIPHER_key_length(cipher); + int ivlen = EVP_CIPHER_iv_length(cipher); + /* not needed if HASH_UPDATE() is fixed : */ + int islen = (sptr != NULL ? sizeof(salt) : 0); + if (!PKCS5_PBKDF2_HMAC(str, str_len, sptr, islen, + iter, dgst, iklen+ivlen, tmpkeyiv)) { + BIO_printf(bio_err, "PKCS5_PBKDF2_HMAC failed\n"); + goto end; + } + /* split and move data back to global buffer */ + memcpy(key, tmpkeyiv, iklen); + memcpy(iv, tmpkeyiv+iklen, ivlen); + } else { + BIO_printf(bio_err, "*** WARNING : " + "deprecated key derivation used.\n" + "Using -iter or -pbkdf2 would be better.\n"); + if (!EVP_BytesToKey(cipher, dgst, sptr, + (unsigned char *)str, str_len, + 1, key, iv)) { + BIO_printf(bio_err, "EVP_BytesToKey failed\n"); + goto end; + } } /* * zero the complete buffer or the string passed from the command - * line bug picked up by Larry J. Hughes Jr. + * line. */ if (str == strbuf) OPENSSL_cleanse(str, SIZE); @@ -453,7 +501,7 @@ int enc_main(int argc, char **argv) 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, siz)) { BIO_printf(bio_err, "invalid hex iv value\n"); goto end; } @@ -461,16 +509,19 @@ int enc_main(int argc, char **argv) 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. + * No IV was explicitly set and no IV was generated. + * 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 (hkey != NULL) { + if (!set_hex(hkey, key, EVP_CIPHER_key_length(cipher))) { + BIO_printf(bio_err, "invalid hex key value\n"); + goto end; + } + /* wiping secret data as we no longer need it */ + OPENSSL_cleanse(hkey, strlen(hkey)); } if ((benc = BIO_new(BIO_f_cipher())) == NULL) @@ -551,8 +602,8 @@ int enc_main(int argc, char **argv) ret = 0; if (verbose) { - BIO_printf(bio_err, "bytes read :%8"BIO_PRI64"u\n", BIO_number_read(in)); - BIO_printf(bio_err, "bytes written:%8"BIO_PRI64"u\n", BIO_number_written(out)); + BIO_printf(bio_err, "bytes read : %8ju\n", BIO_number_read(in)); + BIO_printf(bio_err, "bytes written: %8ju\n", BIO_number_written(out)); } end: ERR_print_errors(bio_err); @@ -567,7 +618,7 @@ int enc_main(int argc, char **argv) #endif release_engine(e); OPENSSL_free(pass); - return (ret); + return ret; } static void show_ciphers(const OBJ_NAME *name, void *arg) @@ -593,25 +644,26 @@ static void show_ciphers(const OBJ_NAME *name, void *arg) BIO_printf(dec->bio, " "); } -static int set_hex(char *in, unsigned char *out, int size) +static int set_hex(const char *in, unsigned char *out, int size) { int i, n; unsigned char j; + i = size * 2; n = strlen(in); - if (n > (size * 2)) { - BIO_printf(bio_err, "hex string is too long\n"); - return (0); + if (n > i) { + BIO_printf(bio_err, "hex string is too long, ignoring excess\n"); + n = i; /* ignore exceeding part */ + } else if (n < i) { + BIO_printf(bio_err, "hex string is too short, padding with zero bytes to length\n"); } + memset(out, 0, size); for (i = 0; i < n; i++) { - j = (unsigned char)*in; - *(in++) = '\0'; - if (j == 0) - break; + j = (unsigned char)*in++; if (!isxdigit(j)) { BIO_printf(bio_err, "non-hex digit\n"); - return (0); + return 0; } j = (unsigned char)OPENSSL_hexchar2int(j); if (i & 1) @@ -619,5 +671,5 @@ static int set_hex(char *in, unsigned char *out, int size) else out[i / 2] = (j << 4); } - return (1); + return 1; } diff --git a/apps/engine.c b/apps/engine.c index 4eeb6424..83f9588a 100644 --- a/apps/engine.c +++ b/apps/engine.c @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-2018 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 @@ -13,12 +13,14 @@ NON_EMPTY_TRANSLATION_UNIT #else # include "apps.h" +# include "progs.h" # include # include # include # include # include # include +# include typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, @@ -26,7 +28,7 @@ typedef enum OPTION_choice { OPT_V = 100, OPT_VV, OPT_VVV, OPT_VVVV } OPTION_CHOICE; -OPTIONS engine_options[] = { +const OPTIONS engine_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] engine...\n"}, {OPT_HELP_STR, 1, '-', " engine... Engines to load\n"}, @@ -47,28 +49,38 @@ OPTIONS engine_options[] = { static int append_buf(char **buf, int *size, const char *s) { - if (*buf == NULL) { - *size = 256; - *buf = app_malloc(*size, "engine buffer"); - **buf = '\0'; - } + const int expand = 256; + int len = strlen(s) + 1; + char *p = *buf; - if (strlen(*buf) + strlen(s) >= (unsigned int)*size) { - char *tmp; - *size += 256; - tmp = OPENSSL_realloc(*buf, *size); - if (tmp == NULL) { - OPENSSL_free(*buf); - *buf = NULL; - return 0; + if (p == NULL) { + *size = ((len + expand - 1) / expand) * expand; + p = *buf = app_malloc(*size, "engine buffer"); + } else { + const int blen = strlen(p); + + if (blen > 0) + len += 2 + blen; + + if (len > *size) { + *size = ((len + expand - 1) / expand) * expand; + p = OPENSSL_realloc(p, *size); + if (p == NULL) { + OPENSSL_free(*buf); + *buf = NULL; + return 0; + } + *buf = p; + } + + if (blen > 0) { + p += blen; + *p++ = ','; + *p++ = ' '; } - *buf = tmp; } - if (**buf != '\0') - OPENSSL_strlcat(*buf, ", ", *size); - OPENSSL_strlcat(*buf, s, *size); - + strcpy(p, s); return 1; } @@ -147,7 +159,7 @@ static int util_verbose(ENGINE *e, int verbose, BIO *out, const char *indent) } cmds = sk_OPENSSL_STRING_new_null(); - if (!cmds) + if (cmds == NULL) goto err; do { @@ -249,15 +261,34 @@ static void util_do_cmds(ENGINE *e, STACK_OF(OPENSSL_STRING) *cmds, if (!ENGINE_ctrl_cmd_string(e, buf, arg, 0)) res = 0; } - if (res) + if (res) { BIO_printf(out, "[Success]: %s\n", cmd); - else { + } else { BIO_printf(out, "[Failure]: %s\n", cmd); ERR_print_errors(out); } } } +struct util_store_cap_data { + ENGINE *engine; + char **cap_buf; + int *cap_size; + int ok; +}; +static void util_store_cap(const OSSL_STORE_LOADER *loader, void *arg) +{ + struct util_store_cap_data *ctx = arg; + + if (OSSL_STORE_LOADER_get0_engine(loader) == ctx->engine) { + char buf[256]; + BIO_snprintf(buf, sizeof(buf), "STORE(%s)", + OSSL_STORE_LOADER_get0_scheme(loader)); + if (!append_buf(ctx->cap_buf, ctx->cap_size, buf)) + ctx->ok = 0; + } +} + int engine_main(int argc, char **argv) { int ret = 1, i; @@ -380,7 +411,7 @@ int engine_main(int argc, char **argv) goto end; fn_c = ENGINE_get_ciphers(e); - if (!fn_c) + if (fn_c == NULL) goto skip_ciphers; n = fn_c(e, NULL, &nids, 0); for (k = 0; k < n; ++k) @@ -389,7 +420,7 @@ int engine_main(int argc, char **argv) skip_ciphers: fn_d = ENGINE_get_digests(e); - if (!fn_d) + if (fn_d == NULL) goto skip_digests; n = fn_d(e, NULL, &nids, 0); for (k = 0; k < n; ++k) @@ -398,14 +429,26 @@ int engine_main(int argc, char **argv) skip_digests: fn_pk = ENGINE_get_pkey_meths(e); - if (!fn_pk) + if (fn_pk == NULL) goto skip_pmeths; n = fn_pk(e, NULL, &nids, 0); for (k = 0; k < n; ++k) if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k]))) goto end; skip_pmeths: - if (cap_buf && (*cap_buf != '\0')) + { + struct util_store_cap_data store_ctx; + + store_ctx.engine = e; + store_ctx.cap_buf = &cap_buf; + store_ctx.cap_size = &cap_size; + store_ctx.ok = 1; + + OSSL_STORE_do_all_loaders(util_store_cap, &store_ctx); + if (!store_ctx.ok) + goto end; + } + if (cap_buf != NULL && (*cap_buf != '\0')) BIO_printf(out, " [%s]\n", cap_buf); OPENSSL_free(cap_buf); @@ -441,6 +484,6 @@ int engine_main(int argc, char **argv) sk_OPENSSL_STRING_free(pre_cmds); sk_OPENSSL_STRING_free(post_cmds); BIO_free_all(out); - return (ret); + return ret; } #endif diff --git a/apps/errstr.c b/apps/errstr.c index 79d83ee4..3ef01f07 100644 --- a/apps/errstr.c +++ b/apps/errstr.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -11,8 +11,8 @@ #include #include #include "apps.h" +#include "progs.h" #include -#include #include #include @@ -20,7 +20,7 @@ typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP } OPTION_CHOICE; -OPTIONS errstr_options[] = { +const OPTIONS errstr_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] errnum...\n"}, {OPT_HELP_STR, 1, '-', " errnum Error number\n"}, {"help", OPT_HELP, '-', "Display this summary"}, @@ -50,9 +50,9 @@ int errstr_main(int argc, char **argv) ret = 0; for (argv = opt_rest(); *argv; argv++) { - if (sscanf(*argv, "%lx", &l) == 0) + if (sscanf(*argv, "%lx", &l) == 0) { ret++; - else { + } else { /* We're not really an SSL application so this won't auto-init, but * we're still interested in SSL error strings */ @@ -63,5 +63,5 @@ int errstr_main(int argc, char **argv) } } end: - return (ret); + return ret; } diff --git a/apps/gendsa.c b/apps/gendsa.c index bdef022c..06e37924 100644 --- a/apps/gendsa.c +++ b/apps/gendsa.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -17,6 +17,7 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # include # include # include @@ -26,17 +27,17 @@ NON_EMPTY_TRANSLATION_UNIT typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, - OPT_OUT, OPT_PASSOUT, OPT_ENGINE, OPT_RAND, OPT_CIPHER + OPT_OUT, OPT_PASSOUT, OPT_ENGINE, OPT_CIPHER, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS gendsa_options[] = { +const OPTIONS gendsa_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [args] dsaparam-file\n"}, {OPT_HELP_STR, 1, '-', "Valid options are:\n"}, {"help", OPT_HELP, '-', "Display this summary"}, {"out", OPT_OUT, '>', "Output the key to the specified file"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, + OPT_R_OPTIONS, {"", OPT_CIPHER, '-', "Encrypt the output with any supported cipher"}, # ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, @@ -50,7 +51,7 @@ int gendsa_main(int argc, char **argv) BIO *out = NULL, *in = NULL; DSA *dsa = NULL; const EVP_CIPHER *enc = NULL; - char *inrand = NULL, *dsaparams = NULL; + char *dsaparams = NULL; char *outfile = NULL, *passoutarg = NULL, *passout = NULL, *prog; OPTION_CHOICE o; int ret = 1, private = 0; @@ -77,8 +78,9 @@ int gendsa_main(int argc, char **argv) case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; - case OPT_RAND: - inrand = opt_arg(); + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_CIPHER: if (!opt_cipher(opt_unknown(), &enc)) @@ -114,21 +116,11 @@ int gendsa_main(int argc, char **argv) if (out == NULL) goto end2; - if (!app_RAND_load_file(NULL, 1) && inrand == NULL) { - 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)); - DSA_get0_pqg(dsa, &p, NULL, NULL); BIO_printf(bio_err, "Generating DSA key, %d bits\n", BN_num_bits(p)); if (!DSA_generate_key(dsa)) goto end; - app_RAND_write_file(NULL); - assert(private); if (!PEM_write_bio_DSAPrivateKey(out, dsa, enc, NULL, 0, NULL, passout)) goto end; @@ -142,6 +134,6 @@ int gendsa_main(int argc, char **argv) DSA_free(dsa); release_engine(e); OPENSSL_free(passout); - return (ret); + return ret; } #endif diff --git a/apps/genpkey.c b/apps/genpkey.c index 9e379772..ce6de94f 100644 --- a/apps/genpkey.c +++ b/apps/genpkey.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-2018 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 @@ -10,6 +10,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -26,7 +27,7 @@ typedef enum OPTION_choice { OPT_ALGORITHM, OPT_PKEYOPT, OPT_GENPARAM, OPT_TEXT, OPT_CIPHER } OPTION_CHOICE; -OPTIONS genpkey_options[] = { +const OPTIONS genpkey_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "output format (DER or PEM)"}, @@ -156,9 +157,9 @@ int genpkey_main(int argc, char **argv) } } - if (do_param) + if (do_param) { rv = PEM_write_bio_Parameters(out, pkey); - else if (outformat == FORMAT_PEM) { + } else if (outformat == FORMAT_PEM) { assert(private); rv = PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, pass); } else if (outformat == FORMAT_ASN1) { diff --git a/apps/genrsa.c b/apps/genrsa.c index 19bc7535..464657c2 100644 --- a/apps/genrsa.c +++ b/apps/genrsa.c @@ -17,6 +17,7 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # include # include # include @@ -27,28 +28,30 @@ NON_EMPTY_TRANSLATION_UNIT # include # define DEFBITS 2048 +# define DEFPRIMES 2 static int genrsa_cb(int p, int n, BN_GENCB *cb); typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_3, OPT_F4, OPT_ENGINE, - OPT_OUT, OPT_RAND, OPT_PASSOUT, OPT_CIPHER + OPT_OUT, OPT_PASSOUT, OPT_CIPHER, OPT_PRIMES, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS genrsa_options[] = { +const OPTIONS genrsa_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"3", OPT_3, '-', "Use 3 for the E value"}, {"F4", OPT_F4, '-', "Use F4 (0x10001) for the E value"}, {"f4", OPT_F4, '-', "Use F4 (0x10001) for the E value"}, {"out", OPT_OUT, 's', "Output the key to specified file"}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, + OPT_R_OPTIONS, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"", OPT_CIPHER, '-', "Encrypt the output with any supported cipher"}, # ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, # endif + {"primes", OPT_PRIMES, 'p', "Specify number of primes"}, {NULL} }; @@ -62,10 +65,10 @@ int genrsa_main(int argc, char **argv) const BIGNUM *e; RSA *rsa = NULL; const EVP_CIPHER *enc = NULL; - int ret = 1, num = DEFBITS, private = 0; + int ret = 1, num = DEFBITS, private = 0, primes = DEFPRIMES; unsigned long f4 = RSA_F4; char *outfile = NULL, *passoutarg = NULL, *passout = NULL; - char *inrand = NULL, *prog, *hexe, *dece; + char *prog, *hexe, *dece; OPTION_CHOICE o; if (bn == NULL || cb == NULL) @@ -97,8 +100,9 @@ opthelp: case OPT_ENGINE: eng = setup_engine(opt_arg(), 0); break; - case OPT_RAND: - inrand = opt_arg(); + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_PASSOUT: passoutarg = opt_arg(); @@ -107,6 +111,10 @@ opthelp: if (!opt_cipher(opt_unknown(), &enc)) goto end; break; + case OPT_PRIMES: + if (!opt_int(opt_arg(), &primes)) + goto end; + break; } } argc = opt_num_rest(); @@ -130,26 +138,16 @@ opthelp: if (out == NULL) goto end; - if (!app_RAND_load_file(NULL, 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)); - - BIO_printf(bio_err, "Generating RSA private key, %d bit long modulus\n", - num); + BIO_printf(bio_err, "Generating RSA private key, %d bit long modulus (%d primes)\n", + num, primes); rsa = eng ? RSA_new_method(eng) : RSA_new(); if (rsa == NULL) goto end; - if (!BN_set_word(bn, f4) || !RSA_generate_key_ex(rsa, num, bn, cb)) + if (!BN_set_word(bn, f4) + || !RSA_generate_multi_prime_key(rsa, num, primes, bn, cb)) goto end; - app_RAND_write_file(NULL); - RSA_get0_key(rsa, NULL, &e, NULL); hexe = BN_bn2hex(e); dece = BN_bn2dec(e); @@ -176,7 +174,7 @@ opthelp: OPENSSL_free(passout); if (ret != 0) ERR_print_errors(bio_err); - return (ret); + return ret; } static int genrsa_cb(int p, int n, BN_GENCB *cb) diff --git a/apps/nseq.c b/apps/nseq.c index 018d5ebd..a067c915 100644 --- a/apps/nseq.c +++ b/apps/nseq.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-2018 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 @@ -10,6 +10,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include @@ -18,7 +19,7 @@ typedef enum OPTION_choice { OPT_TOSEQ, OPT_IN, OPT_OUT } OPTION_CHOICE; -OPTIONS nseq_options[] = { +const OPTIONS nseq_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"toseq", OPT_TOSEQ, '-', "Output NS Sequence file"}, {"in", OPT_IN, '<', "Input file"}, @@ -109,5 +110,5 @@ int nseq_main(int argc, char **argv) BIO_free_all(out); NETSCAPE_CERT_SEQUENCE_free(seq); - return (ret); + return ret; } diff --git a/apps/ocsp.c b/apps/ocsp.c index 4b533348..bd16a5b8 100644 --- a/apps/ocsp.c +++ b/apps/ocsp.c @@ -1,5 +1,5 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2018 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 @@ -17,8 +17,6 @@ NON_EMPTY_TRANSLATION_UNIT * on OpenVMS */ # endif -# define USE_SOCKETS - # include # include # include @@ -27,6 +25,7 @@ NON_EMPTY_TRANSLATION_UNIT /* Needs to be included before the openssl headers */ # include "apps.h" +# include "progs.h" # include # include # include @@ -35,21 +34,6 @@ NON_EMPTY_TRANSLATION_UNIT # include # include -# if defined(NETWARE_CLIB) -# ifdef NETWARE_BSDSOCK -# include -# include -# else -# include -# endif -# elif defined(NETWARE_LIBC) -# ifdef NETWARE_BSDSOCK -# include -# else -# include -# endif -# endif - /* Maximum leeway in validity period: default 5 minutes */ # define MAX_VALIDITY_PERIOD (5 * 60) @@ -63,9 +47,10 @@ static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req, STACK_OF(OPENSSL_STRING) *names, STACK_OF(OCSP_CERTID) *ids, long nsec, long maxage); -static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, - CA_DB *db, X509 *ca, X509 *rcert, +static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req, + CA_DB *db, STACK_OF(X509) *ca, X509 *rcert, EVP_PKEY *rkey, const EVP_MD *md, + STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(X509) *rother, unsigned long flags, int nmin, int ndays, int badsig); @@ -94,12 +79,12 @@ typedef enum OPTION_choice { OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT, OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL, OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER, - OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_HEADER, + OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER, OPT_V_ENUM, OPT_MD } OPTION_CHOICE; -OPTIONS ocsp_options[] = { +const OPTIONS ocsp_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"out", OPT_OUTFILE, '>', "Output filename"}, {"timeout", OPT_TIMEOUT, 'p', @@ -108,7 +93,7 @@ OPTIONS ocsp_options[] = { {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"}, {"port", OPT_PORT, 'p', "Port to run responder on"}, {"ignore_err", OPT_IGNORE_ERR, '-', - "Ignore Error response from OCSP responder, and retry "}, + "Ignore error on OCSP request or response and continue running"}, {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"}, {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"}, {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"}, @@ -171,6 +156,7 @@ OPTIONS ocsp_options[] = { {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"}, {"rother", OPT_ROTHER, '<', "Other certificates to include in response"}, {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"}, + {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"}, {"header", OPT_HEADER, 's', "key=value header to add"}, {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"}, OPT_V_OPTIONS, @@ -181,6 +167,7 @@ int ocsp_main(int argc, char **argv) { BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL; const EVP_MD *cert_id_md = NULL, *rsign_md = NULL; + STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL; int trailing_md = 0; CA_DB *rdb = NULL; EVP_PKEY *key = NULL, *rkey = NULL; @@ -192,7 +179,8 @@ int ocsp_main(int argc, char **argv) STACK_OF(OPENSSL_STRING) *reqnames = NULL; STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL; STACK_OF(X509) *issuers = NULL; - X509 *issuer = NULL, *cert = NULL, *rca_cert = NULL; + X509 *issuer = NULL, *cert = NULL; + STACK_OF(X509) *rca_cert = NULL; X509 *signer = NULL, *rsigner = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = NULL; @@ -218,10 +206,10 @@ int ocsp_main(int argc, char **argv) char *prog; reqnames = sk_OPENSSL_STRING_new_null(); - if (!reqnames) + if (reqnames == NULL) goto end; ids = sk_OCSP_CERTID_new_null(); - if (!ids) + if (ids == NULL) goto end; if ((vpm = X509_VERIFY_PARAM_new()) == NULL) return 1; @@ -435,6 +423,12 @@ int ocsp_main(int argc, char **argv) if (!opt_md(opt_arg(), &rsign_md)) goto end; break; + case OPT_RSIGOPT: + if (rsign_sigopts == NULL) + rsign_sigopts = sk_OPENSSL_STRING_new_null(); + if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg())) + goto end; + break; case OPT_HEADER: header = opt_arg(); value = strchr(header, '='); @@ -470,62 +464,65 @@ int ocsp_main(int argc, char **argv) goto opthelp; /* Have we anything to do? */ - if (!req && !reqin && !respin && !(port && ridx_filename)) + if (req == NULL&& reqin == NULL + && respin == NULL && !(port != NULL && ridx_filename != NULL)) goto opthelp; out = bio_open_default(outfile, 'w', FORMAT_TEXT); if (out == NULL) goto end; - if (!req && (add_nonce != 2)) + if (req == NULL && (add_nonce != 2)) add_nonce = 0; - if (!req && reqin) { + if (req == NULL && reqin != NULL) { derbio = bio_open_default(reqin, 'r', FORMAT_ASN1); if (derbio == NULL) goto end; req = d2i_OCSP_REQUEST_bio(derbio, NULL); BIO_free(derbio); - if (!req) { + if (req == NULL) { BIO_printf(bio_err, "Error reading OCSP request\n"); goto end; } } - if (!req && port) { + if (req == NULL && port != NULL) { acbio = init_responder(port); - if (!acbio) + if (acbio == NULL) goto end; } - if (rsignfile) { - if (!rkeyfile) + if (rsignfile != NULL) { + if (rkeyfile == NULL) rkeyfile = rsignfile; rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate"); - if (!rsigner) { + if (rsigner == NULL) { BIO_printf(bio_err, "Error loading responder certificate\n"); goto end; } - rca_cert = load_cert(rca_filename, FORMAT_PEM, "CA certificate"); - if (rcertfile) { + if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM, + NULL, "CA certificate")) + goto end; + if (rcertfile != NULL) { if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL, "responder other certificates")) goto end; } rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL, "responder private key"); - if (!rkey) + if (rkey == NULL) goto end; } - if (acbio) + if (acbio != NULL) BIO_printf(bio_err, "Waiting for OCSP client connections...\n"); - redo_accept: +redo_accept: - if (acbio) { + if (acbio != NULL) { if (!do_responder(&req, &cbio, acbio)) goto end; - if (!req) { + if (req == NULL) { resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL); @@ -534,30 +531,32 @@ int ocsp_main(int argc, char **argv) } } - if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) { + if (req == NULL + && (signfile != NULL || reqout != NULL + || host != NULL || add_nonce || ridx_filename != NULL)) { BIO_printf(bio_err, "Need an OCSP request for this operation!\n"); goto end; } - if (req && add_nonce) + if (req != NULL && add_nonce) OCSP_request_add1_nonce(req, NULL, -1); - if (signfile) { - if (!keyfile) + if (signfile != NULL) { + if (keyfile == NULL) keyfile = signfile; signer = load_cert(signfile, FORMAT_PEM, "signer certificate"); - if (!signer) { + if (signer == NULL) { BIO_printf(bio_err, "Error loading signer certificate\n"); goto end; } - if (sign_certfile) { + if (sign_certfile != NULL) { if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL, "signer certificates")) goto end; } key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL, "signer private key"); - if (!key) + if (key == NULL) goto end; if (!OCSP_request_sign @@ -567,10 +566,10 @@ int ocsp_main(int argc, char **argv) } } - if (req_text && req) + if (req_text && req != NULL) OCSP_REQUEST_print(out, req, 0); - if (reqout) { + if (reqout != NULL) { derbio = bio_open_default(reqout, 'w', FORMAT_ASN1); if (derbio == NULL) goto end; @@ -578,43 +577,44 @@ int ocsp_main(int argc, char **argv) BIO_free(derbio); } - if (ridx_filename && (!rkey || !rsigner || !rca_cert)) { + if (ridx_filename != NULL + && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) { BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n"); goto end; } - if (ridx_filename && !rdb) { + if (ridx_filename != NULL && rdb == NULL) { rdb = load_index(ridx_filename, NULL); - if (!rdb) + if (rdb == NULL) goto end; if (!index_index(rdb)) goto end; } - if (rdb) { - make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, - rsign_md, rother, rflags, nmin, ndays, badsig); - if (cbio) + if (rdb != NULL) { + make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey, + rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig); + if (cbio != NULL) send_ocsp_response(cbio, resp); - } else if (host) { + } else if (host != NULL) { # ifndef OPENSSL_NO_SOCK resp = process_responder(req, host, path, port, use_ssl, headers, req_timeout); - if (!resp) + if (resp == NULL) goto end; # else BIO_printf(bio_err, "Error creating connect BIO - sockets not supported.\n"); goto end; # endif - } else if (respin) { + } else if (respin != NULL) { derbio = bio_open_default(respin, 'r', FORMAT_ASN1); if (derbio == NULL) goto end; resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); - if (!resp) { + if (resp == NULL) { BIO_printf(bio_err, "Error reading OCSP response\n"); goto end; } @@ -625,7 +625,7 @@ int ocsp_main(int argc, char **argv) done_resp: - if (respout) { + if (respout != NULL) { derbio = bio_open_default(respout, 'w', FORMAT_ASN1); if (derbio == NULL) goto end; @@ -647,7 +647,7 @@ int ocsp_main(int argc, char **argv) OCSP_RESPONSE_print(out, resp, 0); /* If running as responder don't verify our own response */ - if (cbio) { + if (cbio != NULL) { /* If not unlimited, see if we took all we should. */ if (accept_count != -1 && --accept_count <= 0) { ret = 0; @@ -661,26 +661,26 @@ int ocsp_main(int argc, char **argv) resp = NULL; goto redo_accept; } - if (ridx_filename) { + if (ridx_filename != NULL) { ret = 0; goto end; } - if (!store) { + if (store == NULL) { store = setup_verify(CAfile, CApath, noCAfile, noCApath); if (!store) goto end; } if (vpmtouched) X509_STORE_set1_param(store, vpm); - if (verify_certfile) { + if (verify_certfile != NULL) { if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL, "validator certificate")) goto end; } bs = OCSP_response_get1_basic(resp); - if (!bs) { + if (bs == NULL) { BIO_printf(bio_err, "Error parsing response\n"); goto end; } @@ -688,7 +688,7 @@ int ocsp_main(int argc, char **argv) ret = 0; if (!noverify) { - if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) { + if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) { if (i == -1) BIO_printf(bio_err, "WARNING: no nonce in response\n"); else { @@ -708,9 +708,9 @@ int ocsp_main(int argc, char **argv) BIO_printf(bio_err, "Response Verify Failure\n"); ERR_print_errors(bio_err); ret = 1; - } else + } else { BIO_printf(bio_err, "Response verify OK\n"); - + } } print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage); @@ -720,16 +720,17 @@ int ocsp_main(int argc, char **argv) X509_free(signer); X509_STORE_free(store); X509_VERIFY_PARAM_free(vpm); + sk_OPENSSL_STRING_free(rsign_sigopts); EVP_PKEY_free(key); EVP_PKEY_free(rkey); X509_free(cert); sk_X509_pop_free(issuers, X509_free); X509_free(rsigner); - X509_free(rca_cert); + sk_X509_pop_free(rca_cert, X509_free); free_index(rdb); BIO_free_all(cbio); BIO_free_all(acbio); - BIO_free(out); + BIO_free_all(out); OCSP_REQUEST_free(req); OCSP_RESPONSE_free(resp); OCSP_BASICRESP_free(bs); @@ -742,7 +743,7 @@ int ocsp_main(int argc, char **argv) OPENSSL_free(tport); OPENSSL_free(tpath); - return (ret); + return ret; } static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, @@ -750,7 +751,8 @@ static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, STACK_OF(OCSP_CERTID) *ids) { OCSP_CERTID *id; - if (!issuer) { + + if (issuer == NULL) { BIO_printf(bio_err, "No issuer certificate specified\n"); return 0; } @@ -759,7 +761,7 @@ static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, if (*req == NULL) goto err; id = OCSP_cert_to_id(cert_id_md, cert, issuer); - if (!id || !sk_OCSP_CERTID_push(ids, id)) + if (id == NULL || !sk_OCSP_CERTID_push(ids, id)) goto err; if (!OCSP_request_add0_id(*req, id)) goto err; @@ -778,7 +780,8 @@ static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, X509_NAME *iname; ASN1_BIT_STRING *ikey; ASN1_INTEGER *sno; - if (!issuer) { + + if (issuer == NULL) { BIO_printf(bio_err, "No issuer certificate specified\n"); return 0; } @@ -789,7 +792,7 @@ static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, iname = X509_get_subject_name(issuer); ikey = X509_get0_pubkey_bitstr(issuer); sno = s2i_ASN1_INTEGER(NULL, serial); - if (!sno) { + if (sno == NULL) { BIO_printf(bio_err, "Error converting serial number %s\n", serial); return 0; } @@ -816,7 +819,7 @@ static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req, int i, status, reason; ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; - if (!bs || !req || !sk_OPENSSL_STRING_num(names) + if (bs == NULL || req == NULL || !sk_OPENSSL_STRING_num(names) || !sk_OCSP_CERTID_num(ids)) return; @@ -863,16 +866,19 @@ static void print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req, } } -static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, - CA_DB *db, X509 *ca, X509 *rcert, +static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req, + CA_DB *db, STACK_OF(X509) *ca, X509 *rcert, EVP_PKEY *rkey, const EVP_MD *rmd, + STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(X509) *rother, unsigned long flags, int nmin, int ndays, int badsig) { ASN1_TIME *thisupd = NULL, *nextupd = NULL; - OCSP_CERTID *cid, *ca_id = NULL; + OCSP_CERTID *cid; OCSP_BASICRESP *bs = NULL; int i, id_count; + EVP_MD_CTX *mctx = NULL; + EVP_PKEY_CTX *pkctx = NULL; id_count = OCSP_request_onereq_count(req); @@ -892,6 +898,8 @@ static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, OCSP_ONEREQ *one; ASN1_INTEGER *serial; char **inf; + int jj; + int found = 0; ASN1_OBJECT *cert_id_md_oid; const EVP_MD *cert_id_md; one = OCSP_request_onereq_get0(req, i); @@ -900,16 +908,22 @@ static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, 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) { + if (cert_id_md == NULL) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL); goto end; } - OCSP_CERTID_free(ca_id); - ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca); + for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) { + X509 *ca_cert = sk_X509_value(ca, jj); + OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert); - /* Is this request about our CA? */ - if (OCSP_id_issuer_cmp(ca_id, cid)) { + if (OCSP_id_issuer_cmp(ca_id, cid) == 0) + found = 1; + + OCSP_CERTID_free(ca_id); + } + + if (!found) { OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_UNKNOWN, 0, NULL, thisupd, nextupd); @@ -917,15 +931,15 @@ static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, } OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid); inf = lookup_serial(db, serial); - if (!inf) + if (inf == NULL) { OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_UNKNOWN, 0, NULL, thisupd, nextupd); - else if (inf[DB_type][0] == DB_TYPE_VAL) + } 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) { + } else if (inf[DB_type][0] == DB_TYPE_REV) { ASN1_OBJECT *inst = NULL; ASN1_TIME *revtm = NULL; ASN1_GENERALIZEDTIME *invtm = NULL; @@ -935,10 +949,10 @@ static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, single = OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_REVOKED, reason, revtm, thisupd, nextupd); - if (invtm) + if (invtm != NULL) OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date, invtm, 0, 0); - else if (inst) + else if (inst != NULL) OCSP_SINGLERESP_add1_ext_i2d(single, NID_hold_instruction_code, inst, 0, 0); @@ -950,7 +964,23 @@ static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, OCSP_copy_nonce(bs, req); - OCSP_basic_sign(bs, rcert, rkey, rmd, rother, flags); + mctx = EVP_MD_CTX_new(); + if ( mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) { + *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL); + goto end; + } + for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) { + char *sigopt = sk_OPENSSL_STRING_value(sigopts, i); + + if (pkey_ctrl_string(pkctx, sigopt) <= 0) { + BIO_printf(err, "parameter error \"%s\"\n", sigopt); + ERR_print_errors(bio_err); + *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, + NULL); + goto end; + } + } + OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags); if (badsig) { const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs); @@ -960,9 +990,9 @@ static void make_ocsp_response(OCSP_RESPONSE **resp, OCSP_REQUEST *req, *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs); end: + EVP_MD_CTX_free(mctx); ASN1_TIME_free(thisupd); ASN1_TIME_free(nextupd); - OCSP_CERTID_free(ca_id); OCSP_BASICRESP_free(bs); } @@ -1092,7 +1122,7 @@ static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio) if (*q == ' ') break; if (strncmp(q, " HTTP/1.", 8) != 0) { - BIO_printf(bio_err, "Invalid request -- bad HTTP vesion\n"); + BIO_printf(bio_err, "Invalid request -- bad HTTP version\n"); return 1; } *q = '\0'; @@ -1124,13 +1154,14 @@ static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio) } /* Try to read OCSP request */ - if (getbio) { + if (getbio != NULL) { req = d2i_OCSP_REQUEST_bio(getbio, NULL); BIO_free_all(getbio); - } else + } else { req = d2i_OCSP_REQUEST_bio(cbio, NULL); + } - if (!req) { + if (req == NULL) { BIO_printf(bio_err, "Error parsing OCSP request\n"); ERR_print_errors(bio_err); } @@ -1146,7 +1177,7 @@ 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) + if (cbio == NULL) return 0; BIO_printf(cbio, http_resp, i2d_OCSP_RESPONSE(resp, NULL)); i2d_OCSP_RESPONSE_bio(cbio, resp); @@ -1224,11 +1255,11 @@ static OCSP_RESPONSE *query_responder(BIO *cbio, const char *host, openssl_fdset(fd, &confds); tv.tv_usec = 0; tv.tv_sec = req_timeout; - if (BIO_should_read(cbio)) + if (BIO_should_read(cbio)) { rv = select(fd + 1, (void *)&confds, NULL, NULL, &tv); - else if (BIO_should_write(cbio)) + } else if (BIO_should_write(cbio)) { rv = select(fd + 1, NULL, (void *)&confds, NULL, &tv); - else { + } else { BIO_puts(bio_err, "Unexpected retry condition\n"); goto err; } @@ -1259,11 +1290,11 @@ OCSP_RESPONSE *process_responder(OCSP_REQUEST *req, OCSP_RESPONSE *resp = NULL; cbio = BIO_new_connect(host); - if (!cbio) { + if (cbio == NULL) { BIO_printf(bio_err, "Error creating connect BIO\n"); goto end; } - if (port) + if (port != NULL) BIO_set_conn_port(cbio, port); if (use_ssl == 1) { BIO *sbio; @@ -1278,7 +1309,7 @@ OCSP_RESPONSE *process_responder(OCSP_REQUEST *req, } resp = query_responder(cbio, host, path, headers, req, req_timeout); - if (!resp) + if (resp == NULL) BIO_printf(bio_err, "Error querying OCSP responder\n"); end: BIO_free_all(cbio); diff --git a/apps/openssl-vms.cnf b/apps/openssl-vms.cnf index 0092a650..a3ca3930 100644 --- a/apps/openssl-vms.cnf +++ b/apps/openssl-vms.cnf @@ -344,3 +344,5 @@ tsa_name = yes # Must the TSA name be included in the reply? # (optional, default: no) ess_cert_id_chain = no # Must the ESS cert id chain be included? # (optional, default: no) +ess_cert_id_alg = sha1 # algorithm to compute certificate + # identifier (optional, default: sha1) diff --git a/apps/openssl.c b/apps/openssl.c index 2607694f..39b4f2ce 100644 --- a/apps/openssl.c +++ b/apps/openssl.c @@ -7,6 +7,7 @@ * https://www.openssl.org/source/license.html */ +#include #include #include #include @@ -21,26 +22,22 @@ # include #endif #include -#ifdef OPENSSL_FIPS -# include -#endif -#define USE_SOCKETS /* needed for the _O_BINARY defs in the MS world */ #include "s_apps.h" /* Needed to get the other O_xxx flags. */ #ifdef OPENSSL_SYS_VMS # include #endif -#define INCLUDE_FUNCTION_TABLE #include "apps.h" +#define INCLUDE_FUNCTION_TABLE +#include "progs.h" - -#ifdef OPENSSL_NO_CAMELLIA -# define FORMAT "%-15s" -# define COLUMNS 5 -#else -# define FORMAT "%-18s" -# define COLUMNS 4 -#endif +/* Structure to hold the number of columns to be displayed and the + * field width used to display them. + */ +typedef struct { + int columns; + int width; +} DISPLAY_COLUMNS; /* Special sentinel to exit the program. */ #define EXIT_THE_PROGRAM (-1) @@ -54,7 +51,8 @@ static LHASH_OF(FUNCTION) *prog_init(void); static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]); static void list_pkey(void); -static void list_type(FUNC_TYPE ft); +static void list_pkey_meth(void); +static void list_type(FUNC_TYPE ft, int one); static void list_disabled(void); char *default_config_file = NULL; @@ -62,6 +60,20 @@ BIO *bio_in = NULL; BIO *bio_out = NULL; BIO *bio_err = NULL; +static void calculate_columns(DISPLAY_COLUMNS *dc) +{ + FUNCTION *f; + int len, maxlen = 0; + + for (f = functions; f->name != NULL; ++f) + if (f->type == FT_general || f->type == FT_md || f->type == FT_cipher) + if ((len = strlen(f->name)) > maxlen) + maxlen = len; + + dc->width = maxlen + 2; + dc->columns = (80 - 1) / dc->width; +} + static int apps_startup() { #ifdef SIGPIPE @@ -73,18 +85,15 @@ static int apps_startup() | OPENSSL_INIT_LOAD_CONFIG, NULL)) return 0; -#ifndef OPENSSL_NO_UI setup_ui_method(); -#endif return 1; } static void apps_shutdown() { -#ifndef OPENSSL_NO_UI destroy_ui_method(); -#endif + destroy_prefix_method(); } static char *make_config_name() @@ -143,15 +152,8 @@ int main(int argc, char *argv[]) CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); if (getenv("OPENSSL_FIPS")) { -#ifdef OPENSSL_FIPS - if (!FIPS_mode_set(1)) { - ERR_print_errors(bio_err); - return 1; - } -#else BIO_printf(bio_err, "FIPS mode not supported.\n"); return 1; -#endif } if (!apps_startup()) { @@ -254,6 +256,7 @@ int main(int argc, char *argv[]) OPENSSL_free(default_config_file); lh_FUNCTION_free(prog); OPENSSL_free(arg.argv); + app_RAND_write(); BIO_free(bio_in); BIO_free_all(bio_out); @@ -266,19 +269,15 @@ int main(int argc, char *argv[]) EXIT(ret); } -OPTIONS exit_options[] = { - {NULL} -}; - static void list_cipher_fn(const EVP_CIPHER *c, const char *from, const char *to, void *arg) { - if (c) + if (c != NULL) { BIO_printf(arg, "%s\n", EVP_CIPHER_name(c)); - else { - if (!from) + } else { + if (from == NULL) from = ""; - if (!to) + if (to == NULL) to = ""; BIO_printf(arg, "%s => %s\n", from, to); } @@ -287,27 +286,74 @@ static void list_cipher_fn(const EVP_CIPHER *c, static void list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg) { - if (m) + if (m != NULL) { BIO_printf(arg, "%s\n", EVP_MD_name(m)); - else { - if (!from) + } else { + if (from == NULL) from = ""; - if (!to) + if (to == NULL) to = ""; BIO_printf((BIO *)arg, "%s => %s\n", from, to); } } +static void list_missing_help(void) +{ + const FUNCTION *fp; + const OPTIONS *o; + + for (fp = functions; fp->name != NULL; fp++) { + if ((o = fp->help) != NULL) { + /* If there is help, list what flags are not documented. */ + for ( ; o->name != NULL; o++) { + if (o->helpstr == NULL) + BIO_printf(bio_out, "%s %s\n", fp->name, o->name); + } + } else if (fp->func != dgst_main) { + /* If not aliased to the dgst command, */ + BIO_printf(bio_out, "%s *\n", fp->name); + } + } +} + +static void list_options_for_command(const char *command) +{ + const FUNCTION *fp; + const OPTIONS *o; + + for (fp = functions; fp->name != NULL; fp++) + if (strcmp(fp->name, command) == 0) + break; + if (fp->name == NULL) { + BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n", + command); + return; + } + + if ((o = fp->help) == NULL) + return; + + for ( ; o->name != NULL; o++) { + if (o->name == OPT_HELP_STR + || o->name == OPT_MORE_STR + || o->name[0] == '\0') + continue; + BIO_printf(bio_out, "%s %c\n", o->name, o->valtype); + } +} + + /* Unified enum for help and list commands. */ typedef enum HELPLIST_CHOICE { - OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, - OPT_COMMANDS, OPT_DIGEST_COMMANDS, + OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ONE, + OPT_COMMANDS, OPT_DIGEST_COMMANDS, OPT_OPTIONS, OPT_DIGEST_ALGORITHMS, OPT_CIPHER_COMMANDS, OPT_CIPHER_ALGORITHMS, - OPT_PK_ALGORITHMS, OPT_DISABLED + OPT_PK_ALGORITHMS, OPT_PK_METHOD, OPT_DISABLED, OPT_MISSING_HELP } HELPLIST_CHOICE; -OPTIONS list_options[] = { +const OPTIONS list_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, + {"1", OPT_ONE, '-', "List in one column"}, {"commands", OPT_COMMANDS, '-', "List of standard commands"}, {"digest-commands", OPT_DIGEST_COMMANDS, '-', "List of message digest commands"}, @@ -318,8 +364,14 @@ OPTIONS list_options[] = { "List of cipher algorithms"}, {"public-key-algorithms", OPT_PK_ALGORITHMS, '-', "List of public key algorithms"}, + {"public-key-methods", OPT_PK_METHOD, '-', + "List of public key methods"}, {"disabled", OPT_DISABLED, '-', "List of disabled features"}, + {"missing-help", OPT_MISSING_HELP, '-', + "List missing detailed help strings"}, + {"options", OPT_OPTIONS, 's', + "List options for specified command"}, {NULL} }; @@ -327,7 +379,7 @@ int list_main(int argc, char **argv) { char *prog; HELPLIST_CHOICE o; - int done = 0; + int one = 0, done = 0; prog = opt_init(argc, argv, list_options); while ((o = opt_next()) != OPT_EOF) { @@ -340,17 +392,20 @@ opthelp: case OPT_HELP: opt_help(list_options); break; + case OPT_ONE: + one = 1; + break; case OPT_COMMANDS: - list_type(FT_general); + list_type(FT_general, one); break; case OPT_DIGEST_COMMANDS: - list_type(FT_md); + list_type(FT_md, one); break; case OPT_DIGEST_ALGORITHMS: EVP_MD_do_all_sorted(list_md_fn, bio_out); break; case OPT_CIPHER_COMMANDS: - list_type(FT_cipher); + list_type(FT_cipher, one); break; case OPT_CIPHER_ALGORITHMS: EVP_CIPHER_do_all_sorted(list_cipher_fn, bio_out); @@ -358,9 +413,18 @@ opthelp: case OPT_PK_ALGORITHMS: list_pkey(); break; + case OPT_PK_METHOD: + list_pkey_meth(); + break; case OPT_DISABLED: list_disabled(); break; + case OPT_MISSING_HELP: + list_missing_help(); + break; + case OPT_OPTIONS: + list_options_for_command(opt_arg()); + break; } done = 1; } @@ -375,42 +439,60 @@ opthelp: return 0; } -OPTIONS help_options[] = { - {"help", OPT_HELP, '-', "Display this summary"}, +typedef enum HELP_CHOICE { + OPT_hERR = -1, OPT_hEOF = 0, OPT_hHELP +} HELP_CHOICE; + +const OPTIONS help_options[] = { + {OPT_HELP_STR, 1, '-', "Usage: help [options]\n"}, + {OPT_HELP_STR, 1, '-', " help [command]\n"}, + {"help", OPT_hHELP, '-', "Display this summary"}, {NULL} }; + int help_main(int argc, char **argv) { FUNCTION *fp; int i, nl; FUNC_TYPE tp; char *prog; - HELPLIST_CHOICE o; + HELP_CHOICE o; + DISPLAY_COLUMNS dc; prog = opt_init(argc, argv, help_options); - while ((o = opt_next()) != OPT_EOF) { + while ((o = opt_next()) != OPT_hEOF) { switch (o) { - default: + case OPT_hERR: + case OPT_hEOF: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); return 1; - case OPT_HELP: + case OPT_hHELP: opt_help(help_options); return 0; } } + if (opt_num_rest() == 1) { + char *new_argv[3]; + + new_argv[0] = opt_rest()[0]; + new_argv[1] = "--help"; + new_argv[2] = NULL; + return do_cmd(prog_init(), 2, new_argv); + } if (opt_num_rest() != 0) { BIO_printf(bio_err, "Usage: %s\n", prog); return 1; } - BIO_printf(bio_err, "\nStandard commands"); + calculate_columns(&dc); + BIO_printf(bio_err, "Standard commands"); i = 0; tp = FT_none; for (fp = functions; fp->name != NULL; fp++) { nl = 0; - if (((i++) % COLUMNS) == 0) { + if (i++ % dc.columns == 0) { BIO_printf(bio_err, "\n"); nl = 1; } @@ -428,29 +510,35 @@ int help_main(int argc, char **argv) "\nCipher commands (see the `enc' command for more details)\n"); } } - BIO_printf(bio_err, FORMAT, fp->name); + BIO_printf(bio_err, "%-*s", dc.width, fp->name); } BIO_printf(bio_err, "\n\n"); return 0; } -int exit_main(int argc, char **argv) -{ - return EXIT_THE_PROGRAM; -} - -static void list_type(FUNC_TYPE ft) +static void list_type(FUNC_TYPE ft, int one) { FUNCTION *fp; int i = 0; + DISPLAY_COLUMNS dc = {0}; - for (fp = functions; fp->name != NULL; fp++) - if (fp->type == ft) { - if ((i++ % COLUMNS) == 0) + if (!one) + calculate_columns(&dc); + + for (fp = functions; fp->name != NULL; fp++) { + if (fp->type != ft) + continue; + if (one) { + BIO_printf(bio_out, "%s\n", fp->name); + } else { + if (i % dc.columns == 0 && i > 0) BIO_printf(bio_out, "\n"); - BIO_printf(bio_out, FORMAT, fp->name); + BIO_printf(bio_out, "%-*s", dc.width, fp->name); + i++; } - BIO_printf(bio_out, "\n"); + } + if (!one) + BIO_printf(bio_out, "\n\n"); } static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]) @@ -458,7 +546,7 @@ static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]) FUNCTION f, *fp; if (argc <= 0 || argv[0] == NULL) - return (0); + return 0; f.name = argv[0]; fp = lh_FUNCTION_retrieve(prog, &f); if (fp == NULL) { @@ -473,7 +561,7 @@ static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]) } } if (fp != NULL) { - return (fp->func(argc, argv)); + return fp->func(argc, argv); } if ((strncmp(argv[0], "no-", 3)) == 0) { /* @@ -483,7 +571,7 @@ static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]) f.name = argv[0] + 3; if (lh_FUNCTION_retrieve(prog, &f) == NULL) { BIO_printf(bio_out, "%s\n", argv[0]); - return (0); + return 0; } BIO_printf(bio_out, "%s\n", argv[0] + 3); return 1; @@ -495,7 +583,7 @@ static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]) BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n", argv[0]); - return (1); + return 1; } static void list_pkey(void) @@ -527,6 +615,22 @@ static void list_pkey(void) } } +static void list_pkey_meth(void) +{ + size_t i; + size_t meth_count = EVP_PKEY_meth_get_count(); + + for (i = 0; i < meth_count; i++) { + const EVP_PKEY_METHOD *pmeth = EVP_PKEY_meth_get0(i); + int pkey_id, pkey_flags; + + EVP_PKEY_meth_get0_info(&pkey_id, &pkey_flags, pmeth); + BIO_printf(bio_out, "%s\n", OBJ_nid2ln(pkey_id)); + BIO_printf(bio_out, "\tType: %s Algorithm\n", + pkey_flags & ASN1_PKEY_DYNAMIC ? "External" : "Builtin"); + } +} + static int function_cmp(const FUNCTION * a, const FUNCTION * b) { return strncmp(a->name, b->name, 8); @@ -550,6 +654,9 @@ static int SortFnByName(const void *_f1, const void *_f2) static void list_disabled(void) { BIO_puts(bio_out, "Disabled algorithms:\n"); +#ifdef OPENSSL_NO_ARIA + BIO_puts(bio_out, "ARIA\n"); +#endif #ifdef OPENSSL_NO_BF BIO_puts(bio_out, "BF\n"); #endif @@ -655,6 +762,12 @@ static void list_disabled(void) #ifdef OPENSSL_NO_SEED BIO_puts(bio_out, "SEED\n"); #endif +#ifdef OPENSSL_NO_SM3 + BIO_puts(bio_out, "SM3\n"); +#endif +#ifdef OPENSSL_NO_SM4 + BIO_puts(bio_out, "SM4\n"); +#endif #ifdef OPENSSL_NO_SOCK BIO_puts(bio_out, "SOCK\n"); #endif @@ -686,18 +799,25 @@ static void list_disabled(void) static LHASH_OF(FUNCTION) *prog_init(void) { - LHASH_OF(FUNCTION) *ret; + static LHASH_OF(FUNCTION) *ret = NULL; + static int prog_inited = 0; FUNCTION *f; size_t i; + if (prog_inited) + return ret; + + prog_inited = 1; + /* Sort alphabetically within category. For nicer help displays. */ - for (i = 0, f = functions; f->name != NULL; ++f, ++i) ; + for (i = 0, f = functions; f->name != NULL; ++f, ++i) + ; qsort(functions, i, sizeof(*functions), SortFnByName); if ((ret = lh_FUNCTION_new(function_hash, function_cmp)) == NULL) - return (NULL); + return NULL; for (f = functions; f->name != NULL; f++) (void)lh_FUNCTION_insert(ret, f); - return (ret); + return ret; } diff --git a/apps/openssl.cnf b/apps/openssl.cnf index b3e7444e..32ee9e9f 100644 --- a/apps/openssl.cnf +++ b/apps/openssl.cnf @@ -344,3 +344,5 @@ tsa_name = yes # Must the TSA name be included in the reply? # (optional, default: no) ess_cert_id_chain = no # Must the ESS cert id chain be included? # (optional, default: no) +ess_cert_id_alg = sha1 # algorithm to compute certificate + # identifier (optional, default: sha1) diff --git a/apps/opt.c b/apps/opt.c index 6e40f648..a9d163a4 100644 --- a/apps/opt.c +++ b/apps/opt.c @@ -1,13 +1,11 @@ /* - * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2018 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 */ - -/* #define COMPILE_STANDALONE_TEST_DRIVER */ #include "apps.h" #include #if !defined(OPENSSL_SYS_MSDOS) @@ -183,10 +181,10 @@ int opt_format_error(const char *s, unsigned long flags) { OPT_PAIR *ap; - if (flags == OPT_FMT_PEMDER) + if (flags == OPT_FMT_PEMDER) { BIO_printf(bio_err, "%s: Bad format \"%s\"; must be pem or der\n", prog, s); - else { + } else { BIO_printf(bio_err, "%s: Bad format \"%s\"; must be one of:\n", prog, s); for (ap = formats; ap->name; ap++) @@ -266,8 +264,9 @@ int opt_format(const char *s, unsigned long flags, int *result) if ((flags & OPT_FMT_PKCS12) == 0) return opt_format_error(s, flags); *result = FORMAT_PKCS12; - } else + } else { return 0; + } break; } return 1; @@ -277,9 +276,9 @@ int opt_format(const char *s, unsigned long flags, int *result) int opt_cipher(const char *name, const EVP_CIPHER **cipherp) { *cipherp = EVP_get_cipherbyname(name); - if (*cipherp) + if (*cipherp != NULL) return 1; - BIO_printf(bio_err, "%s: Unknown cipher %s\n", prog, name); + BIO_printf(bio_err, "%s: Unrecognized flag %s\n", prog, name); return 0; } @@ -289,9 +288,9 @@ int opt_cipher(const char *name, const EVP_CIPHER **cipherp) int opt_md(const char *name, const EVP_MD **mdp) { *mdp = EVP_get_digestbyname(name); - if (*mdp) + if (*mdp != NULL) return 1; - BIO_printf(bio_err, "%s: Unknown digest %s\n", prog, name); + BIO_printf(bio_err, "%s: Unrecognized flag %s\n", prog, name); return 0; } @@ -327,6 +326,30 @@ int opt_int(const char *value, int *result) return 1; } +static void opt_number_error(const char *v) +{ + size_t i = 0; + struct strstr_pair_st { + char *prefix; + char *name; + } b[] = { + {"0x", "a hexadecimal"}, + {"0X", "a hexadecimal"}, + {"0", "an octal"} + }; + + for (i = 0; i < OSSL_NELEM(b); i++) { + if (strncmp(v, b[i].prefix, strlen(b[i].prefix)) == 0) { + BIO_printf(bio_err, + "%s: Can't parse \"%s\" as %s number\n", + prog, v, b[i].name); + return; + } + } + BIO_printf(bio_err, "%s: Can't parse \"%s\" as a number\n", prog, v); + return; +} + /* Parse a long, put it into *result; return 0 on failure, else 1. */ int opt_long(const char *value, long *result) { @@ -340,8 +363,7 @@ int opt_long(const char *value, long *result) || endp == value || ((l == LONG_MAX || l == LONG_MIN) && errno == ERANGE) || (l == 0 && errno != 0)) { - BIO_printf(bio_err, "%s: Can't parse \"%s\" as a number\n", - prog, value); + opt_number_error(value); errno = oerrno; return 0; } @@ -366,8 +388,7 @@ int opt_imax(const char *value, intmax_t *result) || endp == value || ((m == INTMAX_MAX || m == INTMAX_MIN) && errno == ERANGE) || (m == 0 && errno != 0)) { - BIO_printf(bio_err, "%s: Can't parse \"%s\" as a number\n", - prog, value); + opt_number_error(value); errno = oerrno; return 0; } @@ -389,8 +410,7 @@ int opt_umax(const char *value, uintmax_t *result) || endp == value || (m == UINTMAX_MAX && errno == ERANGE) || (m == 0 && errno != 0)) { - BIO_printf(bio_err, "%s: Can't parse \"%s\" as a number\n", - prog, value); + opt_number_error(value); errno = oerrno; return 0; } @@ -415,8 +435,7 @@ int opt_ulong(const char *value, unsigned long *result) || endptr == value || ((l == ULONG_MAX) && errno == ERANGE) || (l == 0 && errno != 0)) { - BIO_printf(bio_err, "%s: Can't parse \"%s\" as an unsigned number\n", - prog, value); + opt_number_error(value); errno = oerrno; return 0; } @@ -888,90 +907,3 @@ void opt_help(const OPTIONS *list) BIO_printf(bio_err, "%s %s\n", start, help); } } - -#ifdef COMPILE_STANDALONE_TEST_DRIVER -# include - -typedef enum OPTION_choice { - OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, - OPT_IN, OPT_INFORM, OPT_OUT, OPT_COUNT, OPT_U, OPT_FLAG, - OPT_STR, OPT_NOTUSED -} OPTION_CHOICE; - -static OPTIONS options[] = { - {OPT_HELP_STR, 1, '-', "Usage: %s flags\n"}, - {OPT_HELP_STR, 1, '-', "Valid options are:\n"}, - {"help", OPT_HELP, '-', "Display this summary"}, - {"in", OPT_IN, '<', "input file"}, - {OPT_MORE_STR, 1, '-', "more detail about input"}, - {"inform", OPT_INFORM, 'f', "input file format; defaults to pem"}, - {"out", OPT_OUT, '>', "output file"}, - {"count", OPT_COUNT, 'p', "a counter greater than zero"}, - {"u", OPT_U, 'u', "an unsigned number"}, - {"flag", OPT_FLAG, 0, "just some flag"}, - {"str", OPT_STR, 's', "the magic word"}, - {"areallyverylongoption", OPT_HELP, '-', "long way for help"}, - {NULL} -}; - -BIO *bio_err; - -int app_isdir(const char *name) -{ - struct stat sb; - - return name != NULL && stat(name, &sb) >= 0 && S_ISDIR(sb.st_mode); -} - -int main(int ac, char **av) -{ - OPTION_CHOICE o; - char **rest; - char *prog; - - bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT); - - prog = opt_init(ac, av, options); - while ((o = opt_next()) != OPT_EOF) { - switch (c) { - case OPT_NOTUSED: - case OPT_EOF: - case OPT_ERR: - printf("%s: Usage error; try -help.\n", prog); - return 1; - case OPT_HELP: - opt_help(options); - return 0; - case OPT_IN: - printf("in %s\n", opt_arg()); - break; - case OPT_INFORM: - printf("inform %s\n", opt_arg()); - break; - case OPT_OUT: - printf("out %s\n", opt_arg()); - break; - case OPT_COUNT: - printf("count %s\n", opt_arg()); - break; - case OPT_U: - printf("u %s\n", opt_arg()); - break; - case OPT_FLAG: - printf("flag\n"); - break; - case OPT_STR: - printf("str %s\n", opt_arg()); - break; - } - } - argc = opt_num_rest(); - argv = opt_rest(); - - printf("args = %d\n", argc); - if (argc) - while (*argv) - printf(" %s\n", *argv++); - return 0; -} -#endif diff --git a/apps/passwd.c b/apps/passwd.c index f2b0d9a2..aa516c87 100644 --- a/apps/passwd.c +++ b/apps/passwd.c @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-2018 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 @@ -7,26 +7,20 @@ * https://www.openssl.org/source/license.html */ -#if defined OPENSSL_NO_MD5 || defined CHARSET_EBCDIC -# define NO_MD5CRYPT_1 +#include + +#include "apps.h" +#include "progs.h" + +#include +#include +#include +#include +#ifndef OPENSSL_NO_DES +# include #endif - -#if !defined(OPENSSL_NO_DES) || !defined(NO_MD5CRYPT_1) - -# include - -# include "apps.h" - -# include -# include -# include -# include -# ifndef OPENSSL_NO_DES -# include -# endif -# ifndef NO_MD5CRYPT_1 -# include -# endif +#include +#include static unsigned const char cov_2char[64] = { /* from crypto/des/fcrypt.c */ @@ -40,19 +34,31 @@ static unsigned const char cov_2char[64] = { 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A }; +static const char ascii_dollar[] = { 0x24, 0x00 }; + +typedef enum { + passwd_unset = 0, + passwd_crypt, + passwd_md5, + passwd_apr1, + passwd_sha256, + passwd_sha512, + passwd_aixmd5 +} passwd_modes; + 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); + int reverse, size_t pw_maxlen, passwd_modes mode); typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_IN, OPT_NOVERIFY, OPT_QUIET, OPT_TABLE, OPT_REVERSE, OPT_APR1, - OPT_1, OPT_CRYPT, OPT_SALT, OPT_STDIN + OPT_1, OPT_5, OPT_6, OPT_CRYPT, OPT_AIXMD5, OPT_SALT, OPT_STDIN, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS passwd_options[] = { +const OPTIONS passwd_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Read passwords from file"}, {"noverify", OPT_NOVERIFY, '-', @@ -62,13 +68,15 @@ OPTIONS passwd_options[] = { {"reverse", OPT_REVERSE, '-', "Switch table columns"}, {"salt", OPT_SALT, 's', "Use provided salt"}, {"stdin", OPT_STDIN, '-', "Read passwords from stdin"}, -# ifndef NO_MD5CRYPT_1 + {"6", OPT_6, '-', "SHA512-based password algorithm"}, + {"5", OPT_5, '-', "SHA256-based password algorithm"}, {"apr1", OPT_APR1, '-', "MD5-based password algorithm, Apache variant"}, {"1", OPT_1, '-', "MD5-based password algorithm"}, -# endif -# ifndef OPENSSL_NO_DES + {"aixmd5", OPT_AIXMD5, '-', "AIX MD5-based password algorithm"}, +#ifndef OPENSSL_NO_DES {"crypt", OPT_CRYPT, '-', "Standard Unix password algorithm (default)"}, -# endif +#endif + OPT_R_OPTIONS, {NULL} }; @@ -79,12 +87,15 @@ int passwd_main(int argc, char **argv) char *salt_malloc = NULL, *passwd_malloc = NULL, *prog; OPTION_CHOICE o; int in_stdin = 0, pw_source_defined = 0; -# ifndef OPENSSL_NO_UI +#ifndef OPENSSL_NO_UI_CONSOLE int in_noverify = 0; -# endif +#endif int passed_salt = 0, quiet = 0, table = 0, reverse = 0; - int ret = 1, usecrypt = 0, use1 = 0, useapr1 = 0; - size_t passwd_malloc_size = 0, pw_maxlen = 256; + int ret = 1; + passwd_modes mode = passwd_unset; + size_t passwd_malloc_size = 0; + size_t pw_maxlen = 256; /* arbitrary limit, should be enough for most + * passwords */ prog = opt_init(argc, argv, passwd_options); while ((o = opt_next()) != OPT_EOF) { @@ -105,9 +116,9 @@ int passwd_main(int argc, char **argv) pw_source_defined = 1; break; case OPT_NOVERIFY: -# ifndef OPENSSL_NO_UI +#ifndef OPENSSL_NO_UI_CONSOLE in_noverify = 1; -# endif +#endif break; case OPT_QUIET: quiet = 1; @@ -119,13 +130,36 @@ int passwd_main(int argc, char **argv) reverse = 1; break; case OPT_1: - use1 = 1; + if (mode != passwd_unset) + goto opthelp; + mode = passwd_md5; + break; + case OPT_5: + if (mode != passwd_unset) + goto opthelp; + mode = passwd_sha256; + break; + case OPT_6: + if (mode != passwd_unset) + goto opthelp; + mode = passwd_sha512; break; case OPT_APR1: - useapr1 = 1; + if (mode != passwd_unset) + goto opthelp; + mode = passwd_apr1; + break; + case OPT_AIXMD5: + if (mode != passwd_unset) + goto opthelp; + mode = passwd_aixmd5; break; case OPT_CRYPT: - usecrypt = 1; +#ifndef OPENSSL_NO_DES + if (mode != passwd_unset) + goto opthelp; + mode = passwd_crypt; +#endif break; case OPT_SALT: passed_salt = 1; @@ -137,35 +171,31 @@ int passwd_main(int argc, char **argv) in_stdin = 1; pw_source_defined = 1; break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; } } argc = opt_num_rest(); argv = opt_rest(); - if (*argv) { + if (*argv != NULL) { if (pw_source_defined) goto opthelp; pw_source_defined = 1; passwds = argv; } - if (!usecrypt && !use1 && !useapr1) { + if (mode == passwd_unset) { /* use default */ - usecrypt = 1; - } - if (usecrypt + use1 + useapr1 > 1) { - /* conflict */ - goto opthelp; + mode = passwd_crypt; } -# ifdef OPENSSL_NO_DES - if (usecrypt) +#ifdef OPENSSL_NO_DES + if (mode == passwd_crypt) goto opthelp; -# endif -# ifdef NO_MD5CRYPT_1 - if (use1 || useapr1) - goto opthelp; -# endif +#endif if (infile != NULL && in_stdin) { BIO_printf(bio_err, "%s: Can't combine -in and -stdin\n", prog); @@ -182,11 +212,8 @@ int passwd_main(int argc, char **argv) goto end; } - if (usecrypt) + if (mode == passwd_crypt) 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 */ @@ -204,7 +231,7 @@ int passwd_main(int argc, char **argv) * avoid rot of not-frequently-used code. */ if (1) { -# ifndef OPENSSL_NO_UI +#ifndef OPENSSL_NO_UI_CONSOLE /* build a null-terminated list */ static char *passwds_static[2] = { NULL, NULL }; @@ -217,7 +244,7 @@ int passwd_main(int argc, char **argv) } passwds[0] = passwd_malloc; } else { -# endif +#endif BIO_printf(bio_err, "password required\n"); goto end; } @@ -230,8 +257,7 @@ int passwd_main(int argc, char **argv) do { /* loop over list of passwords */ passwd = *passwds++; if (!do_passwd(passed_salt, &salt, &salt_malloc, passwd, bio_out, - quiet, table, reverse, pw_maxlen, usecrypt, use1, - useapr1)) + quiet, table, reverse, pw_maxlen, mode)) goto end; } while (*passwds != NULL); } else { @@ -255,7 +281,7 @@ int passwd_main(int argc, char **argv) if (!do_passwd (passed_salt, &salt, &salt_malloc, passwd, bio_out, quiet, - table, reverse, pw_maxlen, usecrypt, use1, useapr1)) + table, reverse, pw_maxlen, mode)) goto end; } done = (r <= 0); @@ -264,14 +290,15 @@ int passwd_main(int argc, char **argv) ret = 0; end: +#if 0 ERR_print_errors(bio_err); +#endif OPENSSL_free(salt_malloc); OPENSSL_free(passwd_malloc); BIO_free(in); - return (ret); + return 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 @@ -286,6 +313,9 @@ 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 ascii_magic[5]; /* "apr1" plus '\0' */ + char ascii_salt[9]; /* Max 8 chars plus '\0' */ + char *ascii_passwd = NULL; char *salt_out; int n; unsigned int i; @@ -293,41 +323,72 @@ static char *md5crypt(const char *passwd, const char *magic, const char *salt) size_t passwd_len, salt_len, magic_len; passwd_len = strlen(passwd); - out_buf[0] = '$'; - out_buf[1] = 0; + + out_buf[0] = 0; magic_len = strlen(magic); + OPENSSL_strlcpy(ascii_magic, magic, sizeof(ascii_magic)); +#ifdef CHARSET_EBCDIC + if ((magic[0] & 0x80) != 0) /* High bit is 1 in EBCDIC alnums */ + ebcdic2ascii(ascii_magic, ascii_magic, magic_len); +#endif - if (magic_len > 4) /* assert it's "1" or "apr1" */ + /* The salt gets truncated to 8 chars */ + OPENSSL_strlcpy(ascii_salt, salt, sizeof(ascii_salt)); + salt_len = strlen(ascii_salt); +#ifdef CHARSET_EBCDIC + ebcdic2ascii(ascii_salt, ascii_salt, salt_len); +#endif + +#ifdef CHARSET_EBCDIC + ascii_passwd = OPENSSL_strdup(passwd); + if (ascii_passwd == NULL) return NULL; + ebcdic2ascii(ascii_passwd, ascii_passwd, passwd_len); + passwd = ascii_passwd; +#endif - OPENSSL_strlcat(out_buf, magic, sizeof(out_buf)); - OPENSSL_strlcat(out_buf, "$", sizeof(out_buf)); - OPENSSL_strlcat(out_buf, salt, sizeof(out_buf)); + if (magic_len > 0) { + OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); + + if (magic_len > 4) /* assert it's "1" or "apr1" */ + goto err; + + OPENSSL_strlcat(out_buf, ascii_magic, sizeof(out_buf)); + OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); + } + + OPENSSL_strlcat(out_buf, ascii_salt, sizeof(out_buf)); if (strlen(out_buf) > 6 + 8) /* assert "$apr1$..salt.." */ - return NULL; + goto err; - salt_out = out_buf + 2 + magic_len; - salt_len = strlen(salt_out); + salt_out = out_buf; + if (magic_len > 0) + salt_out += 2 + magic_len; if (salt_len > 8) - return NULL; + goto err; md = EVP_MD_CTX_new(); if (md == NULL || !EVP_DigestInit_ex(md, EVP_md5(), NULL) - || !EVP_DigestUpdate(md, passwd, passwd_len) - || !EVP_DigestUpdate(md, "$", 1) - || !EVP_DigestUpdate(md, magic, magic_len) - || !EVP_DigestUpdate(md, "$", 1) - || !EVP_DigestUpdate(md, salt_out, salt_len)) + || !EVP_DigestUpdate(md, passwd, passwd_len)) + goto err; + + if (magic_len > 0) + if (!EVP_DigestUpdate(md, ascii_dollar, 1) + || !EVP_DigestUpdate(md, ascii_magic, magic_len) + || !EVP_DigestUpdate(md, ascii_dollar, 1)) + goto err; + + if (!EVP_DigestUpdate(md, ascii_salt, salt_len)) goto err; md2 = EVP_MD_CTX_new(); if (md2 == NULL || !EVP_DigestInit_ex(md2, EVP_md5(), NULL) || !EVP_DigestUpdate(md2, passwd, passwd_len) - || !EVP_DigestUpdate(md2, salt_out, salt_len) + || !EVP_DigestUpdate(md2, ascii_salt, salt_len) || !EVP_DigestUpdate(md2, passwd, passwd_len) || !EVP_DigestFinal_ex(md2, buf, NULL)) goto err; @@ -356,7 +417,7 @@ static char *md5crypt(const char *passwd, const char *magic, const char *salt) (i & 1) ? passwd_len : sizeof(buf))) goto err; if (i % 3) { - if (!EVP_DigestUpdate(md2, salt_out, salt_len)) + if (!EVP_DigestUpdate(md2, ascii_salt, salt_len)) goto err; } if (i % 7) { @@ -387,15 +448,15 @@ static char *md5crypt(const char *passwd, const char *magic, const char *salt) buf_perm[dest] = buf[source]; buf_perm[14] = buf[5]; buf_perm[15] = buf[11]; -# ifndef PEDANTIC /* Unfortunately, this generates a "no +# ifndef PEDANTIC /* Unfortunately, this generates a "no * effect" warning */ assert(16 == sizeof(buf_perm)); -# endif +# endif output = salt_out + salt_len; assert(output == out_buf + strlen(out_buf)); - *output++ = '$'; + *output++ = ascii_dollar[0]; for (i = 0; i < 15; i += 3) { *output++ = cov_2char[buf_perm[i + 2] & 0x3f]; @@ -410,21 +471,309 @@ static char *md5crypt(const char *passwd, const char *magic, const char *salt) *output++ = cov_2char[buf_perm[i] >> 6]; *output = 0; assert(strlen(out_buf) < sizeof(out_buf)); +#ifdef CHARSET_EBCDIC + ascii2ebcdic(out_buf, out_buf, strlen(out_buf)); +#endif } return out_buf; + err: + OPENSSL_free(ascii_passwd); + EVP_MD_CTX_free(md2); + EVP_MD_CTX_free(md); + return NULL; +} + +/* + * SHA based password algorithm, describe by Ulrich Drepper here: + * https://www.akkadia.org/drepper/SHA-crypt.txt + * (note that it's in the public domain) + */ +static char *shacrypt(const char *passwd, const char *magic, const char *salt) +{ + /* Prefix for optional rounds specification. */ + static const char rounds_prefix[] = "rounds="; + /* Maximum salt string length. */ +# define SALT_LEN_MAX 16 + /* Default number of rounds if not explicitly specified. */ +# define ROUNDS_DEFAULT 5000 + /* Minimum number of rounds. */ +# define ROUNDS_MIN 1000 + /* Maximum number of rounds. */ +# define ROUNDS_MAX 999999999 + + /* "$6$rounds=$......salt......$...shahash(up to 86 chars)...\0" */ + static char out_buf[3 + 17 + 17 + 86 + 1]; + unsigned char buf[SHA512_DIGEST_LENGTH]; + unsigned char temp_buf[SHA512_DIGEST_LENGTH]; + size_t buf_size = 0; + char ascii_magic[2]; + char ascii_salt[17]; /* Max 16 chars plus '\0' */ + char *ascii_passwd = NULL; + size_t n; + EVP_MD_CTX *md = NULL, *md2 = NULL; + const EVP_MD *sha = NULL; + size_t passwd_len, salt_len, magic_len; + unsigned int rounds = 5000; /* Default */ + char rounds_custom = 0; + char *p_bytes = NULL; + char *s_bytes = NULL; + char *cp = NULL; + + passwd_len = strlen(passwd); + magic_len = strlen(magic); + + /* assert it's "5" or "6" */ + if (magic_len != 1) + return NULL; + + switch (magic[0]) { + case '5': + sha = EVP_sha256(); + buf_size = 32; + break; + case '6': + sha = EVP_sha512(); + buf_size = 64; + break; + default: + return NULL; + } + + if (strncmp(salt, rounds_prefix, sizeof(rounds_prefix) - 1) == 0) { + const char *num = salt + sizeof(rounds_prefix) - 1; + char *endp; + unsigned long int srounds = strtoul (num, &endp, 10); + if (*endp == '$') { + salt = endp + 1; + if (srounds > ROUNDS_MAX) + rounds = ROUNDS_MAX; + else if (srounds < ROUNDS_MIN) + rounds = ROUNDS_MIN; + else + rounds = (unsigned int)srounds; + rounds_custom = 1; + } else { + return NULL; + } + } + + OPENSSL_strlcpy(ascii_magic, magic, sizeof(ascii_magic)); +#ifdef CHARSET_EBCDIC + if ((magic[0] & 0x80) != 0) /* High bit is 1 in EBCDIC alnums */ + ebcdic2ascii(ascii_magic, ascii_magic, magic_len); +#endif + + /* The salt gets truncated to 16 chars */ + OPENSSL_strlcpy(ascii_salt, salt, sizeof(ascii_salt)); + salt_len = strlen(ascii_salt); +#ifdef CHARSET_EBCDIC + ebcdic2ascii(ascii_salt, ascii_salt, salt_len); +#endif + +#ifdef CHARSET_EBCDIC + ascii_passwd = OPENSSL_strdup(passwd); + if (ascii_passwd == NULL) + return NULL; + ebcdic2ascii(ascii_passwd, ascii_passwd, passwd_len); + passwd = ascii_passwd; +#endif + + out_buf[0] = 0; + OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); + OPENSSL_strlcat(out_buf, ascii_magic, sizeof(out_buf)); + OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); + if (rounds_custom) { + char tmp_buf[80]; /* "rounds=999999999" */ + sprintf(tmp_buf, "rounds=%u", rounds); +#ifdef CHARSET_EBCDIC + /* In case we're really on a ASCII based platform and just pretend */ + if (tmp_buf[0] != 0x72) /* ASCII 'r' */ + ebcdic2ascii(tmp_buf, tmp_buf, strlen(tmp_buf)); +#endif + OPENSSL_strlcat(out_buf, tmp_buf, sizeof(out_buf)); + OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); + } + OPENSSL_strlcat(out_buf, ascii_salt, sizeof(out_buf)); + + /* assert "$5$rounds=999999999$......salt......" */ + if (strlen(out_buf) > 3 + 17 * rounds_custom + salt_len ) + goto err; + + md = EVP_MD_CTX_new(); + if (md == NULL + || !EVP_DigestInit_ex(md, sha, NULL) + || !EVP_DigestUpdate(md, passwd, passwd_len) + || !EVP_DigestUpdate(md, ascii_salt, salt_len)) + goto err; + + md2 = EVP_MD_CTX_new(); + if (md2 == NULL + || !EVP_DigestInit_ex(md2, sha, NULL) + || !EVP_DigestUpdate(md2, passwd, passwd_len) + || !EVP_DigestUpdate(md2, ascii_salt, salt_len) + || !EVP_DigestUpdate(md2, passwd, passwd_len) + || !EVP_DigestFinal_ex(md2, buf, NULL)) + goto err; + + for (n = passwd_len; n > buf_size; n -= buf_size) { + if (!EVP_DigestUpdate(md, buf, buf_size)) + goto err; + } + if (!EVP_DigestUpdate(md, buf, n)) + goto err; + + n = passwd_len; + while (n) { + if (!EVP_DigestUpdate(md, + (n & 1) ? buf : (unsigned const char *)passwd, + (n & 1) ? buf_size : passwd_len)) + goto err; + n >>= 1; + } + if (!EVP_DigestFinal_ex(md, buf, NULL)) + return NULL; + + /* P sequence */ + if (!EVP_DigestInit_ex(md2, sha, NULL)) + goto err; + + for (n = passwd_len; n > 0; n--) + if (!EVP_DigestUpdate(md2, passwd, passwd_len)) + goto err; + + if (!EVP_DigestFinal_ex(md2, temp_buf, NULL)) + return NULL; + + if ((p_bytes = OPENSSL_zalloc(passwd_len)) == NULL) + goto err; + for (cp = p_bytes, n = passwd_len; n > buf_size; n -= buf_size, cp += buf_size) + memcpy(cp, temp_buf, buf_size); + memcpy(cp, temp_buf, n); + + /* S sequence */ + if (!EVP_DigestInit_ex(md2, sha, NULL)) + goto err; + + for (n = 16 + buf[0]; n > 0; n--) + if (!EVP_DigestUpdate(md2, ascii_salt, salt_len)) + goto err; + + if (!EVP_DigestFinal_ex(md2, temp_buf, NULL)) + return NULL; + + if ((s_bytes = OPENSSL_zalloc(salt_len)) == NULL) + goto err; + for (cp = s_bytes, n = salt_len; n > buf_size; n -= buf_size, cp += buf_size) + memcpy(cp, temp_buf, buf_size); + memcpy(cp, temp_buf, n); + + for (n = 0; n < rounds; n++) { + if (!EVP_DigestInit_ex(md2, sha, NULL)) + goto err; + if (!EVP_DigestUpdate(md2, + (n & 1) ? (unsigned const char *)p_bytes : buf, + (n & 1) ? passwd_len : buf_size)) + goto err; + if (n % 3) { + if (!EVP_DigestUpdate(md2, s_bytes, salt_len)) + goto err; + } + if (n % 7) { + if (!EVP_DigestUpdate(md2, p_bytes, passwd_len)) + goto err; + } + if (!EVP_DigestUpdate(md2, + (n & 1) ? buf : (unsigned const char *)p_bytes, + (n & 1) ? buf_size : passwd_len)) + goto err; + if (!EVP_DigestFinal_ex(md2, buf, NULL)) + goto err; + } + EVP_MD_CTX_free(md2); + EVP_MD_CTX_free(md); + md2 = NULL; + md = NULL; + OPENSSL_free(p_bytes); + OPENSSL_free(s_bytes); + p_bytes = NULL; + s_bytes = NULL; + + cp = out_buf + strlen(out_buf); + *cp++ = ascii_dollar[0]; + +# define b64_from_24bit(B2, B1, B0, N) \ + do { \ + unsigned int w = ((B2) << 16) | ((B1) << 8) | (B0); \ + int i = (N); \ + while (i-- > 0) \ + { \ + *cp++ = cov_2char[w & 0x3f]; \ + w >>= 6; \ + } \ + } while (0) + + switch (magic[0]) { + case '5': + b64_from_24bit (buf[0], buf[10], buf[20], 4); + b64_from_24bit (buf[21], buf[1], buf[11], 4); + b64_from_24bit (buf[12], buf[22], buf[2], 4); + b64_from_24bit (buf[3], buf[13], buf[23], 4); + b64_from_24bit (buf[24], buf[4], buf[14], 4); + b64_from_24bit (buf[15], buf[25], buf[5], 4); + b64_from_24bit (buf[6], buf[16], buf[26], 4); + b64_from_24bit (buf[27], buf[7], buf[17], 4); + b64_from_24bit (buf[18], buf[28], buf[8], 4); + b64_from_24bit (buf[9], buf[19], buf[29], 4); + b64_from_24bit (0, buf[31], buf[30], 3); + break; + case '6': + b64_from_24bit (buf[0], buf[21], buf[42], 4); + b64_from_24bit (buf[22], buf[43], buf[1], 4); + b64_from_24bit (buf[44], buf[2], buf[23], 4); + b64_from_24bit (buf[3], buf[24], buf[45], 4); + b64_from_24bit (buf[25], buf[46], buf[4], 4); + b64_from_24bit (buf[47], buf[5], buf[26], 4); + b64_from_24bit (buf[6], buf[27], buf[48], 4); + b64_from_24bit (buf[28], buf[49], buf[7], 4); + b64_from_24bit (buf[50], buf[8], buf[29], 4); + b64_from_24bit (buf[9], buf[30], buf[51], 4); + b64_from_24bit (buf[31], buf[52], buf[10], 4); + b64_from_24bit (buf[53], buf[11], buf[32], 4); + b64_from_24bit (buf[12], buf[33], buf[54], 4); + b64_from_24bit (buf[34], buf[55], buf[13], 4); + b64_from_24bit (buf[56], buf[14], buf[35], 4); + b64_from_24bit (buf[15], buf[36], buf[57], 4); + b64_from_24bit (buf[37], buf[58], buf[16], 4); + b64_from_24bit (buf[59], buf[17], buf[38], 4); + b64_from_24bit (buf[18], buf[39], buf[60], 4); + b64_from_24bit (buf[40], buf[61], buf[19], 4); + b64_from_24bit (buf[62], buf[20], buf[41], 4); + b64_from_24bit (0, 0, buf[63], 2); + break; + default: + goto err; + } + *cp = '\0'; +#ifdef CHARSET_EBCDIC + ascii2ebcdic(out_buf, out_buf, strlen(out_buf)); +#endif + + return out_buf; + err: EVP_MD_CTX_free(md2); EVP_MD_CTX_free(md); + OPENSSL_free(p_bytes); + OPENSSL_free(s_bytes); + OPENSSL_free(ascii_passwd); return NULL; } -# 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) + int reverse, size_t pw_maxlen, passwd_modes mode) { char *hash = NULL; @@ -433,36 +782,34 @@ static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p, /* 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 = app_malloc(3, "salt buffer"); - if (RAND_bytes((unsigned char *)*salt_p, 2) <= 0) - goto end; - (*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 */ + size_t saltlen = 0; + size_t i; -# ifndef NO_MD5CRYPT_1 - if (use1 || useapr1) { - int i; +#ifndef OPENSSL_NO_DES + if (mode == passwd_crypt) + saltlen = 2; +#endif /* !OPENSSL_NO_DES */ - if (*salt_malloc_p == NULL) - *salt_p = *salt_malloc_p = app_malloc(9, "salt buffer"); - if (RAND_bytes((unsigned char *)*salt_p, 8) <= 0) - goto end; + if (mode == passwd_md5 || mode == passwd_apr1 || mode == passwd_aixmd5) + saltlen = 8; - 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 */ + if (mode == passwd_sha256 || mode == passwd_sha512) + saltlen = 16; + + assert(saltlen != 0); + + if (*salt_malloc_p == NULL) + *salt_p = *salt_malloc_p = app_malloc(saltlen + 1, "salt buffer"); + if (RAND_bytes((unsigned char *)*salt_p, saltlen) <= 0) + goto end; + + for (i = 0; i < saltlen; i++) + (*salt_p)[i] = cov_2char[(*salt_p)[i] & 0x3f]; /* 6 bits */ + (*salt_p)[i] = 0; +# ifdef CHARSET_EBCDIC + /* The password encryption funtion will convert back to ASCII */ + ascii2ebcdic(*salt_p, *salt_p, saltlen); +# endif } assert(*salt_p != NULL); @@ -481,14 +828,16 @@ static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p, assert(strlen(passwd) <= pw_maxlen); /* now compute password hash */ -# ifndef OPENSSL_NO_DES - if (usecrypt) +#ifndef OPENSSL_NO_DES + if (mode == passwd_crypt) hash = DES_crypt(passwd, *salt_p); -# endif -# ifndef NO_MD5CRYPT_1 - if (use1 || useapr1) - hash = md5crypt(passwd, (use1 ? "1" : "apr1"), *salt_p); -# endif +#endif + if (mode == passwd_md5 || mode == passwd_apr1) + hash = md5crypt(passwd, (mode == passwd_md5 ? "1" : "apr1"), *salt_p); + if (mode == passwd_aixmd5) + hash = md5crypt(passwd, "", *salt_p); + if (mode == passwd_sha256 || mode == passwd_sha512) + hash = shacrypt(passwd, (mode == passwd_sha256 ? "5" : "6"), *salt_p); assert(hash != NULL); if (table && !reverse) @@ -502,11 +851,3 @@ static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p, end: return 0; } -#else - -int passwd_main(int argc, char **argv) -{ - BIO_printf(bio_err, "Program not available.\n"); - return (1); -} -#endif diff --git a/apps/pkcs12.c b/apps/pkcs12.c index 85f649d8..c8fc452e 100644 --- a/apps/pkcs12.c +++ b/apps/pkcs12.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-2018 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 @@ -16,6 +16,7 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # include # include # include @@ -27,6 +28,8 @@ NON_EMPTY_TRANSLATION_UNIT # define CLCERTS 0x8 # define CACERTS 0x10 +#define PASSWD_BUF_SIZE 2048 + static int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) **chain); int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, @@ -51,12 +54,13 @@ typedef enum OPTION_choice { OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER, OPT_DESCERT, OPT_EXPORT, OPT_NOITER, OPT_MACITER, OPT_NOMACITER, OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE, - OPT_RAND, OPT_INKEY, OPT_CERTFILE, OPT_NAME, OPT_CSP, OPT_CANAME, + OPT_INKEY, OPT_CERTFILE, OPT_NAME, OPT_CSP, OPT_CANAME, OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH, - OPT_CAFILE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_ENGINE + OPT_CAFILE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_ENGINE, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS pkcs12_options[] = { +const OPTIONS pkcs12_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"}, {"keyex", OPT_KEYEX, '-', "Set MS key exchange type"}, @@ -89,8 +93,7 @@ OPTIONS pkcs12_options[] = { {"macalg", OPT_MACALG, 's', "Digest algorithm used in MAC (default SHA1)"}, {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default 3DES)"}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, + OPT_R_OPTIONS, {"inkey", OPT_INKEY, 's', "Private key if not infile"}, {"certfile", OPT_CERTFILE, '<', "Load certs from file"}, {"name", OPT_NAME, 's', "Use name as friendly name"}, @@ -119,7 +122,7 @@ int pkcs12_main(int argc, char **argv) { char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL; char *name = NULL, *csp_name = NULL; - char pass[2048] = "", macpass[2048] = ""; + char pass[PASSWD_BUF_SIZE] = "", macpass[PASSWD_BUF_SIZE] = ""; int export_cert = 0, options = 0, chain = 0, twopass = 0, keytype = 0; int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER; # ifndef OPENSSL_NO_RC2 @@ -131,7 +134,7 @@ int pkcs12_main(int argc, char **argv) int ret = 1, macver = 1, add_lmk = 0, private = 0; int noprompt = 0; char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL; - char *passin = NULL, *passout = NULL, *inrand = NULL, *macalg = NULL; + char *passin = NULL, *passout = NULL, *macalg = NULL; char *cpass = NULL, *mpass = NULL, *badpass = NULL; const char *CApath = NULL, *CAfile = NULL, *prog; int noCApath = 0, noCAfile = 0; @@ -223,8 +226,9 @@ int pkcs12_main(int argc, char **argv) if (!set_pbe(&key_pbe, opt_arg())) goto opthelp; break; - case OPT_RAND: - inrand = opt_arg(); + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_INKEY: keyname = opt_arg(); @@ -285,7 +289,7 @@ int pkcs12_main(int argc, char **argv) private = 1; - if (passarg) { + if (passarg != NULL) { if (export_cert) passoutarg = passarg; else @@ -297,14 +301,14 @@ int pkcs12_main(int argc, char **argv) goto end; } - if (!cpass) { + if (cpass == NULL) { if (export_cert) cpass = passout; else cpass = passin; } - if (cpass) { + if (cpass != NULL) { mpass = cpass; noprompt = 1; } else { @@ -312,18 +316,12 @@ int pkcs12_main(int argc, char **argv) mpass = macpass; } - if (export_cert || inrand) { - app_RAND_load_file(NULL, (inrand != NULL)); - if (inrand != NULL) - BIO_printf(bio_err, "%ld semi-random bytes loaded\n", - app_RAND_load_files(inrand)); - } - if (twopass) { + /* To avoid bit rot */ if (1) { -#ifndef OPENSSL_NO_UI - if (EVP_read_pw_string - (macpass, sizeof(macpass), "Enter MAC Password:", export_cert)) { +#ifndef OPENSSL_NO_UI_CONSOLE + if (EVP_read_pw_string( + macpass, sizeof(macpass), "Enter MAC Password:", export_cert)) { BIO_printf(bio_err, "Can't read Password\n"); goto end; } @@ -353,7 +351,7 @@ int pkcs12_main(int argc, char **argv) if (!(options & NOKEYS)) { key = load_key(keyname ? keyname : infile, FORMAT_PEM, 1, passin, e, "private key"); - if (!key) + if (key == NULL) goto export_end; } @@ -363,7 +361,7 @@ int pkcs12_main(int argc, char **argv) "certificates")) goto export_end; - if (key) { + if (key != NULL) { /* Look for matching private key */ for (i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); @@ -377,7 +375,7 @@ int pkcs12_main(int argc, char **argv) break; } } - if (!ucert) { + if (ucert == NULL) { BIO_printf(bio_err, "No certificate matches private key\n"); goto export_end; @@ -387,7 +385,7 @@ int pkcs12_main(int argc, char **argv) } /* Add any more certificates asked for */ - if (certfile) { + if (certfile != NULL) { if (!load_certs(certfile, &certs, FORMAT_PEM, NULL, "certificates from certfile")) goto export_end; @@ -429,19 +427,20 @@ int pkcs12_main(int argc, char **argv) X509_alias_set1(sk_X509_value(certs, i), catmp, -1); } - if (csp_name && key) + if (csp_name != NULL && key != NULL) EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name, MBSTRING_ASC, (unsigned char *)csp_name, -1); - if (add_lmk && key) + if (add_lmk && key != NULL) EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1); if (!noprompt) { + /* To avoid bit rot */ if (1) { -#ifndef OPENSSL_NO_UI - if (EVP_read_pw_string(pass, sizeof(pass), "Enter Export Password:", - 1)) { +#ifndef OPENSSL_NO_UI_CONSOLE + if (EVP_read_pw_string(pass, sizeof(pass), + "Enter Export Password:", 1)) { BIO_printf(bio_err, "Can't read Password\n"); goto export_end; } @@ -505,7 +504,7 @@ int pkcs12_main(int argc, char **argv) if (!noprompt) { if (1) { -#ifndef OPENSSL_NO_UI +#ifndef OPENSSL_NO_UI_CONSOLE if (EVP_read_pw_string(pass, sizeof(pass), "Enter Import Password:", 0)) { BIO_printf(bio_err, "Can't read Password\n"); @@ -525,12 +524,20 @@ int pkcs12_main(int argc, char **argv) const ASN1_INTEGER *tmaciter; const X509_ALGOR *macalgid; const ASN1_OBJECT *macobj; - PKCS12_get0_mac(NULL, &macalgid, NULL, &tmaciter, p12); + const ASN1_OCTET_STRING *tmac; + const ASN1_OCTET_STRING *tsalt; + + PKCS12_get0_mac(&tmac, &macalgid, &tsalt, &tmaciter, p12); + /* current hash algorithms do not use parameters so extract just name, + in future alg_print() may be needed */ X509_ALGOR_get0(&macobj, NULL, NULL, macalgid); - BIO_puts(bio_err, "MAC:"); + BIO_puts(bio_err, "MAC: "); i2a_ASN1_OBJECT(bio_err, macobj); - BIO_printf(bio_err, " Iteration %ld\n", - tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L); + BIO_printf(bio_err, ", Iteration %ld\n", + tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L); + BIO_printf(bio_err, "MAC length: %ld, salt length: %ld\n", + tmac != NULL ? ASN1_STRING_length(tmac) : 0L, + tsalt != NULL ? ASN1_STRING_length(tsalt) : 0L); } if (macver) { /* If we enter empty password try no password first */ @@ -572,8 +579,6 @@ int pkcs12_main(int argc, char **argv) ret = 0; end: PKCS12_free(p12); - if (export_cert || inrand) - app_RAND_write_file(NULL); release_engine(e); BIO_free(in); BIO_free_all(out); @@ -581,7 +586,7 @@ int pkcs12_main(int argc, char **argv) OPENSSL_free(badpass); OPENSSL_free(passin); OPENSSL_free(passout); - return (ret); + return ret; } int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass, @@ -609,8 +614,9 @@ int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass, alg_print(p7->d.encrypted->enc_data->algorithm); } bags = PKCS12_unpack_p7encdata(p7, pass, passlen); - } else + } else { continue; + } if (!bags) goto err; if (!dump_certs_pkeys_bags(out, bags, pass, passlen, @@ -785,7 +791,7 @@ static int alg_print(const X509_ALGOR *alg) if (aparamtype == V_ASN1_SEQUENCE) pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM)); if (pbe2 == NULL) { - BIO_puts(bio_err, ""); + BIO_puts(bio_err, ", "); goto done; } X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc); @@ -801,7 +807,7 @@ static int alg_print(const X509_ALGOR *alg) if (aparamtype == V_ASN1_SEQUENCE) kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM)); if (kdf == NULL) { - BIO_puts(bio_err, ""); + BIO_puts(bio_err, ", "); goto done; } @@ -814,13 +820,31 @@ static int alg_print(const X509_ALGOR *alg) BIO_printf(bio_err, ", Iteration %ld, PRF %s", ASN1_INTEGER_get(kdf->iter), OBJ_nid2sn(prfnid)); PBKDF2PARAM_free(kdf); +#ifndef OPENSSL_NO_SCRYPT + } else if (pbenid == NID_id_scrypt) { + SCRYPT_PARAMS *kdf = NULL; + + if (aparamtype == V_ASN1_SEQUENCE) + kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(SCRYPT_PARAMS)); + if (kdf == NULL) { + BIO_puts(bio_err, ", "); + goto done; + } + BIO_printf(bio_err, ", Salt length: %d, Cost(N): %ld, " + "Block size(r): %ld, Paralelizm(p): %ld", + ASN1_STRING_length(kdf->salt), + ASN1_INTEGER_get(kdf->costParameter), + ASN1_INTEGER_get(kdf->blockSize), + ASN1_INTEGER_get(kdf->parallelizationParameter)); + SCRYPT_PARAMS_free(kdf); +#endif } PBE2PARAM_free(pbe2); } else { if (aparamtype == V_ASN1_SEQUENCE) pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM)); if (pbe == NULL) { - BIO_puts(bio_err, ""); + BIO_puts(bio_err, ", "); goto done; } BIO_printf(bio_err, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter)); @@ -874,8 +898,9 @@ int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst, if (attr_nid == NID_undef) { i2a_ASN1_OBJECT(out, attr_obj); BIO_printf(out, ": "); - } else + } else { BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid)); + } if (X509_ATTRIBUTE_count(attr)) { av = X509_ATTRIBUTE_get0_type(attr, 0); @@ -903,8 +928,9 @@ int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst, BIO_printf(out, "\n", av->type); break; } - } else + } else { BIO_printf(out, "\n"); + } } return 1; } diff --git a/apps/pkcs7.c b/apps/pkcs7.c index 209e30d6..c3e9f5c6 100644 --- a/apps/pkcs7.c +++ b/apps/pkcs7.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -12,6 +12,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -25,7 +26,7 @@ typedef enum OPTION_choice { OPT_TEXT, OPT_PRINT, OPT_PRINT_CERTS, OPT_ENGINE } OPTION_CHOICE; -OPTIONS pkcs7_options[] = { +const OPTIONS pkcs7_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, {"in", OPT_IN, '<', "Input file"}, @@ -163,7 +164,7 @@ int pkcs7_main(int argc, char **argv) for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); - X509_CRL_print(out, crl); + X509_CRL_print_ex(out, crl, get_nameopt()); if (!noout) PEM_write_bio_X509_CRL(out, crl); @@ -193,5 +194,5 @@ int pkcs7_main(int argc, char **argv) release_engine(e); BIO_free(in); BIO_free_all(out); - return (ret); + return ret; } diff --git a/apps/pkcs8.c b/apps/pkcs8.c index 0874370d..20553656 100644 --- a/apps/pkcs8.c +++ b/apps/pkcs8.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-2018 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 @@ -11,6 +11,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -24,10 +25,11 @@ typedef enum OPTION_choice { OPT_SCRYPT, OPT_SCRYPT_N, OPT_SCRYPT_R, OPT_SCRYPT_P, #endif OPT_V2, OPT_V1, OPT_V2PRF, OPT_ITER, OPT_PASSIN, OPT_PASSOUT, - OPT_TRADITIONAL + OPT_TRADITIONAL, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS pkcs8_options[] = { +const OPTIONS pkcs8_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'F', "Input format (DER or PEM)"}, {"outform", OPT_OUTFORM, 'F', "Output format (DER or PEM)"}, @@ -36,6 +38,7 @@ OPTIONS pkcs8_options[] = { {"topk8", OPT_TOPK8, '-', "Output PKCS8 file"}, {"noiter", OPT_NOITER, '-', "Use 1 as iteration count"}, {"nocrypt", OPT_NOCRYPT, '-', "Use or expect unencrypted private key"}, + OPT_R_OPTIONS, {"v2", OPT_V2, 's', "Use PKCS#5 v2.0 and cipher"}, {"v1", OPT_V1, 's', "Use PKCS#5 v1.5 and cipher"}, {"v2prf", OPT_V2PRF, 's', "Set the PRF algorithm to use with PKCS#5 v2.0"}, @@ -65,7 +68,7 @@ int pkcs8_main(int argc, char **argv) const EVP_CIPHER *cipher = NULL; char *infile = NULL, *outfile = NULL; char *passinarg = NULL, *passoutarg = NULL, *prog; -#ifndef OPENSSL_NO_UI +#ifndef OPENSSL_NO_UI_CONSOLE char pass[APP_PASS_LEN]; #endif char *passin = NULL, *passout = NULL, *p8pass = NULL; @@ -112,6 +115,10 @@ int pkcs8_main(int argc, char **argv) case OPT_NOCRYPT: nocrypt = 1; break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; case OPT_TRADITIONAL: traditional = 1; break; @@ -196,7 +203,7 @@ int pkcs8_main(int argc, char **argv) if (topk8) { pkey = load_key(infile, informat, 1, passin, e, "key"); - if (!pkey) + if (pkey == NULL) goto end; if ((p8inf = EVP_PKEY2PKCS8(pkey)) == NULL) { BIO_printf(bio_err, "Error converting key\n"); @@ -205,11 +212,11 @@ int pkcs8_main(int argc, char **argv) } if (nocrypt) { assert(private); - if (outformat == FORMAT_PEM) + if (outformat == FORMAT_PEM) { PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf); - else if (outformat == FORMAT_ASN1) + } else if (outformat == FORMAT_ASN1) { i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf); - else { + } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } @@ -232,10 +239,11 @@ int pkcs8_main(int argc, char **argv) ERR_print_errors(bio_err); goto end; } - if (passout) + if (passout != NULL) { p8pass = passout; - else if (1) { -#ifndef OPENSSL_NO_UI + } else if (1) { + /* To avoid bit rot */ +#ifndef OPENSSL_NO_UI_CONSOLE p8pass = pass; if (EVP_read_pw_string (pass, sizeof(pass), "Enter Encryption Password:", 1)) { @@ -247,7 +255,6 @@ int pkcs8_main(int argc, char **argv) BIO_printf(bio_err, "Password required\n"); goto end; } - app_RAND_load_file(NULL, 0); p8 = PKCS8_set0_pbe(p8pass, strlen(p8pass), p8inf, pbe); if (p8 == NULL) { X509_ALGOR_free(pbe); @@ -255,7 +262,6 @@ int pkcs8_main(int argc, char **argv) ERR_print_errors(bio_err); goto end; } - app_RAND_write_file(NULL); assert(private); if (outformat == FORMAT_PEM) PEM_write_bio_PKCS8(out, p8); @@ -272,33 +278,33 @@ int pkcs8_main(int argc, char **argv) } if (nocrypt) { - if (informat == FORMAT_PEM) + if (informat == FORMAT_PEM) { p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL); - else if (informat == FORMAT_ASN1) + } else if (informat == FORMAT_ASN1) { p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL); - else { + } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } else { - if (informat == FORMAT_PEM) + if (informat == FORMAT_PEM) { p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL); - else if (informat == FORMAT_ASN1) + } else if (informat == FORMAT_ASN1) { p8 = d2i_PKCS8_bio(in, NULL); - else { + } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } - if (!p8) { + if (p8 == NULL) { BIO_printf(bio_err, "Error reading key\n"); ERR_print_errors(bio_err); goto end; } - if (passin) + if (passin != NULL) { p8pass = passin; - else if (1) { -#ifndef OPENSSL_NO_UI + } else if (1) { +#ifndef OPENSSL_NO_UI_CONSOLE p8pass = pass; if (EVP_read_pw_string(pass, sizeof(pass), "Enter Password:", 0)) { BIO_printf(bio_err, "Can't read Password\n"); @@ -312,7 +318,7 @@ int pkcs8_main(int argc, char **argv) p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass)); } - if (!p8inf) { + if (p8inf == NULL) { BIO_printf(bio_err, "Error decrypting key\n"); ERR_print_errors(bio_err); goto end; diff --git a/apps/pkey.c b/apps/pkey.c index ad1a3b10..760fc1bb 100644 --- a/apps/pkey.c +++ b/apps/pkey.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-2018 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 @@ -10,6 +10,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -18,10 +19,10 @@ typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_INFORM, OPT_OUTFORM, OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_PUBIN, OPT_PUBOUT, OPT_TEXT_PUB, - OPT_TEXT, OPT_NOOUT, OPT_MD, OPT_TRADITIONAL + OPT_TEXT, OPT_NOOUT, OPT_MD, OPT_TRADITIONAL, OPT_CHECK, OPT_PUB_CHECK } OPTION_CHOICE; -OPTIONS pkey_options[] = { +const OPTIONS pkey_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'f', "Input format (DER or PEM)"}, {"outform", OPT_OUTFORM, 'F', "Output format (DER or PEM)"}, @@ -41,6 +42,8 @@ OPTIONS pkey_options[] = { #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif + {"check", OPT_CHECK, '-', "Check key consistency"}, + {"pubcheck", OPT_PUB_CHECK, '-', "Check public key consistency"}, {NULL} }; @@ -55,7 +58,7 @@ int pkey_main(int argc, char **argv) OPTION_CHOICE o; int informat = FORMAT_PEM, outformat = FORMAT_PEM; int pubin = 0, pubout = 0, pubtext = 0, text = 0, noout = 0, ret = 1; - int private = 0, traditional = 0; + int private = 0, traditional = 0, check = 0, pub_check = 0; prog = opt_init(argc, argv, pkey_options); while ((o = opt_next()) != OPT_EOF) { @@ -110,6 +113,12 @@ int pkey_main(int argc, char **argv) case OPT_TRADITIONAL: traditional = 1; break; + case OPT_CHECK: + check = 1; + break; + case OPT_PUB_CHECK: + pub_check = 1; + break; case OPT_MD: if (!opt_cipher(opt_unknown(), &cipher)) goto opthelp; @@ -136,14 +145,49 @@ int pkey_main(int argc, char **argv) pkey = load_pubkey(infile, informat, 1, passin, e, "Public Key"); else pkey = load_key(infile, informat, 1, passin, e, "key"); - if (!pkey) + if (pkey == NULL) goto end; + if (check || pub_check) { + int r; + EVP_PKEY_CTX *ctx; + + ctx = EVP_PKEY_CTX_new(pkey, e); + if (ctx == NULL) { + ERR_print_errors(bio_err); + goto end; + } + + if (check) + r = EVP_PKEY_check(ctx); + else + r = EVP_PKEY_public_check(ctx); + + if (r == 1) { + BIO_printf(out, "Key is valid\n"); + } else { + /* + * Note: at least for RSA keys if this function returns + * -1, there will be no error reasons. + */ + unsigned long err; + + BIO_printf(out, "Key is invalid\n"); + + while ((err = ERR_peek_error()) != 0) { + BIO_printf(out, "Detailed error: %s\n", + ERR_reason_error_string(err)); + ERR_get_error(); /* remove err from error stack */ + } + } + EVP_PKEY_CTX_free(ctx); + } + if (!noout) { if (outformat == FORMAT_PEM) { - if (pubout) + if (pubout) { PEM_write_bio_PUBKEY(out, pkey); - else { + } else { assert(private); if (traditional) PEM_write_bio_PrivateKey_traditional(out, pkey, cipher, @@ -154,9 +198,9 @@ int pkey_main(int argc, char **argv) NULL, 0, NULL, passout); } } else if (outformat == FORMAT_ASN1) { - if (pubout) + if (pubout) { i2d_PUBKEY_bio(out, pkey); - else { + } else { assert(private); i2d_PrivateKey_bio(out, pkey); } @@ -164,13 +208,12 @@ int pkey_main(int argc, char **argv) BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } - } if (text) { - if (pubtext) + if (pubtext) { EVP_PKEY_print_public(out, pkey, 0, NULL); - else { + } else { assert(private); EVP_PKEY_print_private(out, pkey, 0, NULL); } @@ -179,6 +222,8 @@ int pkey_main(int argc, char **argv) ret = 0; end: + if (ret != 0) + ERR_print_errors(bio_err); EVP_PKEY_free(pkey); release_engine(e); BIO_free_all(out); diff --git a/apps/pkeyparam.c b/apps/pkeyparam.c index 0a1b2d12..41c3f532 100644 --- a/apps/pkeyparam.c +++ b/apps/pkeyparam.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-2018 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 @@ -10,16 +10,18 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, - OPT_IN, OPT_OUT, OPT_TEXT, OPT_NOOUT, OPT_ENGINE + OPT_IN, OPT_OUT, OPT_TEXT, OPT_NOOUT, + OPT_ENGINE, OPT_CHECK } OPTION_CHOICE; -OPTIONS pkeyparam_options[] = { +const OPTIONS pkeyparam_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Input file"}, {"out", OPT_OUT, '>', "Output file"}, @@ -28,6 +30,7 @@ OPTIONS pkeyparam_options[] = { #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif + {"check", OPT_CHECK, '-', "Check key param consistency"}, {NULL} }; @@ -36,7 +39,7 @@ int pkeyparam_main(int argc, char **argv) ENGINE *e = NULL; BIO *in = NULL, *out = NULL; EVP_PKEY *pkey = NULL; - int text = 0, noout = 0, ret = 1; + int text = 0, noout = 0, ret = 1, check = 0; OPTION_CHOICE o; char *infile = NULL, *outfile = NULL, *prog; @@ -67,6 +70,9 @@ int pkeyparam_main(int argc, char **argv) case OPT_NOOUT: noout = 1; break; + case OPT_CHECK: + check = 1; + break; } } argc = opt_num_rest(); @@ -80,12 +86,44 @@ int pkeyparam_main(int argc, char **argv) if (out == NULL) goto end; pkey = PEM_read_bio_Parameters(in, NULL); - if (!pkey) { + if (pkey == NULL) { BIO_printf(bio_err, "Error reading parameters\n"); ERR_print_errors(bio_err); goto end; } + if (check) { + int r; + EVP_PKEY_CTX *ctx; + + ctx = EVP_PKEY_CTX_new(pkey, e); + if (ctx == NULL) { + ERR_print_errors(bio_err); + goto end; + } + + r = EVP_PKEY_param_check(ctx); + + if (r == 1) { + BIO_printf(out, "Parameters are valid\n"); + } else { + /* + * Note: at least for RSA keys if this function returns + * -1, there will be no error reasons. + */ + unsigned long err; + + BIO_printf(out, "Parameters are invalid\n"); + + while ((err = ERR_peek_error()) != 0) { + BIO_printf(out, "Detailed error: %s\n", + ERR_reason_error_string(err)); + ERR_get_error(); /* remove err from error stack */ + } + } + EVP_PKEY_CTX_free(ctx); + } + if (!noout) PEM_write_bio_Parameters(out, pkey); diff --git a/apps/pkeyutl.c b/apps/pkeyutl.c index bbb1274f..77926de1 100644 --- a/apps/pkeyutl.c +++ b/apps/pkeyutl.c @@ -8,6 +8,7 @@ */ #include "apps.h" +#include "progs.h" #include #include #include @@ -36,10 +37,11 @@ typedef enum OPTION_choice { OPT_PUBIN, OPT_CERTIN, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_SIGN, OPT_VERIFY, OPT_VERIFYRECOVER, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT, OPT_DERIVE, OPT_SIGFILE, OPT_INKEY, OPT_PEERKEY, OPT_PASSIN, - OPT_PEERFORM, OPT_KEYFORM, OPT_PKEYOPT, OPT_KDF, OPT_KDFLEN + OPT_PEERFORM, OPT_KEYFORM, OPT_PKEYOPT, OPT_KDF, OPT_KDFLEN, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS pkeyutl_options[] = { +const OPTIONS pkeyutl_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Input file - default stdin"}, {"out", OPT_OUT, '>', "Output file - default stdout"}, @@ -64,6 +66,7 @@ OPTIONS pkeyutl_options[] = { {"peerform", OPT_PEERFORM, 'E', "Peer key format - default PEM"}, {"keyform", OPT_KEYFORM, 'E', "Private key format - default PEM"}, {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"}, + OPT_R_OPTIONS, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, {"engine_impl", OPT_ENGINE_IMPL, '-', @@ -81,7 +84,8 @@ int pkeyutl_main(int argc, char **argv) char hexdump = 0, asn1parse = 0, rev = 0, *prog; unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL; OPTION_CHOICE o; - int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform = FORMAT_PEM; + int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform = + FORMAT_PEM; int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY; int engine_impl = 0; int ret = 1, rv = -1; @@ -133,6 +137,10 @@ int pkeyutl_main(int argc, char **argv) if (!opt_format(opt_arg(), OPT_FMT_PDE, &keyform)) goto opthelp; break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; @@ -192,18 +200,10 @@ int pkeyutl_main(int argc, char **argv) goto opthelp; if (kdfalg != NULL) { - if (kdflen == 0) { - BIO_printf(bio_err, - "%s: no KDF length given (-kdflen parameter).\n", prog); + if (kdflen == 0) goto opthelp; - } - } else if (inkey == NULL) { - BIO_printf(bio_err, - "%s: no private key given (-inkey parameter).\n", prog); - goto opthelp; - } else if (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE) { - BIO_printf(bio_err, - "%s: no peer key given (-peerkey parameter).\n", prog); + } else if ((inkey == NULL) + || (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE)) { goto opthelp; } ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type, @@ -226,29 +226,25 @@ int pkeyutl_main(int argc, char **argv) const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i); if (pkey_ctrl_string(ctx, opt) <= 0) { - BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n", - prog, opt); + BIO_printf(bio_err, "%s: Can't set parameter:\n", prog); ERR_print_errors(bio_err); goto end; } } } - if (sigfile && (pkey_op != EVP_PKEY_OP_VERIFY)) { + if (sigfile != NULL && (pkey_op != EVP_PKEY_OP_VERIFY)) { BIO_printf(bio_err, "%s: Signature file specified for non verify\n", prog); goto end; } - if (!sigfile && (pkey_op == EVP_PKEY_OP_VERIFY)) { + if (sigfile == NULL && (pkey_op == EVP_PKEY_OP_VERIFY)) { BIO_printf(bio_err, "%s: No signature file specified for verify\n", prog); goto end; } -/* FIXME: seed PRNG only if needed */ - app_RAND_load_file(NULL, 0); - if (pkey_op != EVP_PKEY_OP_DERIVE) { in = bio_open_default(infile, 'r', FORMAT_BINARY); if (in == NULL) @@ -258,9 +254,10 @@ int pkeyutl_main(int argc, char **argv) if (out == NULL) goto end; - if (sigfile) { + if (sigfile != NULL) { BIO *sigbio = BIO_new_file(sigfile, "rb"); - if (!sigbio) { + + if (sigbio == NULL) { BIO_printf(bio_err, "Can't open signature file %s\n", sigfile); goto end; } @@ -272,7 +269,7 @@ int pkeyutl_main(int argc, char **argv) } } - if (in) { + if (in != NULL) { /* Read the input data */ buf_inlen = bio_to_mem(&buf_in, keysize * 10, in); if (buf_inlen < 0) { @@ -297,8 +294,9 @@ int pkeyutl_main(int argc, char **argv) if (rv == 1) { BIO_puts(out, "Signature Verified Successfully\n"); ret = 0; - } else + } else { BIO_puts(out, "Signature Verification Failure\n"); + } goto end; } if (kdflen != 0) { @@ -315,11 +313,7 @@ int pkeyutl_main(int argc, char **argv) buf_in, (size_t)buf_inlen); } if (rv <= 0) { - if (pkey_op != EVP_PKEY_OP_DERIVE) { - BIO_puts(bio_err, "Public Key operation error\n"); - } else { - BIO_puts(bio_err, "Key derivation failed\n"); - } + BIO_puts(bio_err, "Public Key operation error\n"); ERR_print_errors(bio_err); goto end; } @@ -328,10 +322,11 @@ int pkeyutl_main(int argc, char **argv) if (asn1parse) { if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1)) ERR_print_errors(bio_err); - } else if (hexdump) + } else if (hexdump) { BIO_dump(out, (char *)buf_out, buf_outlen); - else + } else { BIO_write(out, buf_out, buf_outlen); + } end: EVP_PKEY_CTX_free(ctx); @@ -393,16 +388,13 @@ static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize, impl = e; #endif - if (kdfalg) { + if (kdfalg != NULL) { int kdfnid = OBJ_sn2nid(kdfalg); if (kdfnid == NID_undef) { kdfnid = OBJ_ln2nid(kdfalg); - if (kdfnid == NID_undef) { - BIO_printf(bio_err, "The given KDF \"%s\" is unknown.\n", - kdfalg); + if (kdfnid == NID_undef) goto end; - } } ctx = EVP_PKEY_CTX_new_id(kdfnid, impl); } else { @@ -454,16 +446,16 @@ static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize, } static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file, - ENGINE *e) + ENGINE* e) { EVP_PKEY *peer = NULL; - ENGINE *engine = NULL; + ENGINE* engine = NULL; int ret; if (peerform == FORMAT_ENGINE) engine = e; peer = load_pubkey(file, peerform, 0, NULL, engine, "Peer Key"); - if (!peer) { + if (peer == NULL) { BIO_printf(bio_err, "Error reading peer key %s\n", file); ERR_print_errors(bio_err); return 0; diff --git a/apps/prime.c b/apps/prime.c index c12463d8..69447976 100644 --- a/apps/prime.c +++ b/apps/prime.c @@ -10,6 +10,7 @@ #include #include "apps.h" +#include "progs.h" #include typedef enum OPTION_choice { @@ -17,7 +18,7 @@ typedef enum OPTION_choice { OPT_HEX, OPT_GENERATE, OPT_BITS, OPT_SAFE, OPT_CHECKS } OPTION_CHOICE; -OPTIONS prime_options[] = { +const OPTIONS prime_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [number...]\n"}, {OPT_HELP_STR, 1, '-', " number Number to check for primality\n"}, @@ -112,7 +113,7 @@ opthelp: else r = BN_dec2bn(&bn, argv[0]); - if(!r) { + if (!r) { BIO_printf(bio_err, "Failed to process value (%s)\n", argv[0]); goto end; } diff --git a/apps/progs.pl b/apps/progs.pl index 0d3b4469..f832467b 100644 --- a/apps/progs.pl +++ b/apps/progs.pl @@ -14,24 +14,24 @@ use warnings; use lib '.'; use configdata qw/@disablables %unified_info/; -my %commands = (); -my $cmdre = qr/^\s*int\s+([a-z_][a-z0-9_]*)_main\(\s*int\s+argc\s*,/; - +my %commands = (); +my $cmdre = qr/^\s*int\s+([a-z_][a-z0-9_]*)_main\(\s*int\s+argc\s*,/; my $apps_openssl = shift @ARGV; + # because the program apps/openssl has object files as sources, and # they then have the corresponding C files as source, we need to chain # the lookups in %unified_info my @openssl_source = map { @{$unified_info{sources}->{$_}} } - @{$unified_info{sources}->{$apps_openssl}}; + @{$unified_info{sources}->{$apps_openssl}}; foreach my $filename (@openssl_source) { - open F, $filename or die "Couldn't open $filename: $!\n"; - foreach (grep /$cmdre/, ) { - my @foo = /$cmdre/; - $commands{$1} = 1; - } - close F; + open F, $filename or die "Couldn't open $filename: $!\n"; + foreach ( grep /$cmdre/, ) { + my @foo = /$cmdre/; + $commands{$1} = 1; + } + close F; } @ARGV = sort keys %commands; @@ -66,17 +66,15 @@ DEFINE_LHASH_OF(FUNCTION); EOF foreach (@ARGV) { - printf "extern int %s_main(int argc, char *argv[]);\n", $_; + printf "extern int %s_main(int argc, char *argv[]);\n", $_; } - print "\n"; foreach (@ARGV) { - printf "extern OPTIONS %s_options[];\n", $_; + printf "extern const OPTIONS %s_options[];\n", $_; } +print "\n"; -print "\n#ifdef INCLUDE_FUNCTION_TABLE\n"; -print "static FUNCTION functions[] = {\n"; my %cmd_disabler = ( ciphers => "sock", genrsa => "rsa", @@ -87,78 +85,92 @@ my %cmd_disabler = ( dhparam => "dh", ecparam => "ec", pkcs12 => "des", - ); -foreach my $cmd (@ARGV) { - my $str=" { FT_general, \"$cmd\", ${cmd}_main, ${cmd}_options },\n"; - if ($cmd =~ /^s_/) { - print "#ifndef OPENSSL_NO_SOCK\n${str}#endif\n"; - } elsif (grep { $cmd eq $_ } @disablables) { - print "#ifndef OPENSSL_NO_".uc($cmd)."\n${str}#endif\n"; - } elsif (my $disabler = $cmd_disabler{$cmd}) { - print "#ifndef OPENSSL_NO_".uc($disabler)."\n${str}#endif\n"; - } else { - print $str; - } +); + +print "#ifdef INCLUDE_FUNCTION_TABLE\n"; +print "static FUNCTION functions[] = {\n"; +foreach my $cmd ( @ARGV ) { + my $str = " {FT_general, \"$cmd\", ${cmd}_main, ${cmd}_options},\n"; + if ($cmd =~ /^s_/) { + print "#ifndef OPENSSL_NO_SOCK\n${str}#endif\n"; + } elsif (grep { $cmd eq $_ } @disablables) { + print "#ifndef OPENSSL_NO_" . uc($cmd) . "\n${str}#endif\n"; + } elsif (my $disabler = $cmd_disabler{$cmd}) { + print "#ifndef OPENSSL_NO_" . uc($disabler) . "\n${str}#endif\n"; + } else { + print $str; + } } my %md_disabler = ( blake2b512 => "blake2", blake2s256 => "blake2", - ); +); foreach my $cmd ( - "md2", "md4", "md5", - "gost", - "sha1", "sha224", "sha256", "sha384", "sha512", - "mdc2", "rmd160", "blake2b512", "blake2s256" + "md2", "md4", "md5", + "gost", + "sha1", "sha224", "sha256", "sha384", "sha512", + "mdc2", "rmd160", "blake2b512", "blake2s256", + "sm3" ) { - my $str = " { FT_md, \"".$cmd."\", dgst_main},\n"; - if (grep { $cmd eq $_ } @disablables) { - print "#ifndef OPENSSL_NO_".uc($cmd)."\n${str}#endif\n"; - } elsif (my $disabler = $md_disabler{$cmd}) { - print "#ifndef OPENSSL_NO_".uc($disabler)."\n${str}#endif\n"; - } else { - print $str; - } + my $str = " {FT_md, \"$cmd\", dgst_main},\n"; + if (grep { $cmd eq $_ } @disablables) { + print "#ifndef OPENSSL_NO_" . uc($cmd) . "\n${str}#endif\n"; + } elsif (my $disabler = $md_disabler{$cmd}) { + print "#ifndef OPENSSL_NO_" . uc($disabler) . "\n${str}#endif\n"; + } else { + print $str; + } } my %cipher_disabler = ( des3 => "des", desx => "des", cast5 => "cast", - ); +); foreach my $cmd ( - "aes-128-cbc", "aes-128-ecb", - "aes-192-cbc", "aes-192-ecb", - "aes-256-cbc", "aes-256-ecb", - "camellia-128-cbc", "camellia-128-ecb", - "camellia-192-cbc", "camellia-192-ecb", - "camellia-256-cbc", "camellia-256-ecb", - "base64", "zlib", - "des", "des3", "desx", "idea", "seed", "rc4", "rc4-40", - "rc2", "bf", "cast", "rc5", - "des-ecb", "des-ede", "des-ede3", - "des-cbc", "des-ede-cbc","des-ede3-cbc", - "des-cfb", "des-ede-cfb","des-ede3-cfb", - "des-ofb", "des-ede-ofb","des-ede3-ofb", - "idea-cbc","idea-ecb", "idea-cfb", "idea-ofb", - "seed-cbc","seed-ecb", "seed-cfb", "seed-ofb", - "rc2-cbc", "rc2-ecb", "rc2-cfb","rc2-ofb", "rc2-64-cbc", "rc2-40-cbc", - "bf-cbc", "bf-ecb", "bf-cfb", "bf-ofb", - "cast5-cbc","cast5-ecb", "cast5-cfb","cast5-ofb", - "cast-cbc", "rc5-cbc", "rc5-ecb", "rc5-cfb", "rc5-ofb" + "aes-128-cbc", "aes-128-ecb", + "aes-192-cbc", "aes-192-ecb", + "aes-256-cbc", "aes-256-ecb", + "aria-128-cbc", "aria-128-cfb", + "aria-128-ctr", "aria-128-ecb", "aria-128-ofb", + "aria-128-cfb1", "aria-128-cfb8", + "aria-192-cbc", "aria-192-cfb", + "aria-192-ctr", "aria-192-ecb", "aria-192-ofb", + "aria-192-cfb1", "aria-192-cfb8", + "aria-256-cbc", "aria-256-cfb", + "aria-256-ctr", "aria-256-ecb", "aria-256-ofb", + "aria-256-cfb1", "aria-256-cfb8", + "camellia-128-cbc", "camellia-128-ecb", + "camellia-192-cbc", "camellia-192-ecb", + "camellia-256-cbc", "camellia-256-ecb", + "base64", "zlib", + "des", "des3", "desx", "idea", "seed", "rc4", "rc4-40", + "rc2", "bf", "cast", "rc5", + "des-ecb", "des-ede", "des-ede3", + "des-cbc", "des-ede-cbc","des-ede3-cbc", + "des-cfb", "des-ede-cfb","des-ede3-cfb", + "des-ofb", "des-ede-ofb","des-ede3-ofb", + "idea-cbc","idea-ecb", "idea-cfb", "idea-ofb", + "seed-cbc","seed-ecb", "seed-cfb", "seed-ofb", + "rc2-cbc", "rc2-ecb", "rc2-cfb","rc2-ofb", "rc2-64-cbc", "rc2-40-cbc", + "bf-cbc", "bf-ecb", "bf-cfb", "bf-ofb", + "cast5-cbc","cast5-ecb", "cast5-cfb","cast5-ofb", + "cast-cbc", "rc5-cbc", "rc5-ecb", "rc5-cfb", "rc5-ofb", + "sm4-cbc", "sm4-ecb", "sm4-cfb", "sm4-ofb", "sm4-ctr" ) { - my $str=" { FT_cipher, \"$cmd\", enc_main, enc_options },\n"; - (my $algo= $cmd) =~ s/-.*//g; - if ($cmd eq "zlib") { - print "#ifdef ZLIB\n${str}#endif\n"; - } elsif (grep { $algo eq $_ } @disablables) { - print "#ifndef OPENSSL_NO_".uc($algo)."\n${str}#endif\n"; - } elsif (my $disabler = $cipher_disabler{$algo}) { - print "#ifndef OPENSSL_NO_".uc($disabler)."\n${str}#endif\n"; - } else { - print $str; - } + my $str = " {FT_cipher, \"$cmd\", enc_main, enc_options},\n"; + (my $algo = $cmd) =~ s/-.*//g; + if ($cmd eq "zlib") { + print "#ifdef ZLIB\n${str}#endif\n"; + } elsif (grep { $algo eq $_ } @disablables) { + print "#ifndef OPENSSL_NO_" . uc($algo) . "\n${str}#endif\n"; + } elsif (my $disabler = $cipher_disabler{$algo}) { + print "#ifndef OPENSSL_NO_" . uc($disabler) . "\n${str}#endif\n"; + } else { + print $str; + } } -print " { 0, NULL, NULL}\n};\n"; +print " {0, NULL, NULL}\n};\n"; print "#endif\n"; diff --git a/apps/rand.c b/apps/rand.c index b3ec70a7..4c618150 100644 --- a/apps/rand.c +++ b/apps/rand.c @@ -8,6 +8,7 @@ */ #include "apps.h" +#include "progs.h" #include #include @@ -19,16 +20,16 @@ typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, - OPT_OUT, OPT_ENGINE, OPT_RAND, OPT_BASE64, OPT_HEX + OPT_OUT, OPT_ENGINE, OPT_BASE64, OPT_HEX, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS rand_options[] = { +const OPTIONS rand_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [flags] num\n"}, {OPT_HELP_STR, 1, '-', "Valid options are:\n"}, {"help", OPT_HELP, '-', "Display this summary"}, {"out", OPT_OUT, '>', "Output file"}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, + OPT_R_OPTIONS, {"base64", OPT_BASE64, '-', "Base64 encode output"}, {"hex", OPT_HEX, '-', "Hex encode output"}, #ifndef OPENSSL_NO_ENGINE @@ -41,7 +42,7 @@ int rand_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL; - char *inrand = NULL, *outfile = NULL, *prog; + char *outfile = NULL, *prog; OPTION_CHOICE o; int format = FORMAT_BINARY, i, num = -1, r, ret = 1; @@ -63,8 +64,9 @@ int rand_main(int argc, char **argv) case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; - case OPT_RAND: - inrand = opt_arg(); + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_BASE64: format = FORMAT_BASE64; @@ -84,11 +86,6 @@ int rand_main(int argc, char **argv) goto opthelp; } - app_RAND_load_file(NULL, (inrand != NULL)); - if (inrand != NULL) - BIO_printf(bio_err, "%ld semi-random bytes loaded\n", - app_RAND_load_files(inrand)); - out = bio_open_default(outfile, 'w', format); if (out == NULL) goto end; @@ -122,7 +119,7 @@ int rand_main(int argc, char **argv) } if (format == FORMAT_TEXT) BIO_puts(out, "\n"); - if (BIO_flush(out) <= 0 || !app_RAND_write_file(NULL)) + if (BIO_flush(out) <= 0) goto end; ret = 0; @@ -132,5 +129,5 @@ int rand_main(int argc, char **argv) ERR_print_errors(bio_err); release_engine(e); BIO_free_all(out); - return (ret); + return ret; } diff --git a/apps/rehash.c b/apps/rehash.c index 273ad749..d918ac89 100644 --- a/apps/rehash.c +++ b/apps/rehash.c @@ -1,5 +1,6 @@ /* - * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2013-2014 Timo Ters * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy @@ -7,13 +8,8 @@ * https://www.openssl.org/source/license.html */ -/* - * C implementation based on the original Perl and shell versions - * - * Copyright (c) 2013-2014 Timo Teräs - */ - #include "apps.h" +#include "progs.h" #if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \ (defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000) @@ -254,11 +250,11 @@ static int do_file(const char *filename, const char *fullpath, enum Hash h) goto end; } x = sk_X509_INFO_value(inf, 0); - if (x->x509) { + if (x->x509 != NULL) { type = TYPE_CERT; name = X509_get_subject_name(x->x509); X509_digest(x->x509, evpmd, digest, NULL); - } else if (x->crl) { + } else if (x->crl != NULL) { type = TYPE_CRL; name = X509_CRL_get_issuer(x->crl); X509_CRL_digest(x->crl, evpmd, digest, NULL); @@ -266,7 +262,7 @@ static int do_file(const char *filename, const char *fullpath, enum Hash h) ++errs; goto end; } - if (name) { + if (name != NULL) { if ((h == HASH_NEW) || (h == HASH_BOTH)) errs += add_entry(type, X509_NAME_hash(name), filename, digest, 1, ~0); if ((h == HASH_OLD) || (h == HASH_BOTH)) @@ -448,7 +444,7 @@ typedef enum OPTION_choice { OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE } OPTION_CHOICE; -OPTIONS rehash_options[] = { +const OPTIONS rehash_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert-directory...]\n"}, {OPT_HELP_STR, 1, '-', "Valid options are:\n"}, {"help", OPT_HELP, '-', "Display this summary"}, @@ -499,8 +495,8 @@ int rehash_main(int argc, char **argv) evpmd = EVP_sha1(); evpmdsize = EVP_MD_size(evpmd); - if (*argv) { - while (*argv) + if (*argv != NULL) { + while (*argv != NULL) errs += do_dir(*argv++, h); } else if ((env = getenv("SSL_CERT_DIR")) != NULL) { m = OPENSSL_strdup(env); @@ -516,14 +512,14 @@ int rehash_main(int argc, char **argv) } #else -OPTIONS rehash_options[] = { +const OPTIONS rehash_options[] = { {NULL} }; int rehash_main(int argc, char **argv) { BIO_printf(bio_err, "Not available; use c_rehash script\n"); - return (1); + return 1; } #endif /* defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) */ diff --git a/apps/req.c b/apps/req.c index 2a215695..ac14fdb8 100644 --- a/apps/req.c +++ b/apps/req.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -12,6 +12,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -64,25 +65,29 @@ static int add_DN_object(X509_NAME *n, char *text, const char *def, 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 int join(char buf[], size_t buf_size, const char *name, + const char *tail, const char *desc); static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, int *pkey_type, long *pkeylen, char **palgnam, ENGINE *keygen_engine); static CONF *req_conf = NULL; +static CONF *addext_conf = NULL; static int batch = 0; typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY, OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT, - OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_RAND, OPT_NEWKEY, + OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY, OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS, OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8, OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509, - OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_EXTENSIONS, - OPT_REQEXTS, OPT_MD + OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS, + OPT_REQEXTS, OPT_PRECERT, OPT_MD, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS req_options[] = { +const OPTIONS req_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, @@ -96,8 +101,7 @@ OPTIONS req_options[] = { {"keyout", OPT_KEYOUT, '>', "File to send the key to"}, {"passin", OPT_PASSIN, 's', "Private key password source"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, + OPT_R_OPTIONS, {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"}, {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"}, {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"}, @@ -122,10 +126,13 @@ OPTIONS req_options[] = { "Enable support for multivalued RDNs"}, {"days", OPT_DAYS, 'p', "Number of days cert is valid for"}, {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"}, + {"addext", OPT_ADDEXT, 's', + "Additional cert extension key=value pair (may be given more than once)"}, {"extensions", OPT_EXTENSIONS, 's', "Cert extension section (override value in config file)"}, {"reqexts", OPT_REQEXTS, 's', "Request extension section (override value in config file)"}, + {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"}, {"", OPT_MD, '-', "Any supported digest"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, @@ -147,8 +154,9 @@ int req_main(int argc, char **argv) X509_REQ *req = NULL; const EVP_CIPHER *cipher = NULL; const EVP_MD *md_alg = NULL, *digest = NULL; + BIO *addext_bio = NULL; char *extensions = NULL, *infile = NULL; - char *outfile = NULL, *keyfile = NULL, *inrand = NULL; + char *outfile = NULL, *keyfile = NULL; char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL; char *passin = NULL, *passout = NULL; char *nofree_passin = NULL, *nofree_passout = NULL; @@ -156,14 +164,13 @@ int req_main(int argc, char **argv) char *template = default_config_file, *keyout = NULL; const char *keyalg = NULL; OPTION_CHOICE o; - int ret = 1, x509 = 0, days = 30, i = 0, newreq = 0, verbose = 0; + int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0; int pkey_type = -1, private = 0; int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM; int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0; - int nodes = 0, newhdr = 0, subject = 0, pubkey = 0; + int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0; long newkey = -1; - unsigned long chtype = MBSTRING_ASC, nmflag = 0, reqflag = 0; - char nmflag_set = 0; + unsigned long chtype = MBSTRING_ASC, reqflag = 0; #ifndef OPENSSL_NO_DES cipher = EVP_des_ede3_cbc(); @@ -232,8 +239,9 @@ int req_main(int argc, char **argv) case OPT_PASSOUT: passargout = opt_arg(); break; - case OPT_RAND: - inrand = opt_arg(); + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_NEWKEY: keyalg = opt_arg(); @@ -276,8 +284,7 @@ int req_main(int argc, char **argv) chtype = MBSTRING_UTF8; break; case OPT_NAMEOPT: - nmflag_set = 1; - if (!set_name_ex(&nmflag, opt_arg())) + if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_REQOPT: @@ -311,12 +318,23 @@ int req_main(int argc, char **argv) case OPT_MULTIVALUE_RDN: multirdn = 1; break; + case OPT_ADDEXT: + if (addext_bio == NULL) { + addext_bio = BIO_new(BIO_s_mem()); + } + if (addext_bio == NULL + || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0) + goto end; + break; case OPT_EXTENSIONS: extensions = opt_arg(); break; case OPT_REQEXTS: req_exts = opt_arg(); break; + case OPT_PRECERT: + newreq = precert = 1; + break; case OPT_MD: if (!opt_md(opt_unknown(), &md_alg)) goto opthelp; @@ -328,12 +346,11 @@ int req_main(int argc, char **argv) if (argc != 0) goto opthelp; + if (days && !x509) + BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n"); if (x509 && infile == NULL) newreq = 1; - if (!nmflag_set) - nmflag = XN_FLAG_ONELINE; - /* TODO: simplify this as pkey is still always NULL here */ private = newreq && (pkey == NULL) ? 1 : 0; @@ -345,6 +362,12 @@ int req_main(int argc, char **argv) if (verbose) BIO_printf(bio_err, "Using configuration from %s\n", template); req_conf = app_load_config(template); + if (addext_bio) { + if (verbose) + BIO_printf(bio_err, + "Using additional configuraton from command line\n"); + addext_conf = app_load_config_bio(addext_bio, NULL); + } if (template != default_config_file && !app_load_modules(req_conf)) goto end; @@ -372,21 +395,21 @@ int req_main(int argc, char **argv) if (md_alg == NULL) { p = NCONF_get_string(req_conf, SECTION, "default_md"); - if (p == NULL) + if (p == NULL) { ERR_clear_error(); - else { + } else { if (!opt_md(p, &md_alg)) goto opthelp; digest = md_alg; } } - if (!extensions) { + if (extensions == NULL) { extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS); - if (!extensions) + if (extensions == NULL) ERR_clear_error(); } - if (extensions) { + if (extensions != NULL) { /* Check syntax of file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); @@ -397,6 +420,16 @@ int req_main(int argc, char **argv) goto end; } } + if (addext_conf != NULL) { + /* Check syntax of command line extensions */ + X509V3_CTX ctx; + X509V3_set_ctx_test(&ctx); + X509V3_set_nconf(&ctx, addext_conf); + if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) { + BIO_printf(bio_err, "Error Loading command line extensions\n"); + goto end; + } + } if (passin == NULL) { passin = nofree_passin = @@ -413,28 +446,28 @@ int req_main(int argc, char **argv) } p = NCONF_get_string(req_conf, SECTION, STRING_MASK); - if (!p) + if (p == NULL) ERR_clear_error(); - if (p && !ASN1_STRING_set_default_mask_asc(p)) { + if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) { BIO_printf(bio_err, "Invalid global string mask setting %s\n", p); goto end; } if (chtype != MBSTRING_UTF8) { p = NCONF_get_string(req_conf, SECTION, UTF8_IN); - if (!p) + if (p == NULL) ERR_clear_error(); else if (strcmp(p, "yes") == 0) chtype = MBSTRING_UTF8; } - if (!req_exts) { + if (req_exts == NULL) { req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS); - if (!req_exts) + if (req_exts == NULL) ERR_clear_error(); } - if (req_exts) { + if (req_exts != NULL) { /* Check syntax of file */ X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); @@ -449,33 +482,25 @@ int req_main(int argc, char **argv) if (keyfile != NULL) { pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key"); - if (!pkey) { + if (pkey == NULL) { /* 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, 0); + app_RAND_load_conf(req_conf, SECTION); } } if (newreq && (pkey == NULL)) { - char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE"); - if (randfile == NULL) - ERR_clear_error(); - app_RAND_load_file(randfile, 0); - if (inrand) - app_RAND_load_files(inrand); + app_RAND_load_conf(req_conf, SECTION); if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) { newkey = DEFAULT_KEY_LENGTH; } - if (keyalg) { + if (keyalg != NULL) { genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey, &keyalgstr, gen_eng); - if (!genctx) + if (genctx == NULL) goto end; } @@ -487,14 +512,14 @@ int req_main(int argc, char **argv) goto end; } - if (!genctx) { + if (genctx == NULL) { genctx = set_keygen_ctx(NULL, &pkey_type, &newkey, &keyalgstr, gen_eng); if (!genctx) goto end; } - if (pkeyopts) { + if (pkeyopts != NULL) { char *genopt; for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) { genopt = sk_OPENSSL_STRING_value(pkeyopts, i); @@ -524,8 +549,6 @@ int req_main(int argc, char **argv) EVP_PKEY_CTX_free(genctx); genctx = NULL; - app_RAND_write_file(randfile); - if (keyout == NULL) { keyout = NCONF_get_string(req_conf, SECTION, KEYFILE); if (keyout == NULL) @@ -611,9 +634,10 @@ int req_main(int argc, char **argv) goto end; /* Set version to V3 */ - if (extensions && !X509_set_version(x509ss, 2)) + if ((extensions != NULL || addext_conf != NULL) + && !X509_set_version(x509ss, 2)) goto end; - if (serial) { + if (serial != NULL) { if (!X509_set_serialNumber(x509ss, serial)) goto end; } else { @@ -623,6 +647,10 @@ int req_main(int argc, char **argv) if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req))) goto end; + if (days == 0) { + /* set default days if it's not specified */ + days = 30; + } if (!set_cert_times(x509ss, NULL, NULL, days)) goto end; if (!X509_set_subject_name @@ -638,13 +666,28 @@ int req_main(int argc, char **argv) X509V3_set_nconf(&ext_ctx, req_conf); /* Add extensions */ - if (extensions && !X509V3_EXT_add_nconf(req_conf, - &ext_ctx, extensions, - x509ss)) { + if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf, + &ext_ctx, extensions, + x509ss)) { BIO_printf(bio_err, "Error Loading extension section %s\n", extensions); goto end; } + if (addext_conf != NULL + && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default", + x509ss)) { + BIO_printf(bio_err, "Error Loading command line extensions\n"); + goto end; + } + + /* If a pre-cert was requested, we need to add a poison extension */ + if (precert) { + if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0) + != 1) { + BIO_printf(bio_err, "Error adding poison extension\n"); + goto end; + } + } i = do_X509_sign(x509ss, pkey, digest, sigopts); if (!i) { @@ -660,13 +703,19 @@ int req_main(int argc, char **argv) X509V3_set_nconf(&ext_ctx, req_conf); /* Add extensions */ - if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf, - &ext_ctx, req_exts, - req)) { + if (req_exts != NULL + && !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; } + if (addext_conf != NULL + && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default", + req)) { + BIO_printf(bio_err, "Error Loading command line extensions\n"); + goto end; + } i = do_X509_REQ_sign(req, pkey, digest, sigopts); if (!i) { ERR_print_errors(bio_err); @@ -684,7 +733,7 @@ int req_main(int argc, char **argv) if (verbose) { BIO_printf(bio_err, "Modifying Request's Subject\n"); print_name(bio_err, "old subject=", - X509_REQ_get_subject_name(req), nmflag); + X509_REQ_get_subject_name(req), get_nameopt()); } if (build_subject(req, subj, chtype, multirdn) == 0) { @@ -695,7 +744,7 @@ int req_main(int argc, char **argv) if (verbose) { print_name(bio_err, "new subject=", - X509_REQ_get_subject_name(req), nmflag); + X509_REQ_get_subject_name(req), get_nameopt()); } } @@ -715,8 +764,9 @@ int req_main(int argc, char **argv) } else if (i == 0) { BIO_printf(bio_err, "verify failure\n"); ERR_print_errors(bio_err); - } else /* if (i > 0) */ + } else { /* if (i > 0) */ BIO_printf(bio_err, "verify OK\n"); + } } if (noout && !text && !modulus && !subject && !pubkey) { @@ -744,18 +794,18 @@ int req_main(int argc, char **argv) if (text) { if (x509) - X509_print_ex(out, x509ss, nmflag, reqflag); + X509_print_ex(out, x509ss, get_nameopt(), reqflag); else - X509_REQ_print_ex(out, req, nmflag, reqflag); + X509_REQ_print_ex(out, req, get_nameopt(), reqflag); } if (subject) { if (x509) print_name(out, "subject=", X509_get_subject_name(x509ss), - nmflag); + get_nameopt()); else print_name(out, "subject=", X509_REQ_get_subject_name(req), - nmflag); + get_nameopt()); } if (modulus) { @@ -809,6 +859,7 @@ int req_main(int argc, char **argv) ERR_print_errors(bio_err); } NCONF_free(req_conf); + BIO_free(addext_bio); BIO_free(in); BIO_free_all(out); EVP_PKEY_free(pkey); @@ -827,7 +878,7 @@ int req_main(int argc, char **argv) OPENSSL_free(passin); if (passout != nofree_passout) OPENSSL_free(passout); - return (ret); + return ret; } static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn, @@ -887,7 +938,7 @@ static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn, ret = 1; err: - return (ret); + return ret; } /* @@ -943,7 +994,8 @@ static int prompt_info(X509_REQ *req, if (sk_CONF_VALUE_num(dn_sk)) { i = -1; - start:for (;;) { + start: + for ( ; ; ) { i++; if (sk_CONF_VALUE_num(dn_sk) <= i) break; @@ -968,35 +1020,36 @@ static int prompt_info(X509_REQ *req, if (*type == '+') { mval = -1; type++; - } else + } 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) - >= (int)sizeof(buf)) { - BIO_printf(bio_err, "Name '%s' too long\n", v->name); + if (!join(buf, sizeof(buf), v->name, "_default", "Name")) return 0; - } - if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) { ERR_clear_error(); def = ""; } - BIO_snprintf(buf, sizeof(buf), "%s_value", v->name); + if (!join(buf, sizeof(buf), v->name, "_value", "Name")) + return 0; if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) { ERR_clear_error(); value = NULL; } - BIO_snprintf(buf, sizeof(buf), "%s_min", v->name); + if (!join(buf, sizeof(buf), v->name, "_min", "Name")) + return 0; if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) { ERR_clear_error(); n_min = -1; } - BIO_snprintf(buf, sizeof(buf), "%s_max", v->name); + + if (!join(buf, sizeof(buf), v->name, "_max", "Name")) + return 0; if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) { ERR_clear_error(); n_max = -1; @@ -1022,7 +1075,8 @@ static int prompt_info(X509_REQ *req, } i = -1; - start2: for (;;) { + start2: + for ( ; ; ) { i++; if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i)) break; @@ -1032,32 +1086,31 @@ static int prompt_info(X509_REQ *req, if ((nid = OBJ_txt2nid(type)) == NID_undef) goto start2; - if (BIO_snprintf(buf, sizeof(buf), "%s_default", type) - >= (int)sizeof(buf)) { - BIO_printf(bio_err, "Name '%s' too long\n", v->name); + if (!join(buf, sizeof(buf), type, "_default", "Name")) return 0; - } - if ((def = NCONF_get_string(req_conf, attr_sect, buf)) == NULL) { ERR_clear_error(); def = ""; } - BIO_snprintf(buf, sizeof(buf), "%s_value", type); + if (!join(buf, sizeof(buf), type, "_value", "Name")) + return 0; if ((value = NCONF_get_string(req_conf, attr_sect, buf)) == NULL) { ERR_clear_error(); value = NULL; } - BIO_snprintf(buf, sizeof(buf), "%s_min", type); + if (!join(buf, sizeof(buf), type,"_min", "Name")) + return 0; if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) { ERR_clear_error(); n_min = -1; } - BIO_snprintf(buf, sizeof(buf), "%s_max", type); + if (!join(buf, sizeof(buf), type, "_max", "Name")) + return 0; if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) { ERR_clear_error(); n_max = -1; @@ -1120,8 +1173,9 @@ static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, if (plus_char) { type++; mval = -1; - } else + } else { mval = 0; + } if (!X509_NAME_add_entry_by_txt(subj, type, chtype, (unsigned char *)v->value, -1, -1, mval)) @@ -1155,8 +1209,8 @@ static int add_DN_object(X509_NAME *n, char *text, const char *def, BIO_printf(bio_err, "%s [%s]:", text, def); (void)BIO_flush(bio_err); if (value != NULL) { - OPENSSL_strlcpy(buf, value, sizeof(buf)); - OPENSSL_strlcat(buf, "\n", sizeof(buf)); + if (!join(buf, sizeof(buf), value, "\n", "DN value")) + return 0; BIO_printf(bio_err, "%s\n", value); } else { buf[0] = '\0'; @@ -1170,19 +1224,20 @@ static int add_DN_object(X509_NAME *n, char *text, const char *def, } if (buf[0] == '\0') - return (0); - else if (buf[0] == '\n') { + return 0; + if (buf[0] == '\n') { if ((def == NULL) || (def[0] == '\0')) - return (1); - OPENSSL_strlcpy(buf, def, sizeof(buf)); - OPENSSL_strlcat(buf, "\n", sizeof(buf)); - } else if ((buf[0] == '.') && (buf[1] == '\n')) - return (1); + return 1; + if (!join(buf, sizeof(buf), def, "\n", "DN default")) + return 0; + } 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); + return 0; } buf[--i] = '\0'; #ifdef CHARSET_EBCDIC @@ -1199,7 +1254,7 @@ static int add_DN_object(X509_NAME *n, char *text, const char *def, goto err; ret = 1; err: - return (ret); + return ret; } static int add_attribute_object(X509_REQ *req, char *text, const char *def, @@ -1214,8 +1269,8 @@ static int add_attribute_object(X509_REQ *req, char *text, const char *def, BIO_printf(bio_err, "%s [%s]:", text, def); (void)BIO_flush(bio_err); if (value != NULL) { - OPENSSL_strlcpy(buf, value, sizeof(buf)); - OPENSSL_strlcat(buf, "\n", sizeof(buf)); + if (!join(buf, sizeof(buf), value, "\n", "Attribute value")) + return 0; BIO_printf(bio_err, "%s\n", value); } else { buf[0] = '\0'; @@ -1229,19 +1284,20 @@ static int add_attribute_object(X509_REQ *req, char *text, const char *def, } if (buf[0] == '\0') - return (0); - else if (buf[0] == '\n') { + return 0; + if (buf[0] == '\n') { if ((def == NULL) || (def[0] == '\0')) - return (1); - OPENSSL_strlcpy(buf, def, sizeof(buf)); - OPENSSL_strlcat(buf, "\n", sizeof(buf)); - } else if ((buf[0] == '.') && (buf[1] == '\n')) - return (1); + return 1; + if (!join(buf, sizeof(buf), def, "\n", "Attribute default")) + return 0; + } 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); + return 0; } buf[--i] = '\0'; #ifdef CHARSET_EBCDIC @@ -1260,9 +1316,9 @@ static int add_attribute_object(X509_REQ *req, char *text, const char *def, goto err; } - return (1); + return 1; err: - return (0); + return 0; } static int req_check_len(int len, int n_min, int n_max) @@ -1271,22 +1327,23 @@ static int req_check_len(int len, int n_min, int n_max) BIO_printf(bio_err, "string is too short, it needs to be at least %d bytes long\n", n_min); - return (0); + return 0; } if ((n_max >= 0) && (len > n_max)) { BIO_printf(bio_err, "string is too long, it needs to be no more than %d bytes long\n", n_max); - return (0); + return 0; } - return (1); + return 1; } /* Check if the end of a string matches 'end' */ static int check_end(const char *str, const char *end) { - int elen, slen; + size_t elen, slen; const char *tmp; + elen = strlen(end); slen = strlen(str); if (elen > slen) @@ -1295,6 +1352,24 @@ static int check_end(const char *str, const char *end) return strcmp(tmp, end); } +/* + * Merge the two strings together into the result buffer checking for + * overflow and producing an error message if there is. + */ +static int join(char buf[], size_t buf_size, const char *name, + const char *tail, const char *desc) +{ + const size_t name_len = strlen(name), tail_len = strlen(tail); + + if (name_len + tail_len + 1 > buf_size) { + BIO_printf(bio_err, "%s '%s' too long\n", desc, name); + return 0; + } + memcpy(buf, name, name_len); + memcpy(buf + name_len, tail, tail_len + 1); + return 1; +} + static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, int *pkey_type, long *pkeylen, char **palgnam, ENGINE *keygen_engine) @@ -1312,15 +1387,15 @@ static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, *pkey_type = EVP_PKEY_RSA; keylen = atol(gstr); *pkeylen = keylen; - } else if (strncmp(gstr, "param:", 6) == 0) + } else if (strncmp(gstr, "param:", 6) == 0) { paramfile = gstr + 6; - else { + } else { const char *p = strchr(gstr, ':'); int len; ENGINE *tmpeng; const EVP_PKEY_ASN1_METHOD *ameth; - if (p) + if (p != NULL) len = p - gstr; else len = strlen(gstr); @@ -1331,7 +1406,7 @@ static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len); - if (!ameth) { + if (ameth == NULL) { BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr); return NULL; } @@ -1341,28 +1416,31 @@ static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, ENGINE_finish(tmpeng); #endif if (*pkey_type == EVP_PKEY_RSA) { - if (p) { + if (p != NULL) { keylen = atol(p + 1); *pkeylen = keylen; - } else + } else { keylen = *pkeylen; - } else if (p) + } + } else if (p != NULL) { paramfile = p + 1; + } } - if (paramfile) { + if (paramfile != NULL) { pbio = BIO_new_file(paramfile, "r"); - if (!pbio) { + if (pbio == NULL) { BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile); return NULL; } param = PEM_read_bio_Parameters(pbio, NULL); - if (!param) { + if (param == NULL) { X509 *x; + (void)BIO_reset(pbio); x = PEM_read_bio_X509(pbio, NULL, NULL, NULL); - if (x) { + if (x != NULL) { param = X509_get_pubkey(x); X509_free(x); } @@ -1370,25 +1448,26 @@ static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, BIO_free(pbio); - if (!param) { + if (param == NULL) { BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile); return NULL; } - if (*pkey_type == -1) + if (*pkey_type == -1) { *pkey_type = EVP_PKEY_id(param); - else if (*pkey_type != EVP_PKEY_base_id(param)) { + } else if (*pkey_type != EVP_PKEY_base_id(param)) { BIO_printf(bio_err, "Key Type does not match parameters\n"); EVP_PKEY_free(param); return NULL; } } - if (palgnam) { + if (palgnam != NULL) { const EVP_PKEY_ASN1_METHOD *ameth; ENGINE *tmpeng; const char *anam; + ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type); - if (!ameth) { + if (ameth == NULL) { BIO_puts(bio_err, "Internal error: can't find key algorithm\n"); return NULL; } @@ -1399,12 +1478,13 @@ static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, #endif } - if (param) { + if (param != NULL) { gctx = EVP_PKEY_CTX_new(param, keygen_engine); *pkeylen = EVP_PKEY_bits(param); EVP_PKEY_free(param); - } else + } else { gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine); + } if (gctx == NULL) { BIO_puts(bio_err, "Error allocating keygen context\n"); diff --git a/apps/rsa.c b/apps/rsa.c index 8b15fcba..6458b3d9 100644 --- a/apps/rsa.c +++ b/apps/rsa.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -17,6 +17,7 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # include # include # include @@ -35,7 +36,7 @@ typedef enum OPTION_choice { OPT_NOOUT, OPT_TEXT, OPT_MODULUS, OPT_CHECK, OPT_CIPHER } OPTION_CHOICE; -OPTIONS rsa_options[] = { +const OPTIONS rsa_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'f', "Input format, one of DER NET PEM"}, {"outform", OPT_OUTFORM, 'f', "Output format, one of DER NET PEM PVK"}, @@ -176,12 +177,14 @@ int rsa_main(int argc, char **argv) tmpformat = FORMAT_PEMRSA; else if (informat == FORMAT_ASN1) tmpformat = FORMAT_ASN1RSA; - } else + } else { tmpformat = informat; + } pkey = load_pubkey(infile, tmpformat, 1, passin, e, "Public Key"); - } else + } else { pkey = load_key(infile, informat, 1, passin, e, "Private Key"); + } if (pkey != NULL) rsa = EVP_PKEY_get1_RSA(pkey); @@ -217,9 +220,9 @@ int rsa_main(int argc, char **argv) if (check) { int r = RSA_check_key_ex(rsa, NULL); - if (r == 1) + if (r == 1) { BIO_printf(out, "RSA key ok\n"); - else if (r == 0) { + } else if (r == 0) { unsigned long err; while ((err = ERR_peek_error()) != 0 && @@ -228,7 +231,7 @@ int rsa_main(int argc, char **argv) ERR_GET_REASON(err) != ERR_R_MALLOC_FAILURE) { BIO_printf(out, "RSA key error: %s\n", ERR_reason_error_string(err)); - ERR_get_error(); /* remove e from error stack */ + ERR_get_error(); /* remove err from error stack */ } } else if (r == -1) { ERR_print_errors(bio_err); @@ -251,8 +254,7 @@ int rsa_main(int argc, char **argv) assert(private); i = i2d_RSAPrivateKey_bio(out, rsa); } - } - else if (outformat == FORMAT_PEM) { + } else if (outformat == FORMAT_PEM) { if (pubout || pubin) { if (pubout == 2) i = PEM_write_bio_RSAPublicKey(out, rsa); @@ -297,14 +299,15 @@ int rsa_main(int argc, char **argv) if (i <= 0) { BIO_printf(bio_err, "unable to write key\n"); ERR_print_errors(bio_err); - } else + } else { ret = 0; + } end: release_engine(e); BIO_free_all(out); RSA_free(rsa); OPENSSL_free(passin); OPENSSL_free(passout); - return (ret); + return ret; } #endif diff --git a/apps/rsautl.c b/apps/rsautl.c index d527bf4d..5da8504d 100644 --- a/apps/rsautl.c +++ b/apps/rsautl.c @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-2018 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 @@ -13,6 +13,7 @@ NON_EMPTY_TRANSLATION_UNIT #else # include "apps.h" +# include "progs.h" # include # include # include @@ -32,10 +33,11 @@ typedef enum OPTION_choice { OPT_ENGINE, OPT_IN, OPT_OUT, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_RAW, OPT_OAEP, OPT_SSL, OPT_PKCS, OPT_X931, OPT_SIGN, OPT_VERIFY, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT, - OPT_PUBIN, OPT_CERTIN, OPT_INKEY, OPT_PASSIN, OPT_KEYFORM + OPT_PUBIN, OPT_CERTIN, OPT_INKEY, OPT_PASSIN, OPT_KEYFORM, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS rsautl_options[] = { +const OPTIONS rsautl_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Input file"}, {"out", OPT_OUT, '>', "Output file"}, @@ -57,6 +59,7 @@ OPTIONS rsautl_options[] = { {"encrypt", OPT_ENCRYPT, '-', "Encrypt with public key"}, {"decrypt", OPT_DECRYPT, '-', "Decrypt with private key"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, + OPT_R_OPTIONS, # ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, # endif @@ -153,6 +156,10 @@ int rsautl_main(int argc, char **argv) case OPT_PASSIN: passinarg = opt_arg(); break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; } } argc = opt_num_rest(); @@ -169,9 +176,6 @@ int rsautl_main(int argc, char **argv) goto end; } -/* FIXME: seed PRNG only if needed */ - app_RAND_load_file(NULL, 0); - switch (key_type) { case KEY_PRIVKEY: pkey = load_key(keyfile, keyformat, 0, passin, e, "Private Key"); @@ -190,14 +194,13 @@ int rsautl_main(int argc, char **argv) break; } - if (!pkey) { + if (pkey == NULL) return 1; - } rsa = EVP_PKEY_get1_RSA(pkey); EVP_PKEY_free(pkey); - if (!rsa) { + if (rsa == NULL) { BIO_printf(bio_err, "Error getting RSA key\n"); ERR_print_errors(bio_err); goto end; @@ -261,10 +264,11 @@ int rsautl_main(int argc, char **argv) if (!ASN1_parse_dump(out, rsa_out, rsa_outlen, 1, -1)) { ERR_print_errors(bio_err); } - } else if (hexdump) + } else if (hexdump) { BIO_dump(out, (char *)rsa_out, rsa_outlen); - else + } else { BIO_write(out, rsa_out, rsa_outlen); + } end: RSA_free(rsa); release_engine(e); diff --git a/apps/s_apps.h b/apps/s_apps.h index c47932bf..614aab80 100644 --- a/apps/s_apps.h +++ b/apps/s_apps.h @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -17,37 +17,12 @@ # define _kbhit kbhit #endif -#if defined(OPENSSL_SYS_VMS) && !defined(FD_SET) -/* - * VAX C does not defined fd_set and friends, but it's actually quite simple - */ -/* These definitions are borrowed from SOCKETSHR. /Richard Levitte */ -# define MAX_NOFILE 32 -# define NBBY 8 /* number of bits in a byte */ - -# ifndef FD_SETSIZE -# define FD_SETSIZE MAX_NOFILE -# endif /* FD_SETSIZE */ - -/* How many things we'll allow select to use. 0 if unlimited */ -# define MAXSELFD MAX_NOFILE -typedef int fd_mask; /* int here! VMS prototypes int, not long */ -# define NFDBITS (sizeof(fd_mask) * NBBY)/* bits per mask (power of 2!) */ -# define NFDSHIFT 5 /* Shift based on above */ - -typedef fd_mask fd_set; -# define FD_SET(n, p) (*(p) |= (1 << ((n) % NFDBITS))) -# define FD_CLR(n, p) (*(p) &= ~(1 << ((n) % NFDBITS))) -# define FD_ISSET(n, p) (*(p) & (1 << ((n) % NFDBITS))) -# define FD_ZERO(p) memset((p), 0, sizeof(*(p))) -#endif - #define PORT "4433" #define PROTOCOL "tcp" -typedef int (*do_server_cb)(int s, int stype, unsigned char *context); +typedef int (*do_server_cb)(int s, int stype, int prot, unsigned char *context); int do_server(int *accept_sock, const char *host, const char *port, - int family, int type, + int family, int type, int protocol, do_server_cb cb, unsigned char *context, int naccept); #ifdef HEADER_X509_H @@ -59,11 +34,12 @@ int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key, STACK_OF(X509) *chain, int build_chain); int ssl_print_sigalgs(BIO *out, SSL *s); int ssl_print_point_formats(BIO *out, SSL *s); -int ssl_print_curves(BIO *out, SSL *s, int noshared); +int ssl_print_groups(BIO *out, SSL *s, int noshared); #endif int ssl_print_tmp_key(BIO *out, SSL *s); int init_client(int *sock, const char *host, const char *port, - int family, int type); + const char *bindhost, const char *bindport, + int family, int type, int protocol); int should_retry(int i); long bio_dump_callback(BIO *bio, int cmd, const char *argp, @@ -99,4 +75,6 @@ int ssl_load_stores(SSL_CTX *ctx, const char *vfyCApath, const char *chCAfile, STACK_OF(X509_CRL) *crls, int crl_download); void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose); +int set_keylog_file(SSL_CTX *ctx, const char *keylog_file); +void print_ca_names(BIO *bio, SSL *s); #endif diff --git a/apps/s_cb.c b/apps/s_cb.c index afa30654..23031092 100644 --- a/apps/s_cb.c +++ b/apps/s_cb.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -11,9 +11,7 @@ #include #include #include /* for memcpy() and strcmp() */ -#define USE_SOCKETS #include "apps.h" -#undef USE_SOCKETS #include #include #include @@ -32,6 +30,7 @@ VERIFY_CB_ARGS verify_args = { 0, 0, X509_V_OK, 0 }; static unsigned char cookie_secret[COOKIE_SECRET_LENGTH]; static int cookie_initialized = 0; #endif +static BIO *bio_keylog = NULL; static const char *lookup(int val, const STRINT_PAIR* list, const char* def) { @@ -52,13 +51,14 @@ int verify_callback(int ok, X509_STORE_CTX *ctx) if (!verify_args.quiet || !ok) { BIO_printf(bio_err, "depth=%d ", depth); - if (err_cert) { + if (err_cert != NULL) { X509_NAME_print_ex(bio_err, X509_get_subject_name(err_cert), - 0, XN_FLAG_ONELINE); + 0, get_nameopt()); BIO_puts(bio_err, "\n"); - } else + } else { BIO_puts(bio_err, "\n"); + } } if (!ok) { BIO_printf(bio_err, "verify error:num=%d:%s\n", err, @@ -76,7 +76,7 @@ int verify_callback(int ok, X509_STORE_CTX *ctx) case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: BIO_puts(bio_err, "issuer= "); X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert), - 0, XN_FLAG_ONELINE); + 0, get_nameopt()); BIO_puts(bio_err, "\n"); break; case X509_V_ERR_CERT_NOT_YET_VALID: @@ -100,7 +100,7 @@ int verify_callback(int ok, X509_STORE_CTX *ctx) policies_print(ctx); if (ok && !verify_args.quiet) BIO_printf(bio_err, "verify return:%d\n", ok); - return (ok); + return ok; } int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file) @@ -111,7 +111,7 @@ int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file) BIO_printf(bio_err, "unable to get certificate from '%s'\n", cert_file); ERR_print_errors(bio_err); - return (0); + return 0; } if (key_file == NULL) key_file = cert_file; @@ -119,7 +119,7 @@ int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file) BIO_printf(bio_err, "unable to get private key from '%s'\n", key_file); ERR_print_errors(bio_err); - return (0); + return 0; } /* @@ -134,10 +134,10 @@ int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file) if (!SSL_CTX_check_private_key(ctx)) { BIO_printf(bio_err, "Private key does not match the certificate public key\n"); - return (0); + return 0; } } - return (1); + return 1; } int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key, @@ -205,7 +205,7 @@ static void ssl_print_client_cert_types(BIO *bio, SSL *s) if (i) BIO_puts(bio, ", "); - if (cname) + if (cname != NULL) BIO_puts(bio, cname); else BIO_printf(bio, "UNKNOWN (%d),", cert_type); @@ -213,12 +213,35 @@ static void ssl_print_client_cert_types(BIO *bio, SSL *s) BIO_puts(bio, "\n"); } +static const char *get_sigtype(int nid) +{ + switch (nid) { + case EVP_PKEY_RSA: + return "RSA"; + + case EVP_PKEY_RSA_PSS: + return "RSA-PSS"; + + case EVP_PKEY_DSA: + return "DSA"; + + case EVP_PKEY_EC: + return "ECDSA"; + + case NID_ED25519: + return "Ed25519"; + + default: + return NULL; + } +} + static int do_print_sigalgs(BIO *out, SSL *s, int shared) { int i, nsig, client; client = SSL_is_server(s) ? 0 : 1; if (shared) - nsig = SSL_get_shared_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL); + nsig = SSL_get_shared_sigalgs(s, 0, NULL, NULL, NULL, NULL, NULL); else nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL); if (nsig == 0) @@ -241,20 +264,15 @@ static int do_print_sigalgs(BIO *out, SSL *s, int shared) SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash); if (i) BIO_puts(out, ":"); - if (sign_nid == EVP_PKEY_RSA) - sstr = "RSA"; - else if (sign_nid == EVP_PKEY_DSA) - sstr = "DSA"; - else if (sign_nid == EVP_PKEY_EC) - sstr = "ECDSA"; + sstr = get_sigtype(sign_nid); if (sstr) - BIO_printf(out, "%s+", sstr); + BIO_printf(out, "%s", sstr); else - BIO_printf(out, "0x%02X+", (int)rsign); + BIO_printf(out, "0x%02X", (int)rsign); if (hash_nid != NID_undef) - BIO_printf(out, "%s", OBJ_nid2sn(hash_nid)); - else - BIO_printf(out, "0x%02X", (int)rhash); + BIO_printf(out, "+%s", OBJ_nid2sn(hash_nid)); + else if (sstr == NULL) + BIO_printf(out, "+0x%02X", (int)rhash); } BIO_puts(out, "\n"); return 1; @@ -262,13 +280,15 @@ static int do_print_sigalgs(BIO *out, SSL *s, int shared) int ssl_print_sigalgs(BIO *out, SSL *s) { - int mdnid; + int nid; if (!SSL_is_server(s)) ssl_print_client_cert_types(out, s); do_print_sigalgs(out, s, 0); do_print_sigalgs(out, s, 1); - if (SSL_get_peer_signature_nid(s, &mdnid)) - BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(mdnid)); + if (SSL_get_peer_signature_nid(s, &nid) && nid != NID_undef) + BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(nid)); + if (SSL_get_peer_signature_type_nid(s, &nid)) + BIO_printf(out, "Peer signature type: %s\n", get_sigtype(nid)); return 1; } @@ -307,55 +327,58 @@ int ssl_print_point_formats(BIO *out, SSL *s) return 1; } -int ssl_print_curves(BIO *out, SSL *s, int noshared) +int ssl_print_groups(BIO *out, SSL *s, int noshared) { - int i, ncurves, *curves, nid; - const char *cname; + int i, ngroups, *groups, nid; + const char *gname; - ncurves = SSL_get1_curves(s, NULL); - if (ncurves <= 0) + ngroups = SSL_get1_groups(s, NULL); + if (ngroups <= 0) return 1; - curves = app_malloc(ncurves * sizeof(int), "curves to print"); - SSL_get1_curves(s, curves); + groups = app_malloc(ngroups * sizeof(int), "groups to print"); + SSL_get1_groups(s, groups); - BIO_puts(out, "Supported Elliptic Curves: "); - for (i = 0; i < ncurves; i++) { + BIO_puts(out, "Supported Elliptic Groups: "); + for (i = 0; i < ngroups; i++) { if (i) BIO_puts(out, ":"); - nid = curves[i]; + nid = groups[i]; /* If unrecognised print out hex version */ - if (nid & TLSEXT_nid_unknown) + if (nid & TLSEXT_nid_unknown) { BIO_printf(out, "0x%04X", nid & 0xFFFF); - else { + } else { + /* TODO(TLS1.3): Get group name here */ /* Use NIST name for curve if it exists */ - cname = EC_curve_nid2nist(nid); - if (!cname) - cname = OBJ_nid2sn(nid); - BIO_printf(out, "%s", cname); + gname = EC_curve_nid2nist(nid); + if (gname == NULL) + gname = OBJ_nid2sn(nid); + BIO_printf(out, "%s", gname); } } - OPENSSL_free(curves); + OPENSSL_free(groups); if (noshared) { BIO_puts(out, "\n"); return 1; } - BIO_puts(out, "\nShared Elliptic curves: "); - ncurves = SSL_get_shared_curve(s, -1); - for (i = 0; i < ncurves; i++) { + BIO_puts(out, "\nShared Elliptic groups: "); + ngroups = SSL_get_shared_group(s, -1); + for (i = 0; i < ngroups; i++) { if (i) BIO_puts(out, ":"); - nid = SSL_get_shared_curve(s, i); - cname = EC_curve_nid2nist(nid); - if (!cname) - cname = OBJ_nid2sn(nid); - BIO_printf(out, "%s", cname); + nid = SSL_get_shared_group(s, i); + /* TODO(TLS1.3): Convert for DH groups */ + gname = EC_curve_nid2nist(nid); + if (gname == NULL) + gname = OBJ_nid2sn(nid); + BIO_printf(out, "%s", gname); } - if (ncurves == 0) + if (ngroups == 0) BIO_puts(out, "NONE"); BIO_puts(out, "\n"); return 1; } #endif + int ssl_print_tmp_key(BIO *out, SSL *s) { EVP_PKEY *key; @@ -379,7 +402,7 @@ int ssl_print_tmp_key(BIO *out, SSL *s) nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec)); EC_KEY_free(ec); cname = EC_curve_nid2nist(nid); - if (!cname) + if (cname == NULL) cname = OBJ_nid2sn(nid); BIO_printf(out, "ECDH, %s, %d bits\n", cname, EVP_PKEY_bits(key)); } @@ -400,19 +423,19 @@ long bio_dump_callback(BIO *bio, int cmd, const char *argp, out = (BIO *)BIO_get_callback_arg(bio); if (out == NULL) - return (ret); + return ret; if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) { BIO_printf(out, "read from %p [%p] (%lu bytes => %ld (0x%lX))\n", (void *)bio, (void *)argp, (unsigned long)argi, ret, ret); BIO_dump(out, argp, (int)ret); - return (ret); + return ret; } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) { BIO_printf(out, "write to %p [%p] (%lu bytes => %ld (0x%lX))\n", (void *)bio, (void *)argp, (unsigned long)argi, ret, ret); BIO_dump(out, argp, (int)ret); } - return (ret); + return ret; } void apps_ssl_info_callback(const SSL *s, int where, int ret) @@ -441,10 +464,9 @@ void apps_ssl_info_callback(const SSL *s, int where, int ret) if (ret == 0) BIO_printf(bio_err, "%s:failed in %s\n", str, SSL_state_string_long(s)); - else if (ret < 0) { + else if (ret < 0) BIO_printf(bio_err, "%s:error in %s\n", str, SSL_state_string_long(s)); - } } } @@ -453,12 +475,15 @@ static STRINT_PAIR ssl_versions[] = { {"TLS 1.0", TLS1_VERSION}, {"TLS 1.1", TLS1_1_VERSION}, {"TLS 1.2", TLS1_2_VERSION}, + {"TLS 1.3", TLS1_3_VERSION}, {"DTLS 1.0", DTLS1_VERSION}, {"DTLS 1.0 (bad)", DTLS1_BAD_VER}, {NULL} }; + static STRINT_PAIR alert_types[] = { {" close_notify", 0}, + {" end_of_early_data", 1}, {" unexpected_message", 10}, {" bad_record_mac", 20}, {" decryption_failed", 21}, @@ -479,33 +504,43 @@ static STRINT_PAIR alert_types[] = { {" protocol_version", 70}, {" insufficient_security", 71}, {" internal_error", 80}, + {" inappropriate_fallback", 86}, {" user_canceled", 90}, {" no_renegotiation", 100}, + {" missing_extension", 109}, {" unsupported_extension", 110}, {" certificate_unobtainable", 111}, {" unrecognized_name", 112}, {" bad_certificate_status_response", 113}, {" bad_certificate_hash_value", 114}, {" unknown_psk_identity", 115}, + {" certificate_required", 116}, {NULL} }; static STRINT_PAIR handshakes[] = { - {", HelloRequest", 0}, - {", ClientHello", 1}, - {", ServerHello", 2}, - {", HelloVerifyRequest", 3}, - {", NewSessionTicket", 4}, - {", Certificate", 11}, - {", ServerKeyExchange", 12}, - {", CertificateRequest", 13}, - {", ServerHelloDone", 14}, - {", CertificateVerify", 15}, - {", ClientKeyExchange", 16}, - {", Finished", 20}, + {", HelloRequest", SSL3_MT_HELLO_REQUEST}, + {", ClientHello", SSL3_MT_CLIENT_HELLO}, + {", ServerHello", SSL3_MT_SERVER_HELLO}, + {", HelloVerifyRequest", DTLS1_MT_HELLO_VERIFY_REQUEST}, + {", NewSessionTicket", SSL3_MT_NEWSESSION_TICKET}, + {", EndOfEarlyData", SSL3_MT_END_OF_EARLY_DATA}, + {", EncryptedExtensions", SSL3_MT_ENCRYPTED_EXTENSIONS}, + {", Certificate", SSL3_MT_CERTIFICATE}, + {", ServerKeyExchange", SSL3_MT_SERVER_KEY_EXCHANGE}, + {", CertificateRequest", SSL3_MT_CERTIFICATE_REQUEST}, + {", ServerHelloDone", SSL3_MT_SERVER_DONE}, + {", CertificateVerify", SSL3_MT_CERTIFICATE_VERIFY}, + {", ClientKeyExchange", SSL3_MT_CLIENT_KEY_EXCHANGE}, + {", Finished", SSL3_MT_FINISHED}, {", CertificateUrl", 21}, - {", CertificateStatus", 22}, + {", CertificateStatus", SSL3_MT_CERTIFICATE_STATUS}, {", SupplementalData", 23}, + {", KeyUpdate", SSL3_MT_KEY_UPDATE}, +#ifndef OPENSSL_NO_NEXTPROTONEG + {", NextProto", SSL3_MT_NEXT_PROTO}, +#endif + {", MessageHash", SSL3_MT_MESSAGE_HASH}, {NULL} }; @@ -522,13 +557,14 @@ void msg_cb(int write_p, int version, int content_type, const void *buf, version == TLS1_VERSION || version == TLS1_1_VERSION || version == TLS1_2_VERSION || + version == TLS1_3_VERSION || version == DTLS1_VERSION || version == DTLS1_BAD_VER) { switch (content_type) { case 20: - str_content_type = "ChangeCipherSpec"; + str_content_type = ", ChangeCipherSpec"; break; case 21: - str_content_type = "Alert"; + str_content_type = ", Alert"; str_details1 = ", ???"; if (len == 2) { switch (bp[0]) { @@ -543,13 +579,13 @@ void msg_cb(int write_p, int version, int content_type, const void *buf, } break; case 22: - str_content_type = "Handshake"; + str_content_type = ", Handshake"; str_details1 = "???"; if (len > 0) str_details1 = lookup((int)bp[0], handshakes, "???"); break; case 23: - str_content_type = "ApplicationData"; + str_content_type = ", ApplicationData"; break; #ifndef OPENSSL_NO_HEARTBEATS case 24: @@ -602,7 +638,7 @@ static STRINT_PAIR tlsext_types[] = { {"client authz", TLSEXT_TYPE_client_authz}, {"server authz", TLSEXT_TYPE_server_authz}, {"cert type", TLSEXT_TYPE_cert_type}, - {"elliptic curves", TLSEXT_TYPE_elliptic_curves}, + {"supported_groups", TLSEXT_TYPE_supported_groups}, {"EC point formats", TLSEXT_TYPE_ec_point_formats}, {"SRP", TLSEXT_TYPE_srp}, {"signature algorithms", TLSEXT_TYPE_signature_algorithms}, @@ -625,6 +661,12 @@ static STRINT_PAIR tlsext_types[] = { #ifdef TLSEXT_TYPE_extended_master_secret {"extended master secret", TLSEXT_TYPE_extended_master_secret}, #endif + {"key share", TLSEXT_TYPE_key_share}, + {"supported versions", TLSEXT_TYPE_supported_versions}, + {"psk", TLSEXT_TYPE_psk}, + {"psk kex modes", TLSEXT_TYPE_psk_kex_modes}, + {"certificate authorities", TLSEXT_TYPE_certificate_authorities}, + {"post handshake auth", TLSEXT_TYPE_post_handshake_auth}, {NULL} }; @@ -645,9 +687,9 @@ int generate_cookie_callback(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len) { unsigned char *buffer; - size_t length; + size_t length = 0; unsigned short port; - BIO_ADDR *peer = NULL; + BIO_ADDR *lpeer = NULL, *peer = NULL; /* Initialize a random secret */ if (!cookie_initialized) { @@ -658,17 +700,24 @@ int generate_cookie_callback(SSL *ssl, unsigned char *cookie, cookie_initialized = 1; } - peer = BIO_ADDR_new(); - if (peer == NULL) { - BIO_printf(bio_err, "memory full\n"); - return 0; + if (SSL_is_dtls(ssl)) { + lpeer = peer = BIO_ADDR_new(); + if (peer == NULL) { + BIO_printf(bio_err, "memory full\n"); + return 0; + } + + /* Read peer information */ + (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), peer); + } else { + peer = ourpeer; } - /* Read peer information */ - (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), peer); - /* Create buffer with peer's address and port */ - BIO_ADDR_rawaddress(peer, NULL, &length); + if (!BIO_ADDR_rawaddress(peer, NULL, &length)) { + BIO_printf(bio_err, "Failed getting peer address\n"); + return 0; + } OPENSSL_assert(length != 0); port = BIO_ADDR_rawport(peer); length += sizeof(port); @@ -682,7 +731,7 @@ int generate_cookie_callback(SSL *ssl, unsigned char *cookie, buffer, length, cookie, cookie_len); OPENSSL_free(buffer); - BIO_ADDR_free(peer); + BIO_ADDR_free(lpeer); return 1; } @@ -774,24 +823,24 @@ static int set_cert_cb(SSL *ssl, void *arg) #endif SSL_certs_clear(ssl); - if (!exc) + if (exc == NULL) return 1; /* * Go to end of list and traverse backwards since we prepend newer * entries this retains the original order. */ - while (exc->next) + while (exc->next != NULL) exc = exc->next; i = 0; - while (exc) { + while (exc != NULL) { i++; rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain); BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i); X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0, - XN_FLAG_ONELINE); + get_nameopt()); BIO_puts(bio_err, "\n"); print_chain_flags(ssl, rv); if (rv & CERT_PKEY_VALID) { @@ -807,8 +856,9 @@ static int set_cert_cb(SSL *ssl, void *arg) if (exc->build_chain) { if (!SSL_build_cert_chain(ssl, 0)) return 0; - } else if (exc->chain) + } else if (exc->chain != NULL) { SSL_set1_chain(ssl, exc->chain); + } } exc = exc->prev; } @@ -845,7 +895,7 @@ void ssl_excert_free(SSL_EXCERT *exc) { SSL_EXCERT *curr; - if (!exc) + if (exc == NULL) return; while (exc) { X509_free(exc->cert); @@ -860,33 +910,33 @@ void ssl_excert_free(SSL_EXCERT *exc) int load_excert(SSL_EXCERT **pexc) { SSL_EXCERT *exc = *pexc; - if (!exc) + if (exc == NULL) return 1; /* If nothing in list, free and set to NULL */ - if (!exc->certfile && !exc->next) { + if (exc->certfile == NULL && exc->next == NULL) { ssl_excert_free(exc); *pexc = NULL; return 1; } for (; exc; exc = exc->next) { - if (!exc->certfile) { + if (exc->certfile == NULL) { BIO_printf(bio_err, "Missing filename\n"); return 0; } exc->cert = load_cert(exc->certfile, exc->certform, "Server Certificate"); - if (!exc->cert) + if (exc->cert == NULL) return 0; - if (exc->keyfile) { + if (exc->keyfile != NULL) { exc->key = load_key(exc->keyfile, exc->keyform, 0, NULL, NULL, "Server Key"); } else { exc->key = load_key(exc->certfile, exc->certform, 0, NULL, NULL, "Server Key"); } - if (!exc->key) + if (exc->key == NULL) return 0; - if (exc->chainfile) { + if (exc->chainfile != NULL) { if (!load_certs(exc->chainfile, &exc->chain, FORMAT_PEM, NULL, "Server Chain")) return 0; @@ -918,7 +968,7 @@ int args_excert(int opt, SSL_EXCERT **pexc) case OPT_X__LAST: return 0; case OPT_X_CERT: - if (exc->certfile && !ssl_excert_prepend(&exc)) { + if (exc->certfile != NULL && !ssl_excert_prepend(&exc)) { BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog()); goto err; } @@ -926,14 +976,14 @@ int args_excert(int opt, SSL_EXCERT **pexc) exc->certfile = opt_arg(); break; case OPT_X_KEY: - if (exc->keyfile) { + if (exc->keyfile != NULL) { BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog()); goto err; } exc->keyfile = opt_arg(); break; case OPT_X_CHAIN: - if (exc->chainfile) { + if (exc->chainfile != NULL) { BIO_printf(bio_err, "%s: Chain already specified\n", opt_getprog()); goto err; @@ -976,11 +1026,11 @@ static void print_raw_cipherlist(SSL *s) const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist); if (i) BIO_puts(bio_err, ":"); - if (c) + if (c != NULL) { BIO_puts(bio_err, SSL_CIPHER_get_name(c)); - else if (!memcmp(rlist, scsv_id, num)) + } else if (memcmp(rlist, scsv_id, num) == 0) { BIO_puts(bio_err, "SCSV"); - else { + } else { size_t j; BIO_puts(bio_err, "0x"); for (j = 0; j < num; j++) @@ -1002,8 +1052,8 @@ static char *hexencode(const unsigned char *data, size_t len) int ilen = (int) outlen; if (outlen < len || ilen < 0 || outlen != (size_t)ilen) { - BIO_printf(bio_err, "%s: %"BIO_PRI64"u-byte buffer too large to hexencode\n", - opt_getprog(), (uint64_t)len); + BIO_printf(bio_err, "%s: %zu-byte buffer too large to hexencode\n", + opt_getprog(), len); exit(1); } cp = out = app_malloc(ilen, "TLSA hex data buffer"); @@ -1068,7 +1118,6 @@ void print_ssl_summary(SSL *s) { const SSL_CIPHER *c; X509 *peer; - /* const char *pnam = SSL_is_server(s) ? "client" : "server"; */ BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s)); print_raw_cipherlist(s); @@ -1076,23 +1125,26 @@ void print_ssl_summary(SSL *s) BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c)); do_print_sigalgs(bio_err, s, 0); peer = SSL_get_peer_certificate(s); - if (peer) { + if (peer != NULL) { int nid; BIO_puts(bio_err, "Peer certificate: "); X509_NAME_print_ex(bio_err, X509_get_subject_name(peer), - 0, XN_FLAG_ONELINE); + 0, get_nameopt()); BIO_puts(bio_err, "\n"); if (SSL_get_peer_signature_nid(s, &nid)) BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid)); + if (SSL_get_peer_signature_type_nid(s, &nid)) + BIO_printf(bio_err, "Signature type: %s\n", get_sigtype(nid)); print_verify_detail(s, bio_err); - } else + } else { BIO_puts(bio_err, "No peer certificate\n"); + } X509_free(peer); #ifndef OPENSSL_NO_EC ssl_print_point_formats(bio_err, s); if (SSL_is_server(s)) - ssl_print_curves(bio_err, s, 1); + ssl_print_groups(bio_err, s, 1); else ssl_print_tmp_key(bio_err, s); #else @@ -1111,7 +1163,7 @@ int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str, const char *flag = sk_OPENSSL_STRING_value(str, i); const char *arg = sk_OPENSSL_STRING_value(str, i + 1); if (SSL_CONF_cmd(cctx, flag, arg) <= 0) { - if (arg) + if (arg != NULL) BIO_printf(bio_err, "Error with command: \"%s %s\"\n", flag, arg); else @@ -1245,7 +1297,7 @@ static int security_callback_debug(const SSL *s, const SSL_CTX *ctx, cert_md = 1; break; } - if (nm) + if (nm != NULL) BIO_printf(sdb->out, "%s=", nm); switch (op & SSL_SECOP_OTHER_TYPE) { @@ -1333,3 +1385,68 @@ void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose) SSL_CTX_set_security_callback(ctx, security_callback_debug); SSL_CTX_set0_security_ex_data(ctx, &sdb); } + +static void keylog_callback(const SSL *ssl, const char *line) +{ + if (bio_keylog == NULL) { + BIO_printf(bio_err, "Keylog callback is invoked without valid file!\n"); + return; + } + + /* + * There might be concurrent writers to the keylog file, so we must ensure + * that the given line is written at once. + */ + BIO_printf(bio_keylog, "%s\n", line); + (void)BIO_flush(bio_keylog); +} + +int set_keylog_file(SSL_CTX *ctx, const char *keylog_file) +{ + /* Close any open files */ + BIO_free_all(bio_keylog); + bio_keylog = NULL; + + if (ctx == NULL || keylog_file == NULL) { + /* Keylogging is disabled, OK. */ + return 0; + } + + /* + * Append rather than write in order to allow concurrent modification. + * Furthermore, this preserves existing keylog files which is useful when + * the tool is run multiple times. + */ + bio_keylog = BIO_new_file(keylog_file, "a"); + if (bio_keylog == NULL) { + BIO_printf(bio_err, "Error writing keylog file %s\n", keylog_file); + return 1; + } + + /* Write a header for seekable, empty files (this excludes pipes). */ + if (BIO_tell(bio_keylog) == 0) { + BIO_puts(bio_keylog, + "# SSL/TLS secrets log file, generated by OpenSSL\n"); + (void)BIO_flush(bio_keylog); + } + SSL_CTX_set_keylog_callback(ctx, keylog_callback); + return 0; +} + +void print_ca_names(BIO *bio, SSL *s) +{ + const char *cs = SSL_is_server(s) ? "server" : "client"; + const STACK_OF(X509_NAME) *sk = SSL_get0_peer_CA_list(s); + int i; + + if (sk == NULL || sk_X509_NAME_num(sk) == 0) { + BIO_printf(bio, "---\nNo %s certificate CA names sent\n", cs); + return; + } + + BIO_printf(bio, "---\nAcceptable %s certificate CA names\n",cs); + for (i = 0; i < sk_X509_NAME_num(sk); i++) { + X509_NAME_print_ex(bio, sk_X509_NAME_value(sk, i), 0, get_nameopt()); + BIO_write(bio, "\n", 1); + } +} diff --git a/apps/s_client.c b/apps/s_client.c index fb89f0cd..a319d217 100644 --- a/apps/s_client.c +++ b/apps/s_client.c @@ -1,5 +1,6 @@ /* * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2005 Nokia. 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 @@ -7,33 +8,7 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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 "e_os.h" #include #include #include @@ -54,8 +29,8 @@ typedef unsigned int u_int; #endif -#define USE_SOCKETS #include "apps.h" +#include "progs.h" #include #include #include @@ -72,6 +47,7 @@ typedef unsigned int u_int; #endif #include "s_apps.h" #include "timeouts.h" +#include "internal/sockets.h" #if defined(__has_feature) # if __has_feature(memory_sanitizer) @@ -90,11 +66,14 @@ static char *keymatexportlabel = NULL; static int keymatexportlen = 20; static BIO *bio_c_out = NULL; static int c_quiet = 0; +static char *sess_out = NULL; +static SSL_SESSION *psksess = NULL; static void print_stuff(BIO *berr, SSL *con, int full); #ifndef OPENSSL_NO_OCSP static int ocsp_resp_cb(SSL *s, void *arg); #endif +static int ldap_ExtendedResponse_parse(const char *buf, long rem); static int saved_errno; @@ -132,13 +111,10 @@ static void do_ssl_shutdown(SSL *ssl) } while (ret < 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 - */ +#ifndef OPENSSL_NO_PSK static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, @@ -155,8 +131,9 @@ static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity, if (c_debug) BIO_printf(bio_c_out, "NULL received PSK identity hint, continuing anyway\n"); - } else if (c_debug) + } 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 @@ -197,6 +174,76 @@ static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity, } #endif +const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 }; +const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 }; + +static int psk_use_session_cb(SSL *s, const EVP_MD *md, + const unsigned char **id, size_t *idlen, + SSL_SESSION **sess) +{ + SSL_SESSION *usesess = NULL; + const SSL_CIPHER *cipher = NULL; + + if (psksess != NULL) { + SSL_SESSION_up_ref(psksess); + usesess = psksess; + } else { + long key_len; + unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len); + + if (key == NULL) { + BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", + psk_key); + return 0; + } + + if (key_len == EVP_MD_size(EVP_sha256())) + cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id); + else if (key_len == EVP_MD_size(EVP_sha384())) + cipher = SSL_CIPHER_find(s, tls13_aes256gcmsha384_id); + + if (cipher == NULL) { + /* Doesn't look like a suitable TLSv1.3 key. Ignore it */ + OPENSSL_free(key); + *id = NULL; + *idlen = 0; + *sess = NULL; + return 1; + } + usesess = SSL_SESSION_new(); + if (usesess == NULL + || !SSL_SESSION_set1_master_key(usesess, key, key_len) + || !SSL_SESSION_set_cipher(usesess, cipher) + || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) { + OPENSSL_free(key); + goto err; + } + OPENSSL_free(key); + } + + cipher = SSL_SESSION_get0_cipher(usesess); + if (cipher == NULL) + goto err; + + if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) { + /* PSK not usable, ignore it */ + *id = NULL; + *idlen = 0; + *sess = NULL; + SSL_SESSION_free(usesess); + } else { + *sess = usesess; + *id = (unsigned char *)psk_identity; + *idlen = strlen(psk_identity); + } + + return 1; + + err: + SSL_SESSION_free(usesess); + return 0; +} + /* This is a context that we pass to callbacks */ typedef struct tlsextctx_st { BIO *biodebug; @@ -371,10 +418,11 @@ static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type, unsigned char ext_buf[4 + 65536]; /* Reconstruct the type/len fields prior to extension data */ - ext_buf[0] = ext_type >> 8; - ext_buf[1] = ext_type & 0xFF; - ext_buf[2] = inlen >> 8; - ext_buf[3] = inlen & 0xFF; + inlen &= 0xffff; /* for formal memcmpy 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", @@ -522,32 +570,30 @@ static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset) typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, - OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_UNIX, - OPT_XMPPHOST, OPT_VERIFY, + OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_BIND, OPT_UNIX, + OPT_XMPPHOST, OPT_VERIFY, OPT_NAMEOPT, OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN, OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET, OPT_BRIEF, OPT_PREXIT, OPT_CRLF, OPT_QUIET, OPT_NBIO, - OPT_SSL_CLIENT_ENGINE, OPT_RAND, OPT_IGN_EOF, OPT_NO_IGN_EOF, + OPT_SSL_CLIENT_ENGINE, OPT_IGN_EOF, OPT_NO_IGN_EOF, OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG, OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE, -#ifndef OPENSSL_NO_PSK - OPT_PSK_IDENTITY, OPT_PSK, -#endif + OPT_PSK_IDENTITY, OPT_PSK, OPT_PSK_SESS, #ifndef OPENSSL_NO_SRP OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER, OPT_SRP_MOREGROUPS, #endif OPT_SSL3, OPT_SSL_CONFIG, - OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1, - OPT_DTLS1_2, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS, - OPT_CERT_CHAIN, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, - OPT_VERIFYCAPATH, + OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1, + OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS, + OPT_CERT_CHAIN, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_NEXTPROTONEG, OPT_ALPN, - OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, - OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_SMTPHOST, - OPT_ASYNC, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF, + OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC, + OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST, + OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, + OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE, OPT_V_ENUM, OPT_X_ENUM, OPT_S_ENUM, @@ -555,15 +601,18 @@ typedef enum OPTION_choice { #ifndef OPENSSL_NO_CT OPT_CT, OPT_NOCT, OPT_CTLOG_FILE, #endif - OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME + OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME, + OPT_FORCE_PHA, + OPT_R_ENUM } OPTION_CHOICE; -OPTIONS s_client_options[] = { +const OPTIONS s_client_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"host", OPT_HOST, 's', "Use -connect instead"}, {"port", OPT_PORT, 'p', "Use -connect instead"}, {"connect", OPT_CONNECT, 's', "TCP/IP where to connect (default is :" PORT ")"}, + {"bind", OPT_BIND, 's', "bind local address for connection"}, {"proxy", OPT_PROXY, 's', "Connect to via specified proxy to the real server"}, #ifdef AF_UNIX @@ -577,6 +626,7 @@ OPTIONS s_client_options[] = { {"cert", OPT_CERT, '<', "Certificate file to use, PEM format assumed"}, {"certform", OPT_CERTFORM, 'F', "Certificate format (PEM or DER) PEM default"}, + {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"}, {"key", OPT_KEY, 's', "Private key file to use, if not in -cert file"}, {"keyform", OPT_KEYFORM, 'E', "Key format (PEM, DER or engine) PEM default"}, {"pass", OPT_PASS, 's', "Private key file pass phrase source"}, @@ -586,6 +636,8 @@ OPTIONS s_client_options[] = { "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, + {"requestCAfile", OPT_REQCAFILE, '<', + "PEM format file of CA names to send to the server"}, {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"}, {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's', "DANE TLSA rrdata presentation form"}, @@ -607,9 +659,8 @@ OPTIONS s_client_options[] = { {"starttls", OPT_STARTTLS, 's', "Use the appropriate STARTTLS command before starting TLS"}, {"xmpphost", OPT_XMPPHOST, 's', - "Host to use with \"-starttls xmpp[-server]\""}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, + "Alias of -name option for \"-starttls xmpp[-server]\""}, + OPT_R_OPTIONS, {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"}, {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"}, {"use_srtp", OPT_USE_SRTP, 's', @@ -618,8 +669,11 @@ OPTIONS s_client_options[] = { "Export keying material using label"}, {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p', "Export len bytes of keying material (default 20)"}, + {"maxfraglen", OPT_MAXFRAGLEN, 'p', + "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"}, {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"}, - {"name", OPT_SMTPHOST, 's', "Hostname to use for \"-starttls smtp\""}, + {"name", OPT_PROTOHOST, 's', + "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""}, {"CRL", OPT_CRL, '<', "CRL file to use"}, {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"}, {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"}, @@ -647,7 +701,9 @@ OPTIONS s_client_options[] = { "CA file for certificate verification (PEM format)"}, {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"}, {"servername", OPT_SERVERNAME, 's', - "Set TLS extension servername in ClientHello"}, + "Set TLS extension servername (SNI) in ClientHello (default)"}, + {"noservername", OPT_NOSERVERNAME, '-', + "Do not send the server name (SNI) extension in the ClientHello"}, {"tlsextdebug", OPT_TLSEXTDEBUG, '-', "Hex dump of all TLS extensions received"}, #ifndef OPENSSL_NO_OCSP @@ -659,11 +715,12 @@ OPTIONS s_client_options[] = { "Enable ALPN extension, considering named protocols supported (comma-separated list)"}, {"async", OPT_ASYNC, '-', "Support asynchronous operation"}, {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified configuration file"}, - {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'n', + {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "}, + {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p', "Size used to split data for encrypt pipelines"}, - {"max_pipelines", OPT_MAX_PIPELINES, 'n', + {"max_pipelines", OPT_MAX_PIPELINES, 'p', "Maximum number of encrypt/decrypt pipelines to be used"}, - {"read_buf", OPT_READ_BUF, 'n', + {"read_buf", OPT_READ_BUF, 'p', "Default read buffer size to be used for connections"}, OPT_S_OPTIONS, OPT_V_OPTIONS, @@ -680,6 +737,9 @@ OPTIONS s_client_options[] = { #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"}, #endif +#ifndef OPENSSL_NO_TLS1_3 + {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"}, +#endif #ifndef OPENSSL_NO_DTLS {"dtls", OPT_DTLS, '-', "Use any version of DTLS"}, {"timeout", OPT_TIMEOUT, '-', @@ -692,6 +752,9 @@ OPTIONS s_client_options[] = { #ifndef OPENSSL_NO_DTLS1_2 {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"}, #endif +#ifndef OPENSSL_NO_SCTP + {"sctp", OPT_SCTP, '-', "Use SCTP"}, +#endif #ifndef OPENSSL_NO_SSL_TRACE {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"}, #endif @@ -699,10 +762,9 @@ OPTIONS s_client_options[] = { {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"}, #endif {"nbio", OPT_NBIO, '-', "Use non-blocking IO"}, -#ifndef OPENSSL_NO_PSK {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"}, {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"}, -#endif + {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"}, #ifndef OPENSSL_NO_SRP {"srpuser", OPT_SRPUSER, 's', "SRP authentication for 'user'"}, {"srppass", OPT_SRPPASS, 's', "Password for 'user'"}, @@ -726,6 +788,9 @@ OPTIONS s_client_options[] = { {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"}, {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"}, #endif + {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"}, + {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"}, + {"force_pha", OPT_FORCE_PHA, '-', "Force-enable post-handshake-authentication"}, {NULL, OPT_EOF, 0x00, NULL} }; @@ -739,7 +804,13 @@ typedef enum PROTOCOL_choice { PROTO_XMPP, PROTO_XMPP_SERVER, PROTO_CONNECT, - PROTO_IRC + PROTO_IRC, + PROTO_MYSQL, + PROTO_POSTGRES, + PROTO_LMTP, + PROTO_NNTP, + PROTO_SIEVE, + PROTO_LDAP } PROTOCOL_CHOICE; static const OPT_PAIR services[] = { @@ -751,6 +822,12 @@ static const OPT_PAIR services[] = { {"xmpp-server", PROTO_XMPP_SERVER}, {"telnet", PROTO_TELNET}, {"irc", PROTO_IRC}, + {"mysql", PROTO_MYSQL}, + {"postgres", PROTO_POSTGRES}, + {"lmtp", PROTO_LMTP}, + {"nntp", PROTO_NNTP}, + {"sieve", PROTO_SIEVE}, + {"ldap", PROTO_LDAP}, {NULL, 0} }; @@ -760,7 +837,7 @@ static const OPT_PAIR services[] = { #define IS_PROT_FLAG(o) \ (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \ - || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2) + || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2) /* Free |*dest| and optionally set it to a copy of |source|. */ static void freeandcopy(char **dest, const char *source) @@ -771,6 +848,24 @@ static void freeandcopy(char **dest, const char *source) *dest = OPENSSL_strdup(source); } +static int new_session_cb(SSL *S, SSL_SESSION *sess) +{ + BIO *stmp = BIO_new_file(sess_out, "w"); + + if (stmp == NULL) { + BIO_printf(bio_err, "Error writing session file %s\n", sess_out); + } else { + PEM_write_bio_SSL_SESSION(stmp, sess); + BIO_free(stmp); + } + + /* + * We always return a "fail" response so that the session gets freed again + * because we haven't used the reference. + */ + return 0; +} + int s_client_main(int argc, char **argv) { BIO *sbio; @@ -790,15 +885,15 @@ int s_client_main(int argc, char **argv) const SSL_METHOD *meth = TLS_client_method(); const char *CApath = NULL, *CAfile = NULL; char *cbuf = NULL, *sbuf = NULL; - char *mbuf = NULL, *proxystr = NULL, *connectstr = NULL; + char *mbuf = NULL, *proxystr = NULL, *connectstr = NULL, *bindstr = NULL; char *cert_file = NULL, *key_file = NULL, *chain_file = NULL; char *chCApath = NULL, *chCAfile = NULL, *host = NULL; char *port = OPENSSL_strdup(PORT); - char *inrand = NULL; + char *bindhost = NULL, *bindport = NULL; char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL; - char *sess_in = NULL, *sess_out = NULL, *crl_file = NULL, *p; - char *xmpphost = NULL; - const char *ehlo = "mail.example.com"; + char *ReqCAfile = NULL; + char *sess_in = NULL, *crl_file = NULL, *p; + const char *protohost = NULL; struct timeval timeout, *timeoutp; fd_set readfds, writefds; int noCApath = 0, noCAfile = 0; @@ -809,7 +904,7 @@ int s_client_main(int argc, char **argv) int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0; int ret = 1, in_init = 1, i, nbio_test = 0, s = -1, k, width, state = 0; int sbuf_len, sbuf_off, cmdletters = 1; - int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM; + int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0; int starttls_proto = PROTO_OFF, crl_format = FORMAT_PEM, crl_download = 0; int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending; #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) @@ -817,7 +912,6 @@ int s_client_main(int argc, char **argv) #endif int read_buf_len = 0; int fallback_scsv = 0; - long randamt = 0; OPTION_CHOICE o; #ifndef OPENSSL_NO_DTLS int enable_timeouts = 0; @@ -830,7 +924,8 @@ int s_client_main(int argc, char **argv) #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) struct timeval tv; #endif - char *servername = NULL; + const char *servername = NULL; + int noservername = 0; const char *alpn_in = NULL; tlsextctx tlsextcbp = { NULL, 0 }; const char *ssl_config = NULL; @@ -851,16 +946,23 @@ int s_client_main(int argc, char **argv) #endif int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0; int async = 0; - unsigned int split_send_fragment = 0; - unsigned int max_pipelines = 0; + unsigned int max_send_fragment = 0; + unsigned int split_send_fragment = 0, max_pipelines = 0; enum { use_inet, use_unix, use_unknown } connect_type = use_unknown; int count4or6 = 0; + uint8_t maxfraglen = 0; int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0; int c_tlsextdebug = 0; #ifndef OPENSSL_NO_OCSP int c_status_req = 0; #endif BIO *bio_c_msg = NULL; + const char *keylog_file = NULL, *early_data_file = NULL; +#ifndef OPENSSL_NO_DTLS + int isdtls = 0; +#endif + char *psksessf = NULL; + int force_pha = 0; FD_ZERO(&readfds); FD_ZERO(&writefds); @@ -953,6 +1055,9 @@ int s_client_main(int argc, char **argv) connect_type = use_inet; freeandcopy(&connectstr, opt_arg()); break; + case OPT_BIND: + freeandcopy(&bindstr, opt_arg()); + break; case OPT_PROXY: proxystr = opt_arg(); starttls_proto = PROTO_CONNECT; @@ -965,10 +1070,9 @@ int s_client_main(int argc, char **argv) break; #endif case OPT_XMPPHOST: - xmpphost = opt_arg(); - break; - case OPT_SMTPHOST: - ehlo = opt_arg(); + /* fall through, since this is an alias */ + case OPT_PROTOHOST: + protohost = opt_arg(); break; case OPT_VERIFY: verify = SSL_VERIFY_PEER; @@ -979,6 +1083,10 @@ int s_client_main(int argc, char **argv) case OPT_CERT: cert_file = opt_arg(); break; + case OPT_NAMEOPT: + if (!set_nameopt(opt_arg())) + goto end; + break; case OPT_CRL: crl_file = opt_arg(); break; @@ -1054,8 +1162,9 @@ int s_client_main(int argc, char **argv) } #endif break; - case OPT_RAND: - inrand = opt_arg(); + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_IGN_EOF: c_ign_eof = 1; @@ -1105,7 +1214,6 @@ int s_client_main(int argc, char **argv) case OPT_STATE: state = 1; break; -#ifndef OPENSSL_NO_PSK case OPT_PSK_IDENTITY: psk_identity = opt_arg(); break; @@ -1117,7 +1225,9 @@ int s_client_main(int argc, char **argv) goto end; } break; -#endif + case OPT_PSK_SESS: + psksessf = opt_arg(); + break; #ifndef OPENSSL_NO_SRP case OPT_SRPUSER: srp_arg.srplogin = opt_arg(); @@ -1154,6 +1264,10 @@ int s_client_main(int argc, char **argv) min_version = SSL3_VERSION; max_version = SSL3_VERSION; break; + case OPT_TLS1_3: + min_version = TLS1_3_VERSION; + max_version = TLS1_3_VERSION; + break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; @@ -1170,6 +1284,7 @@ int s_client_main(int argc, char **argv) #ifndef OPENSSL_NO_DTLS meth = DTLS_client_method(); socket_type = SOCK_DGRAM; + isdtls = 1; #endif break; case OPT_DTLS1: @@ -1178,6 +1293,7 @@ int s_client_main(int argc, char **argv) min_version = DTLS1_VERSION; max_version = DTLS1_VERSION; socket_type = SOCK_DGRAM; + isdtls = 1; #endif break; case OPT_DTLS1_2: @@ -1186,6 +1302,12 @@ int s_client_main(int argc, char **argv) min_version = DTLS1_2_VERSION; max_version = DTLS1_2_VERSION; socket_type = SOCK_DGRAM; + isdtls = 1; +#endif + break; + case OPT_SCTP: +#ifndef OPENSSL_NO_SCTP + protocol = IPPROTO_SCTP; #endif break; case OPT_TIMEOUT: @@ -1232,6 +1354,9 @@ int s_client_main(int argc, char **argv) case OPT_BUILD_CHAIN: build_chain = 1; break; + case OPT_REQCAFILE: + ReqCAfile = opt_arg(); + break; case OPT_CAFILE: CAfile = opt_arg(); break; @@ -1297,6 +1422,9 @@ int s_client_main(int argc, char **argv) case OPT_SERVERNAME: servername = opt_arg(); break; + case OPT_NOSERVERNAME: + noservername = 1; + break; case OPT_USE_SRTP: srtp_profiles = opt_arg(); break; @@ -1309,15 +1437,33 @@ int s_client_main(int argc, char **argv) case OPT_ASYNC: async = 1; break; + case OPT_MAXFRAGLEN: + len = atoi(opt_arg()); + switch (len) { + case 512: + maxfraglen = TLSEXT_max_fragment_length_512; + break; + case 1024: + maxfraglen = TLSEXT_max_fragment_length_1024; + break; + case 2048: + maxfraglen = TLSEXT_max_fragment_length_2048; + break; + case 4096: + maxfraglen = TLSEXT_max_fragment_length_4096; + break; + default: + BIO_printf(bio_err, + "%s: Max Fragment Len %u is out of permitted values", + prog, len); + goto opthelp; + } + break; + case OPT_MAX_SEND_FRAG: + max_send_fragment = atoi(opt_arg()); + break; case OPT_SPLIT_SEND_FRAG: split_send_fragment = atoi(opt_arg()); - if (split_send_fragment == 0) { - /* - * Not allowed - set to a deliberately bad value so we get an - * error message below - */ - split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH + 1; - } break; case OPT_MAX_PIPELINES: max_pipelines = atoi(opt_arg()); @@ -1325,21 +1471,64 @@ int s_client_main(int argc, char **argv) case OPT_READ_BUF: read_buf_len = atoi(opt_arg()); break; + case OPT_KEYLOG_FILE: + keylog_file = opt_arg(); + break; + case OPT_EARLY_DATA: + early_data_file = opt_arg(); + break; + case OPT_FORCE_PHA: + force_pha = 1; + break; } } if (count4or6 >= 2) { BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog); goto opthelp; } + if (noservername) { + if (servername != NULL) { + BIO_printf(bio_err, + "%s: Can't use -servername and -noservername together\n", + prog); + goto opthelp; + } + if (dane_tlsa_domain != NULL) { + BIO_printf(bio_err, + "%s: Can't use -dane_tlsa_domain and -noservername together\n", + prog); + goto opthelp; + } + } argc = opt_num_rest(); - if (argc != 0) + if (argc == 1) { + /* If there's a positional argument, it's the equivalent of + * OPT_CONNECT. + * Don't allow -connect and a separate argument. + */ + if (connectstr != NULL) { + BIO_printf(bio_err, + "%s: must not provide both -connect option and target parameter\n", + prog); + goto opthelp; + } + connect_type = use_inet; + freeandcopy(&connectstr, *opt_rest()); + } else if (argc != 0) { goto opthelp; + } - if (proxystr) { +#ifndef OPENSSL_NO_NEXTPROTONEG + if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) { + BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n"); + goto opthelp; + } +#endif + if (proxystr != NULL) { int res; char *tmp_host = host, *tmp_port = port; if (connectstr == NULL) { - BIO_printf(bio_err, "%s: -proxy requires use of -connect\n", prog); + BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog); goto opthelp; } res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST); @@ -1364,7 +1553,19 @@ int s_client_main(int argc, char **argv) OPENSSL_free(tmp_port); if (!res) { BIO_printf(bio_err, - "%s: -connect argument malformed or ambiguous\n", + "%s: -connect argument or target parameter malformed or ambiguous\n", + prog); + goto end; + } + } + + if (bindstr != NULL) { + int res; + res = BIO_parse_hostserv(bindstr, &bindhost, &bindport, + BIO_PARSE_PRIO_HOST); + if (!res) { + BIO_printf(bio_err, + "%s: -bind argument parameter malformed or ambiguous\n", prog); goto end; } @@ -1378,15 +1579,16 @@ int s_client_main(int argc, char **argv) } #endif - if (split_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) { - BIO_printf(bio_err, "Bad split send fragment size\n"); - goto end; - } - - if (max_pipelines > SSL_MAX_PIPELINES) { - BIO_printf(bio_err, "Bad max pipelines value\n"); - goto end; +#ifndef OPENSSL_NO_SCTP + if (protocol == IPPROTO_SCTP) { + if (socket_type != SOCK_DGRAM) { + BIO_printf(bio_err, "Can't use -sctp without DTLS\n"); + goto end; + } + /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */ + socket_type = SOCK_STREAM; } +#endif #if !defined(OPENSSL_NO_NEXTPROTONEG) next_proto.status = -1; @@ -1409,7 +1611,7 @@ int s_client_main(int argc, char **argv) if (key_file == NULL) key_file = cert_file; - if (key_file) { + if (key_file != NULL) { key = load_key(key_file, key_format, 0, pass, e, "client certificate private key file"); if (key == NULL) { @@ -1418,7 +1620,7 @@ int s_client_main(int argc, char **argv) } } - if (cert_file) { + if (cert_file != NULL) { cert = load_cert(cert_file, cert_format, "client certificate file"); if (cert == NULL) { ERR_print_errors(bio_err); @@ -1426,13 +1628,13 @@ int s_client_main(int argc, char **argv) } } - if (chain_file) { + if (chain_file != NULL) { if (!load_certs(chain_file, &chain, FORMAT_PEM, NULL, "client certificate chain")) goto end; } - if (crl_file) { + if (crl_file != NULL) { X509_CRL *crl; crl = load_crl(crl_file, crl_format); if (crl == NULL) { @@ -1452,20 +1654,10 @@ int s_client_main(int argc, char **argv) if (!load_excert(&exc)) goto end; - if (!app_RAND_load_file(NULL, 1) && inrand == NULL - && !RAND_status()) { - BIO_printf(bio_err, - "warning, not much extra random data, consider using the -rand option\n"); - } - if (inrand != NULL) { - randamt = app_RAND_load_files(inrand); - BIO_printf(bio_err, "%ld semi-random bytes loaded\n", randamt); - } - if (bio_c_out == NULL) { if (c_quiet && !c_debug) { bio_c_out = BIO_new(BIO_s_null()); - if (c_msg && !bio_c_msg) + if (c_msg && bio_c_msg == NULL) bio_c_msg = dup_bio_out(FORMAT_TEXT); } else if (bio_c_out == NULL) bio_c_out = dup_bio_out(FORMAT_TEXT); @@ -1486,10 +1678,7 @@ int s_client_main(int argc, char **argv) if (sdebug) ssl_ctx_security_debug(ctx, sdebug); - if (!config_ctx(cctx, ssl_args, ctx)) - goto end; - - if (ssl_config) { + if (ssl_config != NULL) { if (SSL_CTX_config(ctx, ssl_config) == 0) { BIO_printf(bio_err, "Error using configuration \"%s\"\n", ssl_config); @@ -1498,11 +1687,9 @@ int s_client_main(int argc, char **argv) } } - if (min_version != 0 - && SSL_CTX_set_min_proto_version(ctx, min_version) == 0) + if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto end; - if (max_version != 0 - && SSL_CTX_set_max_proto_version(ctx, max_version) == 0) + if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto end; if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) { @@ -1514,23 +1701,60 @@ int s_client_main(int argc, char **argv) if (async) { SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC); } - if (split_send_fragment > 0) { - SSL_CTX_set_split_send_fragment(ctx, split_send_fragment); + + if (max_send_fragment > 0 + && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) { + BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n", + prog, max_send_fragment); + goto end; } - if (max_pipelines > 0) { - SSL_CTX_set_max_pipelines(ctx, max_pipelines); + + if (split_send_fragment > 0 + && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) { + BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n", + prog, split_send_fragment); + goto end; + } + + if (max_pipelines > 0 + && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) { + BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n", + prog, max_pipelines); + goto end; } if (read_buf_len > 0) { SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len); } + if (maxfraglen > 0 + && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) { + BIO_printf(bio_err, + "%s: Max Fragment Length code %u is out of permitted values" + "\n", prog, maxfraglen); + goto end; + } + + if (!config_ctx(cctx, ssl_args, ctx)) + 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; } + if (ReqCAfile != NULL) { + STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null(); + + if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) { + sk_X509_NAME_pop_free(nm, X509_NAME_free); + BIO_printf(bio_err, "Error loading CA names\n"); + ERR_print_errors(bio_err); + goto end; + } + SSL_CTX_set0_CA_list(ctx, nm); + } #ifndef OPENSSL_NO_ENGINE if (ssl_client_engine) { if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) { @@ -1550,6 +1774,25 @@ int s_client_main(int argc, char **argv) SSL_CTX_set_psk_client_callback(ctx, psk_client_cb); } #endif + if (psksessf != NULL) { + BIO *stmp = BIO_new_file(psksessf, "r"); + + if (stmp == NULL) { + BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf); + ERR_print_errors(bio_err); + goto end; + } + psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); + BIO_free(stmp); + if (psksess == NULL) { + BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf); + ERR_print_errors(bio_err); + goto end; + } + } + if (psk_key != NULL || psksess != NULL) + SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb); + #ifndef OPENSSL_NO_SRTP if (srtp_profiles != NULL) { /* Returns 0 on success! */ @@ -1561,11 +1804,11 @@ int s_client_main(int argc, char **argv) } #endif - if (exc) + if (exc != NULL) ssl_ctx_set_excert(ctx, exc); #if !defined(OPENSSL_NO_NEXTPROTONEG) - if (next_proto.data) + if (next_proto.data != NULL) SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto); #endif if (alpn_in) { @@ -1634,7 +1877,7 @@ int s_client_main(int argc, char **argv) if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain)) goto end; - if (servername != NULL) { + if (!noservername) { tlsextcbp.biodebug = bio_err; SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp); @@ -1666,18 +1909,38 @@ int s_client_main(int argc, char **argv) } } + /* + * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can + * come at any time. Therefore we use a callback to write out the session + * when we know about it. This approach works for < TLSv1.3 as well. + */ + if (sess_out != NULL) { + SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT + | SSL_SESS_CACHE_NO_INTERNAL_STORE); + SSL_CTX_sess_set_new_cb(ctx, new_session_cb); + } + + if (set_keylog_file(ctx, keylog_file)) + goto end; + con = SSL_new(ctx); - if (sess_in) { + if (con == NULL) + goto end; + + if (force_pha) + SSL_force_post_handshake_auth(con); + + if (sess_in != NULL) { SSL_SESSION *sess; BIO *stmp = BIO_new_file(sess_in, "r"); - if (!stmp) { + if (stmp == NULL) { 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) { + if (sess == NULL) { BIO_printf(bio_err, "Can't open session file %s\n", sess_in); ERR_print_errors(bio_err); goto end; @@ -1687,13 +1950,16 @@ int s_client_main(int argc, char **argv) ERR_print_errors(bio_err); goto end; } + SSL_SESSION_free(sess); } if (fallback_scsv) SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV); - if (servername != NULL) { + if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) { + if (servername == NULL) + servername = (host == NULL) ? "localhost" : host; if (!SSL_set_tlsext_host_name(con, servername)) { BIO_printf(bio_err, "Unable to set TLS servername extension.\n"); ERR_print_errors(bio_err); @@ -1727,7 +1993,8 @@ int s_client_main(int argc, char **argv) } re_start: - if (init_client(&s, host, port, socket_family, socket_type) == 0) { + if (init_client(&s, host, port, bindhost, bindport, socket_family, + socket_type, protocol) == 0) { BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error()); BIO_closesocket(s); goto end; @@ -1742,10 +2009,16 @@ int s_client_main(int argc, char **argv) BIO_printf(bio_c_out, "Turned on non blocking io\n"); } #ifndef OPENSSL_NO_DTLS - if (socket_type == SOCK_DGRAM) { + if (isdtls) { union BIO_sock_info_u peer_info; - sbio = BIO_new_dgram(s, BIO_NOCLOSE); +#ifndef OPENSSL_NO_SCTP + if (protocol == IPPROTO_SCTP) + sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE); + else +#endif + sbio = BIO_new_dgram(s, BIO_NOCLOSE); + if ((peer_info.addr = BIO_ADDR_new()) == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); BIO_closesocket(s); @@ -1786,9 +2059,10 @@ int s_client_main(int argc, char **argv) BIO_free(sbio); goto shut; } - } else + } else { /* want to do MTU discovery */ BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL); + } } else #endif /* OPENSSL_NO_DTLS */ sbio = BIO_new_socket(s, BIO_NOCLOSE); @@ -1849,6 +2123,7 @@ int s_client_main(int argc, char **argv) switch ((PROTOCOL_CHOICE) starttls_proto) { case PROTO_OFF: break; + case PROTO_LMTP: case PROTO_SMTP: { /* @@ -1861,27 +2136,34 @@ int s_client_main(int argc, char **argv) */ int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); + BIO_push(fbio, sbio); - /* wait for multi-line response to end from SMTP */ + /* Wait for multi-line response to end from LMTP or SMTP */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); - } - while (mbuf_len > 3 && mbuf[3] == '-'); - BIO_printf(fbio, "EHLO %s\r\n", ehlo); + } while (mbuf_len > 3 && mbuf[3] == '-'); + if (protohost == NULL) + protohost = "mail.example.com"; + if (starttls_proto == (int)PROTO_LMTP) + BIO_printf(fbio, "LHLO %s\r\n", protohost); + else + BIO_printf(fbio, "EHLO %s\r\n", protohost); (void)BIO_flush(fbio); - /* wait for multi-line response to end EHLO SMTP response */ + /* + * Wait for multi-line response to end LHLO LMTP or EHLO SMTP + * response. + */ do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (strstr(mbuf, "STARTTLS")) foundit = 1; - } - while (mbuf_len > 3 && mbuf[3] == '-'); + } while (mbuf_len > 3 && mbuf[3] == '-'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, - "didn't find starttls in server response," + "Didn't find STARTTLS in server response," " trying anyway...\n"); BIO_printf(sbio, "STARTTLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); @@ -1902,6 +2184,7 @@ int s_client_main(int argc, char **argv) { int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); + BIO_push(fbio, sbio); BIO_gets(fbio, mbuf, BUFSIZZ); /* STARTTLS command requires CAPABILITY... */ @@ -1919,7 +2202,7 @@ int s_client_main(int argc, char **argv) BIO_free(fbio); if (!foundit) BIO_printf(bio_err, - "didn't find STARTTLS in server response," + "Didn't find STARTTLS in server response," " trying anyway...\n"); BIO_printf(sbio, ". STARTTLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); @@ -1928,6 +2211,7 @@ int s_client_main(int argc, char **argv) case PROTO_FTP: { BIO *fbio = BIO_new(BIO_f_buffer()); + BIO_push(fbio, sbio); /* wait for multi-line response to end from FTP */ do { @@ -1949,9 +2233,13 @@ int s_client_main(int argc, char **argv) "xmlns:stream='http://etherx.jabber.org/streams' " "xmlns='jabber:%s' to='%s' version='1.0'>", starttls_proto == PROTO_XMPP ? "client" : "server", - xmpphost ? xmpphost : host); + protohost ? protohost : host); seen = BIO_read(sbio, mbuf, BUFSIZZ); - mbuf[seen] = 0; + if (seen < 0) { + BIO_printf(bio_err, "BIO_read failed\n"); + goto end; + } + mbuf[seen] = '\0'; while (!strstr (mbuf, ""); seen = BIO_read(sbio, sbuf, BUFSIZZ); - sbuf[seen] = 0; + if (seen < 0) { + BIO_printf(bio_err, "BIO_read failed\n"); + goto shut; + } + sbuf[seen] = '\0'; if (!strstr(sbuf, "= bytes) { + BIO_printf(bio_err, "Cannot confirm server version. "); + goto shut; + } else if (packet[pos++] == '\0') { + break; + } + } + + /* make sure we have at least 15 bytes left in the packet */ + if (pos + 15 > bytes) { + BIO_printf(bio_err, + "MySQL server handshake packet is broken.\n"); + goto shut; + } + + pos += 12; /* skip over conn id[4] + SALT[8] */ + if (packet[pos++] != '\0') { /* verify filler */ + BIO_printf(bio_err, + "MySQL packet is broken.\n"); + goto shut; + } + + /* capability flags[2] */ + if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) { + BIO_printf(bio_err, "MySQL server does not support SSL.\n"); + goto shut; + } + + /* Sending SSL Handshake packet. */ + BIO_write(sbio, ssl_req, sizeof(ssl_req)); + (void)BIO_flush(sbio); + } + break; + case PROTO_POSTGRES: + { + static const unsigned char ssl_request[] = { + /* Length SSLRequest */ + 0, 0, 0, 8, 4, 210, 22, 47 + }; + int bytes; + + /* Send SSLRequest packet */ + BIO_write(sbio, ssl_request, 8); + (void)BIO_flush(sbio); + + /* Reply will be a single S if SSL is enabled */ + bytes = BIO_read(sbio, sbuf, BUFSIZZ); + if (bytes != 1 || sbuf[0] != 'S') + goto shut; + } + break; + case PROTO_NNTP: + { + int foundit = 0; + BIO *fbio = BIO_new(BIO_f_buffer()); + + BIO_push(fbio, sbio); + BIO_gets(fbio, mbuf, BUFSIZZ); + /* STARTTLS command requires CAPABILITIES... */ + BIO_printf(fbio, "CAPABILITIES\r\n"); + (void)BIO_flush(fbio); + /* wait for multi-line CAPABILITIES response */ + do { + mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); + if (strstr(mbuf, "STARTTLS")) + foundit = 1; + } while (mbuf_len > 1 && mbuf[0] != '.'); + (void)BIO_flush(fbio); + BIO_pop(fbio); + BIO_free(fbio); + if (!foundit) + BIO_printf(bio_err, + "Didn't find STARTTLS in server response," + " trying anyway...\n"); + BIO_printf(sbio, "STARTTLS\r\n"); + mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ); + if (mbuf_len < 0) { + BIO_printf(bio_err, "BIO_read failed\n"); + goto end; + } + mbuf[mbuf_len] = '\0'; + if (strstr(mbuf, "382") == NULL) { + BIO_printf(bio_err, "STARTTLS failed: %s", mbuf); + goto shut; + } + } + break; + case PROTO_SIEVE: + { + int foundit = 0; + BIO *fbio = BIO_new(BIO_f_buffer()); + + BIO_push(fbio, sbio); + /* wait for multi-line response to end from Sieve */ + do { + mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); + /* + * According to RFC 5804 § 1.7, capability + * is case-insensitive, make it uppercase + */ + if (mbuf_len > 1 && mbuf[0] == '"') { + make_uppercase(mbuf); + if (strncmp(mbuf, "\"STARTTLS\"", 10) == 0) + foundit = 1; + } + } while (mbuf_len > 1 && mbuf[0] == '"'); + (void)BIO_flush(fbio); + BIO_pop(fbio); + BIO_free(fbio); + if (!foundit) + BIO_printf(bio_err, + "Didn't find STARTTLS in server response," + " trying anyway...\n"); + BIO_printf(sbio, "STARTTLS\r\n"); + mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ); + if (mbuf_len < 0) { + BIO_printf(bio_err, "BIO_read failed\n"); + goto end; + } + mbuf[mbuf_len] = '\0'; + if (mbuf_len < 2) { + BIO_printf(bio_err, "STARTTLS failed: %s", mbuf); + goto shut; + } + /* + * According to RFC 5804 § 2.2, response codes are case- + * insensitive, make it uppercase but preserve the response. + */ + strncpy(sbuf, mbuf, 2); + make_uppercase(sbuf); + if (strncmp(sbuf, "OK", 2) != 0) { + BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf); + goto shut; + } + } + break; + case PROTO_LDAP: + { + /* StartTLS Operation according to RFC 4511 */ + static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n" + "[LDAPMessage]\n" + "messageID=INTEGER:1\n" + "extendedReq=EXPLICIT:23A,IMPLICIT:0C," + "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n"; + long errline = -1; + char *genstr = NULL; + int result = -1; + ASN1_TYPE *atyp = NULL; + BIO *ldapbio = BIO_new(BIO_s_mem()); + CONF *cnf = NCONF_new(NULL); + + if (cnf == NULL) { + BIO_free(ldapbio); + goto end; + } + BIO_puts(ldapbio, ldap_tls_genconf); + if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) { + BIO_free(ldapbio); + NCONF_free(cnf); + if (errline <= 0) { + BIO_printf(bio_err, "NCONF_load_bio failed\n"); + goto end; + } else { + BIO_printf(bio_err, "Error on line %ld\n", errline); + goto end; + } + } + BIO_free(ldapbio); + genstr = NCONF_get_string(cnf, "default", "asn1"); + if (genstr == NULL) { + NCONF_free(cnf); + BIO_printf(bio_err, "NCONF_get_string failed\n"); + goto end; + } + atyp = ASN1_generate_nconf(genstr, cnf); + if (atyp == NULL) { + NCONF_free(cnf); + BIO_printf(bio_err, "ASN1_generate_nconf failed\n"); + goto end; + } + NCONF_free(cnf); + + /* Send SSLRequest packet */ + BIO_write(sbio, atyp->value.sequence->data, + atyp->value.sequence->length); + (void)BIO_flush(sbio); + ASN1_TYPE_free(atyp); + + mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ); + if (mbuf_len < 0) { + BIO_printf(bio_err, "BIO_read failed\n"); + goto end; + } + result = ldap_ExtendedResponse_parse(mbuf, mbuf_len); + if (result < 0) { + BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n"); + goto shut; + } else if (result > 0) { + BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n", + result); + goto shut; + } + mbuf_len = 0; + } + break; + } + + if (early_data_file != NULL + && ((SSL_get0_session(con) != NULL + && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0) + || (psksess != NULL + && SSL_SESSION_get_max_early_data(psksess) > 0))) { + BIO *edfile = BIO_new_file(early_data_file, "r"); + size_t readbytes, writtenbytes; + int finish = 0; + + if (edfile == NULL) { + BIO_printf(bio_err, "Cannot open early data file\n"); + goto shut; + } + + while (!finish) { + if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes)) + finish = 1; + + while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) { + switch (SSL_get_error(con, 0)) { + case SSL_ERROR_WANT_WRITE: + case SSL_ERROR_WANT_ASYNC: + case SSL_ERROR_WANT_READ: + /* Just keep trying - busy waiting */ + continue; + default: + BIO_printf(bio_err, "Error writing early data\n"); + BIO_free(edfile); + ERR_print_errors(bio_err); + goto shut; + } + } + } + + BIO_free(edfile); } for (;;) { @@ -2120,7 +2711,8 @@ int s_client_main(int argc, char **argv) else timeoutp = NULL; - if (SSL_in_init(con) && !SSL_total_renegotiations(con)) { + if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0 + && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) { in_init = 1; tty_on = 0; } else { @@ -2128,15 +2720,6 @@ int s_client_main(int argc, char **argv) if (in_init) { in_init = 0; - 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(con); @@ -2231,7 +2814,6 @@ int s_client_main(int argc, char **argv) BIO_printf(bio_err, "bad select %d\n", get_last_socket_error()); goto shut; - /* goto end; */ } } @@ -2322,10 +2904,9 @@ int s_client_main(int argc, char **argv) BIO_printf(bio_c_out, "DONE\n"); ret = 0; goto shut; - /* goto end; */ } - sbuf_len -= i;; + sbuf_len -= i; sbuf_off += i; if (sbuf_len <= 0) { read_ssl = 1; @@ -2392,7 +2973,6 @@ int s_client_main(int argc, char **argv) case SSL_ERROR_SSL: ERR_print_errors(bio_err); goto shut; - /* break; */ } } /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */ @@ -2438,6 +3018,15 @@ int s_client_main(int argc, char **argv) SSL_renegotiate(con); cbuf_len = 0; } + + if (!c_ign_eof && (cbuf[0] == 'K' || cbuf[0] == 'k' ) + && cmdletters) { + BIO_printf(bio_err, "KEYUPDATE\n"); + SSL_key_update(con, + cbuf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED + : SSL_KEY_UPDATE_NOT_REQUESTED); + cbuf_len = 0; + } #ifndef OPENSSL_NO_HEARTBEATS else if ((!c_ign_eof) && (cbuf[0] == 'B' && cmdletters)) { BIO_printf(bio_err, "HEARTBEATING\n"); @@ -2495,10 +3084,12 @@ int s_client_main(int argc, char **argv) print_stuff(bio_c_out, con, 1); SSL_free(con); } + SSL_SESSION_free(psksess); #if !defined(OPENSSL_NO_NEXTPROTONEG) OPENSSL_free(next_proto.data); #endif SSL_CTX_free(ctx); + set_keylog_file(NULL, NULL); X509_free(cert); sk_X509_CRL_pop_free(crls, X509_CRL_free); EVP_PKEY_free(key); @@ -2508,6 +3099,7 @@ int s_client_main(int argc, char **argv) OPENSSL_free(srp_arg.srppassin); #endif OPENSSL_free(connectstr); + OPENSSL_free(bindstr); OPENSSL_free(host); OPENSSL_free(port); X509_VERIFY_PARAM_free(vpm); @@ -2523,17 +3115,14 @@ int s_client_main(int argc, char **argv) bio_c_out = NULL; BIO_free(bio_c_msg); bio_c_msg = NULL; - return (ret); + return ret; } static void print_stuff(BIO *bio, SSL *s, int full) { X509 *peer = NULL; - char buf[BUFSIZ]; STACK_OF(X509) *sk; - STACK_OF(X509_NAME) *sk2; const SSL_CIPHER *c; - X509_NAME *xn; int i; #ifndef OPENSSL_NO_COMP const COMP_METHOD *comp, *expansion; @@ -2552,12 +3141,12 @@ static void print_stuff(BIO *bio, SSL *s, int full) 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)); - BIO_printf(bio, "%2d s:%s\n", i, buf); - X509_NAME_oneline(X509_get_issuer_name(sk_X509_value(sk, i)), - buf, sizeof(buf)); - BIO_printf(bio, " i:%s\n", buf); + BIO_printf(bio, "%2d s:", i); + X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt()); + BIO_puts(bio, "\n"); + BIO_printf(bio, " i:"); + X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt()); + BIO_puts(bio, "\n"); if (c_showcerts) PEM_write_bio_X509(bio, sk_X509_value(sk, i)); } @@ -2571,25 +3160,11 @@ static void print_stuff(BIO *bio, SSL *s, int full) /* 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)); - BIO_printf(bio, "subject=%s\n", 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); - } + dump_cert_text(bio, peer); } else { - BIO_printf(bio, "---\nNo client certificate CA names sent\n"); + BIO_printf(bio, "no peer certificate available\n"); } + print_ca_names(bio, s); ssl_print_sigalgs(bio, s); ssl_print_tmp_key(bio, s); @@ -2628,8 +3203,8 @@ static void print_stuff(BIO *bio, SSL *s, int full) #endif BIO_printf(bio, - "---\nSSL handshake has read %"BIO_PRI64"u" - " bytes and written %"BIO_PRI64"u bytes\n", + "---\nSSL handshake has read %ju bytes " + "and written %ju bytes\n", BIO_number_read(SSL_get_rbio(s)), BIO_number_written(SSL_get_wbio(s))); } @@ -2705,6 +3280,23 @@ static void print_stuff(BIO *bio, SSL *s, int full) } #endif + if (SSL_version(s) == TLS1_3_VERSION) { + switch (SSL_get_early_data_status(s)) { + case SSL_EARLY_DATA_NOT_SENT: + BIO_printf(bio, "Early data was not sent\n"); + break; + + case SSL_EARLY_DATA_REJECTED: + BIO_printf(bio, "Early data was rejected\n"); + break; + + case SSL_EARLY_DATA_ACCEPTED: + BIO_printf(bio, "Early data was accepted\n"); + break; + + } + } + SSL_SESSION_print(bio, SSL_get_session(s)); if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) { BIO_printf(bio, "Keying material exporter:\n"); @@ -2739,12 +3331,12 @@ static int ocsp_resp_cb(SSL *s, void *arg) OCSP_RESPONSE *rsp; len = SSL_get_tlsext_status_ocsp_resp(s, &p); BIO_puts(arg, "OCSP response: "); - if (!p) { + if (p == NULL) { BIO_puts(arg, "no response sent\n"); return 1; } rsp = d2i_OCSP_RESPONSE(NULL, &p, len); - if (!rsp) { + if (rsp == NULL) { BIO_puts(arg, "response parse error\n"); BIO_dump_indent(arg, (char *)p, len, 4); return 0; @@ -2757,4 +3349,88 @@ static int ocsp_resp_cb(SSL *s, void *arg) } # endif +static int ldap_ExtendedResponse_parse(const char *buf, long rem) +{ + const unsigned char *cur, *end; + long len; + int tag, xclass, inf, ret = -1; + + cur = (const unsigned char *)buf; + end = cur + rem; + + /* + * From RFC 4511: + * + * LDAPMessage ::= SEQUENCE { + * messageID MessageID, + * protocolOp CHOICE { + * ... + * extendedResp ExtendedResponse, + * ... }, + * controls [0] Controls OPTIONAL } + * + * ExtendedResponse ::= [APPLICATION 24] SEQUENCE { + * COMPONENTS OF LDAPResult, + * responseName [10] LDAPOID OPTIONAL, + * responseValue [11] OCTET STRING OPTIONAL } + * + * LDAPResult ::= SEQUENCE { + * resultCode ENUMERATED { + * success (0), + * ... + * other (80), + * ... }, + * matchedDN LDAPDN, + * diagnosticMessage LDAPString, + * referral [3] Referral OPTIONAL } + */ + + /* pull SEQUENCE */ + inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); + if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE || + (rem = end - cur, len > rem)) { + BIO_printf(bio_err, "Unexpected LDAP response\n"); + goto end; + } + + rem = len; /* ensure that we don't overstep the SEQUENCE */ + + /* pull MessageID */ + inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); + if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER || + (rem = end - cur, len > rem)) { + BIO_printf(bio_err, "No MessageID\n"); + goto end; + } + + cur += len; /* shall we check for MessageId match or just skip? */ + + /* pull [APPLICATION 24] */ + rem = end - cur; + inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); + if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION || + tag != 24) { + BIO_printf(bio_err, "Not ExtendedResponse\n"); + goto end; + } + + /* pull resultCode */ + rem = end - cur; + inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); + if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 || + (rem = end - cur, len > rem)) { + BIO_printf(bio_err, "Not LDAPResult\n"); + goto end; + } + + /* len should always be one, but just in case... */ + for (ret = 0, inf = 0; inf < len; inf++) { + ret <<= 8; + ret |= cur[inf]; + } + /* There is more data, but we don't care... */ + end: + return ret; +} + #endif /* OPENSSL_NO_SOCK */ diff --git a/apps/s_server.c b/apps/s_server.c index 31c90fdd..c772069a 100644 --- a/apps/s_server.c +++ b/apps/s_server.c @@ -1,5 +1,7 @@ /* * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved + * Copyright 2005 Nokia. All rights reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy @@ -7,38 +9,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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. - */ - #include #include #include @@ -65,10 +35,9 @@ typedef unsigned int u_int; #endif -#include #include -#define USE_SOCKETS #include "apps.h" +#include "progs.h" #include #include #include @@ -89,21 +58,23 @@ typedef unsigned int u_int; #ifdef CHARSET_EBCDIC #include #endif +#include "internal/sockets.h" static int not_resumable_sess_cb(SSL *s, int is_forward_secure); -static int sv_body(int s, int stype, unsigned char *context); -static int www_body(int s, int stype, unsigned char *context); -static int rev_body(int s, int stype, unsigned char *context); +static int sv_body(int s, int stype, int prot, unsigned char *context); +static int www_body(int s, int stype, int prot, unsigned char *context); +static int rev_body(int s, int stype, int prot, unsigned char *context); static void close_accept_socket(void); static int init_ssl_connection(SSL *s); static void print_stats(BIO *bp, SSL_CTX *ctx); -static int generate_session_id(const SSL *ssl, unsigned char *id, +static int generate_session_id(SSL *ssl, unsigned char *id, unsigned int *id_len); static void init_session_cache_ctx(SSL_CTX *sctx); static void free_sessions(void); #ifndef OPENSSL_NO_DH static DH *load_dh_param(const char *dhfile); #endif +static void print_connection_info(SSL *con); static const int bufsize = 16 * 1024; static int accept_socket = -1; @@ -144,11 +115,15 @@ static long socket_mtu; * code. */ static int dtlslisten = 0; +static int stateless = 0; -#ifndef OPENSSL_NO_PSK -static const char psk_identity[] = "Client_identity"; +static int early_data = 0; +static SSL_SESSION *psksess = NULL; + +static char *psk_identity = "Client_identity"; char *psk_key = NULL; /* by default PSK is not used */ +#ifndef OPENSSL_NO_PSK static unsigned int psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk, unsigned int max_psk_len) @@ -158,7 +133,7 @@ static unsigned int psk_server_cb(SSL *ssl, const char *identity, if (s_debug) BIO_printf(bio_s_out, "psk_server_cb\n"); - if (!identity) { + if (identity == NULL) { BIO_printf(bio_err, "Error: client did not send PSK identity\n"); goto out_err; } @@ -168,12 +143,12 @@ static unsigned int psk_server_cb(SSL *ssl, const char *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" + BIO_printf(bio_s_out, "PSK warning: client identity not what we expected" " (got '%s' expected '%s')\n", identity, psk_identity); - goto out_err; - } - if (s_debug) + } else { + if (s_debug) BIO_printf(bio_s_out, "PSK client identity found\n"); + } /* convert the PSK key to binary */ key = OPENSSL_hexstr2buf(psk_key, &key_len); @@ -205,6 +180,59 @@ static unsigned int psk_server_cb(SSL *ssl, const char *identity, } #endif +#define TLS13_AES_128_GCM_SHA256_BYTES ((const unsigned char *)"\x13\x01") +#define TLS13_AES_256_GCM_SHA384_BYTES ((const unsigned char *)"\x13\x02") + +static int psk_find_session_cb(SSL *ssl, const unsigned char *identity, + size_t identity_len, SSL_SESSION **sess) +{ + SSL_SESSION *tmpsess = NULL; + unsigned char *key; + long key_len; + const SSL_CIPHER *cipher = NULL; + + if (strlen(psk_identity) != identity_len + || memcmp(psk_identity, identity, identity_len) != 0) + return 0; + + if (psksess != NULL) { + SSL_SESSION_up_ref(psksess); + *sess = psksess; + return 1; + } + + key = OPENSSL_hexstr2buf(psk_key, &key_len); + if (key == NULL) { + BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", + psk_key); + return 0; + } + + if (key_len == EVP_MD_size(EVP_sha256())) + cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id); + else if (key_len == EVP_MD_size(EVP_sha384())) + cipher = SSL_CIPHER_find(ssl, tls13_aes256gcmsha384_id); + + if (cipher == NULL) { + /* Doesn't look like a suitable TLSv1.3 key. Ignore it */ + OPENSSL_free(key); + return 0; + } + + tmpsess = SSL_SESSION_new(); + if (tmpsess == NULL + || !SSL_SESSION_set1_master_key(tmpsess, key, key_len) + || !SSL_SESSION_set_cipher(tmpsess, cipher) + || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) { + OPENSSL_free(key); + return 0; + } + OPENSSL_free(key); + *sess = tmpsess; + + return 1; +} + #ifndef OPENSSL_NO_SRP /* This is a context that we pass to callbacks */ typedef struct srpsrvparm_st { @@ -229,7 +257,7 @@ static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg) 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); + return -1; } if (p->user == NULL) { @@ -329,9 +357,9 @@ static int ebcdic_read(BIO *b, char *out, int outl) BIO *next = BIO_next(b); if (out == NULL || outl == 0) - return (0); + return 0; if (next == NULL) - return (0); + return 0; ret = BIO_read(next, out, outl); if (ret > 0) @@ -347,7 +375,7 @@ static int ebcdic_write(BIO *b, const char *in, int inl) int num; if ((in == NULL) || (inl <= 0)) - return (0); + return 0; if (next == NULL) return 0; @@ -370,7 +398,7 @@ static int ebcdic_write(BIO *b, const char *in, int inl) ret = BIO_write(next, wbuf->buff, inl); - return (ret); + return ret; } static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -379,7 +407,7 @@ static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr) BIO *next = BIO_next(b); if (next == NULL) - return (0); + return 0; switch (cmd) { case BIO_CTRL_DUP: ret = 0L; @@ -388,7 +416,7 @@ static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr) ret = BIO_ctrl(next, cmd, num, ptr); break; } - return (ret); + return ret; } static int ebcdic_gets(BIO *bp, char *buf, int size) @@ -432,17 +460,25 @@ static int ssl_servername_cb(SSL *s, int *ad, void *arg) { tlsextctx *p = (tlsextctx *) arg; const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); - if (servername && p->biodebug) - BIO_printf(p->biodebug, "Hostname in TLS extension: \"%s\"\n", - servername); - if (!p->servername) + if (servername != NULL && p->biodebug != NULL) { + const char *cp = servername; + unsigned char uc; + + BIO_printf(p->biodebug, "Hostname in TLS extension: \""); + while ((uc = *cp++) != 0) + BIO_printf(p->biodebug, + isascii(uc) && isprint(uc) ? "%c" : "\\x%02x", uc); + BIO_printf(p->biodebug, "\"\n"); + } + + if (p->servername == NULL) return SSL_TLSEXT_ERR_NOACK; - if (servername) { + if (servername != NULL) { if (strcasecmp(servername, p->servername)) return p->extension_error; - if (ctx2) { + if (ctx2 != NULL) { BIO_printf(p->biodebug, "Switching server context.\n"); SSL_set_SSL_CTX(s, ctx2); } @@ -452,49 +488,45 @@ static int ssl_servername_cb(SSL *s, int *ad, void *arg) /* Structure passed to cert status callback */ typedef struct tlsextstatusctx_st { + int timeout; + /* File to load OCSP Response from (or NULL if no file) */ + char *respin; /* Default responder to use */ char *host, *path, *port; int use_ssl; - int timeout; int verbose; } tlsextstatusctx; -static tlsextstatusctx tlscstatp = { NULL, NULL, NULL, 0, -1, 0 }; +static tlsextstatusctx tlscstatp = { -1 }; #ifndef OPENSSL_NO_OCSP -/* - * 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) +/* + * Helper function to get an OCSP_RESPONSE from a responder. This is a + * simplified version. It examines certificates each time and makes one OCSP + * responder query for each request. A full version would store details such as + * the OCSP certificate IDs and minimise the number of OCSP responses by caching + * them until they were considered "expired". + */ +static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx, + OCSP_RESPONSE **resp) { - tlsextstatusctx *srctx = arg; char *host = NULL, *port = NULL, *path = NULL; int use_ssl; - unsigned char *rspder = NULL; - int rspderlen; STACK_OF(OPENSSL_STRING) *aia = NULL; X509 *x = NULL; X509_STORE_CTX *inctx = NULL; 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 (srctx->verbose) - BIO_puts(bio_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 (aia != NULL) { if (!OCSP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &host, &port, &path, &use_ssl)) { BIO_puts(bio_err, "cert_status: can't parse AIA URL\n"); @@ -504,7 +536,7 @@ static int cert_status_cb(SSL *s, void *arg) BIO_printf(bio_err, "cert_status: AIA URL: %s\n", sk_OPENSSL_STRING_value(aia, 0)); } else { - if (!srctx->host) { + if (srctx->host == NULL) { BIO_puts(bio_err, "cert_status: no AIA and no default responder URL\n"); goto done; @@ -530,7 +562,7 @@ static int cert_status_cb(SSL *s, void *arg) } id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj)); X509_OBJECT_free(obj); - if (!id) + if (id == NULL) goto err; req = OCSP_REQUEST_new(); if (req == NULL) @@ -545,29 +577,24 @@ static int cert_status_cb(SSL *s, void *arg) if (!OCSP_REQUEST_add_ext(req, ext, -1)) goto err; } - resp = process_responder(req, host, path, port, use_ssl, NULL, + *resp = process_responder(req, host, path, port, use_ssl, NULL, srctx->timeout); - if (!resp) { + if (*resp == NULL) { BIO_puts(bio_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(bio_err, "cert_status: ocsp response sent:\n"); - OCSP_RESPONSE_print(bio_err, resp, 2); - } + ret = SSL_TLSEXT_ERR_OK; goto done; err: ret = SSL_TLSEXT_ERR_ALERT_FATAL; done: - if (ret != SSL_TLSEXT_ERR_OK) - ERR_print_errors(bio_err); - if (aia) { + /* + * If we parsed aia we need to free; otherwise they were copied and we + * don't + */ + if (aia != NULL) { OPENSSL_free(host); OPENSSL_free(path); OPENSSL_free(port); @@ -575,10 +602,64 @@ static int cert_status_cb(SSL *s, void *arg) } OCSP_CERTID_free(id); OCSP_REQUEST_free(req); - OCSP_RESPONSE_free(resp); X509_STORE_CTX_free(inctx); return ret; } + +/* + * Certificate Status callback. This is called when a client includes a + * certificate status request extension. The response is either obtained from a + * file, or from an OCSP responder. + */ +static int cert_status_cb(SSL *s, void *arg) +{ + tlsextstatusctx *srctx = arg; + OCSP_RESPONSE *resp = NULL; + unsigned char *rspder = NULL; + int rspderlen; + int ret = SSL_TLSEXT_ERR_ALERT_FATAL; + + if (srctx->verbose) + BIO_puts(bio_err, "cert_status: callback called\n"); + + if (srctx->respin != NULL) { + BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1); + if (derbio == NULL) { + BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n"); + goto err; + } + resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); + BIO_free(derbio); + if (resp == NULL) { + BIO_puts(bio_err, "cert_status: Error reading OCSP response\n"); + goto err; + } + } else { + ret = get_ocsp_resp_from_responder(s, srctx, &resp); + if (ret != SSL_TLSEXT_ERR_OK) + goto err; + } + + rspderlen = i2d_OCSP_RESPONSE(resp, &rspder); + if (rspderlen <= 0) + goto err; + + SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen); + if (srctx->verbose) { + BIO_puts(bio_err, "cert_status: ocsp response sent:\n"); + OCSP_RESPONSE_print(bio_err, resp, 2); + } + + ret = SSL_TLSEXT_ERR_OK; + + err: + if (ret != SSL_TLSEXT_ERR_OK) + ERR_print_errors(bio_err); + + OCSP_RESPONSE_free(resp); + + return ret; +} #endif #ifndef OPENSSL_NO_NEXTPROTONEG @@ -655,7 +736,7 @@ static char *srtp_profiles = NULL; typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE, OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT, - OPT_VERIFY, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL, + OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM, OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT, OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT, @@ -664,23 +745,26 @@ typedef enum OPTION_choice { OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF, OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE, - OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_MSG, OPT_MSGFILE, OPT_TRACE, - OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE, OPT_CRLF, - OPT_QUIET, OPT_BRIEF, OPT_NO_DHE, - OPT_NO_RESUME_EPHEMERAL, OPT_PSK_HINT, OPT_PSK, OPT_SRPVFILE, - OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, - OPT_SSL_CONFIG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF, - OPT_SSL3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1, - OPT_DTLS1_2, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, - OPT_ID_PREFIX, OPT_RAND, OPT_SERVERNAME, OPT_SERVERNAME_FATAL, + OPT_STATUS_TIMEOUT, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE, + OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE, + OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE, + OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK, + OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW, + OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG, + OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF, + OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1, + OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS, + OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL, OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, + OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_EARLY_DATA, + OPT_R_ENUM, OPT_S_ENUM, OPT_V_ENUM, OPT_X_ENUM } OPTION_CHOICE; -OPTIONS s_server_options[] = { +const OPTIONS s_server_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"port", OPT_PORT, 'p', "TCP/IP port to listen on for connections (default is " PORT ")"}, @@ -699,6 +783,7 @@ OPTIONS s_server_options[] = { {"Verify", OPT_UPPER_V_VERIFY, 'n', "Turn on peer certificate verification, must have a cert"}, {"cert", OPT_CERT, '<', "Certificate file to use; default is " TEST_CERT}, + {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"}, {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"}, {"serverinfo", OPT_SERVERINFO, 's', "PEM serverinfo file for certificate"}, @@ -751,8 +836,7 @@ OPTIONS s_server_options[] = { {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"}, {"id_prefix", OPT_ID_PREFIX, 's', "Generate SSL/TLS session IDs prefixed by arg"}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, + OPT_R_OPTIONS, {"keymatexport", OPT_KEYMATEXPORT, 's', "Export keying material using label"}, {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p', @@ -790,6 +874,8 @@ OPTIONS s_server_options[] = { {"status_timeout", OPT_STATUS_TIMEOUT, 'n', "Status request responder timeout"}, {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"}, + {"status_file", OPT_STATUS_FILE, '<', + "File containing DER encoded OCSP Response"}, #endif #ifndef OPENSSL_NO_SSL_TRACE {"trace", OPT_TRACE, '-', "trace protocol messages"}, @@ -805,20 +891,23 @@ OPTIONS s_server_options[] = { {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"}, {"ssl_config", OPT_SSL_CONFIG, 's', "Configure SSL_CTX using the configuration 'val'"}, - {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'n', + {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "}, + {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p', "Size used to split data for encrypt pipelines"}, - {"max_pipelines", OPT_MAX_PIPELINES, 'n', + {"max_pipelines", OPT_MAX_PIPELINES, 'p', "Maximum number of encrypt/decrypt pipelines to be used"}, - {"read_buf", OPT_READ_BUF, 'n', + {"read_buf", OPT_READ_BUF, 'p', "Default read buffer size to be used for connections"}, OPT_S_OPTIONS, OPT_V_OPTIONS, OPT_X_OPTIONS, {"nbio", OPT_NBIO, '-', "Use non-blocking IO"}, + {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"}, #ifndef OPENSSL_NO_PSK {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"}, - {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"}, #endif + {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"}, + {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"}, #ifndef OPENSSL_NO_SRP {"srpvfile", OPT_SRPVFILE, '<', "The verifier file for SRP"}, {"srpuserseed", OPT_SRPUSERSEED, 's', @@ -836,6 +925,9 @@ OPTIONS s_server_options[] = { #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"}, #endif +#ifndef OPENSSL_NO_TLS1_3 + {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"}, +#endif #ifndef OPENSSL_NO_DTLS {"dtls", OPT_DTLS, '-', "Use any DTLS version"}, {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"}, @@ -843,12 +935,16 @@ OPTIONS s_server_options[] = { {"listen", OPT_LISTEN, '-', "Listen for a DTLS ClientHello with a cookie and then connect"}, #endif + {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"}, #ifndef OPENSSL_NO_DTLS1 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"}, #endif #ifndef OPENSSL_NO_DTLS1_2 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"}, #endif +#ifndef OPENSSL_NO_SCTP + {"sctp", OPT_SCTP, '-', "Use SCTP"}, +#endif #ifndef OPENSSL_NO_DH {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"}, #endif @@ -865,12 +961,16 @@ OPTIONS s_server_options[] = { #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif + {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"}, + {"max_early_data", OPT_MAX_EARLY, 'n', + "The maximum number of bytes of early data"}, + {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"}, {NULL, OPT_EOF, 0, NULL} }; #define IS_PROT_FLAG(o) \ (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \ - || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2) + || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2) int s_server_main(int argc, char *argv[]) { @@ -885,7 +985,7 @@ int s_server_main(int argc, char *argv[]) X509 *s_cert = NULL, *s_dcert = NULL; X509_VERIFY_PARAM *vpm = NULL; const char *CApath = NULL, *CAfile = NULL, *chCApath = NULL, *chCAfile = NULL; - char *dpassarg = NULL, *dpass = NULL, *inrand = NULL; + char *dpassarg = NULL, *dpass = NULL; char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL; char *crl_file = NULL, *prog; #ifdef AF_UNIX @@ -902,7 +1002,7 @@ int s_server_main(int argc, char *argv[]) int s_cert_format = FORMAT_PEM, s_key_format = FORMAT_PEM; int s_dcert_format = FORMAT_PEM, s_dkey_format = FORMAT_PEM; int rev = 0, naccept = -1, sdebug = 0; - int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM; + int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0; int state = 0, crl_format = FORMAT_PEM, crl_download = 0; char *host = NULL; char *port = BUF_strdup(PORT); @@ -922,8 +1022,8 @@ int s_server_main(int argc, char *argv[]) #ifndef OPENSSL_NO_PSK /* by default do not send a PSK identity hint */ char *psk_identity_hint = NULL; - char *p; #endif + char *p; #ifndef OPENSSL_NO_SRP char *srpuserseed = NULL; char *srp_verifier_file = NULL; @@ -938,8 +1038,12 @@ int s_server_main(int argc, char *argv[]) int s_tlsextstatus = 0; #endif int no_resume_ephemeral = 0; + unsigned int max_send_fragment = 0; unsigned int split_send_fragment = 0, max_pipelines = 0; const char *s_serverinfo_file = NULL; + const char *keylog_file = NULL; + int max_early_data = -1; + char *psksessf = NULL; /* Init of few remaining global variables */ local_argc = argc; @@ -1076,6 +1180,10 @@ int s_server_main(int argc, char *argv[]) case OPT_CERT: s_cert_file = opt_arg(); break; + case OPT_NAMEOPT: + if (!set_nameopt(opt_arg())) + goto end; + break; case OPT_CRL: crl_file = opt_arg(); break; @@ -1236,6 +1344,12 @@ int s_server_main(int argc, char *argv[]) BIO_printf(bio_err, "Error parsing URL\n"); goto end; } +#endif + break; + case OPT_STATUS_FILE: +#ifndef OPENSSL_NO_OCSP + s_tlsextstatus = 1; + tlscstatp.respin = opt_arg(); #endif break; case OPT_MSG: @@ -1275,20 +1389,24 @@ int s_server_main(int argc, char *argv[]) case OPT_NO_RESUME_EPHEMERAL: no_resume_ephemeral = 1; break; + case OPT_PSK_IDENTITY: + psk_identity = opt_arg(); + break; case OPT_PSK_HINT: #ifndef OPENSSL_NO_PSK psk_identity_hint = opt_arg(); #endif break; case OPT_PSK: -#ifndef OPENSSL_NO_PSK for (p = psk_key = opt_arg(); *p; p++) { if (isxdigit(_UC(*p))) continue; BIO_printf(bio_err, "Not a hex number '%s'\n", *argv); goto end; } -#endif + break; + case OPT_PSK_SESS: + psksessf = opt_arg(); break; case OPT_SRPVFILE: #ifndef OPENSSL_NO_SRP @@ -1323,6 +1441,10 @@ int s_server_main(int argc, char *argv[]) min_version = SSL3_VERSION; max_version = SSL3_VERSION; break; + case OPT_TLS1_3: + min_version = TLS1_3_VERSION; + max_version = TLS1_3_VERSION; + break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; @@ -1355,6 +1477,11 @@ int s_server_main(int argc, char *argv[]) min_version = DTLS1_2_VERSION; max_version = DTLS1_2_VERSION; socket_type = SOCK_DGRAM; +#endif + break; + case OPT_SCTP: +#ifndef OPENSSL_NO_SCTP + protocol = IPPROTO_SCTP; #endif break; case OPT_TIMEOUT: @@ -1372,14 +1499,18 @@ int s_server_main(int argc, char *argv[]) dtlslisten = 1; #endif break; + case OPT_STATELESS: + stateless = 1; + break; case OPT_ID_PREFIX: session_id_prefix = opt_arg(); break; case OPT_ENGINE: engine = setup_engine(opt_arg(), 1); break; - case OPT_RAND: - inrand = opt_arg(); + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_SERVERNAME: tlsextcbp.servername = opt_arg(); @@ -1415,15 +1546,11 @@ int s_server_main(int argc, char *argv[]) case OPT_ASYNC: async = 1; break; + case OPT_MAX_SEND_FRAG: + max_send_fragment = atoi(opt_arg()); + break; case OPT_SPLIT_SEND_FRAG: split_send_fragment = atoi(opt_arg()); - if (split_send_fragment == 0) { - /* - * Not allowed - set to a deliberately bad value so we get an - * error message below - */ - split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH + 1; - } break; case OPT_MAX_PIPELINES: max_pipelines = atoi(opt_arg()); @@ -1431,12 +1558,30 @@ int s_server_main(int argc, char *argv[]) case OPT_READ_BUF: read_buf_len = atoi(opt_arg()); break; - + case OPT_KEYLOG_FILE: + keylog_file = opt_arg(); + break; + case OPT_MAX_EARLY: + max_early_data = atoi(opt_arg()); + if (max_early_data < 0) { + BIO_printf(bio_err, "Invalid value for max_early_data\n"); + goto end; + } + break; + case OPT_EARLY_DATA: + early_data = 1; + break; } } argc = opt_num_rest(); argv = opt_rest(); +#ifndef OPENSSL_NO_NEXTPROTONEG + if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) { + BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n"); + goto opthelp; + } +#endif #ifndef OPENSSL_NO_DTLS if (www && socket_type == SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n"); @@ -1449,6 +1594,11 @@ int s_server_main(int argc, char *argv[]) } #endif + if (stateless && socket_type != SOCK_STREAM) { + BIO_printf(bio_err, "Can only use --stateless with TLS\n"); + goto end; + } + #ifdef AF_UNIX if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) { BIO_printf(bio_err, @@ -1457,15 +1607,16 @@ int s_server_main(int argc, char *argv[]) } #endif - if (split_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) { - BIO_printf(bio_err, "Bad split send fragment size\n"); - goto end; - } - - if (max_pipelines > SSL_MAX_PIPELINES) { - BIO_printf(bio_err, "Bad max pipelines value\n"); - goto end; +#ifndef OPENSSL_NO_SCTP + if (protocol == IPPROTO_SCTP) { + if (socket_type != SOCK_DGRAM) { + BIO_printf(bio_err, "Can't use -sctp without DTLS\n"); + goto end; + } + /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */ + socket_type = SOCK_STREAM; } +#endif if (!app_passwd(passarg, dpassarg, &pass, &dpass)) { BIO_printf(bio_err, "Error getting password\n"); @@ -1484,7 +1635,7 @@ int s_server_main(int argc, char *argv[]) if (nocert == 0) { s_key = load_key(s_key_file, s_key_format, 0, pass, engine, "server certificate private key file"); - if (!s_key) { + if (s_key == NULL) { ERR_print_errors(bio_err); goto end; } @@ -1492,20 +1643,20 @@ int s_server_main(int argc, char *argv[]) s_cert = load_cert(s_cert_file, s_cert_format, "server certificate file"); - if (!s_cert) { + if (s_cert == NULL) { ERR_print_errors(bio_err); goto end; } - if (s_chain_file) { + if (s_chain_file != NULL) { if (!load_certs(s_chain_file, &s_chain, FORMAT_PEM, NULL, "server certificate chain")) goto end; } - if (tlsextcbp.servername) { + if (tlsextcbp.servername != NULL) { s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine, "second server certificate private key file"); - if (!s_key2) { + if (s_key2 == NULL) { ERR_print_errors(bio_err); goto end; } @@ -1513,7 +1664,7 @@ int s_server_main(int argc, char *argv[]) s_cert2 = load_cert(s_cert_file2, s_cert_format, "second server certificate file"); - if (!s_cert2) { + if (s_cert2 == NULL) { ERR_print_errors(bio_err); goto end; } @@ -1533,16 +1684,16 @@ int s_server_main(int argc, char *argv[]) goto end; } - if (crl_file) { + if (crl_file != NULL) { X509_CRL *crl; crl = load_crl(crl_file, crl_format); - if (!crl) { + if (crl == NULL) { 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)) { + if (crls == NULL || !sk_X509_CRL_push(crls, crl)) { BIO_puts(bio_err, "Error adding CRL\n"); ERR_print_errors(bio_err); X509_CRL_free(crl); @@ -1550,14 +1701,14 @@ int s_server_main(int argc, char *argv[]) } } - if (s_dcert_file) { + if (s_dcert_file != NULL) { if (s_dkey_file == NULL) s_dkey_file = s_dcert_file; s_dkey = load_key(s_dkey_file, s_dkey_format, 0, dpass, engine, "second certificate private key file"); - if (!s_dkey) { + if (s_dkey == NULL) { ERR_print_errors(bio_err); goto end; } @@ -1565,11 +1716,11 @@ int s_server_main(int argc, char *argv[]) s_dcert = load_cert(s_dcert_file, s_dcert_format, "second server certificate file"); - if (!s_dcert) { + if (s_dcert == NULL) { ERR_print_errors(bio_err); goto end; } - if (s_dchain_file) { + if (s_dchain_file != NULL) { if (!load_certs(s_dchain_file, &s_dchain, FORMAT_PEM, NULL, "second server certificate chain")) goto end; @@ -1577,19 +1728,10 @@ int s_server_main(int argc, char *argv[]) } - if (!app_RAND_load_file(NULL, 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) + if (s_msg && bio_s_msg == NULL) bio_s_msg = dup_bio_out(FORMAT_TEXT); } else { if (bio_s_out == NULL) @@ -1615,10 +1757,6 @@ int s_server_main(int argc, char *argv[]) } if (sdebug) ssl_ctx_security_debug(ctx, sdebug); - - if (!config_ctx(cctx, ssl_args, ctx)) - goto end; - if (ssl_config) { if (SSL_CTX_config(ctx, ssl_config) == 0) { BIO_printf(bio_err, "Error using configuration \"%s\"\n", @@ -1627,11 +1765,9 @@ int s_server_main(int argc, char *argv[]) goto end; } } - if (min_version != 0 - && SSL_CTX_set_min_proto_version(ctx, min_version) == 0) + if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto end; - if (max_version != 0 - && SSL_CTX_set_max_proto_version(ctx, max_version) == 0) + if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto end; if (session_id_prefix) { @@ -1646,7 +1782,7 @@ int s_server_main(int argc, char *argv[]) BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix); } SSL_CTX_set_quiet_shutdown(ctx, 1); - if (exc) + if (exc != NULL) ssl_ctx_set_excert(ctx, exc); if (state) @@ -1661,11 +1797,25 @@ int s_server_main(int argc, char *argv[]) if (async) { SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC); } - if (split_send_fragment > 0) { - SSL_CTX_set_split_send_fragment(ctx, split_send_fragment); + + if (max_send_fragment > 0 + && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) { + BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n", + prog, max_send_fragment); + goto end; } - if (max_pipelines > 0) { - SSL_CTX_set_max_pipelines(ctx, max_pipelines); + + if (split_send_fragment > 0 + && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) { + BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n", + prog, split_send_fragment); + goto end; + } + if (max_pipelines > 0 + && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) { + BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n", + prog, max_pipelines); + goto end; } if (read_buf_len > 0) { @@ -1693,6 +1843,8 @@ int s_server_main(int argc, char *argv[]) } ssl_ctx_add_crls(ctx, crls, 0); + if (!config_ctx(cctx, ssl_args, ctx)) + goto end; if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile, crls, crl_download)) { @@ -1709,7 +1861,7 @@ int s_server_main(int argc, char *argv[]) } } - if (ctx2) { + if (ctx2 != NULL) { BIO_printf(bio_s_out, "Setting secondary ctx parameters\n"); if (sdebug) @@ -1727,7 +1879,7 @@ int s_server_main(int argc, char *argv[]) BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix); } SSL_CTX_set_quiet_shutdown(ctx2, 1); - if (exc) + if (exc != NULL) ssl_ctx_set_excert(ctx2, exc); if (state) @@ -1770,9 +1922,9 @@ int s_server_main(int argc, char *argv[]) if (!no_dhe) { DH *dh = NULL; - if (dhfile) + if (dhfile != NULL) dh = load_dh_param(dhfile); - else if (s_cert_file) + else if (s_cert_file != NULL) dh = load_dh_param(s_cert_file); if (dh != NULL) { @@ -1782,16 +1934,16 @@ int s_server_main(int argc, char *argv[]) } (void)BIO_flush(bio_s_out); - if (dh == NULL) + if (dh == NULL) { SSL_CTX_set_dh_auto(ctx, 1); - else if (!SSL_CTX_set_tmp_dh(ctx, dh)) { + } else if (!SSL_CTX_set_tmp_dh(ctx, dh)) { BIO_puts(bio_err, "Error setting temp DH parameters\n"); ERR_print_errors(bio_err); DH_free(dh); goto end; } - if (ctx2) { + if (ctx2 != NULL) { if (!dhfile) { DH *dh2 = load_dh_param(s_cert_file2); if (dh2 != NULL) { @@ -1802,9 +1954,9 @@ int s_server_main(int argc, char *argv[]) dh = dh2; } } - if (dh == NULL) + if (dh == NULL) { SSL_CTX_set_dh_auto(ctx2, 1); - else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) { + } else if (!SSL_CTX_set_tmp_dh(ctx2, dh)) { BIO_puts(bio_err, "Error setting temp DH parameters\n"); ERR_print_errors(bio_err); DH_free(dh); @@ -1824,7 +1976,8 @@ int s_server_main(int argc, char *argv[]) goto end; } - if (ctx2 && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain)) + if (ctx2 != NULL + && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain)) goto end; if (s_dcert != NULL) { @@ -1836,7 +1989,7 @@ int s_server_main(int argc, char *argv[]) SSL_CTX_set_not_resumable_session_callback(ctx, not_resumable_sess_cb); - if (ctx2) + if (ctx2 != NULL) SSL_CTX_set_not_resumable_session_callback(ctx2, not_resumable_sess_cb); } @@ -1853,6 +2006,26 @@ int s_server_main(int argc, char *argv[]) goto end; } #endif + if (psksessf != NULL) { + BIO *stmp = BIO_new_file(psksessf, "r"); + + if (stmp == NULL) { + BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf); + ERR_print_errors(bio_err); + goto end; + } + psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); + BIO_free(stmp); + if (psksess == NULL) { + BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf); + ERR_print_errors(bio_err); + goto end; + } + + } + + if (psk_key != NULL || psksess != NULL) + SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb); SSL_CTX_set_verify(ctx, s_server_verify, verify_callback); if (!SSL_CTX_set_session_id_context(ctx, @@ -1867,7 +2040,7 @@ int s_server_main(int argc, char *argv[]) SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback); SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback); - if (ctx2) { + if (ctx2 != NULL) { SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback); if (!SSL_CTX_set_session_id_context(ctx2, (void *)&s_server_session_id_context, @@ -1917,6 +2090,11 @@ int s_server_main(int argc, char *argv[]) } } #endif + if (set_keylog_file(ctx, keylog_file)) + goto end; + + if (max_early_data >= 0) + SSL_CTX_set_max_early_data(ctx, max_early_data); BIO_printf(bio_s_out, "ACCEPT\n"); (void)BIO_flush(bio_s_out); @@ -1931,12 +2109,14 @@ int s_server_main(int argc, char *argv[]) && unlink_unix_path) unlink(host); #endif - do_server(&accept_socket, host, port, socket_family, socket_type, + do_server(&accept_socket, host, port, socket_family, socket_type, protocol, server_cb, context, naccept); print_stats(bio_s_out, ctx); ret = 0; end: SSL_CTX_free(ctx); + SSL_SESSION_free(psksess); + set_keylog_file(NULL, NULL); X509_free(s_cert); sk_X509_CRL_pop_free(crls, X509_CRL_free); X509_free(s_dcert); @@ -1971,7 +2151,7 @@ int s_server_main(int argc, char *argv[]) #ifdef CHARSET_EBCDIC BIO_meth_free(methods_ebcdic); #endif - return (ret); + return ret; } static void print_stats(BIO *bio, SSL_CTX *ssl_ctx) @@ -2002,7 +2182,7 @@ static void print_stats(BIO *bio, SSL_CTX *ssl_ctx) SSL_CTX_sess_get_cache_size(ssl_ctx)); } -static int sv_body(int s, int stype, unsigned char *context) +static int sv_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; fd_set readfds; @@ -2016,6 +2196,13 @@ static int sv_body(int s, int stype, unsigned char *context) struct timeval tv; #else struct timeval *timeoutp; +#endif +#ifndef OPENSSL_NO_DTLS +# ifndef OPENSSL_NO_SCTP + int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP); +# else + int isdtls = (stype == SOCK_DGRAM); +# endif #endif buf = app_malloc(bufsize, "server buffer"); @@ -2026,31 +2213,38 @@ static int sv_body(int s, int stype, unsigned char *context) BIO_printf(bio_err, "Turned on non blocking io\n"); } + con = SSL_new(ctx); if (con == NULL) { - con = SSL_new(ctx); - - if (s_tlsextdebug) { - SSL_set_tlsext_debug_callback(con, tlsext_cb); - SSL_set_tlsext_debug_arg(con, bio_s_out); - } - - if (context - && !SSL_set_session_id_context(con, - context, strlen((char *)context))) { - BIO_printf(bio_err, "Error setting session id context\n"); - ret = -1; - goto err; - } + ret = -1; + goto err; } + + if (s_tlsextdebug) { + SSL_set_tlsext_debug_callback(con, tlsext_cb); + SSL_set_tlsext_debug_arg(con, bio_s_out); + } + + if (context != NULL + && !SSL_set_session_id_context(con, context, + strlen((char *)context))) { + BIO_printf(bio_err, "Error setting session id context\n"); + ret = -1; + goto err; + } + if (!SSL_clear(con)) { BIO_printf(bio_err, "Error clearing SSL connection\n"); ret = -1; goto err; } #ifndef OPENSSL_NO_DTLS - if (stype == SOCK_DGRAM) { - - sbio = BIO_new_dgram(s, BIO_NOCLOSE); + if (isdtls) { +# ifndef OPENSSL_NO_SCTP + if (prot == IPPROTO_SCTP) + sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE); + else +# endif + sbio = BIO_new_dgram(s, BIO_NOCLOSE); if (enable_timeouts) { timeout.tv_sec = 0; @@ -2081,12 +2275,21 @@ static int sv_body(int s, int stype, unsigned char *context) /* 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); +# ifndef OPENSSL_NO_SCTP + if (prot != IPPROTO_SCTP) +# endif + /* Turn on cookie exchange. Not necessary for SCTP */ + SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE); } else #endif sbio = BIO_new_socket(s, BIO_NOCLOSE); + if (sbio == NULL) { + BIO_printf(bio_err, "Unable to create BIO\n"); + ERR_print_errors(bio_err); + goto err; + } + if (s_nbio_test) { BIO *test; @@ -2117,6 +2320,49 @@ static int sv_body(int s, int stype, unsigned char *context) SSL_set_tlsext_debug_arg(con, bio_s_out); } + if (early_data) { + int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR; + size_t readbytes; + + while (edret != SSL_READ_EARLY_DATA_FINISH) { + for (;;) { + edret = SSL_read_early_data(con, buf, bufsize, &readbytes); + if (edret != SSL_READ_EARLY_DATA_ERROR) + break; + + switch (SSL_get_error(con, 0)) { + case SSL_ERROR_WANT_WRITE: + case SSL_ERROR_WANT_ASYNC: + case SSL_ERROR_WANT_READ: + /* Just keep trying - busy waiting */ + continue; + default: + BIO_printf(bio_err, "Error reading early data\n"); + ERR_print_errors(bio_err); + goto err; + } + } + if (readbytes > 0) { + if (write_header) { + BIO_printf(bio_s_out, "Early data received:\n"); + write_header = 0; + } + raw_write_stdout(buf, (unsigned int)readbytes); + (void)BIO_flush(bio_s_out); + } + } + if (write_header) { + if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT) + BIO_printf(bio_s_out, "No early data received\n"); + else + BIO_printf(bio_s_out, "Early data was rejected\n"); + } else { + BIO_printf(bio_s_out, "\nEnd of early data\n"); + } + if (SSL_is_init_finished(con)) + print_connection_info(con); + } + if (fileno_stdin() > s) width = fileno_stdin() + 1; else @@ -2197,8 +2443,9 @@ static int sv_body(int s, int stype, unsigned char *context) } } assert(lf_num == 0); - } else + } else { i = raw_read_stdin(buf, bufsize); + } if (!s_quiet && !s_brief) { if ((i <= 0) || (buf[0] == 'Q')) { @@ -2233,9 +2480,6 @@ static int sv_body(int s, int stype, unsigned char *context) 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, @@ -2246,10 +2490,29 @@ static int sv_body(int s, int stype, unsigned char *context) 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] == 'K' || buf[0] == 'k') + && ((buf[1] == '\n') || (buf[1] == '\r'))) { + SSL_key_update(con, buf[0] == 'K' ? + SSL_KEY_UPDATE_REQUESTED + : SSL_KEY_UPDATE_NOT_REQUESTED); + i = SSL_do_handshake(con); + printf("SSL_do_handshake -> %d\n", i); + i = 0; + continue; + } + if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) { + SSL_set_verify(con, SSL_VERIFY_PEER, NULL); + i = SSL_verify_client_post_handshake(con); + if (i == 0) { + printf("Failed to initiate request\n"); + ERR_print_errors(bio_err); + } else { + i = SSL_do_handshake(con); + printf("SSL_do_handshake -> %d\n", i); + i = 0; + } + continue; } if (buf[0] == 'P') { static const char *str = "Lets print some clear text\n"; @@ -2414,7 +2677,7 @@ static int sv_body(int s, int stype, unsigned char *context) if (ret >= 0) BIO_printf(bio_s_out, "ACCEPT\n"); (void)BIO_flush(bio_s_out); - return (ret); + return ret; } static void close_accept_socket(void) @@ -2425,97 +2688,105 @@ static void close_accept_socket(void) } } +static int is_retryable(SSL *con, int i) +{ + int err = SSL_get_error(con, i); + + /* If it's not a fatal error, it must be retryable */ + return (err != SSL_ERROR_SSL) + && (err != SSL_ERROR_SYSCALL) + && (err != SSL_ERROR_ZERO_RETURN); +} + static int init_ssl_connection(SSL *con) { int i; - const char *str; - X509 *peer; long verify_err; - char buf[BUFSIZ]; -#if !defined(OPENSSL_NO_NEXTPROTONEG) - const unsigned char *next_proto_neg; - unsigned next_proto_neg_len; -#endif - unsigned char *exportedkeymat; int retry = 0; -#ifndef OPENSSL_NO_DTLS - if (dtlslisten) { + if (dtlslisten || stateless) { BIO_ADDR *client = NULL; - if ((client = BIO_ADDR_new()) == NULL) { - BIO_printf(bio_err, "ERROR - memory\n"); - return 0; + if (dtlslisten) { + if ((client = BIO_ADDR_new()) == NULL) { + BIO_printf(bio_err, "ERROR - memory\n"); + return 0; + } + i = DTLSv1_listen(con, client); + } else { + i = SSL_stateless(con); } - i = DTLSv1_listen(con, client); if (i > 0) { BIO *wbio; int fd = -1; - wbio = SSL_get_wbio(con); - if (wbio) { - BIO_get_fd(wbio, &fd); - } + if (dtlslisten) { + wbio = SSL_get_wbio(con); + if (wbio) { + BIO_get_fd(wbio, &fd); + } - if (!wbio || BIO_connect(fd, client, 0) == 0) { - BIO_printf(bio_err, "ERROR - unable to connect\n"); + if (!wbio || BIO_connect(fd, client, 0) == 0) { + BIO_printf(bio_err, "ERROR - unable to connect\n"); + BIO_ADDR_free(client); + return 0; + } BIO_ADDR_free(client); - return 0; + dtlslisten = 0; + } else { + stateless = 0; } - BIO_ADDR_free(client); - dtlslisten = 0; i = SSL_accept(con); } else { BIO_ADDR_free(client); } - } else -#endif + } else { + do { + i = SSL_accept(con); - do { - i = SSL_accept(con); - - if (i <= 0) - retry = BIO_sock_should_retry(i); + if (i <= 0) + retry = is_retryable(con, i); #ifdef CERT_CB_TEST_RETRY - { - while (i <= 0 - && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP - && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) { - BIO_printf(bio_err, - "LOOKUP from certificate callback during accept\n"); - i = SSL_accept(con); - if (i <= 0) - retry = BIO_sock_should_retry(i); + { + while (i <= 0 + && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP + && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) { + BIO_printf(bio_err, + "LOOKUP from certificate callback during accept\n"); + i = SSL_accept(con); + if (i <= 0) + retry = is_retryable(con, i); + } } - } #endif #ifndef OPENSSL_NO_SRP - while (i <= 0 - && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { - BIO_printf(bio_s_out, "LOOKUP during accept %s\n", - srp_callback_parm.login); - 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); - if (i <= 0) - retry = BIO_sock_should_retry(i); - } + 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); + if (i <= 0) + retry = is_retryable(con, i); + } #endif - } while (i < 0 && SSL_waiting_for_async(con)); + } while (i < 0 && SSL_waiting_for_async(con)); + } if (i <= 0) { - if ((dtlslisten && i == 0) - || (!dtlslisten && retry)) { + if (((dtlslisten || stateless) && i == 0) + || (!dtlslisten && !stateless && retry)) { BIO_printf(bio_s_out, "DELAY\n"); - return (1); + return 1; } BIO_printf(bio_err, "ERROR\n"); @@ -2527,9 +2798,25 @@ static int init_ssl_connection(SSL *con) } /* Always print any error messages */ ERR_print_errors(bio_err); - return (0); + return 0; } + print_connection_info(con); + return 1; +} + +static void print_connection_info(SSL *con) +{ + const char *str; + X509 *peer; + char buf[BUFSIZ]; +#if !defined(OPENSSL_NO_NEXTPROTONEG) + const unsigned char *next_proto_neg; + unsigned next_proto_neg_len; +#endif + unsigned char *exportedkeymat; + int i; + if (s_brief) print_ssl_summary(con); @@ -2539,10 +2826,7 @@ static int init_ssl_connection(SSL *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)); - BIO_printf(bio_s_out, "subject=%s\n", buf); - X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof(buf)); - BIO_printf(bio_s_out, "issuer=%s\n", buf); + dump_cert_text(bio_s_out, peer); X509_free(peer); peer = NULL; } @@ -2553,8 +2837,9 @@ static int init_ssl_connection(SSL *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); + ssl_print_groups(bio_s_out, con, 0); #endif + print_ca_names(bio_s_out, con); BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)"); #if !defined(OPENSSL_NO_NEXTPROTONEG) @@ -2603,7 +2888,6 @@ static int init_ssl_connection(SSL *con) } (void)BIO_flush(bio_s_out); - return (1); } #ifndef OPENSSL_NO_DH @@ -2617,11 +2901,11 @@ static DH *load_dh_param(const char *dhfile) ret = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); err: BIO_free(bio); - return (ret); + return ret; } #endif -static int www_body(int s, int stype, unsigned char *context) +static int www_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; int ret = 1; @@ -2663,7 +2947,7 @@ static int www_body(int s, int stype, unsigned char *context) SSL_set_tlsext_debug_arg(con, bio_s_out); } - if (context + if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) goto err; @@ -2843,8 +3127,9 @@ static int www_body(int s, int stype, unsigned char *context) } ssl_print_sigalgs(io, con); #ifndef OPENSSL_NO_EC - ssl_print_curves(io, con, 0); + ssl_print_groups(io, con, 0); #endif + print_ca_names(io, con); BIO_printf(io, (SSL_session_reused(con) ? "---\nReused, " : "---\nNew, ")); c = SSL_get_current_cipher(con); @@ -3004,10 +3289,10 @@ static int www_body(int s, int stype, unsigned char *context) BIO_printf(bio_s_out, "ACCEPT\n"); OPENSSL_free(buf); BIO_free_all(io); - return (ret); + return ret; } -static int rev_body(int s, int stype, unsigned char *context) +static int rev_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; int i; @@ -3032,7 +3317,7 @@ static int rev_body(int s, int stype, unsigned char *context) SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } - if (context + if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { ERR_print_errors(bio_err); @@ -3157,11 +3442,11 @@ static int rev_body(int s, int stype, unsigned char *context) OPENSSL_free(buf); BIO_free_all(io); - return (ret); + return ret; } #define MAX_SESSION_ID_ATTEMPTS 10 -static int generate_session_id(const SSL *ssl, unsigned char *id, +static int generate_session_id(SSL *ssl, unsigned char *id, unsigned int *id_len) { unsigned int count = 0; diff --git a/apps/s_socket.c b/apps/s_socket.c index 458aa862..4b82011a 100644 --- a/apps/s_socket.c +++ b/apps/s_socket.c @@ -28,22 +28,27 @@ typedef unsigned int u_int; #ifndef OPENSSL_NO_SOCK -# define USE_SOCKETS # include "apps.h" -# undef USE_SOCKETS # include "s_apps.h" +# include "internal/sockets.h" # include # include +/* Keep track of our peer's address for the cookie callback */ +BIO_ADDR *ourpeer = NULL; + /* * init_client - helper routine to set up socket communication * @sock: pointer to storage of resulting socket. * @host: the host name or path (for AF_UNIX) to connect to. * @port: the port to connect to (ignored for AF_UNIX). + * @bindhost: source host or path (for AF_UNIX). + * @bindport: source port (ignored for AF_UNIX). * @family: desired socket family, may be AF_INET, AF_INET6, AF_UNIX or * AF_UNSPEC * @type: socket type, must be SOCK_STREAM or SOCK_DGRAM + * @protocol: socket protocol, e.g. IPPROTO_TCP or IPPROTO_UDP (or 0 for any) * * This will create a socket and use it to connect to a host:port, or if * family == AF_UNIX, to the path found in host. @@ -55,21 +60,35 @@ typedef unsigned int u_int; * Returns 1 on success, 0 on failure. */ int init_client(int *sock, const char *host, const char *port, - int family, int type) + const char *bindhost, const char *bindport, + int family, int type, int protocol) { BIO_ADDRINFO *res = NULL; + BIO_ADDRINFO *bindaddr = NULL; const BIO_ADDRINFO *ai = NULL; + const BIO_ADDRINFO *bi = NULL; + int found = 0; int ret; - if (!BIO_sock_init()) + if (BIO_sock_init() != 1) return 0; - ret = BIO_lookup(host, port, BIO_LOOKUP_CLIENT, family, type, &res); + ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol, + &res); if (ret == 0) { ERR_print_errors(bio_err); return 0; } + if (bindhost != NULL || bindport != NULL) { + ret = BIO_lookup_ex(bindhost, bindport, BIO_LOOKUP_CLIENT, + family, type, protocol, &bindaddr); + if (ret == 0) { + ERR_print_errors (bio_err); + goto out; + } + } + ret = 0; for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) { /* Admittedly, these checks are quite paranoid, we should not get @@ -77,7 +96,19 @@ int init_client(int *sock, const char *host, const char *port, * asked for. */ OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(ai)) - && (type == 0 || type == BIO_ADDRINFO_socktype(ai))); + && (type == 0 || type == BIO_ADDRINFO_socktype(ai)) + && (protocol == 0 + || protocol == BIO_ADDRINFO_protocol(ai))); + + if (bindaddr != NULL) { + for (bi = bindaddr; bi != NULL; bi = BIO_ADDRINFO_next(bi)) { + if (BIO_ADDRINFO_family(bi) == BIO_ADDRINFO_family(ai)) + break; + } + if (bi == NULL) + continue; + ++found; + } *sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai), BIO_ADDRINFO_protocol(ai), 0); @@ -87,6 +118,34 @@ int init_client(int *sock, const char *host, const char *port, */ continue; } + + if (bi != NULL) { + if (!BIO_bind(*sock, BIO_ADDRINFO_address(bi), + BIO_SOCK_REUSEADDR)) { + BIO_closesocket(*sock); + *sock = INVALID_SOCKET; + break; + } + } + +#ifndef OPENSSL_NO_SCTP + if (protocol == IPPROTO_SCTP) { + /* + * For SCTP we have to set various options on the socket prior to + * connecting. This is done automatically by BIO_new_dgram_sctp(). + * We don't actually need the created BIO though so we free it again + * immediately. + */ + BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE); + + if (tmpbio == NULL) { + ERR_print_errors(bio_err); + return 0; + } + BIO_free(tmpbio); + } +#endif + if (!BIO_connect(*sock, BIO_ADDRINFO_address(ai), 0)) { BIO_closesocket(*sock); *sock = INVALID_SOCKET; @@ -98,12 +157,27 @@ int init_client(int *sock, const char *host, const char *port, } if (*sock == INVALID_SOCKET) { + if (bindaddr != NULL && !found) { + BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n", + BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " : + BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 " : + BIO_ADDRINFO_family(res) == AF_UNIX ? "unix " : "", + bindhost != NULL ? bindhost : "", + bindport != NULL ? ":" : "", + bindport != NULL ? bindport : ""); + ERR_clear_error(); + ret = 0; + } ERR_print_errors(bio_err); } else { /* Remove any stale errors from previous connection attempts */ ERR_clear_error(); ret = 1; } +out: + if (bindaddr != NULL) { + BIO_ADDRINFO_free (bindaddr); + } BIO_ADDRINFO_free(res); return ret; } @@ -129,7 +203,7 @@ int init_client(int *sock, const char *host, const char *port, * 0 on failure, something other on success. */ int do_server(int *accept_sock, const char *host, const char *port, - int family, int type, do_server_cb cb, + int family, int type, int protocol, do_server_cb cb, unsigned char *context, int naccept) { int asock = 0; @@ -142,10 +216,11 @@ int do_server(int *accept_sock, const char *host, const char *port, int sock_options = BIO_SOCK_REUSEADDR; int ret = 0; - if (!BIO_sock_init()) + if (BIO_sock_init() != 1) return 0; - if (!BIO_lookup(host, port, BIO_LOOKUP_SERVER, family, type, &res)) { + if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol, + &res)) { ERR_print_errors(bio_err); return 0; } @@ -153,7 +228,8 @@ int do_server(int *accept_sock, const char *host, const char *port, /* Admittedly, these checks are quite paranoid, we should not get * anything in the BIO_ADDRINFO chain that we haven't asked for */ OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res)) - && (type == 0 || type == BIO_ADDRINFO_socktype(res))); + && (type == 0 || type == BIO_ADDRINFO_socktype(res)) + && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res))); sock_family = BIO_ADDRINFO_family(res); sock_type = BIO_ADDRINFO_socktype(res); @@ -185,6 +261,25 @@ int do_server(int *accept_sock, const char *host, const char *port, goto end; } +#ifndef OPENSSL_NO_SCTP + if (protocol == IPPROTO_SCTP) { + /* + * For SCTP we have to set various options on the socket prior to + * accepting. This is done automatically by BIO_new_dgram_sctp(). + * We don't actually need the created BIO though so we free it again + * immediately. + */ + BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE); + + if (tmpbio == NULL) { + BIO_closesocket(asock); + ERR_print_errors(bio_err); + goto end; + } + BIO_free(tmpbio); + } +#endif + BIO_ADDRINFO_free(res); res = NULL; @@ -192,15 +287,22 @@ int do_server(int *accept_sock, const char *host, const char *port, *accept_sock = asock; for (;;) { if (type == SOCK_STREAM) { + BIO_ADDR_free(ourpeer); + ourpeer = BIO_ADDR_new(); + if (ourpeer == NULL) { + BIO_closesocket(asock); + ERR_print_errors(bio_err); + goto end; + } do { - sock = BIO_accept_ex(asock, NULL, 0); + sock = BIO_accept_ex(asock, ourpeer, 0); } while (sock < 0 && BIO_sock_should_retry(sock)); if (sock < 0) { ERR_print_errors(bio_err); BIO_closesocket(asock); break; } - i = (*cb)(sock, type, context); + i = (*cb)(sock, type, protocol, context); /* * Give the socket time to send its last data before we close it. @@ -228,7 +330,7 @@ int do_server(int *accept_sock, const char *host, const char *port, shutdown(sock, 1); /* SHUT_WR */ BIO_closesocket(sock); } else { - i = (*cb)(asock, type, context); + i = (*cb)(asock, type, protocol, context); } if (naccept != -1) @@ -244,6 +346,8 @@ int do_server(int *accept_sock, const char *host, const char *port, if (family == AF_UNIX) unlink(host); # endif + BIO_ADDR_free(ourpeer); + ourpeer = NULL; return ret; } diff --git a/apps/s_time.c b/apps/s_time.c index dc0ec4af..149107c5 100644 --- a/apps/s_time.c +++ b/apps/s_time.c @@ -7,6 +7,8 @@ * https://www.openssl.org/source/license.html */ +#define NO_SHUTDOWN + #include #include #include @@ -15,8 +17,8 @@ #ifndef OPENSSL_NO_SOCK -#define USE_SOCKETS #include "apps.h" +#include "progs.h" #include #include #include @@ -26,29 +28,50 @@ # include OPENSSL_UNISTD #endif +#undef ioctl +#define ioctl ioctlsocket + #define SSL_CONNECT_NAME "localhost:4433" +/* no default cert. */ +/* + * #define TEST_CERT "client.pem" + */ + +#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 #define SECONDSSTR "30" static SSL *doConnection(SSL *scon, const char *host, SSL_CTX *ctx); +/* + * Define a HTTP get command globally. + * Also define the size of the command, this is two bytes less than + * the size of the string because the %s is replaced by the URL. + */ static const char fmt_http_get_cmd[] = "GET %s HTTP/1.0\r\n\r\n"; +static const size_t fmt_http_get_cmd_size = sizeof(fmt_http_get_cmd) - 2; typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, - OPT_CONNECT, OPT_CIPHER, OPT_CERT, OPT_KEY, OPT_CAPATH, + OPT_CONNECT, OPT_CIPHER, OPT_CERT, OPT_NAMEOPT, OPT_KEY, OPT_CAPATH, OPT_CAFILE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NEW, OPT_REUSE, OPT_BUGS, OPT_VERIFY, OPT_TIME, OPT_SSL3, OPT_WWW } OPTION_CHOICE; -OPTIONS s_time_options[] = { +const OPTIONS s_time_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"connect", OPT_CONNECT, 's', "Where to connect as post:port (default is " SSL_CONNECT_NAME ")"}, {"cipher", OPT_CIPHER, 's', "Cipher to use, see 'openssl ciphers'"}, {"cert", OPT_CERT, '<', "Cert file to use, PEM format assumed"}, + {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"}, {"key", OPT_KEY, '<', "File with key, PEM; default is -cert file"}, {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"}, {"cafile", OPT_CAFILE, '<', "PEM format file of CA's"}, @@ -125,6 +148,10 @@ int s_time_main(int argc, char **argv) case OPT_CERT: certfile = opt_arg(); break; + case OPT_NAMEOPT: + if (!set_nameopt(opt_arg())) + goto end; + break; case OPT_KEY: keyfile = opt_arg(); break; @@ -152,7 +179,7 @@ int s_time_main(int argc, char **argv) break; case OPT_WWW: www_path = opt_arg(); - buf_size = strlen(www_path) + sizeof(fmt_http_get_cmd) - 2; /* 2 is for %s */ + buf_size = strlen(www_path) + fmt_http_get_cmd_size; if (buf_size > sizeof(buf)) { BIO_printf(bio_err, "%s: -www option is too long\n", prog); goto end; @@ -169,20 +196,21 @@ int s_time_main(int argc, char **argv) if (cipher == NULL) cipher = getenv("SSL_CIPHER"); - if (cipher == NULL) + if (cipher == NULL) { BIO_printf(bio_err, "No CIPHER specified\n"); + goto end; + } if ((ctx = SSL_CTX_new(meth)) == NULL) goto end; - SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); SSL_CTX_set_quiet_shutdown(ctx, 1); if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto end; if (st_bugs) SSL_CTX_set_options(ctx, SSL_OP_ALL); - if (cipher != NULL && !SSL_CTX_set_cipher_list(ctx, cipher)) + if (!SSL_CTX_set_cipher_list(ctx, cipher)) goto end; if (!set_cert_stuff(ctx, certfile, keyfile)) goto end; @@ -208,20 +236,26 @@ int s_time_main(int argc, char **argv) goto end; if (www_path != NULL) { - buf_len = BIO_snprintf(buf, sizeof(buf), - fmt_http_get_cmd, www_path); - if (SSL_write(scon, buf, buf_len) <= 0) + buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd, + www_path); + if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0) goto end; - while ((i = SSL_read(scon, buf, sizeof(buf))) > 0) - bytes_read += i; + while ((i = SSL_read(scon, buf, sizeof(buf))) > 0 || + SSL_get_error(scon, i) == SSL_ERROR_WANT_READ || + SSL_get_error(scon, i) == SSL_ERROR_WANT_WRITE) + if (i > 0) bytes_read += i; } +#ifdef NO_SHUTDOWN SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); +#else + SSL_shutdown(scon); +#endif BIO_closesocket(SSL_get_fd(scon)); nConn += 1; - if (SSL_session_reused(scon)) + if (SSL_session_reused(scon)) { ver = 'r'; - else { + } else { ver = SSL_version(scon); if (ver == TLS1_VERSION) ver = 't'; @@ -262,14 +296,19 @@ int s_time_main(int argc, char **argv) } if (www_path != NULL) { - buf_len = BIO_snprintf(buf, sizeof(buf), - fmt_http_get_cmd, www_path); - if (SSL_write(scon, buf, buf_len) <= 0) + buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd, www_path); + if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0) goto end; - while ((i = SSL_read(scon, buf, sizeof(buf))) > 0) + while ((i = SSL_read(scon, buf, sizeof(buf))) > 0 || + SSL_get_error(scon, i) == SSL_ERROR_WANT_READ || + SSL_get_error(scon, i) == SSL_ERROR_WANT_WRITE) continue; } +#ifdef NO_SHUTDOWN SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); +#else + SSL_shutdown(scon); +#endif BIO_closesocket(SSL_get_fd(scon)); nConn = 0; @@ -288,21 +327,27 @@ int s_time_main(int argc, char **argv) if ((doConnection(scon, host, ctx)) == NULL) goto end; - if (www_path) { - BIO_snprintf(buf, sizeof(buf), "GET %s HTTP/1.0\r\n\r\n", - www_path); - if (SSL_write(scon, buf, strlen(buf)) <= 0) + if (www_path != NULL) { + buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd, + www_path); + if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0) goto end; - while ((i = SSL_read(scon, buf, sizeof(buf))) > 0) - bytes_read += i; + while ((i = SSL_read(scon, buf, sizeof(buf))) > 0 || + SSL_get_error(scon, i) == SSL_ERROR_WANT_READ || + SSL_get_error(scon, i) == SSL_ERROR_WANT_WRITE) + if (i > 0) bytes_read += i; } +#ifdef NO_SHUTDOWN SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); +#else + SSL_shutdown(scon); +#endif BIO_closesocket(SSL_get_fd(scon)); nConn += 1; - if (SSL_session_reused(scon)) + if (SSL_session_reused(scon)) { ver = 'r'; - else { + } else { ver = SSL_version(scon); if (ver == TLS1_VERSION) ver = 't'; @@ -328,7 +373,7 @@ int s_time_main(int argc, char **argv) end: SSL_free(scon); SSL_CTX_free(ctx); - return (ret); + return ret; } /*- @@ -338,13 +383,13 @@ static SSL *doConnection(SSL *scon, const char *host, SSL_CTX *ctx) { BIO *conn; SSL *serverCon; - int i; + int width, i; + fd_set readfds; if ((conn = BIO_new(BIO_s_connect())) == NULL) return NULL; BIO_set_conn_hostname(conn, host); - BIO_set_conn_mode(conn, BIO_SOCK_NODELAY); if (scon == NULL) serverCon = SSL_new(ctx); @@ -356,7 +401,26 @@ static SSL *doConnection(SSL *scon, const char *host, SSL_CTX *ctx) SSL_set_bio(serverCon, conn, conn); /* ok, lets connect */ - i = SSL_connect(serverCon); + 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_args.error != X509_V_OK) @@ -369,17 +433,6 @@ static SSL *doConnection(SSL *scon, const char *host, SSL_CTX *ctx) return NULL; } -#if defined(SOL_SOCKET) && defined(SO_LINGER) - { - struct linger no_linger; - - no_linger.l_onoff = 1; - no_linger.l_linger = 0; - (void) setsockopt(SSL_get_fd(serverCon), SOL_SOCKET, SO_LINGER, - (char*)&no_linger, sizeof(no_linger)); - } -#endif - return serverCon; } #endif /* OPENSSL_NO_SOCK */ diff --git a/apps/sess_id.c b/apps/sess_id.c index 2b63e69c..70966de3 100644 --- a/apps/sess_id.c +++ b/apps/sess_id.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -11,6 +11,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -23,7 +24,7 @@ typedef enum OPTION_choice { OPT_TEXT, OPT_CERT, OPT_NOOUT, OPT_CONTEXT } OPTION_CHOICE; -OPTIONS sess_id_options[] = { +const OPTIONS sess_id_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'F', "Input format - default PEM (DER or PEM)"}, {"outform", OPT_OUTFORM, 'f', @@ -100,14 +101,14 @@ int sess_id_main(int argc, char **argv) } peer = SSL_SESSION_get0_peer(x); - if (context) { + if (context != NULL) { size_t ctx_len = strlen(context); if (ctx_len > SSL_MAX_SID_CTX_LENGTH) { BIO_printf(bio_err, "Context too long\n"); goto end; } if (!SSL_SESSION_set1_id_context(x, (unsigned char *)context, - ctx_len)) { + ctx_len)) { BIO_printf(bio_err, "Error setting id context\n"); goto end; } @@ -131,13 +132,13 @@ int sess_id_main(int argc, char **argv) } if (!noout && !cert) { - if (outformat == FORMAT_ASN1) + if (outformat == FORMAT_ASN1) { i = i2d_SSL_SESSION_bio(out, x); - else if (outformat == FORMAT_PEM) + } else if (outformat == FORMAT_PEM) { i = PEM_write_bio_SSL_SESSION(out, x); - else if (outformat == FORMAT_NSS) + } else if (outformat == FORMAT_NSS) { i = SSL_SESSION_print_keylog(out, x); - else { + } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } @@ -146,11 +147,11 @@ int sess_id_main(int argc, char **argv) goto end; } } else if (!noout && (peer != NULL)) { /* just print the certificate */ - if (outformat == FORMAT_ASN1) + if (outformat == FORMAT_ASN1) { i = (int)i2d_X509_bio(out, peer); - else if (outformat == FORMAT_PEM) + } else if (outformat == FORMAT_PEM) { i = PEM_write_bio_X509(out, peer); - else { + } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } @@ -163,7 +164,7 @@ int sess_id_main(int argc, char **argv) end: BIO_free_all(out); SSL_SESSION_free(x); - return (ret); + return ret; } static SSL_SESSION *load_sess_id(char *infile, int format) @@ -186,5 +187,5 @@ static SSL_SESSION *load_sess_id(char *infile, int format) end: BIO_free(in); - return (x); + return x; } diff --git a/apps/smime.c b/apps/smime.c index e18d7de7..6fd47377 100644 --- a/apps/smime.c +++ b/apps/smime.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-2018 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 @@ -12,6 +12,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -37,15 +38,16 @@ typedef enum OPTION_choice { OPT_PK7OUT, OPT_TEXT, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCHAIN, OPT_NOCERTS, OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_NOSIGS, OPT_STREAM, OPT_INDEF, OPT_NOINDEF, - OPT_CRLFEOL, OPT_RAND, OPT_ENGINE, OPT_PASSIN, + OPT_CRLFEOL, OPT_ENGINE, OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, OPT_MD, OPT_CIPHER, OPT_INKEY, OPT_KEYFORM, OPT_CERTFILE, OPT_CAFILE, + OPT_R_ENUM, OPT_V_ENUM, OPT_CAPATH, OPT_NOCAFILE, OPT_NOCAPATH, OPT_IN, OPT_INFORM, OPT_OUT, OPT_OUTFORM, OPT_CONTENT } OPTION_CHOICE; -OPTIONS smime_options[] = { +const OPTIONS smime_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] cert.pem...\n"}, {OPT_HELP_STR, 1, '-', " cert.pem... recipient certs for encryption\n"}, @@ -89,15 +91,14 @@ OPTIONS smime_options[] = { {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"resign", OPT_RESIGN, '-', "Resign a signed message"}, - {"nochain", OPT_NOCHAIN, '-', + {"nochain", OPT_NOCHAIN, '-', "set PKCS7_NOCHAIN so certificates contained in the message are not used as untrusted CAs" }, {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"}, {"stream", OPT_STREAM, '-', "Enable CMS streaming" }, {"indef", OPT_INDEF, '-', "Same as -stream" }, {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"}, {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only"}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, + OPT_R_OPTIONS, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, @@ -121,15 +122,12 @@ int smime_main(int argc, char **argv) const EVP_CIPHER *cipher = NULL; const EVP_MD *sign_md = NULL; const char *CAfile = NULL, *CApath = NULL, *prog = NULL; - char *certfile = NULL, *keyfile = NULL, *contfile = NULL, *inrand = NULL; - char *infile = NULL, *outfile = NULL, *signerfile = NULL, *recipfile = - NULL; - char *passinarg = NULL, *passin = NULL, *to = NULL, *from = - NULL, *subject = NULL; + char *certfile = NULL, *keyfile = NULL, *contfile = NULL; + char *infile = NULL, *outfile = NULL, *signerfile = NULL, *recipfile = NULL; + char *passinarg = NULL, *passin = NULL, *to = NULL, *from = NULL, *subject = NULL; OPTION_CHOICE o; int noCApath = 0, noCAfile = 0; - int flags = PKCS7_DETACHED, operation = 0, ret = 0, need_rand = 0, indef = - 0; + int flags = PKCS7_DETACHED, operation = 0, ret = 0, indef = 0; int informat = FORMAT_SMIME, outformat = FORMAT_SMIME, keyform = FORMAT_PEM; int vpmtouched = 0, rv = 0; @@ -224,9 +222,9 @@ int smime_main(int argc, char **argv) flags |= PKCS7_CRLFEOL; mime_eol = "\r\n"; break; - case OPT_RAND: - inrand = opt_arg(); - need_rand = 1; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); @@ -245,7 +243,7 @@ int smime_main(int argc, char **argv) break; case OPT_SIGNER: /* If previous -signer argument add signer to list */ - if (signerfile) { + if (signerfile != NULL) { if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; @@ -273,7 +271,7 @@ int smime_main(int argc, char **argv) break; case OPT_INKEY: /* If previous -inkey argument add signer to list */ - if (keyfile) { + if (keyfile != NULL) { if (signerfile == NULL) { BIO_printf(bio_err, "%s: Must have -signer before -inkey\n", prog); @@ -323,7 +321,7 @@ int smime_main(int argc, char **argv) argc = opt_num_rest(); argv = opt_rest(); - if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) { + if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) { BIO_puts(bio_err, "Multiple signers or keys not allowed\n"); goto opthelp; } @@ -334,8 +332,8 @@ int smime_main(int argc, char **argv) BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto opthelp; } - if (signerfile) { - if (!sksigners + if (signerfile != NULL) { + if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); @@ -345,15 +343,14 @@ int smime_main(int argc, char **argv) keyfile = signerfile; sk_OPENSSL_STRING_push(skkeys, keyfile); } - if (!sksigners) { + if (sksigners == NULL) { BIO_printf(bio_err, "No signer certificate specified\n"); goto opthelp; } signerfile = NULL; keyfile = NULL; - need_rand = 1; } else if (operation == SMIME_DECRYPT) { - if (!recipfile && !keyfile) { + if (recipfile == NULL && keyfile == NULL) { BIO_printf(bio_err, "No recipient certificate or key specified\n"); goto opthelp; @@ -363,22 +360,15 @@ int smime_main(int argc, char **argv) BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n"); goto opthelp; } - need_rand = 1; - } else if (!operation) + } else if (!operation) { goto opthelp; + } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } - if (need_rand) { - app_RAND_load_file(NULL, (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)) @@ -395,7 +385,7 @@ int smime_main(int argc, char **argv) } if (operation == SMIME_ENCRYPT) { - if (!cipher) { + if (cipher == NULL) { #ifndef OPENSSL_NO_DES cipher = EVP_des_ede3_cbc(); #else @@ -404,9 +394,9 @@ int smime_main(int argc, char **argv) #endif } encerts = sk_X509_new_null(); - if (!encerts) + if (encerts == NULL) goto end; - while (*argv) { + while (*argv != NULL) { cert = load_cert(*argv, FORMAT_PEM, "recipient certificate file"); if (cert == NULL) @@ -417,7 +407,7 @@ int smime_main(int argc, char **argv) } } - if (certfile) { + if (certfile != NULL) { if (!load_certs(certfile, &other, FORMAT_PEM, NULL, "certificate file")) { ERR_print_errors(bio_err); @@ -425,7 +415,7 @@ int smime_main(int argc, char **argv) } } - if (recipfile && (operation == SMIME_DECRYPT)) { + if (recipfile != NULL && (operation == SMIME_DECRYPT)) { if ((recip = load_cert(recipfile, FORMAT_PEM, "recipient certificate file")) == NULL) { ERR_print_errors(bio_err); @@ -434,17 +424,18 @@ int smime_main(int argc, char **argv) } if (operation == SMIME_DECRYPT) { - if (!keyfile) + if (keyfile == NULL) keyfile = recipfile; } else if (operation == SMIME_SIGN) { - if (!keyfile) + if (keyfile == NULL) keyfile = signerfile; - } else + } else { keyfile = NULL; + } - if (keyfile) { + if (keyfile != NULL) { key = load_key(keyfile, keyform, 0, passin, e, "signing key file"); - if (!key) + if (key == NULL) goto end; } @@ -453,22 +444,22 @@ int smime_main(int argc, char **argv) goto end; if (operation & SMIME_IP) { - if (informat == FORMAT_SMIME) + if (informat == FORMAT_SMIME) { p7 = SMIME_read_PKCS7(in, &indata); - else if (informat == FORMAT_PEM) + } else if (informat == FORMAT_PEM) { p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL); - else if (informat == FORMAT_ASN1) + } else if (informat == FORMAT_ASN1) { p7 = d2i_PKCS7_bio(in, NULL); - else { + } else { BIO_printf(bio_err, "Bad input format for PKCS#7 file\n"); goto end; } - if (!p7) { + if (p7 == NULL) { BIO_printf(bio_err, "Error reading S/MIME message\n"); goto end; } - if (contfile) { + if (contfile != NULL) { BIO_free(indata); if ((indata = BIO_new_file(contfile, "rb")) == NULL) { BIO_printf(bio_err, "Can't read content file %s\n", contfile); @@ -505,11 +496,12 @@ int smime_main(int argc, char **argv) if (flags & PKCS7_DETACHED) { if (outformat == FORMAT_SMIME) flags |= PKCS7_STREAM; - } else if (indef) + } else if (indef) { flags |= PKCS7_STREAM; + } flags |= PKCS7_PARTIAL; p7 = PKCS7_sign(NULL, NULL, other, in, flags); - if (!p7) + if (p7 == NULL) goto end; if (flags & PKCS7_NOCERTS) { for (i = 0; i < sk_X509_num(other); i++) { @@ -517,17 +509,18 @@ int smime_main(int argc, char **argv) PKCS7_add_certificate(p7, x); } } - } else + } else { flags |= PKCS7_REUSE_DIGEST; + } for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) { signerfile = sk_OPENSSL_STRING_value(sksigners, i); keyfile = sk_OPENSSL_STRING_value(skkeys, i); signer = load_cert(signerfile, FORMAT_PEM, "signer certificate"); - if (!signer) + if (signer == NULL) goto end; key = load_key(keyfile, keyform, 0, passin, e, "signing key file"); - if (!key) + if (key == NULL) goto end; if (!PKCS7_sign_add_signer(p7, signer, key, sign_md, flags)) goto end; @@ -543,7 +536,7 @@ int smime_main(int argc, char **argv) } } - if (!p7) { + if (p7 == NULL) { BIO_printf(bio_err, "Error creating PKCS#7 structure\n"); goto end; } @@ -569,9 +562,9 @@ int smime_main(int argc, char **argv) goto end; } sk_X509_free(signers); - } else if (operation == SMIME_PK7OUT) + } else if (operation == SMIME_PK7OUT) { PEM_write_bio_PKCS7(out, p7); - else { + } else { if (to) BIO_printf(out, "To: %s%s", to, mime_eol); if (from) @@ -583,11 +576,11 @@ int smime_main(int argc, char **argv) rv = SMIME_write_PKCS7(out, p7, indata, flags); else rv = SMIME_write_PKCS7(out, p7, in, flags); - } else if (outformat == FORMAT_PEM) + } else if (outformat == FORMAT_PEM) { rv = PEM_write_bio_PKCS7_stream(out, p7, in, flags); - else if (outformat == FORMAT_ASN1) + } else if (outformat == FORMAT_ASN1) { rv = i2d_PKCS7_bio_stream(out, p7, in, flags); - else { + } else { BIO_printf(bio_err, "Bad output format for PKCS#7 file\n"); goto end; } @@ -599,8 +592,6 @@ int smime_main(int argc, char **argv) } ret = 0; end: - if (need_rand) - app_RAND_write_file(NULL); if (ret) ERR_print_errors(bio_err); sk_X509_pop_free(encerts, X509_free); @@ -619,17 +610,18 @@ int smime_main(int argc, char **argv) BIO_free(indata); BIO_free_all(out); OPENSSL_free(passin); - return (ret); + return ret; } static int save_certs(char *signerfile, STACK_OF(X509) *signers) { int i; BIO *tmp; - if (!signerfile) + + if (signerfile == NULL) return 1; tmp = BIO_new_file(signerfile, "w"); - if (!tmp) + if (tmp == NULL) return 0; for (i = 0; i < sk_X509_num(signers); i++) PEM_write_bio_X509(tmp, sk_X509_value(signers, i)); @@ -652,5 +644,4 @@ static int smime_cb(int ok, X509_STORE_CTX *ctx) policies_print(ctx); return ok; - } diff --git a/apps/speed.c b/apps/speed.c index b0a7b6ec..c59f266f 100644 --- a/apps/speed.c +++ b/apps/speed.c @@ -1,5 +1,6 @@ /* * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,23 +8,8 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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. - * - */ - #undef SECONDS #define SECONDS 3 -#define PRIME_SECONDS 10 #define RSA_SECONDS 10 #define DSA_SECONDS 10 #define ECDSA_SECONDS 10 @@ -34,6 +20,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -125,13 +112,9 @@ # define NO_FORK #endif -#undef BUFSIZE -#define BUFSIZE (1024*16+1) #define MAX_MISALIGNMENT 63 -#define ALGOR_NUM 30 -#define SIZE_NUM 6 -#define PRIME_NUM 3 +#define ALGOR_NUM 31 #define RSA_NUM 7 #define DSA_NUM 3 @@ -139,14 +122,19 @@ #define MAX_ECDH_SIZE 256 #define MISALIGN 64 +typedef struct openssl_speed_sec_st { + int sym; + int rsa; + int dsa; + int ecdsa; + int ecdh; +} openssl_speed_sec_t; + static volatile int run = 0; static int mr = 0; static int usertime = 1; -typedef void *(*kdf_fn) ( - const void *in, size_t inlen, void *out, size_t *xoutlen); - typedef struct loopargs_st { ASYNC_JOB *inprogress_job; ASYNC_WAIT_CTX *wait_ctx; @@ -154,6 +142,7 @@ typedef struct loopargs_st { unsigned char *buf2; unsigned char *buf_malloc; unsigned char *buf2_malloc; + unsigned char *key; unsigned int siglen; #ifndef OPENSSL_NO_RSA RSA *rsa_key[RSA_NUM]; @@ -163,12 +152,10 @@ typedef struct loopargs_st { #endif #ifndef OPENSSL_NO_EC EC_KEY *ecdsa[EC_NUM]; - EC_KEY *ecdh_a[EC_NUM]; - EC_KEY *ecdh_b[EC_NUM]; + EVP_PKEY_CTX *ecdh_ctx[EC_NUM]; unsigned char *secret_a; unsigned char *secret_b; - size_t outlen; - kdf_fn kdf; + size_t outlen[EC_NUM]; #endif EVP_CIPHER_CTX *ctx; HMAC_CTX *hctx; @@ -212,7 +199,9 @@ static int AES_cbc_256_encrypt_loop(void *args); static int AES_ige_192_encrypt_loop(void *args); static int AES_ige_256_encrypt_loop(void *args); static int CRYPTO_gcm128_aad_loop(void *args); +static int RAND_bytes_loop(void *args); static int EVP_Update_loop(void *args); +static int EVP_Update_loop_ccm(void *args); static int EVP_Digest_loop(void *args); #ifndef OPENSSL_NO_RSA static int RSA_sign_loop(void *args); @@ -225,19 +214,26 @@ static int DSA_verify_loop(void *args); #ifndef OPENSSL_NO_EC static int ECDSA_sign_loop(void *args); static int ECDSA_verify_loop(void *args); -static int ECDH_compute_key_loop(void *args); #endif -static int run_benchmark(int async_jobs, int (*loop_function)(void *), loopargs_t *loopargs); +static int run_benchmark(int async_jobs, int (*loop_function) (void *), + loopargs_t * loopargs); static double Time_F(int s); -static void print_message(const char *s, long num, int length); +static void print_message(const char *s, long num, int length, int tm); static void pkey_print_message(const char *str, const char *str2, long num, 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); +static int do_multi(int multi, int size_num); #endif +static const int lengths_list[] = { + 16, 64, 256, 1024, 8 * 1024, 16 * 1024 +}; +static int lengths_single = 0; + +static const int *lengths = lengths_list; + static const char *names[ALGOR_NUM] = { "md2", "mdc2", "md4", "md5", "hmac(md5)", "sha1", "rmd160", "rc4", "des cbc", "des ede3", "idea cbc", "seed cbc", @@ -245,14 +241,11 @@ static const char *names[ALGOR_NUM] = { "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" + "aes-128 ige", "aes-192 ige", "aes-256 ige", "ghash", + "rand" }; -static double results[ALGOR_NUM][SIZE_NUM]; - -static const int lengths[SIZE_NUM] = { - 16, 64, 256, 1024, 8 * 1024, 16 * 1024 -}; +static double results[ALGOR_NUM][OSSL_NELEM(lengths_list)]; #ifndef OPENSSL_NO_RSA static double rsa_results[RSA_NUM][2]; @@ -265,11 +258,6 @@ static double ecdsa_results[EC_NUM][2]; static double ecdh_results[EC_NUM][1]; #endif -#if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_EC) -static const char rnd_seed[] = - "string to make the random number generator think it has entropy"; -#endif - #ifdef SIGALRM # if defined(__STDC__) || defined(sgi) || defined(_AIX) # define SIGRETTYPE void @@ -346,7 +334,8 @@ static double Time_F(int s) } #endif -static void multiblock_speed(const EVP_CIPHER *evp_cipher); +static void multiblock_speed(const EVP_CIPHER *evp_cipher, + const openssl_speed_sec_t *seconds); static int found(const char *name, const OPT_PAIR *pairs, int *result) { @@ -361,10 +350,11 @@ static int found(const char *name, const OPT_PAIR *pairs, int *result) typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ELAPSED, OPT_EVP, OPT_DECRYPT, OPT_ENGINE, OPT_MULTI, - OPT_MR, OPT_MB, OPT_MISALIGN, OPT_ASYNCJOBS + OPT_MR, OPT_MB, OPT_MISALIGN, OPT_ASYNCJOBS, OPT_R_ENUM, + OPT_PRIMES, OPT_SECONDS, OPT_BYTES } OPTION_CHOICE; -OPTIONS speed_options[] = { +const OPTIONS speed_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] ciphers...\n"}, {OPT_HELP_STR, 1, '-', "Valid options are:\n"}, {"help", OPT_HELP, '-', "Display this summary"}, @@ -384,9 +374,15 @@ OPTIONS speed_options[] = { {"async_jobs", OPT_ASYNCJOBS, 'p', "Enable async mode and start pnum jobs"}, #endif + OPT_R_OPTIONS, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif + {"primes", OPT_PRIMES, 'p', "Specify number of primes (for RSA only)"}, + {"seconds", OPT_SECONDS, 'p', + "Run benchmarks for pnum seconds"}, + {"bytes", OPT_BYTES, 'p', + "Run cipher, digest and rand benchmarks on pnum bytes"}, {NULL}, }; @@ -420,6 +416,7 @@ OPTIONS speed_options[] = { #define D_IGE_192_AES 27 #define D_IGE_256_AES 28 #define D_GHASH 29 +#define D_RAND 30 static OPT_PAIR doit_choices[] = { #ifndef OPENSSL_NO_MD2 {"md2", D_MD2}, @@ -485,6 +482,7 @@ static OPT_PAIR doit_choices[] = { {"cast5", D_CBC_CAST}, #endif {"ghash", D_GHASH}, + {"rand", D_RAND}, {NULL} }; @@ -584,24 +582,24 @@ static OPT_PAIR ecdh_choices[] = { #else # define COND(unused_cond) (run && count<0x7fffffff) # define COUNT(d) (count) -#endif /* SIGALRM */ +#endif /* SIGALRM */ static int testnum; /* Nb of iterations to do per algorithm and key-size */ -static long c[ALGOR_NUM][SIZE_NUM]; +static long c[ALGOR_NUM][OSSL_NELEM(lengths_list)]; #ifndef OPENSSL_NO_MD2 static int EVP_Digest_MD2_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char md2[MD2_DIGEST_LENGTH]; int count; for (count = 0; COND(c[D_MD2][testnum]); count++) { if (!EVP_Digest(buf, (size_t)lengths[testnum], md2, NULL, EVP_md2(), - NULL)) + NULL)) return -1; } return count; @@ -611,14 +609,14 @@ static int EVP_Digest_MD2_loop(void *args) #ifndef OPENSSL_NO_MDC2 static int EVP_Digest_MDC2_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char mdc2[MDC2_DIGEST_LENGTH]; int count; for (count = 0; COND(c[D_MDC2][testnum]); count++) { if (!EVP_Digest(buf, (size_t)lengths[testnum], mdc2, NULL, EVP_mdc2(), - NULL)) + NULL)) return -1; } return count; @@ -628,14 +626,14 @@ static int EVP_Digest_MDC2_loop(void *args) #ifndef OPENSSL_NO_MD4 static int EVP_Digest_MD4_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char md4[MD4_DIGEST_LENGTH]; int count; for (count = 0; COND(c[D_MD4][testnum]); count++) { if (!EVP_Digest(buf, (size_t)lengths[testnum], md4, NULL, EVP_md4(), - NULL)) + NULL)) return -1; } return count; @@ -645,7 +643,7 @@ static int EVP_Digest_MD4_loop(void *args) #ifndef OPENSSL_NO_MD5 static int MD5_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char md5[MD5_DIGEST_LENGTH]; int count; @@ -656,7 +654,7 @@ static int MD5_loop(void *args) static int HMAC_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; HMAC_CTX *hctx = tempargs->hctx; unsigned char hmac[MD5_DIGEST_LENGTH]; @@ -673,7 +671,7 @@ static int HMAC_loop(void *args) static int SHA1_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char sha[SHA_DIGEST_LENGTH]; int count; @@ -684,7 +682,7 @@ static int SHA1_loop(void *args) static int SHA256_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char sha256[SHA256_DIGEST_LENGTH]; int count; @@ -695,7 +693,7 @@ static int SHA256_loop(void *args) static int SHA512_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char sha512[SHA512_DIGEST_LENGTH]; int count; @@ -707,7 +705,7 @@ static int SHA512_loop(void *args) #ifndef OPENSSL_NO_WHIRLPOOL static int WHIRLPOOL_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char whirlpool[WHIRLPOOL_DIGEST_LENGTH]; int count; @@ -720,13 +718,13 @@ static int WHIRLPOOL_loop(void *args) #ifndef OPENSSL_NO_RMD160 static int EVP_Digest_RMD160_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char rmd160[RIPEMD160_DIGEST_LENGTH]; int count; for (count = 0; COND(c[D_RMD160][testnum]); count++) { if (!EVP_Digest(buf, (size_t)lengths[testnum], &(rmd160[0]), - NULL, EVP_ripemd160(), NULL)) + NULL, EVP_ripemd160(), NULL)) return -1; } return count; @@ -737,7 +735,7 @@ static int EVP_Digest_RMD160_loop(void *args) static RC4_KEY rc4_ks; static int RC4_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; int count; for (count = 0; COND(c[D_RC4][testnum]); count++) @@ -753,24 +751,23 @@ static DES_key_schedule sch2; static DES_key_schedule sch3; static int DES_ncbc_encrypt_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; int count; for (count = 0; COND(c[D_CBC_DES][testnum]); count++) DES_ncbc_encrypt(buf, buf, lengths[testnum], &sch, - &DES_iv, DES_ENCRYPT); + &DES_iv, DES_ENCRYPT); return count; } static int DES_ede3_cbc_encrypt_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; int count; for (count = 0; COND(c[D_EDE3_DES][testnum]); count++) DES_ede3_cbc_encrypt(buf, buf, lengths[testnum], - &sch, &sch2, &sch3, - &DES_iv, DES_ENCRYPT); + &sch, &sch2, &sch3, &DES_iv, DES_ENCRYPT); return count; } #endif @@ -781,82 +778,76 @@ static unsigned char iv[2 * MAX_BLOCK_SIZE / 8]; static AES_KEY aes_ks1, aes_ks2, aes_ks3; static int AES_cbc_128_encrypt_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; int count; for (count = 0; COND(c[D_CBC_128_AES][testnum]); count++) AES_cbc_encrypt(buf, buf, - (size_t)lengths[testnum], &aes_ks1, - iv, AES_ENCRYPT); + (size_t)lengths[testnum], &aes_ks1, iv, AES_ENCRYPT); return count; } static int AES_cbc_192_encrypt_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; int count; for (count = 0; COND(c[D_CBC_192_AES][testnum]); count++) AES_cbc_encrypt(buf, buf, - (size_t)lengths[testnum], &aes_ks2, - iv, AES_ENCRYPT); + (size_t)lengths[testnum], &aes_ks2, iv, AES_ENCRYPT); return count; } static int AES_cbc_256_encrypt_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; int count; for (count = 0; COND(c[D_CBC_256_AES][testnum]); count++) AES_cbc_encrypt(buf, buf, - (size_t)lengths[testnum], &aes_ks3, - iv, AES_ENCRYPT); + (size_t)lengths[testnum], &aes_ks3, iv, AES_ENCRYPT); return count; } static int AES_ige_128_encrypt_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; int count; for (count = 0; COND(c[D_IGE_128_AES][testnum]); count++) AES_ige_encrypt(buf, buf2, - (size_t)lengths[testnum], &aes_ks1, - iv, AES_ENCRYPT); + (size_t)lengths[testnum], &aes_ks1, iv, AES_ENCRYPT); return count; } static int AES_ige_192_encrypt_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; int count; for (count = 0; COND(c[D_IGE_192_AES][testnum]); count++) AES_ige_encrypt(buf, buf2, - (size_t)lengths[testnum], &aes_ks2, - iv, AES_ENCRYPT); + (size_t)lengths[testnum], &aes_ks2, iv, AES_ENCRYPT); return count; } static int AES_ige_256_encrypt_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; int count; for (count = 0; COND(c[D_IGE_256_AES][testnum]); count++) AES_ige_encrypt(buf, buf2, - (size_t)lengths[testnum], &aes_ks3, - iv, AES_ENCRYPT); + (size_t)lengths[testnum], &aes_ks3, iv, AES_ENCRYPT); return count; } static int CRYPTO_gcm128_aad_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; GCM128_CONTEXT *gcm_ctx = tempargs->gcm_ctx; int count; @@ -865,34 +856,85 @@ static int CRYPTO_gcm128_aad_loop(void *args) return count; } +static int RAND_bytes_loop(void *args) +{ + loopargs_t *tempargs = *(loopargs_t **) args; + unsigned char *buf = tempargs->buf; + int count; + + for (count = 0; COND(c[D_RAND][testnum]); count++) + RAND_bytes(buf, lengths[testnum]); + return count; +} + static long save_count = 0; static int decrypt = 0; static int EVP_Update_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_CIPHER_CTX *ctx = tempargs->ctx; - int outl, count; + int outl, count, rc; #ifndef SIGALRM int nb_iter = save_count * 4 * lengths[0] / lengths[testnum]; #endif - if (decrypt) - for (count = 0; COND(nb_iter); count++) - EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]); - else - for (count = 0; COND(nb_iter); count++) - EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]); + if (decrypt) { + for (count = 0; COND(nb_iter); count++) { + rc = EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]); + if (rc != 1) + EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1); + } + } else { + for (count = 0; COND(nb_iter); count++) { + rc = EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]); + if (rc != 1) + EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1); + } + } if (decrypt) EVP_DecryptFinal_ex(ctx, buf, &outl); else EVP_EncryptFinal_ex(ctx, buf, &outl); return count; } +/* + * CCM does not support streaming. For the purpose of performance measurement, + * each message is encrypted using the same (key,iv)-pair. Do not use this + * code in your application. + */ +static int EVP_Update_loop_ccm(void *args) +{ + loopargs_t *tempargs = *(loopargs_t **) args; + unsigned char *buf = tempargs->buf; + EVP_CIPHER_CTX *ctx = tempargs->ctx; + int outl, count; + unsigned char tag[12]; +#ifndef SIGALRM + int nb_iter = save_count * 4 * lengths[0] / lengths[testnum]; +#endif + if (decrypt) { + for (count = 0; COND(nb_iter); count++) { + EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv); + EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(tag), tag); + EVP_DecryptUpdate(ctx, NULL, &outl, NULL, lengths[testnum]); + EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]); + EVP_DecryptFinal_ex(ctx, buf, &outl); + } + } else { + for (count = 0; COND(nb_iter); count++) { + EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv); + EVP_EncryptUpdate(ctx, NULL, &outl, NULL, lengths[testnum]); + EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]); + EVP_EncryptFinal_ex(ctx, buf, &outl); + } + } + return count; +} static const EVP_MD *evp_md = NULL; static int EVP_Digest_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char md[EVP_MAX_MD_SIZE]; int count; @@ -912,7 +954,7 @@ static long rsa_c[RSA_NUM][2]; /* # RSA iteration test */ static int RSA_sign_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; unsigned int *rsa_num = &tempargs->siglen; @@ -932,14 +974,15 @@ static int RSA_sign_loop(void *args) static int RSA_verify_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; unsigned int rsa_num = tempargs->siglen; RSA **rsa_key = tempargs->rsa_key; int ret, count; for (count = 0; COND(rsa_c[testnum][1]); count++) { - ret = RSA_verify(NID_md5_sha1, buf, 36, buf2, rsa_num, rsa_key[testnum]); + ret = + RSA_verify(NID_md5_sha1, buf, 36, buf2, rsa_num, rsa_key[testnum]); if (ret <= 0) { BIO_printf(bio_err, "RSA verify failure\n"); ERR_print_errors(bio_err); @@ -955,7 +998,7 @@ static int RSA_verify_loop(void *args) static long dsa_c[DSA_NUM][2]; static int DSA_sign_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; DSA **dsa_key = tempargs->dsa_key; @@ -975,7 +1018,7 @@ static int DSA_sign_loop(void *args) static int DSA_verify_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; DSA **dsa_key = tempargs->dsa_key; @@ -998,15 +1041,14 @@ static int DSA_verify_loop(void *args) static long ecdsa_c[EC_NUM][2]; static int ECDSA_sign_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EC_KEY **ecdsa = tempargs->ecdsa; unsigned char *ecdsasig = tempargs->buf2; unsigned int *ecdsasiglen = &tempargs->siglen; int ret, count; for (count = 0; COND(ecdsa_c[testnum][0]); count++) { - ret = ECDSA_sign(0, buf, 20, - ecdsasig, ecdsasiglen, ecdsa[testnum]); + ret = ECDSA_sign(0, buf, 20, ecdsasig, ecdsasiglen, ecdsa[testnum]); if (ret == 0) { BIO_printf(bio_err, "ECDSA sign failure\n"); ERR_print_errors(bio_err); @@ -1019,15 +1061,14 @@ static int ECDSA_sign_loop(void *args) static int ECDSA_verify_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; + loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EC_KEY **ecdsa = tempargs->ecdsa; unsigned char *ecdsasig = tempargs->buf2; unsigned int ecdsasiglen = tempargs->siglen; int ret, count; for (count = 0; COND(ecdsa_c[testnum][1]); count++) { - ret = ECDSA_verify(0, buf, 20, ecdsasig, ecdsasiglen, - ecdsa[testnum]); + ret = ECDSA_verify(0, buf, 20, ecdsasig, ecdsasiglen, ecdsa[testnum]); if (ret != 1) { BIO_printf(bio_err, "ECDSA verify failure\n"); ERR_print_errors(bio_err); @@ -1041,37 +1082,24 @@ static int ECDSA_verify_loop(void *args) /* ******************************************************************** */ static long ecdh_c[EC_NUM][1]; -static int ECDH_compute_key_loop(void *args) +static int ECDH_EVP_derive_key_loop(void *args) { - loopargs_t *tempargs = *(loopargs_t **)args; - EC_KEY **ecdh_a = tempargs->ecdh_a; - EC_KEY **ecdh_b = tempargs->ecdh_b; - unsigned char *secret_a = tempargs->secret_a; + loopargs_t *tempargs = *(loopargs_t **) args; + EVP_PKEY_CTX *ctx = tempargs->ecdh_ctx[testnum]; + unsigned char *derived_secret = tempargs->secret_a; int count; - size_t outlen = tempargs->outlen; - kdf_fn kdf = tempargs->kdf; + size_t *outlen = &(tempargs->outlen[testnum]); + + for (count = 0; COND(ecdh_c[testnum][0]); count++) + EVP_PKEY_derive(ctx, derived_secret, outlen); - for (count = 0; COND(ecdh_c[testnum][0]); count++) { - ECDH_compute_key(secret_a, outlen, - EC_KEY_get0_public_key(ecdh_b[testnum]), - ecdh_a[testnum], kdf); - } return count; } -static const size_t KDF1_SHA1_len = 20; -static void *KDF1_SHA1(const void *in, size_t inlen, void *out, - size_t *outlen) -{ - if (*outlen < SHA_DIGEST_LENGTH) - return NULL; - *outlen = SHA_DIGEST_LENGTH; - return SHA1(in, inlen, out); -} #endif /* OPENSSL_NO_EC */ static int run_benchmark(int async_jobs, - int (*loop_function)(void *), loopargs_t *loopargs) + int (*loop_function) (void *), loopargs_t * loopargs) { int job_op_count = 0; int total_op_count = 0; @@ -1127,14 +1155,16 @@ static int run_benchmark(int async_jobs, if (loopargs[i].inprogress_job == NULL) continue; - if (!ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, NULL, &num_job_fds) - || num_job_fds > 1) { + if (!ASYNC_WAIT_CTX_get_all_fds + (loopargs[i].wait_ctx, NULL, &num_job_fds) + || num_job_fds > 1) { BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n"); ERR_print_errors(bio_err); error = 1; break; } - ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd, &num_job_fds); + ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd, + &num_job_fds); FD_SET(job_fd, &waitfdset); if (job_fd > max_fd) max_fd = job_fd; @@ -1142,9 +1172,9 @@ static int run_benchmark(int async_jobs, if (max_fd >= (OSSL_ASYNC_FD)FD_SETSIZE) { BIO_printf(bio_err, - "Error: max_fd (%d) must be smaller than FD_SETSIZE (%d). " - "Decrease the value of async_jobs\n", - max_fd, FD_SETSIZE); + "Error: max_fd (%d) must be smaller than FD_SETSIZE (%d). " + "Decrease the value of async_jobs\n", + max_fd, FD_SETSIZE); ERR_print_errors(bio_err); error = 1; break; @@ -1169,14 +1199,16 @@ static int run_benchmark(int async_jobs, if (loopargs[i].inprogress_job == NULL) continue; - if (!ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, NULL, &num_job_fds) - || num_job_fds > 1) { + if (!ASYNC_WAIT_CTX_get_all_fds + (loopargs[i].wait_ctx, NULL, &num_job_fds) + || num_job_fds > 1) { BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n"); ERR_print_errors(bio_err); error = 1; break; } - ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd, &num_job_fds); + ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd, + &num_job_fds); #if defined(OPENSSL_SYS_UNIX) if (num_job_fds == 1 && !FD_ISSET(job_fd, &waitfdset)) @@ -1188,9 +1220,10 @@ static int run_benchmark(int async_jobs, continue; #endif - ret = ASYNC_start_job(&loopargs[i].inprogress_job, - loopargs[i].wait_ctx, &job_op_count, loop_function, - (void *)(loopargs + i), sizeof(loopargs_t)); + ret = ASYNC_start_job(&loopargs[i].inprogress_job, + loopargs[i].wait_ctx, &job_op_count, + loop_function, (void *)(loopargs + i), + sizeof(loopargs_t)); switch (ret) { case ASYNC_PAUSE: break; @@ -1221,6 +1254,7 @@ static int run_benchmark(int async_jobs, int speed_main(int argc, char **argv) { ENGINE *e = NULL; + int (*loopfunc)(void *args); loopargs_t *loopargs = NULL; int async_init = 0; int loopargs_len = 0; @@ -1233,6 +1267,9 @@ int speed_main(int argc, char **argv) int doit[ALGOR_NUM] = { 0 }; int ret = 1, i, k, misalign = 0; long count = 0; + int size_num = OSSL_NELEM(lengths_list); + int keylen; + int buflen; #ifndef NO_FORK int multi = 0; #endif @@ -1241,7 +1278,9 @@ int speed_main(int argc, char **argv) || !defined(OPENSSL_NO_EC) long rsa_count = 1; #endif +#ifndef OPENSSL_NO_EC size_t loop; +#endif /* What follows are the buffers and key material. */ #ifndef OPENSSL_NO_RC5 @@ -1316,6 +1355,7 @@ int speed_main(int argc, char **argv) sizeof(test15360) }; int rsa_doit[RSA_NUM] = { 0 }; + int primes = RSA_DEFAULT_PRIME_NUM; #endif #ifndef OPENSSL_NO_DSA static const unsigned int dsa_bits[DSA_NUM] = { 512, 1024, 2048 }; @@ -1357,13 +1397,16 @@ int speed_main(int argc, char **argv) 163, 233, 283, 409, 571, 163, 233, 283, 409, - 571, 253 /* X25519 */ + 571, 253 /* X25519 */ }; int ecdsa_doit[EC_NUM] = { 0 }; int ecdh_doit[EC_NUM] = { 0 }; #endif /* ndef OPENSSL_NO_EC */ + openssl_speed_sec_t seconds = { SECONDS, RSA_SECONDS, DSA_SECONDS, + ECDSA_SECONDS, ECDH_SECONDS }; + prog = opt_init(argc, argv, speed_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { @@ -1446,13 +1489,30 @@ int speed_main(int argc, char **argv) goto end; #endif break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; + case OPT_PRIMES: + if (!opt_int(opt_arg(), &primes)) + goto end; + break; + case OPT_SECONDS: + seconds.sym = seconds.rsa = seconds.dsa = seconds.ecdsa + = seconds.ecdh = atoi(opt_arg()); + break; + case OPT_BYTES: + lengths_single = atoi(opt_arg()); + lengths = &lengths_single; + size_num = 1; + break; } } argc = opt_num_rest(); argv = opt_rest(); /* Remaining arguments are algorithms. */ - for ( ; *argv; argv++) { + for (; *argv; argv++) { if (found(*argv, doit_choices, &i)) { doit[i] = 1; continue; @@ -1494,14 +1554,12 @@ int speed_main(int argc, char **argv) } #endif if (strcmp(*argv, "aes") == 0) { - doit[D_CBC_128_AES] = doit[D_CBC_192_AES] = - doit[D_CBC_256_AES] = 1; + doit[D_CBC_128_AES] = doit[D_CBC_192_AES] = doit[D_CBC_256_AES] = 1; continue; } #ifndef OPENSSL_NO_CAMELLIA if (strcmp(*argv, "camellia") == 0) { - doit[D_CBC_128_CML] = doit[D_CBC_192_CML] = - doit[D_CBC_256_CML] = 1; + doit[D_CBC_128_CML] = doit[D_CBC_192_CML] = doit[D_CBC_256_CML] = 1; continue; } #endif @@ -1539,7 +1597,8 @@ int speed_main(int argc, char **argv) } loopargs_len = (async_jobs == 0 ? 1 : async_jobs); - loopargs = app_malloc(loopargs_len * sizeof(loopargs_t), "array of loopargs"); + loopargs = + app_malloc(loopargs_len * sizeof(loopargs_t), "array of loopargs"); memset(loopargs, 0, loopargs_len * sizeof(loopargs_t)); for (i = 0; i < loopargs_len; i++) { @@ -1551,8 +1610,12 @@ int speed_main(int argc, char **argv) } } - loopargs[i].buf_malloc = app_malloc((int)BUFSIZE + MAX_MISALIGNMENT + 1, "input buffer"); - loopargs[i].buf2_malloc = app_malloc((int)BUFSIZE + MAX_MISALIGNMENT + 1, "input buffer"); + buflen = lengths[size_num - 1] + MAX_MISALIGNMENT + 1; + loopargs[i].buf_malloc = app_malloc(buflen, "input buffer"); + loopargs[i].buf2_malloc = app_malloc(buflen, "input buffer"); + memset(loopargs[i].buf_malloc, 0, buflen); + memset(loopargs[i].buf2_malloc, 0, buflen); + /* Align the start of buffers on a 64 byte boundary */ loopargs[i].buf = loopargs[i].buf_malloc + misalign; loopargs[i].buf2 = loopargs[i].buf2_malloc + misalign; @@ -1563,7 +1626,7 @@ int speed_main(int argc, char **argv) } #ifndef NO_FORK - if (multi && do_multi(multi)) + if (multi && do_multi(multi, size_num)) goto show_res; #endif @@ -1601,14 +1664,19 @@ int speed_main(int argc, char **argv) #ifndef OPENSSL_NO_RSA for (i = 0; i < loopargs_len; i++) { + if (primes > RSA_DEFAULT_PRIME_NUM) { + /* for multi-prime RSA, skip this */ + break; + } for (k = 0; k < RSA_NUM; k++) { const unsigned char *p; p = rsa_data[k]; - loopargs[i].rsa_key[k] = d2i_RSAPrivateKey(NULL, &p, rsa_data_length[k]); + loopargs[i].rsa_key[k] = + d2i_RSAPrivateKey(NULL, &p, rsa_data_length[k]); if (loopargs[i].rsa_key[k] == NULL) { - BIO_printf(bio_err, "internal error loading RSA key number %d\n", - k); + BIO_printf(bio_err, + "internal error loading RSA key number %d\n", k); goto end; } } @@ -1616,9 +1684,9 @@ int speed_main(int argc, char **argv) #endif #ifndef OPENSSL_NO_DSA for (i = 0; i < loopargs_len; i++) { - loopargs[i].dsa_key[0] = get_dsa512(); - loopargs[i].dsa_key[1] = get_dsa1024(); - loopargs[i].dsa_key[2] = get_dsa2048(); + loopargs[i].dsa_key[0] = get_dsa(512); + loopargs[i].dsa_key[1] = get_dsa(1024); + loopargs[i].dsa_key[2] = get_dsa(2048); } #endif #ifndef OPENSSL_NO_DES @@ -1698,8 +1766,9 @@ int speed_main(int argc, char **argv) c[D_IGE_192_AES][0] = count; c[D_IGE_256_AES][0] = count; c[D_GHASH][0] = count; + c[D_RAND][0] = count; - for (i = 1; i < SIZE_NUM; i++) { + for (i = 1; i < size_num; i++) { long l0, l1; l0 = (long)lengths[0]; @@ -1716,6 +1785,7 @@ int speed_main(int argc, char **argv) c[D_SHA512][i] = c[D_SHA512][0] * 4 * l0 / l1; c[D_WHIRLPOOL][i] = c[D_WHIRLPOOL][0] * 4 * l0 / l1; c[D_GHASH][i] = c[D_GHASH][0] * 4 * l0 / l1; + c[D_RAND][i] = c[D_RAND][0] * 4 * l0 / l1; l0 = (long)lengths[i - 1]; @@ -1749,7 +1819,7 @@ int speed_main(int argc, char **argv) rsa_doit[i] = 0; else { if (rsa_c[i][0] == 0) { - rsa_c[i][0] = 1; /* Set minimum iteration Nb to 1. */ + rsa_c[i][0] = 1; /* Set minimum iteration Nb to 1. */ rsa_c[i][1] = 20; } } @@ -1766,7 +1836,7 @@ int speed_main(int argc, char **argv) dsa_doit[i] = 0; else { if (dsa_c[i][0] == 0) { - dsa_c[i][0] = 1; /* Set minimum iteration Nb to 1. */ + dsa_c[i][0] = 1; /* Set minimum iteration Nb to 1. */ dsa_c[i][1] = 1; } } @@ -1855,17 +1925,18 @@ int speed_main(int argc, char **argv) # else /* not worth fixing */ # error "You cannot disable DES on systems without SIGALRM." -# endif /* OPENSSL_NO_DES */ +# endif /* OPENSSL_NO_DES */ #else # ifndef _WIN32 signal(SIGALRM, sig_done); # endif -#endif /* SIGALRM */ +#endif /* SIGALRM */ #ifndef OPENSSL_NO_MD2 if (doit[D_MD2]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_MD2], c[D_MD2][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_MD2], c[D_MD2][testnum], lengths[testnum], + seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_MD2_loop, loopargs); d = Time_F(STOP); @@ -1875,8 +1946,9 @@ int speed_main(int argc, char **argv) #endif #ifndef OPENSSL_NO_MDC2 if (doit[D_MDC2]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_MDC2], c[D_MDC2][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_MDC2], c[D_MDC2][testnum], lengths[testnum], + seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_MDC2_loop, loopargs); d = Time_F(STOP); @@ -1887,8 +1959,9 @@ int speed_main(int argc, char **argv) #ifndef OPENSSL_NO_MD4 if (doit[D_MD4]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_MD4], c[D_MD4][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_MD4], c[D_MD4][testnum], lengths[testnum], + seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_MD4_loop, loopargs); d = Time_F(STOP); @@ -1899,8 +1972,9 @@ int speed_main(int argc, char **argv) #ifndef OPENSSL_NO_MD5 if (doit[D_MD5]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_MD5], c[D_MD5][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_MD5], c[D_MD5][testnum], lengths[testnum], + seconds.sym); Time_F(START); count = run_benchmark(async_jobs, MD5_loop, loopargs); d = Time_F(STOP); @@ -1921,8 +1995,9 @@ int speed_main(int argc, char **argv) HMAC_Init_ex(loopargs[i].hctx, hmac_key, len, EVP_md5(), NULL); } - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_HMAC], c[D_HMAC][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_HMAC], c[D_HMAC][testnum], lengths[testnum], + seconds.sym); Time_F(START); count = run_benchmark(async_jobs, HMAC_loop, loopargs); d = Time_F(STOP); @@ -1934,8 +2009,9 @@ int speed_main(int argc, char **argv) } #endif if (doit[D_SHA1]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_SHA1], c[D_SHA1][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_SHA1], c[D_SHA1][testnum], lengths[testnum], + seconds.sym); Time_F(START); count = run_benchmark(async_jobs, SHA1_loop, loopargs); d = Time_F(STOP); @@ -1943,8 +2019,9 @@ int speed_main(int argc, char **argv) } } if (doit[D_SHA256]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_SHA256], c[D_SHA256][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_SHA256], c[D_SHA256][testnum], + lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, SHA256_loop, loopargs); d = Time_F(STOP); @@ -1952,19 +2029,20 @@ int speed_main(int argc, char **argv) } } if (doit[D_SHA512]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_SHA512], c[D_SHA512][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_SHA512], c[D_SHA512][testnum], + lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, SHA512_loop, loopargs); d = Time_F(STOP); print_result(D_SHA512, testnum, count, d); } } - #ifndef OPENSSL_NO_WHIRLPOOL if (doit[D_WHIRLPOOL]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_WHIRLPOOL], c[D_WHIRLPOOL][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_WHIRLPOOL], c[D_WHIRLPOOL][testnum], + lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, WHIRLPOOL_loop, loopargs); d = Time_F(STOP); @@ -1975,8 +2053,9 @@ int speed_main(int argc, char **argv) #ifndef OPENSSL_NO_RMD160 if (doit[D_RMD160]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_RMD160], c[D_RMD160][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_RMD160], c[D_RMD160][testnum], + lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_RMD160_loop, loopargs); d = Time_F(STOP); @@ -1986,8 +2065,9 @@ int speed_main(int argc, char **argv) #endif #ifndef OPENSSL_NO_RC4 if (doit[D_RC4]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_RC4], c[D_RC4][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_RC4], c[D_RC4][testnum], lengths[testnum], + seconds.sym); Time_F(START); count = run_benchmark(async_jobs, RC4_loop, loopargs); d = Time_F(STOP); @@ -1997,8 +2077,9 @@ int speed_main(int argc, char **argv) #endif #ifndef OPENSSL_NO_DES if (doit[D_CBC_DES]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_CBC_DES], c[D_CBC_DES][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_CBC_DES], c[D_CBC_DES][testnum], + lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, DES_ncbc_encrypt_loop, loopargs); d = Time_F(STOP); @@ -2007,10 +2088,12 @@ int speed_main(int argc, char **argv) } if (doit[D_EDE3_DES]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_EDE3_DES], c[D_EDE3_DES][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_EDE3_DES], c[D_EDE3_DES][testnum], + lengths[testnum], seconds.sym); Time_F(START); - count = run_benchmark(async_jobs, DES_ede3_cbc_encrypt_loop, loopargs); + count = + run_benchmark(async_jobs, DES_ede3_cbc_encrypt_loop, loopargs); d = Time_F(STOP); print_result(D_EDE3_DES, testnum, count, d); } @@ -2018,74 +2101,83 @@ int speed_main(int argc, char **argv) #endif if (doit[D_CBC_128_AES]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { + for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_CBC_128_AES], c[D_CBC_128_AES][testnum], - lengths[testnum]); + lengths[testnum], seconds.sym); Time_F(START); - count = run_benchmark(async_jobs, AES_cbc_128_encrypt_loop, loopargs); + count = + run_benchmark(async_jobs, AES_cbc_128_encrypt_loop, loopargs); d = Time_F(STOP); print_result(D_CBC_128_AES, testnum, count, d); } } if (doit[D_CBC_192_AES]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { + for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_CBC_192_AES], c[D_CBC_192_AES][testnum], - lengths[testnum]); + lengths[testnum], seconds.sym); Time_F(START); - count = run_benchmark(async_jobs, AES_cbc_192_encrypt_loop, loopargs); + count = + run_benchmark(async_jobs, AES_cbc_192_encrypt_loop, loopargs); d = Time_F(STOP); print_result(D_CBC_192_AES, testnum, count, d); } } if (doit[D_CBC_256_AES]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { + for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_CBC_256_AES], c[D_CBC_256_AES][testnum], - lengths[testnum]); + lengths[testnum], seconds.sym); Time_F(START); - count = run_benchmark(async_jobs, AES_cbc_256_encrypt_loop, loopargs); + count = + run_benchmark(async_jobs, AES_cbc_256_encrypt_loop, loopargs); d = Time_F(STOP); print_result(D_CBC_256_AES, testnum, count, d); } } if (doit[D_IGE_128_AES]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { + for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_IGE_128_AES], c[D_IGE_128_AES][testnum], - lengths[testnum]); + lengths[testnum], seconds.sym); Time_F(START); - count = run_benchmark(async_jobs, AES_ige_128_encrypt_loop, loopargs); + count = + run_benchmark(async_jobs, AES_ige_128_encrypt_loop, loopargs); d = Time_F(STOP); print_result(D_IGE_128_AES, testnum, count, d); } } if (doit[D_IGE_192_AES]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { + for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_IGE_192_AES], c[D_IGE_192_AES][testnum], - lengths[testnum]); + lengths[testnum], seconds.sym); Time_F(START); - count = run_benchmark(async_jobs, AES_ige_192_encrypt_loop, loopargs); + count = + run_benchmark(async_jobs, AES_ige_192_encrypt_loop, loopargs); d = Time_F(STOP); print_result(D_IGE_192_AES, testnum, count, d); } } if (doit[D_IGE_256_AES]) { - for (testnum = 0; testnum < SIZE_NUM; testnum++) { + for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_IGE_256_AES], c[D_IGE_256_AES][testnum], - lengths[testnum]); + lengths[testnum], seconds.sym); Time_F(START); - count = run_benchmark(async_jobs, AES_ige_256_encrypt_loop, loopargs); + count = + run_benchmark(async_jobs, AES_ige_256_encrypt_loop, loopargs); d = Time_F(STOP); print_result(D_IGE_256_AES, testnum, count, d); } } if (doit[D_GHASH]) { for (i = 0; i < loopargs_len; i++) { - loopargs[i].gcm_ctx = CRYPTO_gcm128_new(&aes_ks1, (block128_f) AES_encrypt); - CRYPTO_gcm128_setiv(loopargs[i].gcm_ctx, (unsigned char *)"0123456789ab", 12); + loopargs[i].gcm_ctx = + CRYPTO_gcm128_new(&aes_ks1, (block128_f) AES_encrypt); + CRYPTO_gcm128_setiv(loopargs[i].gcm_ctx, + (unsigned char *)"0123456789ab", 12); } - for (testnum = 0; testnum < SIZE_NUM; testnum++) { - print_message(names[D_GHASH], c[D_GHASH][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_GHASH], c[D_GHASH][testnum], + lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, CRYPTO_gcm128_aad_loop, loopargs); d = Time_F(STOP); @@ -2094,7 +2186,6 @@ int speed_main(int argc, char **argv) for (i = 0; i < loopargs_len; i++) CRYPTO_gcm128_release(loopargs[i].gcm_ctx); } - #ifndef OPENSSL_NO_CAMELLIA if (doit[D_CBC_128_CML]) { if (async_jobs > 0) { @@ -2102,9 +2193,9 @@ int speed_main(int argc, char **argv) names[D_CBC_128_CML]); doit[D_CBC_128_CML] = 0; } - for (testnum = 0; testnum < SIZE_NUM && async_init == 0; testnum++) { + for (testnum = 0; testnum < size_num && async_init == 0; testnum++) { print_message(names[D_CBC_128_CML], c[D_CBC_128_CML][testnum], - lengths[testnum]); + lengths[testnum], seconds.sym); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_128_CML][testnum]); count++) Camellia_cbc_encrypt(loopargs[0].buf, loopargs[0].buf, @@ -2120,9 +2211,9 @@ int speed_main(int argc, char **argv) names[D_CBC_192_CML]); doit[D_CBC_192_CML] = 0; } - for (testnum = 0; testnum < SIZE_NUM && async_init == 0; testnum++) { + for (testnum = 0; testnum < size_num && async_init == 0; testnum++) { print_message(names[D_CBC_192_CML], c[D_CBC_192_CML][testnum], - lengths[testnum]); + lengths[testnum], seconds.sym); if (async_jobs > 0) { BIO_printf(bio_err, "Async mode is not supported, exiting..."); exit(1); @@ -2142,9 +2233,9 @@ int speed_main(int argc, char **argv) names[D_CBC_256_CML]); doit[D_CBC_256_CML] = 0; } - for (testnum = 0; testnum < SIZE_NUM && async_init == 0; testnum++) { + for (testnum = 0; testnum < size_num && async_init == 0; testnum++) { print_message(names[D_CBC_256_CML], c[D_CBC_256_CML][testnum], - lengths[testnum]); + lengths[testnum], seconds.sym); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_256_CML][testnum]); count++) Camellia_cbc_encrypt(loopargs[0].buf, loopargs[0].buf, @@ -2162,8 +2253,9 @@ int speed_main(int argc, char **argv) names[D_CBC_IDEA]); doit[D_CBC_IDEA] = 0; } - for (testnum = 0; testnum < SIZE_NUM && async_init == 0; testnum++) { - print_message(names[D_CBC_IDEA], c[D_CBC_IDEA][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num && async_init == 0; testnum++) { + print_message(names[D_CBC_IDEA], c[D_CBC_IDEA][testnum], + lengths[testnum], seconds.sym); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_IDEA][testnum]); count++) IDEA_cbc_encrypt(loopargs[0].buf, loopargs[0].buf, @@ -2181,8 +2273,9 @@ int speed_main(int argc, char **argv) names[D_CBC_SEED]); doit[D_CBC_SEED] = 0; } - for (testnum = 0; testnum < SIZE_NUM && async_init == 0; testnum++) { - print_message(names[D_CBC_SEED], c[D_CBC_SEED][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num && async_init == 0; testnum++) { + print_message(names[D_CBC_SEED], c[D_CBC_SEED][testnum], + lengths[testnum], seconds.sym); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_SEED][testnum]); count++) SEED_cbc_encrypt(loopargs[0].buf, loopargs[0].buf, @@ -2199,8 +2292,9 @@ int speed_main(int argc, char **argv) names[D_CBC_RC2]); doit[D_CBC_RC2] = 0; } - for (testnum = 0; testnum < SIZE_NUM && async_init == 0; testnum++) { - print_message(names[D_CBC_RC2], c[D_CBC_RC2][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num && async_init == 0; testnum++) { + print_message(names[D_CBC_RC2], c[D_CBC_RC2][testnum], + lengths[testnum], seconds.sym); if (async_jobs > 0) { BIO_printf(bio_err, "Async mode is not supported, exiting..."); exit(1); @@ -2222,8 +2316,9 @@ int speed_main(int argc, char **argv) names[D_CBC_RC5]); doit[D_CBC_RC5] = 0; } - for (testnum = 0; testnum < SIZE_NUM && async_init == 0; testnum++) { - print_message(names[D_CBC_RC5], c[D_CBC_RC5][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num && async_init == 0; testnum++) { + print_message(names[D_CBC_RC5], c[D_CBC_RC5][testnum], + lengths[testnum], seconds.sym); if (async_jobs > 0) { BIO_printf(bio_err, "Async mode is not supported, exiting..."); exit(1); @@ -2245,8 +2340,9 @@ int speed_main(int argc, char **argv) names[D_CBC_BF]); doit[D_CBC_BF] = 0; } - for (testnum = 0; testnum < SIZE_NUM && async_init == 0; testnum++) { - print_message(names[D_CBC_BF], c[D_CBC_BF][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num && async_init == 0; testnum++) { + print_message(names[D_CBC_BF], c[D_CBC_BF][testnum], + lengths[testnum], seconds.sym); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_BF][testnum]); count++) BF_cbc_encrypt(loopargs[0].buf, loopargs[0].buf, @@ -2264,8 +2360,9 @@ int speed_main(int argc, char **argv) names[D_CBC_CAST]); doit[D_CBC_CAST] = 0; } - for (testnum = 0; testnum < SIZE_NUM && async_init == 0; testnum++) { - print_message(names[D_CBC_CAST], c[D_CBC_CAST][testnum], lengths[testnum]); + for (testnum = 0; testnum < size_num && async_init == 0; testnum++) { + print_message(names[D_CBC_CAST], c[D_CBC_CAST][testnum], + lengths[testnum], seconds.sym); Time_F(START); for (count = 0, run = 1; COND(c[D_CBC_CAST][testnum]); count++) CAST_cbc_encrypt(loopargs[0].buf, loopargs[0].buf, @@ -2276,6 +2373,16 @@ int speed_main(int argc, char **argv) } } #endif + if (doit[D_RAND]) { + for (testnum = 0; testnum < size_num; testnum++) { + print_message(names[D_RAND], c[D_RAND][testnum], lengths[testnum], + seconds.sym); + Time_F(START); + count = run_benchmark(async_jobs, RAND_bytes_loop, loopargs); + d = Time_F(STOP); + print_result(D_RAND, testnum, count, d); + } + } if (doit[D_EVP]) { if (multiblock && evp_cipher) { @@ -2290,11 +2397,11 @@ int speed_main(int argc, char **argv) BIO_printf(bio_err, "Async mode is not supported, exiting..."); exit(1); } - multiblock_speed(evp_cipher); + multiblock_speed(evp_cipher, &seconds); ret = 0; goto end; } - for (testnum = 0; testnum < SIZE_NUM; testnum++) { + for (testnum = 0; testnum < size_num; testnum++) { if (evp_cipher) { names[D_EVP] = OBJ_nid2ln(EVP_CIPHER_nid(evp_cipher)); @@ -2302,19 +2409,33 @@ int speed_main(int argc, char **argv) * -O3 -fschedule-insns messes up an optimization here! * names[D_EVP] somehow becomes NULL */ - print_message(names[D_EVP], save_count, lengths[testnum]); + print_message(names[D_EVP], save_count, lengths[testnum], + seconds.sym); for (k = 0; k < loopargs_len; k++) { loopargs[k].ctx = EVP_CIPHER_CTX_new(); - if (decrypt) - EVP_DecryptInit_ex(loopargs[k].ctx, evp_cipher, NULL, key16, iv); - else - EVP_EncryptInit_ex(loopargs[k].ctx, evp_cipher, NULL, key16, iv); + EVP_CipherInit_ex(loopargs[k].ctx, evp_cipher, NULL, NULL, + iv, decrypt ? 0 : 1); + EVP_CIPHER_CTX_set_padding(loopargs[k].ctx, 0); + + keylen = EVP_CIPHER_CTX_key_length(loopargs[k].ctx); + loopargs[k].key = app_malloc(keylen, "evp_cipher key"); + EVP_CIPHER_CTX_rand_key(loopargs[k].ctx, loopargs[k].key); + EVP_CipherInit_ex(loopargs[k].ctx, NULL, NULL, + loopargs[k].key, NULL, -1); + OPENSSL_clear_free(loopargs[k].key, keylen); + } + switch (EVP_CIPHER_mode(evp_cipher)) { + case EVP_CIPH_CCM_MODE: + loopfunc = EVP_Update_loop_ccm; + break; + default: + loopfunc = EVP_Update_loop; } Time_F(START); - count = run_benchmark(async_jobs, EVP_Update_loop, loopargs); + count = run_benchmark(async_jobs, loopfunc, loopargs); d = Time_F(STOP); for (k = 0; k < loopargs_len; k++) { EVP_CIPHER_CTX_free(loopargs[k].ctx); @@ -2322,7 +2443,8 @@ int speed_main(int argc, char **argv) } if (evp_md) { names[D_EVP] = OBJ_nid2ln(EVP_MD_type(evp_md)); - print_message(names[D_EVP], save_count, lengths[testnum]); + print_message(names[D_EVP], save_count, lengths[testnum], + seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_loop, loopargs); d = Time_F(STOP); @@ -2340,6 +2462,34 @@ int speed_main(int argc, char **argv) if (!rsa_doit[testnum]) continue; for (i = 0; i < loopargs_len; i++) { + if (primes > 2) { + /* we haven't set keys yet, generate multi-prime RSA keys */ + BIGNUM *bn = BN_new(); + + if (bn == NULL) + goto end; + if (!BN_set_word(bn, RSA_F4)) { + BN_free(bn); + goto end; + } + + BIO_printf(bio_err, "Generate multi-prime RSA key for %s\n", + rsa_choices[testnum].name); + + loopargs[i].rsa_key[testnum] = RSA_new(); + if (loopargs[i].rsa_key[testnum] == NULL) { + BN_free(bn); + goto end; + } + + if (!RSA_generate_multi_prime_key(loopargs[i].rsa_key[testnum], + rsa_bits[testnum], + primes, bn, NULL)) { + BN_free(bn); + goto end; + } + BN_free(bn); + } st = RSA_sign(NID_md5_sha1, loopargs[i].buf, 36, loopargs[i].buf2, &loopargs[i].siglen, loopargs[i].rsa_key[testnum]); if (st == 0) @@ -2352,7 +2502,8 @@ int speed_main(int argc, char **argv) rsa_count = 1; } else { pkey_print_message("private", "rsa", - rsa_c[testnum][0], rsa_bits[testnum], RSA_SECONDS); + rsa_c[testnum][0], rsa_bits[testnum], + seconds.rsa); /* RSA_blinding_on(rsa_key[testnum],NULL); */ Time_F(START); count = run_benchmark(async_jobs, RSA_sign_loop, loopargs); @@ -2361,7 +2512,7 @@ int speed_main(int argc, char **argv) mr ? "+R1:%ld:%d:%.2f\n" : "%ld %d bit private RSA's in %.2fs\n", count, rsa_bits[testnum], d); - rsa_results[testnum][0] = d / (double)count; + rsa_results[testnum][0] = (double)count / d; rsa_count = count; } @@ -2378,7 +2529,8 @@ int speed_main(int argc, char **argv) rsa_doit[testnum] = 0; } else { pkey_print_message("public", "rsa", - rsa_c[testnum][1], rsa_bits[testnum], RSA_SECONDS); + rsa_c[testnum][1], rsa_bits[testnum], + seconds.rsa); Time_F(START); count = run_benchmark(async_jobs, RSA_verify_loop, loopargs); d = Time_F(STOP); @@ -2386,7 +2538,7 @@ int speed_main(int argc, char **argv) mr ? "+R2:%ld:%d:%.2f\n" : "%ld %d bit public RSA's in %.2fs\n", count, rsa_bits[testnum], d); - rsa_results[testnum][1] = d / (double)count; + rsa_results[testnum][1] = (double)count / d; } if (rsa_count <= 1) { @@ -2401,9 +2553,6 @@ int speed_main(int argc, char **argv) RAND_bytes(loopargs[i].buf, 36); #ifndef OPENSSL_NO_DSA - if (RAND_status() != 1) { - RAND_seed(rnd_seed, sizeof(rnd_seed)); - } for (testnum = 0; testnum < DSA_NUM; testnum++) { int st = 0; if (!dsa_doit[testnum]) @@ -2424,7 +2573,8 @@ int speed_main(int argc, char **argv) rsa_count = 1; } else { pkey_print_message("sign", "dsa", - dsa_c[testnum][0], dsa_bits[testnum], DSA_SECONDS); + dsa_c[testnum][0], dsa_bits[testnum], + seconds.dsa); Time_F(START); count = run_benchmark(async_jobs, DSA_sign_loop, loopargs); d = Time_F(STOP); @@ -2432,7 +2582,7 @@ int speed_main(int argc, char **argv) mr ? "+R3:%ld:%d:%.2f\n" : "%ld %d bit DSA signs in %.2fs\n", count, dsa_bits[testnum], d); - dsa_results[testnum][0] = d / (double)count; + dsa_results[testnum][0] = (double)count / d; rsa_count = count; } @@ -2449,7 +2599,8 @@ int speed_main(int argc, char **argv) dsa_doit[testnum] = 0; } else { pkey_print_message("verify", "dsa", - dsa_c[testnum][1], dsa_bits[testnum], DSA_SECONDS); + dsa_c[testnum][1], dsa_bits[testnum], + seconds.dsa); Time_F(START); count = run_benchmark(async_jobs, DSA_verify_loop, loopargs); d = Time_F(STOP); @@ -2457,7 +2608,7 @@ int speed_main(int argc, char **argv) mr ? "+R4:%ld:%d:%.2f\n" : "%ld %d bit DSA verify in %.2fs\n", count, dsa_bits[testnum], d); - dsa_results[testnum][1] = d / (double)count; + dsa_results[testnum][1] = (double)count / d; } if (rsa_count <= 1) { @@ -2469,16 +2620,14 @@ int speed_main(int argc, char **argv) #endif /* OPENSSL_NO_DSA */ #ifndef OPENSSL_NO_EC - if (RAND_status() != 1) { - RAND_seed(rnd_seed, sizeof(rnd_seed)); - } for (testnum = 0; testnum < EC_NUM; testnum++) { int st = 1; if (!ecdsa_doit[testnum]) continue; /* Ignore Curve */ for (i = 0; i < loopargs_len; i++) { - loopargs[i].ecdsa[testnum] = EC_KEY_new_by_curve_name(test_curves[testnum]); + loopargs[i].ecdsa[testnum] = + EC_KEY_new_by_curve_name(test_curves[testnum]); if (loopargs[i].ecdsa[testnum] == NULL) { st = 0; break; @@ -2494,7 +2643,8 @@ int speed_main(int argc, char **argv) /* Perform ECDSA signature test */ EC_KEY_generate_key(loopargs[i].ecdsa[testnum]); st = ECDSA_sign(0, loopargs[i].buf, 20, loopargs[i].buf2, - &loopargs[i].siglen, loopargs[i].ecdsa[testnum]); + &loopargs[i].siglen, + loopargs[i].ecdsa[testnum]); if (st == 0) break; } @@ -2506,7 +2656,8 @@ int speed_main(int argc, char **argv) } else { pkey_print_message("sign", "ecdsa", ecdsa_c[testnum][0], - test_curves_bits[testnum], ECDSA_SECONDS); + test_curves_bits[testnum], + seconds.ecdsa); Time_F(START); count = run_benchmark(async_jobs, ECDSA_sign_loop, loopargs); d = Time_F(STOP); @@ -2515,14 +2666,15 @@ int speed_main(int argc, char **argv) mr ? "+R5:%ld:%d:%.2f\n" : "%ld %d bit ECDSA signs in %.2fs \n", count, test_curves_bits[testnum], d); - ecdsa_results[testnum][0] = d / (double)count; + ecdsa_results[testnum][0] = (double)count / d; rsa_count = count; } /* Perform ECDSA verification test */ for (i = 0; i < loopargs_len; i++) { st = ECDSA_verify(0, loopargs[i].buf, 20, loopargs[i].buf2, - loopargs[i].siglen, loopargs[i].ecdsa[testnum]); + loopargs[i].siglen, + loopargs[i].ecdsa[testnum]); if (st != 1) break; } @@ -2534,7 +2686,8 @@ int speed_main(int argc, char **argv) } else { pkey_print_message("verify", "ecdsa", ecdsa_c[testnum][1], - test_curves_bits[testnum], ECDSA_SECONDS); + test_curves_bits[testnum], + seconds.ecdsa); Time_F(START); count = run_benchmark(async_jobs, ECDSA_verify_loop, loopargs); d = Time_F(STOP); @@ -2542,7 +2695,7 @@ int speed_main(int argc, char **argv) mr ? "+R6:%ld:%d:%.2f\n" : "%ld %d bit ECDSA verify in %.2fs\n", count, test_curves_bits[testnum], d); - ecdsa_results[testnum][1] = d / (double)count; + ecdsa_results[testnum][1] = (double)count / d; } if (rsa_count <= 1) { @@ -2553,93 +2706,159 @@ int speed_main(int argc, char **argv) } } - if (RAND_status() != 1) { - RAND_seed(rnd_seed, sizeof(rnd_seed)); - } for (testnum = 0; testnum < EC_NUM; testnum++) { int ecdh_checks = 1; if (!ecdh_doit[testnum]) continue; + for (i = 0; i < loopargs_len; i++) { - loopargs[i].ecdh_a[testnum] = EC_KEY_new_by_curve_name(test_curves[testnum]); - loopargs[i].ecdh_b[testnum] = EC_KEY_new_by_curve_name(test_curves[testnum]); - if (loopargs[i].ecdh_a[testnum] == NULL || - loopargs[i].ecdh_b[testnum] == NULL) { + EVP_PKEY_CTX *kctx = NULL; + EVP_PKEY_CTX *test_ctx = NULL; + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY *key_A = NULL; + EVP_PKEY *key_B = NULL; + size_t outlen; + size_t test_outlen; + + /* Ensure that the error queue is empty */ + if (ERR_peek_error()) { + BIO_printf(bio_err, + "WARNING: the error queue contains previous unhandled errors.\n"); + ERR_print_errors(bio_err); + } + + /* Let's try to create a ctx directly from the NID: this works for + * curves like Curve25519 that are not implemented through the low + * level EC interface. + * If this fails we try creating a EVP_PKEY_EC generic param ctx, + * then we set the curve by NID before deriving the actual keygen + * ctx for that specific curve. */ + kctx = EVP_PKEY_CTX_new_id(test_curves[testnum], NULL); /* keygen ctx from NID */ + if (!kctx) { + EVP_PKEY_CTX *pctx = NULL; + EVP_PKEY *params = NULL; + + /* If we reach this code EVP_PKEY_CTX_new_id() failed and a + * "int_ctx_new:unsupported algorithm" error was added to the + * error queue. + * We remove it from the error queue as we are handling it. */ + unsigned long error = ERR_peek_error(); /* peek the latest error in the queue */ + if (error == ERR_peek_last_error() && /* oldest and latest errors match */ + /* check that the error origin matches */ + ERR_GET_LIB(error) == ERR_LIB_EVP && + ERR_GET_FUNC(error) == EVP_F_INT_CTX_NEW && + ERR_GET_REASON(error) == EVP_R_UNSUPPORTED_ALGORITHM) + ERR_get_error(); /* pop error from queue */ + if (ERR_peek_error()) { + BIO_printf(bio_err, + "Unhandled error in the error queue during ECDH init.\n"); + ERR_print_errors(bio_err); + rsa_count = 1; + break; + } + + if ( /* Create the context for parameter generation */ + !(pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL)) || + /* Initialise the parameter generation */ + !EVP_PKEY_paramgen_init(pctx) || + /* Set the curve by NID */ + !EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, + test_curves + [testnum]) || + /* Create the parameter object params */ + !EVP_PKEY_paramgen(pctx, ¶ms)) { + ecdh_checks = 0; + BIO_printf(bio_err, "ECDH EC params init failure.\n"); + ERR_print_errors(bio_err); + rsa_count = 1; + break; + } + /* Create the context for the key generation */ + kctx = EVP_PKEY_CTX_new(params, NULL); + + EVP_PKEY_free(params); + params = NULL; + EVP_PKEY_CTX_free(pctx); + pctx = NULL; + } + if (kctx == NULL || /* keygen ctx is not null */ + !EVP_PKEY_keygen_init(kctx) /* init keygen ctx */ ) { ecdh_checks = 0; + BIO_printf(bio_err, "ECDH keygen failure.\n"); + ERR_print_errors(bio_err); + rsa_count = 1; break; } + + if (!EVP_PKEY_keygen(kctx, &key_A) || /* generate secret key A */ + !EVP_PKEY_keygen(kctx, &key_B) || /* generate secret key B */ + !(ctx = EVP_PKEY_CTX_new(key_A, NULL)) || /* derivation ctx from skeyA */ + !EVP_PKEY_derive_init(ctx) || /* init derivation ctx */ + !EVP_PKEY_derive_set_peer(ctx, key_B) || /* set peer pubkey in ctx */ + !EVP_PKEY_derive(ctx, NULL, &outlen) || /* determine max length */ + outlen == 0 || /* ensure outlen is a valid size */ + outlen > MAX_ECDH_SIZE /* avoid buffer overflow */ ) { + ecdh_checks = 0; + BIO_printf(bio_err, "ECDH key generation failure.\n"); + ERR_print_errors(bio_err); + rsa_count = 1; + break; + } + + /* Here we perform a test run, comparing the output of a*B and b*A; + * we try this here and assume that further EVP_PKEY_derive calls + * never fail, so we can skip checks in the actually benchmarked + * code, for maximum performance. */ + if (!(test_ctx = EVP_PKEY_CTX_new(key_B, NULL)) || /* test ctx from skeyB */ + !EVP_PKEY_derive_init(test_ctx) || /* init derivation test_ctx */ + !EVP_PKEY_derive_set_peer(test_ctx, key_A) || /* set peer pubkey in test_ctx */ + !EVP_PKEY_derive(test_ctx, NULL, &test_outlen) || /* determine max length */ + !EVP_PKEY_derive(ctx, loopargs[i].secret_a, &outlen) || /* compute a*B */ + !EVP_PKEY_derive(test_ctx, loopargs[i].secret_b, &test_outlen) || /* compute b*A */ + test_outlen != outlen /* compare output length */ ) { + ecdh_checks = 0; + BIO_printf(bio_err, "ECDH computation failure.\n"); + ERR_print_errors(bio_err); + rsa_count = 1; + break; + } + + /* Compare the computation results: CRYPTO_memcmp() returns 0 if equal */ + if (CRYPTO_memcmp(loopargs[i].secret_a, + loopargs[i].secret_b, outlen)) { + ecdh_checks = 0; + BIO_printf(bio_err, "ECDH computations don't match.\n"); + ERR_print_errors(bio_err); + rsa_count = 1; + break; + } + + loopargs[i].ecdh_ctx[testnum] = ctx; + loopargs[i].outlen[testnum] = outlen; + + EVP_PKEY_free(key_A); + EVP_PKEY_free(key_B); + EVP_PKEY_CTX_free(kctx); + kctx = NULL; + EVP_PKEY_CTX_free(test_ctx); + test_ctx = NULL; } - if (ecdh_checks == 0) { - BIO_printf(bio_err, "ECDH failure.\n"); - ERR_print_errors(bio_err); - rsa_count = 1; - } else { - for (i = 0; i < loopargs_len; i++) { - /* generate two ECDH key pairs */ - if (!EC_KEY_generate_key(loopargs[i].ecdh_a[testnum]) || - !EC_KEY_generate_key(loopargs[i].ecdh_b[testnum])) { - BIO_printf(bio_err, "ECDH key generation failure.\n"); - ERR_print_errors(bio_err); - ecdh_checks = 0; - rsa_count = 1; - } else { - int secret_size_a, secret_size_b; - /* - * 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 = EC_GROUP_get_degree( - EC_KEY_get0_group(loopargs[i].ecdh_a[testnum])); - - if (field_size <= 24 * 8) { /* 192 bits */ - loopargs[i].outlen = KDF1_SHA1_len; - loopargs[i].kdf = KDF1_SHA1; - } else { - loopargs[i].outlen = (field_size + 7) / 8; - loopargs[i].kdf = NULL; - } - secret_size_a = - ECDH_compute_key(loopargs[i].secret_a, loopargs[i].outlen, - EC_KEY_get0_public_key(loopargs[i].ecdh_b[testnum]), - loopargs[i].ecdh_a[testnum], loopargs[i].kdf); - secret_size_b = - ECDH_compute_key(loopargs[i].secret_b, loopargs[i].outlen, - EC_KEY_get0_public_key(loopargs[i].ecdh_a[testnum]), - loopargs[i].ecdh_b[testnum], loopargs[i].kdf); - if (secret_size_a != secret_size_b) - ecdh_checks = 0; - else - ecdh_checks = 1; - - for (k = 0; k < secret_size_a && ecdh_checks == 1; k++) { - if (loopargs[i].secret_a[k] != loopargs[i].secret_b[k]) - 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; - break; - } - } - } - if (ecdh_checks != 0) { - pkey_print_message("", "ecdh", - ecdh_c[testnum][0], - test_curves_bits[testnum], ECDH_SECONDS); - Time_F(START); - count = run_benchmark(async_jobs, ECDH_compute_key_loop, loopargs); - 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[testnum], d); - ecdh_results[testnum][0] = d / (double)count; - rsa_count = count; - } + if (ecdh_checks != 0) { + pkey_print_message("", "ecdh", + ecdh_c[testnum][0], + test_curves_bits[testnum], + seconds.ecdh); + Time_F(START); + count = + run_benchmark(async_jobs, ECDH_EVP_derive_key_loop, loopargs); + d = Time_F(STOP); + BIO_printf(bio_err, + mr ? "+R7:%ld:%d:%.2f\n" : + "%ld %d-bit ECDH ops in %.2fs\n", count, + test_curves_bits[testnum], d); + ecdh_results[testnum][0] = (double)count / d; + rsa_count = count; } if (rsa_count <= 1) { @@ -2684,7 +2903,7 @@ int speed_main(int argc, char **argv) ("The 'numbers' are in 1000s of bytes per second processed.\n"); printf("type "); } - for (testnum = 0; testnum < SIZE_NUM; testnum++) + for (testnum = 0; testnum < size_num; testnum++) printf(mr ? ":%d" : "%7d bytes", lengths[testnum]); printf("\n"); } @@ -2696,7 +2915,7 @@ int speed_main(int argc, char **argv) printf("+F:%d:%s", k, names[k]); else printf("%-13s", names[k]); - for (testnum = 0; testnum < SIZE_NUM; testnum++) { + for (testnum = 0; testnum < size_num; testnum++) { if (results[k][testnum] > 10000 && !mr) printf(" %11.2fk", results[k][testnum] / 1e3); else @@ -2718,8 +2937,8 @@ int speed_main(int argc, char **argv) k, rsa_bits[k], rsa_results[k][0], rsa_results[k][1]); else printf("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]); + rsa_bits[k], 1.0 / rsa_results[k][0], 1.0 / rsa_results[k][1], + rsa_results[k][0], rsa_results[k][1]); } #endif #ifndef OPENSSL_NO_DSA @@ -2736,8 +2955,8 @@ int speed_main(int argc, char **argv) k, dsa_bits[k], dsa_results[k][0], dsa_results[k][1]); else printf("dsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n", - dsa_bits[k], dsa_results[k][0], dsa_results[k][1], - 1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1]); + dsa_bits[k], 1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1], + dsa_results[k][0], dsa_results[k][1]); } #endif #ifndef OPENSSL_NO_EC @@ -2758,8 +2977,8 @@ int speed_main(int argc, char **argv) printf("%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]); + 1.0 / ecdsa_results[k][0], 1.0 / ecdsa_results[k][1], + ecdsa_results[k][0], ecdsa_results[k][1]); } testnum = 1; @@ -2779,7 +2998,7 @@ int speed_main(int argc, char **argv) printf("%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]); + 1.0 / ecdh_results[k][0], ecdh_results[k][0]); } #endif @@ -2802,8 +3021,7 @@ int speed_main(int argc, char **argv) #ifndef OPENSSL_NO_EC for (k = 0; k < EC_NUM; k++) { EC_KEY_free(loopargs[i].ecdsa[k]); - EC_KEY_free(loopargs[i].ecdh_a[k]); - EC_KEY_free(loopargs[i].ecdh_b[k]); + EVP_PKEY_CTX_free(loopargs[i].ecdh_ctx[k]); } OPENSSL_free(loopargs[i].secret_a); OPENSSL_free(loopargs[i].secret_b); @@ -2820,17 +3038,17 @@ int speed_main(int argc, char **argv) } OPENSSL_free(loopargs); release_engine(e); - return (ret); + return ret; } -static void print_message(const char *s, long num, int length) +static void print_message(const char *s, long num, int length, int tm) { #ifdef SIGALRM BIO_printf(bio_err, mr ? "+DT:%s:%d:%d\n" - : "Doing %s for %ds on %d size blocks: ", s, SECONDS, length); + : "Doing %s for %ds on %d size blocks: ", s, tm, length); (void)BIO_flush(bio_err); - alarm(SECONDS); + alarm(tm); #else BIO_printf(bio_err, mr ? "+DN:%s:%ld:%d\n" @@ -2897,7 +3115,7 @@ static char *sstrsep(char **string, const char *delim) return token; } -static int do_multi(int multi) +static int do_multi(int multi, int size_num) { int n; int fd[2]; @@ -2943,8 +3161,9 @@ static int do_multi(int multi) if (p) *p = '\0'; if (buf[0] != '+') { - BIO_printf(bio_err, "Don't understand line '%s' from child %d\n", - buf, n); + BIO_printf(bio_err, + "Don't understand line '%s' from child %d\n", buf, + n); continue; } printf("Got: %s from %d\n", buf, n); @@ -2955,7 +3174,7 @@ static int do_multi(int multi) p = buf + 3; alg = atoi(sstrsep(&p, sep)); sstrsep(&p, sep); - for (j = 0; j < SIZE_NUM; ++j) + for (j = 0; j < size_num; ++j) results[alg][j] += atof(sstrsep(&p, sep)); } else if (strncmp(buf, "+F2:", 4) == 0) { int k; @@ -2966,16 +3185,10 @@ static int do_multi(int multi) 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; + 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; + rsa_results[k][1] += d; } # ifndef OPENSSL_NO_DSA else if (strncmp(buf, "+F3:", 4) == 0) { @@ -2987,16 +3200,10 @@ static int do_multi(int multi) 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; + 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; + dsa_results[k][1] += d; } # endif # ifndef OPENSSL_NO_EC @@ -3009,18 +3216,10 @@ static int do_multi(int multi) 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; + 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; + ecdsa_results[k][1] += d; } else if (strncmp(buf, "+F5:", 4) == 0) { int k; double d; @@ -3030,18 +3229,15 @@ static int do_multi(int multi) 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; - + ecdh_results[k][0] += d; } # endif else if (strncmp(buf, "+H:", 3) == 0) { ; } else - BIO_printf(bio_err, "Unknown type '%s' from child %d\n", buf, n); + BIO_printf(bio_err, "Unknown type '%s' from child %d\n", buf, + n); } fclose(f); @@ -3051,26 +3247,39 @@ static int do_multi(int multi) } #endif -static void multiblock_speed(const EVP_CIPHER *evp_cipher) +static void multiblock_speed(const EVP_CIPHER *evp_cipher, + const openssl_speed_sec_t *seconds) { - static int mblengths[] = + static const int mblengths_list[] = { 8 * 1024, 2 * 8 * 1024, 4 * 8 * 1024, 8 * 8 * 1024, 8 * 16 * 1024 }; - int j, count, num = OSSL_NELEM(mblengths); + const int *mblengths = mblengths_list; + int j, count, keylen, num = OSSL_NELEM(mblengths_list); const char *alg_name; - unsigned char *inp, *out, no_key[32], no_iv[16]; + unsigned char *inp, *out, *key, no_key[32], no_iv[16]; EVP_CIPHER_CTX *ctx; double d = 0.0; + if (lengths_single) { + mblengths = &lengths_single; + num = 1; + } + inp = app_malloc(mblengths[num - 1], "multiblock input buffer"); out = app_malloc(mblengths[num - 1] + 1024, "multiblock output buffer"); ctx = EVP_CIPHER_CTX_new(); - 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); + EVP_EncryptInit_ex(ctx, evp_cipher, NULL, NULL, no_iv); + + keylen = EVP_CIPHER_CTX_key_length(ctx); + key = app_malloc(keylen, "evp_cipher key"); + EVP_CIPHER_CTX_rand_key(ctx, key); + EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL); + OPENSSL_clear_free(key, keylen); + + EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY, sizeof(no_key), no_key); alg_name = OBJ_nid2ln(EVP_CIPHER_nid(evp_cipher)); for (j = 0; j < num; j++) { - print_message(alg_name, 0, mblengths[j]); + print_message(alg_name, 0, mblengths[j], seconds->sym); Time_F(START); for (count = 0, run = 1; run && count < 0x7fffffff; count++) { unsigned char aad[EVP_AEAD_TLS1_AAD_LEN]; @@ -3103,8 +3312,8 @@ static void multiblock_speed(const EVP_CIPHER *evp_cipher) RAND_bytes(out, 16); len += 16; - aad[11] = len >> 8; - aad[12] = len; + 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); diff --git a/apps/spkac.c b/apps/spkac.c index 34490679..8ed9dd92 100644 --- a/apps/spkac.c +++ b/apps/spkac.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-2018 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 @@ -12,11 +12,11 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include #include -#include #include #include @@ -24,14 +24,15 @@ typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_NOOUT, OPT_PUBKEY, OPT_VERIFY, OPT_IN, OPT_OUT, OPT_ENGINE, OPT_KEY, OPT_CHALLENGE, OPT_PASSIN, OPT_SPKAC, - OPT_SPKSECT + OPT_SPKSECT, OPT_KEYFORM } OPTION_CHOICE; -OPTIONS spkac_options[] = { +const OPTIONS spkac_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Input file"}, {"out", OPT_OUT, '>', "Output file"}, {"key", OPT_KEY, '<', "Create SPKAC using private key"}, + {"keyform", OPT_KEYFORM, 'f', "Private key file format - default PEM (PEM, DER, or ENGINE)"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"challenge", OPT_CHALLENGE, 's', "Challenge string"}, {"spkac", OPT_SPKAC, 's', "Alternative SPKAC name"}, @@ -58,6 +59,7 @@ int spkac_main(int argc, char **argv) char *spkstr = NULL, *prog; const char *spkac = "SPKAC", *spksect = "default"; int i, ret = 1, verify = 0, noout = 0, pubkey = 0; + int keyformat = FORMAT_PEM; OPTION_CHOICE o; prog = opt_init(argc, argv, spkac_options); @@ -93,6 +95,10 @@ int spkac_main(int argc, char **argv) case OPT_KEY: keyfile = opt_arg(); break; + case OPT_KEYFORM: + if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat)) + goto opthelp; + break; case OPT_CHALLENGE: challenge = opt_arg(); break; @@ -118,7 +124,7 @@ int spkac_main(int argc, char **argv) if (keyfile != NULL) { pkey = load_key(strcmp(keyfile, "-") ? keyfile : NULL, - FORMAT_PEM, 1, passin, e, "private key"); + keyformat, 1, passin, e, "private key"); if (pkey == NULL) goto end; spki = NETSCAPE_SPKI_new(); @@ -192,5 +198,5 @@ int spkac_main(int argc, char **argv) EVP_PKEY_free(pkey); release_engine(e); OPENSSL_free(passin); - return (ret); + return ret; } diff --git a/apps/srp.c b/apps/srp.c index 0ead68e8..5e7f3b9f 100644 --- a/apps/srp.c +++ b/apps/srp.c @@ -22,11 +22,11 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # define BASE_SECTION "srp" # define CONFIG_FILE "openssl.cnf" -# define ENV_RANDFILE "RANDFILE" # define ENV_DATABASE "srpvfile" # define ENV_DEFAULT_SRP "default_srp" @@ -139,8 +139,8 @@ static char *srp_verify_user(const char *user, const char *srp_verifier, BIO_printf(bio_err, "Pass %s\n", password); OPENSSL_assert(srp_usersalt != NULL); - if (!(gNid = SRP_create_verifier(user, password, &srp_usersalt, - &verifier, N, g)) ) { + if ((gNid = SRP_create_verifier(user, password, &srp_usersalt, + &verifier, N, g)) == NULL) { BIO_printf(bio_err, "Internal error validating SRP verifier\n"); } else { if (strcmp(verifier, srp_verifier)) @@ -170,8 +170,8 @@ static char *srp_create_user(char *user, char **srp_verifier, if (verbose) BIO_printf(bio_err, "Creating\n user=\"%s\"\n g=\"%s\"\n N=\"%s\"\n", user, g, N); - if (!(gNid = SRP_create_verifier(user, password, &salt, - srp_verifier, N, g)) ) { + if ((gNid = SRP_create_verifier(user, password, &salt, + srp_verifier, N, g)) == NULL) { BIO_printf(bio_err, "Internal error creating SRP verifier\n"); } else { *srp_usersalt = salt; @@ -189,10 +189,10 @@ typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SRPVFILE, OPT_ADD, OPT_DELETE, OPT_MODIFY, OPT_LIST, OPT_GN, OPT_USERINFO, - OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE + OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE, OPT_R_ENUM } OPTION_CHOICE; -OPTIONS srp_options[] = { +const OPTIONS srp_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"verbose", OPT_VERBOSE, '-', "Talk a lot while doing things"}, {"config", OPT_CONFIG, '<', "A config file"}, @@ -207,6 +207,7 @@ OPTIONS srp_options[] = { {"userinfo", OPT_USERINFO, 's', "Additional info to be set for user"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, + OPT_R_OPTIONS, # ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, # endif @@ -222,7 +223,7 @@ int srp_main(int argc, char **argv) int doupdatedb = 0, mode = OPT_ERR; char *user = NULL, *passinarg = NULL, *passoutarg = NULL; char *passin = NULL, *passout = NULL, *gN = NULL, *userinfo = NULL; - char *randfile = NULL, *section = NULL; + char *section = NULL; char **gNrow = NULL, *configfile = NULL; char *srpvfile = NULL, **pp, *prog; OPTION_CHOICE o; @@ -278,12 +279,16 @@ int srp_main(int argc, char **argv) case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; } } argc = opt_num_rest(); argv = opt_rest(); - if (srpvfile && configfile) { + if (srpvfile != NULL && configfile != NULL) { BIO_printf(bio_err, "-srpvfile and -configfile cannot be specified together.\n"); goto end; @@ -300,7 +305,7 @@ int srp_main(int argc, char **argv) } user = *argv++; } - if ((passinarg || passoutarg) && argc != 1) { + if ((passinarg != NULL || passoutarg != NULL) && argc != 1) { BIO_printf(bio_err, "-passin, -passout arguments only valid with one user.\n"); goto opthelp; @@ -311,8 +316,8 @@ int srp_main(int argc, char **argv) goto end; } - if (!srpvfile) { - if (!configfile) + if (srpvfile == NULL) { + if (configfile == NULL) configfile = default_config_file; if (verbose) @@ -336,8 +341,7 @@ int srp_main(int argc, char **argv) goto end; } - if (randfile == NULL) - randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE"); + app_RAND_load_conf(conf, BASE_SECTION); if (verbose) BIO_printf(bio_err, @@ -348,10 +352,6 @@ int srp_main(int argc, char **argv) if (srpvfile == NULL) goto end; } - if (randfile == NULL) - ERR_clear_error(); - else - app_RAND_load_file(randfile, 0); if (verbose) BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n", @@ -397,17 +397,15 @@ int srp_main(int argc, char **argv) if (user != NULL && verbose > 1) BIO_printf(bio_err, "Processing user \"%s\"\n", user); - if ((userindex = get_index(db, user, 'U')) >= 0) { + if ((userindex = get_index(db, user, 'U')) >= 0) print_user(db, userindex, (verbose > 0) || mode == OPT_LIST); - } if (mode == OPT_LIST) { if (user == NULL) { BIO_printf(bio_err, "List all users\n"); - for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { + for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) print_user(db, i, 1); - } } else if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, ignored. t\n", user); @@ -603,11 +601,9 @@ int srp_main(int argc, char **argv) OPENSSL_free(passout); if (ret) ERR_print_errors(bio_err); - if (randfile) - app_RAND_write_file(randfile); NCONF_free(conf); free_index(db); release_engine(e); - return (ret); + return ret; } #endif diff --git a/apps/storeutl.c b/apps/storeutl.c new file mode 100644 index 00000000..d40d263e --- /dev/null +++ b/apps/storeutl.c @@ -0,0 +1,471 @@ +/* + * Copyright 2016-2018 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 + +#include "apps.h" +#include "progs.h" +#include +#include +#include + +static int process(const char *uri, const UI_METHOD *uimeth, PW_CB_DATA *uidata, + int expected, int criterion, OSSL_STORE_SEARCH *search, + int text, int noout, int recursive, int indent, BIO *out, + const char *prog); + +typedef enum OPTION_choice { + OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE, OPT_OUT, OPT_PASSIN, + OPT_NOOUT, OPT_TEXT, OPT_RECURSIVE, + OPT_SEARCHFOR_CERTS, OPT_SEARCHFOR_KEYS, OPT_SEARCHFOR_CRLS, + OPT_CRITERION_SUBJECT, OPT_CRITERION_ISSUER, OPT_CRITERION_SERIAL, + OPT_CRITERION_FINGERPRINT, OPT_CRITERION_ALIAS, + OPT_MD +} OPTION_CHOICE; + +const OPTIONS storeutl_options[] = { + {OPT_HELP_STR, 1, '-', "Usage: %s [options] uri\nValid options are:\n"}, + {"help", OPT_HELP, '-', "Display this summary"}, + {"out", OPT_OUT, '>', "Output file - default stdout"}, + {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, + {"text", OPT_TEXT, '-', "Print a text form of the objects"}, + {"noout", OPT_NOOUT, '-', "No PEM output, just status"}, + {"certs", OPT_SEARCHFOR_CERTS, '-', "Search for certificates only"}, + {"keys", OPT_SEARCHFOR_KEYS, '-', "Search for keys only"}, + {"crls", OPT_SEARCHFOR_CRLS, '-', "Search for CRLs only"}, + {"subject", OPT_CRITERION_SUBJECT, 's', "Search by subject"}, + {"issuer", OPT_CRITERION_ISSUER, 's', "Search by issuer and serial, issuer name"}, + {"serial", OPT_CRITERION_SERIAL, 's', "Search by issuer and serial, serial number"}, + {"fingerprint", OPT_CRITERION_FINGERPRINT, 's', "Search by public key fingerprint, given in hex"}, + {"alias", OPT_CRITERION_ALIAS, 's', "Search by alias"}, + {"", OPT_MD, '-', "Any supported digest"}, +#ifndef OPENSSL_NO_ENGINE + {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, +#endif + {"r", OPT_RECURSIVE, '-', "Recurse through names"}, + {NULL} +}; + +int storeutl_main(int argc, char *argv[]) +{ + int ret = 1, noout = 0, text = 0, recursive = 0; + char *outfile = NULL, *passin = NULL, *passinarg = NULL; + BIO *out = NULL; + ENGINE *e = NULL; + OPTION_CHOICE o; + char *prog = opt_init(argc, argv, storeutl_options); + PW_CB_DATA pw_cb_data; + int expected = 0; + int criterion = 0; + X509_NAME *subject = NULL, *issuer = NULL; + ASN1_INTEGER *serial = NULL; + unsigned char *fingerprint = NULL; + size_t fingerprintlen = 0; + char *alias = NULL; + OSSL_STORE_SEARCH *search = NULL; + const EVP_MD *digest = NULL; + + while ((o = opt_next()) != OPT_EOF) { + switch (o) { + case OPT_EOF: + case OPT_ERR: + opthelp: + BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); + goto end; + case OPT_HELP: + opt_help(storeutl_options); + ret = 0; + goto end; + case OPT_OUT: + outfile = opt_arg(); + break; + case OPT_PASSIN: + passinarg = opt_arg(); + break; + case OPT_NOOUT: + noout = 1; + break; + case OPT_TEXT: + text = 1; + break; + case OPT_RECURSIVE: + recursive = 1; + break; + case OPT_SEARCHFOR_CERTS: + case OPT_SEARCHFOR_KEYS: + case OPT_SEARCHFOR_CRLS: + if (expected != 0) { + BIO_printf(bio_err, "%s: only one search type can be given.\n", + prog); + goto end; + } + { + static const struct { + enum OPTION_choice choice; + int type; + } map[] = { + {OPT_SEARCHFOR_CERTS, OSSL_STORE_INFO_CERT}, + {OPT_SEARCHFOR_KEYS, OSSL_STORE_INFO_PKEY}, + {OPT_SEARCHFOR_CRLS, OSSL_STORE_INFO_CRL}, + }; + size_t i; + + for (i = 0; i < OSSL_NELEM(map); i++) { + if (o == map[i].choice) { + expected = map[i].type; + break; + } + } + /* + * If expected wasn't set at this point, it means the map + * isn't syncronised with the possible options leading here. + */ + OPENSSL_assert(expected != 0); + } + break; + case OPT_CRITERION_SUBJECT: + if (criterion != 0) { + BIO_printf(bio_err, "%s: criterion already given.\n", + prog); + goto end; + } + criterion = OSSL_STORE_SEARCH_BY_NAME; + if (subject != NULL) { + BIO_printf(bio_err, "%s: subject already given.\n", + prog); + goto end; + } + if ((subject = parse_name(opt_arg(), MBSTRING_UTF8, 1)) == NULL) { + BIO_printf(bio_err, "%s: can't parse subject argument.\n", + prog); + goto end; + } + break; + case OPT_CRITERION_ISSUER: + if (criterion != 0 + || (criterion == OSSL_STORE_SEARCH_BY_ISSUER_SERIAL + && issuer != NULL)) { + BIO_printf(bio_err, "%s: criterion already given.\n", + prog); + goto end; + } + criterion = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; + if (issuer != NULL) { + BIO_printf(bio_err, "%s: issuer already given.\n", + prog); + goto end; + } + if ((issuer = parse_name(opt_arg(), MBSTRING_UTF8, 1)) == NULL) { + BIO_printf(bio_err, "%s: can't parse issuer argument.\n", + prog); + goto end; + } + break; + case OPT_CRITERION_SERIAL: + if (criterion != 0 + || (criterion == OSSL_STORE_SEARCH_BY_ISSUER_SERIAL + && serial != NULL)) { + BIO_printf(bio_err, "%s: criterion already given.\n", + prog); + goto end; + } + criterion = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; + if (serial != NULL) { + BIO_printf(bio_err, "%s: serial number already given.\n", + prog); + goto end; + } + if ((serial = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL) { + BIO_printf(bio_err, "%s: can't parse serial number argument.\n", + prog); + goto end; + } + break; + case OPT_CRITERION_FINGERPRINT: + if (criterion != 0 + || (criterion == OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT + && fingerprint != NULL)) { + BIO_printf(bio_err, "%s: criterion already given.\n", + prog); + goto end; + } + criterion = OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT; + if (fingerprint != NULL) { + BIO_printf(bio_err, "%s: fingerprint already given.\n", + prog); + goto end; + } + { + long tmplen = 0; + + if ((fingerprint = OPENSSL_hexstr2buf(opt_arg(), &tmplen)) + == NULL) { + BIO_printf(bio_err, + "%s: can't parse fingerprint argument.\n", + prog); + goto end; + } + fingerprintlen = (size_t)tmplen; + } + break; + case OPT_CRITERION_ALIAS: + if (criterion != 0) { + BIO_printf(bio_err, "%s: criterion already given.\n", + prog); + goto end; + } + criterion = OSSL_STORE_SEARCH_BY_ALIAS; + if (alias != NULL) { + BIO_printf(bio_err, "%s: alias already given.\n", + prog); + goto end; + } + if ((alias = OPENSSL_strdup(opt_arg())) == NULL) { + BIO_printf(bio_err, "%s: can't parse alias argument.\n", + prog); + goto end; + } + break; + case OPT_ENGINE: + e = setup_engine(opt_arg(), 0); + break; + case OPT_MD: + if (!opt_md(opt_unknown(), &digest)) + goto opthelp; + } + } + argc = opt_num_rest(); + argv = opt_rest(); + + if (argc == 0) { + BIO_printf(bio_err, "%s: No URI given, nothing to do...\n", prog); + goto opthelp; + } + if (argc > 1) { + BIO_printf(bio_err, "%s: Unknown extra parameters after URI\n", prog); + goto opthelp; + } + + if (criterion != 0) { + switch (criterion) { + case OSSL_STORE_SEARCH_BY_NAME: + if ((search = OSSL_STORE_SEARCH_by_name(subject)) == NULL) { + ERR_print_errors(bio_err); + goto end; + } + break; + case OSSL_STORE_SEARCH_BY_ISSUER_SERIAL: + if (issuer == NULL || serial == NULL) { + BIO_printf(bio_err, + "%s: both -issuer and -serial must be given.\n", + prog); + goto end; + } + if ((search = OSSL_STORE_SEARCH_by_issuer_serial(issuer, serial)) + == NULL) { + ERR_print_errors(bio_err); + goto end; + } + break; + case OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT: + if ((search = OSSL_STORE_SEARCH_by_key_fingerprint(digest, + fingerprint, + fingerprintlen)) + == NULL) { + ERR_print_errors(bio_err); + goto end; + } + break; + case OSSL_STORE_SEARCH_BY_ALIAS: + if ((search = OSSL_STORE_SEARCH_by_alias(alias)) == NULL) { + ERR_print_errors(bio_err); + goto end; + } + break; + } + } + + if (!app_passwd(passinarg, NULL, &passin, NULL)) { + BIO_printf(bio_err, "Error getting passwords\n"); + goto end; + } + pw_cb_data.password = passin; + pw_cb_data.prompt_info = argv[0]; + + out = bio_open_default(outfile, 'w', FORMAT_TEXT); + if (out == NULL) + goto end; + + ret = process(argv[0], get_ui_method(), &pw_cb_data, + expected, criterion, search, + text, noout, recursive, 0, out, prog); + + end: + OPENSSL_free(alias); + ASN1_INTEGER_free(serial); + X509_NAME_free(subject); + X509_NAME_free(issuer); + OSSL_STORE_SEARCH_free(search); + BIO_free_all(out); + OPENSSL_free(passin); + release_engine(e); + return ret; +} + +static int indent_printf(int indent, BIO *bio, const char *format, ...) +{ + va_list args; + int ret; + + va_start(args, format); + + ret = BIO_printf(bio, "%*s", indent, "") + BIO_vprintf(bio, format, args); + + va_end(args); + return ret; +} + +static int process(const char *uri, const UI_METHOD *uimeth, PW_CB_DATA *uidata, + int expected, int criterion, OSSL_STORE_SEARCH *search, + int text, int noout, int recursive, int indent, BIO *out, + const char *prog) +{ + OSSL_STORE_CTX *store_ctx = NULL; + int ret = 1, items = 0; + + if ((store_ctx = OSSL_STORE_open(uri, uimeth, uidata, NULL, NULL)) + == NULL) { + BIO_printf(bio_err, "Couldn't open file or uri %s\n", uri); + ERR_print_errors(bio_err); + return ret; + } + + if (expected != 0) { + if (!OSSL_STORE_expect(store_ctx, expected)) { + ERR_print_errors(bio_err); + goto end2; + } + } + + if (criterion != 0) { + if (!OSSL_STORE_supports_search(store_ctx, criterion)) { + BIO_printf(bio_err, + "%s: the store scheme doesn't support the given search criteria.\n", + prog); + goto end2; + } + + if (!OSSL_STORE_find(store_ctx, search)) { + ERR_print_errors(bio_err); + goto end2; + } + } + + /* From here on, we count errors, and we'll return the count at the end */ + ret = 0; + + for (;;) { + OSSL_STORE_INFO *info = OSSL_STORE_load(store_ctx); + int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info); + const char *infostr = + info == NULL ? NULL : OSSL_STORE_INFO_type_string(type); + + if (info == NULL) { + if (OSSL_STORE_eof(store_ctx)) + break; + + if (OSSL_STORE_error(store_ctx)) { + if (recursive) + ERR_clear_error(); + else + ERR_print_errors(bio_err); + ret++; + continue; + } + + BIO_printf(bio_err, + "ERROR: OSSL_STORE_load() returned NULL without " + "eof or error indications\n"); + BIO_printf(bio_err, " This is an error in the loader\n"); + ERR_print_errors(bio_err); + ret++; + break; + } + + if (type == OSSL_STORE_INFO_NAME) { + const char *name = OSSL_STORE_INFO_get0_NAME(info); + const char *desc = OSSL_STORE_INFO_get0_NAME_description(info); + indent_printf(indent, bio_out, "%d: %s: %s\n", items, infostr, + name); + if (desc != NULL) + indent_printf(indent, bio_out, "%s\n", desc); + } else { + indent_printf(indent, bio_out, "%d: %s\n", items, infostr); + } + + /* + * Unfortunately, PEM_X509_INFO_write_bio() is sorely lacking in + * functionality, so we must figure out how exactly to write things + * ourselves... + */ + switch (type) { + case OSSL_STORE_INFO_NAME: + if (recursive) { + const char *suburi = OSSL_STORE_INFO_get0_NAME(info); + ret += process(suburi, uimeth, uidata, + expected, criterion, search, + text, noout, recursive, indent + 2, out, prog); + } + break; + case OSSL_STORE_INFO_PARAMS: + if (text) + EVP_PKEY_print_params(out, OSSL_STORE_INFO_get0_PARAMS(info), + 0, NULL); + if (!noout) + PEM_write_bio_Parameters(out, + OSSL_STORE_INFO_get0_PARAMS(info)); + break; + case OSSL_STORE_INFO_PKEY: + if (text) + EVP_PKEY_print_private(out, OSSL_STORE_INFO_get0_PKEY(info), + 0, NULL); + if (!noout) + PEM_write_bio_PrivateKey(out, OSSL_STORE_INFO_get0_PKEY(info), + NULL, NULL, 0, NULL, NULL); + break; + case OSSL_STORE_INFO_CERT: + if (text) + X509_print(out, OSSL_STORE_INFO_get0_CERT(info)); + if (!noout) + PEM_write_bio_X509(out, OSSL_STORE_INFO_get0_CERT(info)); + break; + case OSSL_STORE_INFO_CRL: + if (text) + X509_CRL_print(out, OSSL_STORE_INFO_get0_CRL(info)); + if (!noout) + PEM_write_bio_X509_CRL(out, OSSL_STORE_INFO_get0_CRL(info)); + break; + default: + BIO_printf(bio_err, "!!! Unknown code\n"); + ret++; + break; + } + items++; + OSSL_STORE_INFO_free(info); + } + indent_printf(indent, out, "Total found: %d\n", items); + + end2: + if (!OSSL_STORE_close(store_ctx)) { + ERR_print_errors(bio_err); + ret++; + } + + return ret; +} diff --git a/apps/testdsa.h b/apps/testdsa.h index 1e4502a1..3c4b459d 100644 --- a/apps/testdsa.h +++ b/apps/testdsa.h @@ -1,5 +1,5 @@ /* - * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1998-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 @@ -8,9 +8,7 @@ */ /* used by speed.c */ -DSA *get_dsa512(void); -DSA *get_dsa1024(void); -DSA *get_dsa2048(void); +DSA *get_dsa(int); static unsigned char dsa512_priv[] = { 0x65, 0xe5, 0xc7, 0x38, 0x60, 0x24, 0xb5, 0x89, 0xd4, 0x9c, 0xeb, 0x4c, @@ -49,40 +47,6 @@ static unsigned char dsa512_g[] = { 0xA2, 0x03, 0x9D, 0x20, }; -DSA *get_dsa512() -{ - DSA *dsa; - BIGNUM *priv_key, *pub_key, *p, *q, *g; - - if ((dsa = DSA_new()) == NULL) - return (NULL); - priv_key = BN_bin2bn(dsa512_priv, sizeof(dsa512_priv), NULL); - pub_key = BN_bin2bn(dsa512_pub, sizeof(dsa512_pub), NULL); - p = BN_bin2bn(dsa512_p, sizeof(dsa512_p), NULL); - q = BN_bin2bn(dsa512_q, sizeof(dsa512_q), NULL); - g = BN_bin2bn(dsa512_g, sizeof(dsa512_g), NULL); - if ((priv_key == NULL) || (pub_key == NULL) || (p == NULL) || (q == NULL) - || (g == NULL)) { - goto err; - } - if (!DSA_set0_pqg(dsa, p, q, g)) - goto err; - p = q = g = NULL; - - if (!DSA_set0_key(dsa, pub_key, priv_key)) - goto err; - - return dsa; - err: - DSA_free(dsa); - BN_free(priv_key); - BN_free(pub_key); - BN_free(p); - BN_free(q); - BN_free(g); - return NULL; -} - static unsigned char dsa1024_priv[] = { 0x7d, 0x21, 0xda, 0xbb, 0x62, 0x15, 0x47, 0x36, 0x07, 0x67, 0x12, 0xe8, 0x8c, 0xaa, 0x1c, 0xcd, 0x38, 0x12, 0x61, 0x18, @@ -135,40 +99,6 @@ static unsigned char dsa1024_g[] = { 0x6A, 0x7E, 0xD8, 0x32, 0xED, 0x0E, 0x02, 0xB8, }; -DSA *get_dsa1024() -{ - DSA *dsa; - BIGNUM *priv_key, *pub_key, *p, *q, *g; - - if ((dsa = DSA_new()) == NULL) - return (NULL); - priv_key = BN_bin2bn(dsa1024_priv, sizeof(dsa1024_priv), NULL); - pub_key = BN_bin2bn(dsa1024_pub, sizeof(dsa1024_pub), NULL); - p = BN_bin2bn(dsa1024_p, sizeof(dsa1024_p), NULL); - q = BN_bin2bn(dsa1024_q, sizeof(dsa1024_q), NULL); - g = BN_bin2bn(dsa1024_g, sizeof(dsa1024_g), NULL); - if ((priv_key == NULL) || (pub_key == NULL) || (p == NULL) || (q == NULL) - || (g == NULL)) { - goto err; - } - if (!DSA_set0_pqg(dsa, p, q, g)) - goto err; - p = q = g = NULL; - - if (!DSA_set0_key(dsa, pub_key, priv_key)) - goto err; - - return dsa; - err: - DSA_free(dsa); - BN_free(priv_key); - BN_free(pub_key); - BN_free(p); - BN_free(q); - BN_free(g); - return NULL; -} - static unsigned char dsa2048_priv[] = { 0x32, 0x67, 0x92, 0xf6, 0xc4, 0xe2, 0xe2, 0xe8, 0xa0, 0x8b, 0x6b, 0x45, 0x0c, 0x8a, 0x76, 0xb0, 0xee, 0xcf, 0x91, 0xa7, @@ -254,25 +184,66 @@ static unsigned char dsa2048_g[] = { 0xF8, 0xB2, 0xE5, 0x38, }; -DSA *get_dsa2048() +typedef struct testdsa_st { + unsigned char *priv; + unsigned char *pub; + unsigned char *p; + unsigned char *g; + unsigned char *q; + int priv_l; + int pub_l; + int p_l; + int g_l; + int q_l; +} testdsa; + +#define set_dsa_ptr(st, bits) \ + do { \ + st.priv = dsa##bits##_priv; \ + st.pub = dsa##bits##_pub; \ + st.p = dsa##bits##_p; \ + st.g = dsa##bits##_g; \ + st.q = dsa##bits##_q; \ + st.priv_l = sizeof(dsa##bits##_priv); \ + st.pub_l = sizeof(dsa##bits##_pub); \ + st.p_l = sizeof(dsa##bits##_p); \ + st.g_l = sizeof(dsa##bits##_g); \ + st.q_l = sizeof(dsa##bits##_q); \ + } while (0) + +DSA *get_dsa(int dsa_bits) { DSA *dsa; BIGNUM *priv_key, *pub_key, *p, *q, *g; + testdsa dsa_t; + + switch (dsa_bits) { + case 512: + set_dsa_ptr(dsa_t, 512); + break; + case 1024: + set_dsa_ptr(dsa_t, 1024); + break; + case 2048: + set_dsa_ptr(dsa_t, 2048); + break; + default: + return NULL; + } if ((dsa = DSA_new()) == NULL) - return (NULL); - priv_key = BN_bin2bn(dsa2048_priv, sizeof(dsa2048_priv), NULL); - pub_key = BN_bin2bn(dsa2048_pub, sizeof(dsa2048_pub), NULL); - p = BN_bin2bn(dsa2048_p, sizeof(dsa2048_p), NULL); - q = BN_bin2bn(dsa2048_q, sizeof(dsa2048_q), NULL); - g = BN_bin2bn(dsa2048_g, sizeof(dsa2048_g), NULL); + return NULL; + priv_key = BN_bin2bn(dsa_t.priv, dsa_t.priv_l, NULL); + pub_key = BN_bin2bn(dsa_t.pub, dsa_t.pub_l, NULL); + p = BN_bin2bn(dsa_t.p, dsa_t.p_l, NULL); + q = BN_bin2bn(dsa_t.q, dsa_t.q_l, NULL); + g = BN_bin2bn(dsa_t.g, dsa_t.g_l, NULL); if ((priv_key == NULL) || (pub_key == NULL) || (p == NULL) || (q == NULL) - || (g == NULL)) { + || (g == NULL)) { goto err; } if (!DSA_set0_pqg(dsa, p, q, g)) goto err; - p = q = g = NULL; if (!DSA_set0_key(dsa, pub_key, priv_key)) goto err; @@ -287,4 +258,3 @@ DSA *get_dsa2048() BN_free(g); return NULL; } - diff --git a/apps/ts.c b/apps/ts.c index 0e07c088..930c1daa 100644 --- a/apps/ts.c +++ b/apps/ts.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-2018 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 @@ -15,6 +15,7 @@ NON_EMPTY_TRANSLATION_UNIT # include # include # include "apps.h" +# include "progs.h" # include # include # include @@ -79,22 +80,21 @@ static int verify_cb(int ok, X509_STORE_CTX *ctx); typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE, OPT_CONFIG, OPT_SECTION, OPT_QUERY, OPT_DATA, - OPT_DIGEST, OPT_RAND, OPT_TSPOLICY, OPT_NO_NONCE, OPT_CERT, + OPT_DIGEST, OPT_TSPOLICY, OPT_NO_NONCE, OPT_CERT, OPT_IN, OPT_TOKEN_IN, OPT_OUT, OPT_TOKEN_OUT, OPT_TEXT, OPT_REPLY, OPT_QUERYFILE, OPT_PASSIN, OPT_INKEY, OPT_SIGNER, OPT_CHAIN, OPT_VERIFY, OPT_CAPATH, OPT_CAFILE, OPT_UNTRUSTED, - OPT_MD, OPT_V_ENUM + OPT_MD, OPT_V_ENUM, OPT_R_ENUM } OPTION_CHOICE; -OPTIONS ts_options[] = { +const OPTIONS ts_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"config", OPT_CONFIG, '<', "Configuration file"}, {"section", OPT_SECTION, 's', "Section to use within config file"}, {"query", OPT_QUERY, '-', "Generate a TS query"}, {"data", OPT_DATA, '<', "File to hash"}, {"digest", OPT_DIGEST, 's', "Digest (as a hex string)"}, - {"rand", OPT_RAND, 's', - "Load the file(s) into the random number generator"}, + OPT_R_OPTIONS, {"tspolicy", OPT_TSPOLICY, 's', "Policy OID to use"}, {"no_nonce", OPT_NO_NONCE, '-', "Do not include a nonce"}, {"cert", OPT_CERT, '-', "Put cert request into query"}, @@ -158,7 +158,7 @@ int ts_main(int argc, char **argv) const char *section = NULL; char **helpp; char *password = NULL; - char *data = NULL, *digest = NULL, *rnd = NULL, *policy = NULL; + char *data = NULL, *digest = NULL, *policy = NULL; char *in = NULL, *out = NULL, *queryfile = NULL, *passin = NULL; char *inkey = NULL, *signer = NULL, *chain = NULL, *CApath = NULL; const EVP_MD *md = NULL; @@ -207,8 +207,9 @@ int ts_main(int argc, char **argv) case OPT_DIGEST: digest = opt_arg(); break; - case OPT_RAND: - rnd = opt_arg(); + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; break; case OPT_TSPOLICY: policy = opt_arg(); @@ -275,16 +276,6 @@ int ts_main(int argc, char **argv) if (mode == OPT_ERR || opt_num_rest() != 0) goto opthelp; - /* Seed the random number generator if it is going to be used. */ - if (mode == OPT_QUERY && !no_nonce) { - if (!app_RAND_load_file(NULL, 1) && rnd == NULL) - BIO_printf(bio_err, "warning, not much extra random " - "data, consider using the -rand option\n"); - if (rnd != NULL) - BIO_printf(bio_err, "%ld semi-random bytes loaded\n", - app_RAND_load_files(rnd)); - } - if (mode == OPT_REPLY && passin && !app_passwd(passin, NULL, &password, NULL)) { BIO_printf(bio_err, "Error getting password.\n"); @@ -296,19 +287,14 @@ int ts_main(int argc, char **argv) goto end; /* Check parameter consistency and execute the appropriate function. */ - switch (mode) { - default: - case OPT_ERR: - goto opthelp; - case OPT_QUERY: + if (mode == OPT_QUERY) { if (vpmtouched) goto opthelp; if ((data != NULL) && (digest != NULL)) goto opthelp; ret = !query_command(data, digest, md, policy, no_nonce, cert, in, out, text); - break; - case OPT_REPLY: + } else if (mode == OPT_REPLY) { if (vpmtouched) goto opthelp; if ((in != NULL) && (queryfile != NULL)) @@ -320,21 +306,22 @@ int ts_main(int argc, char **argv) ret = !reply_command(conf, section, engine, queryfile, password, inkey, md, signer, chain, policy, in, token_in, out, token_out, text); - break; - case OPT_VERIFY: + + } else if (mode == OPT_VERIFY) { if ((in == NULL) || !EXACTLY_ONE(queryfile, data, digest)) goto opthelp; ret = !verify_command(data, digest, queryfile, in, token_in, CApath, CAfile, untrusted, vpmtouched ? vpm : NULL); + } else { + goto opthelp; } end: X509_VERIFY_PARAM_free(vpm); - app_RAND_write_file(NULL); NCONF_free(conf); OPENSSL_free(password); - return (ret); + return ret; } /* @@ -501,7 +488,7 @@ static int create_digest(BIO *input, const char *digest, const EVP_MD *md, if (md_value_len < 0) return 0; - if (input) { + if (input != NULL) { unsigned char buffer[4096]; int length; @@ -593,7 +580,7 @@ static int reply_command(CONF *conf, const char *section, const char *engine, } else { response = create_response(conf, section, engine, queryfile, passin, inkey, md, signer, chain, policy); - if (response) + if (response != NULL) BIO_printf(bio_err, "Response has been generated.\n"); else BIO_printf(bio_err, "Response is not generated.\n"); @@ -712,6 +699,8 @@ static TS_RESP *create_response(CONF *conf, const char *section, const char *eng goto end; } + if (!TS_CONF_set_ess_cert_id_digest(conf, section, resp_ctx)) + goto end; if (!TS_CONF_set_def_policy(conf, section, policy, resp_ctx)) goto end; if (!TS_CONF_set_policies(conf, section, resp_ctx)) @@ -747,13 +736,14 @@ static ASN1_INTEGER *serial_cb(TS_RESP_CTX *ctx, void *data) const char *serial_file = (const char *)data; ASN1_INTEGER *serial = next_serial(serial_file); - if (!serial) { + if (serial == NULL) { TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION, "Error during serial number " "generation."); TS_RESP_CTX_add_failure_info(ctx, TS_INFO_ADD_INFO_NOT_AVAILABLE); - } else + } else { save_ts_serial(serial_file, serial); + } return serial; } @@ -916,8 +906,9 @@ static TS_VERIFY_CTX *create_verify_ctx(const char *data, const char *digest, goto err; if ((ctx = TS_REQ_to_TS_VERIFY_CTX(request, NULL)) == NULL) goto err; - } else + } else { return NULL; + } /* Add the signature verification flag and arguments. */ TS_VERIFY_CTX_add_flags(ctx, f | TS_VFY_SIGNATURE); diff --git a/apps/tsget.in b/apps/tsget.in index c6193e57..71bcc245 100644 --- a/apps/tsget.in +++ b/apps/tsget.in @@ -1,6 +1,6 @@ #!{- $config{hashbangperl} -} -# Copyright (c) 2002 The OpenTSA Project. All rights reserved. # Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright (c) 2002 The OpenTSA Project. 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 diff --git a/apps/verify.c b/apps/verify.c index 0925ee62..5ad6ef41 100644 --- a/apps/verify.c +++ b/apps/verify.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -11,6 +11,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -27,11 +28,11 @@ typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, OPT_ENGINE, OPT_CAPATH, OPT_CAFILE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_UNTRUSTED, OPT_TRUSTED, OPT_CRLFILE, OPT_CRL_DOWNLOAD, OPT_SHOW_CHAIN, - OPT_V_ENUM, + OPT_V_ENUM, OPT_NAMEOPT, OPT_VERBOSE } OPTION_CHOICE; -OPTIONS verify_options[] = { +const OPTIONS verify_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] cert.pem...\n"}, {OPT_HELP_STR, 1, '-', "Valid options are:\n"}, {"help", OPT_HELP, '-', "Display this summary"}, @@ -51,6 +52,7 @@ OPTIONS verify_options[] = { "Attempt to download CRL information for this certificate"}, {"show_chain", OPT_SHOW_CHAIN, '-', "Display information about the certificate chain"}, + {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"}, OPT_V_OPTIONS, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, @@ -149,6 +151,10 @@ int verify_main(int argc, char **argv) case OPT_SHOW_CHAIN: show_chain = 1; break; + case OPT_NAMEOPT: + if (!set_nameopt(opt_arg())) + goto end; + break; case OPT_VERBOSE: v_verbose = 1; break; @@ -223,9 +229,9 @@ static int check(X509_STORE *ctx, const char *file, (file == NULL) ? "stdin" : file); goto end; } - if (tchain) + if (tchain != NULL) X509_STORE_CTX_set0_trusted_stack(csc, tchain); - if (crls) + if (crls != NULL) X509_STORE_CTX_set0_crls(csc, crls); i = X509_verify_cert(csc); if (i > 0 && X509_STORE_CTX_get_error(csc) == X509_V_OK) { @@ -242,7 +248,7 @@ static int check(X509_STORE *ctx, const char *file, printf("depth=%d: ", j); X509_NAME_print_ex_fp(stdout, X509_get_subject_name(cert), - 0, XN_FLAG_ONELINE); + 0, get_nameopt()); if (j < num_untrusted) printf(" (untrusted)"); printf("\n"); @@ -268,10 +274,10 @@ static int cb(int ok, X509_STORE_CTX *ctx) X509 *current_cert = X509_STORE_CTX_get_current_cert(ctx); if (!ok) { - if (current_cert) { + if (current_cert != NULL) { X509_NAME_print_ex(bio_err, X509_get_subject_name(current_cert), - 0, XN_FLAG_ONELINE); + 0, get_nameopt()); BIO_printf(bio_err, "\n"); } BIO_printf(bio_err, "%serror %d at %d depth lookup: %s\n", @@ -308,5 +314,5 @@ static int cb(int ok, X509_STORE_CTX *ctx) policies_print(ctx); if (!v_verbose) ERR_clear_error(); - return (ok); + return ok; } diff --git a/apps/version.c b/apps/version.c index 2f8be364..0ff0299d 100644 --- a/apps/version.c +++ b/apps/version.c @@ -11,6 +11,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -32,10 +33,10 @@ typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, - OPT_B, OPT_D, OPT_E, OPT_F, OPT_O, OPT_P, OPT_V, OPT_A + OPT_B, OPT_D, OPT_E, OPT_F, OPT_O, OPT_P, OPT_V, OPT_A, OPT_R } OPTION_CHOICE; -OPTIONS version_options[] = { +const OPTIONS version_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"a", OPT_A, '-', "Show all data"}, {"b", OPT_B, '-', "Show build date"}, @@ -44,13 +45,24 @@ OPTIONS version_options[] = { {"f", OPT_F, '-', "Show compiler flags used"}, {"o", OPT_O, '-', "Show some internal datatype options"}, {"p", OPT_P, '-', "Show target build platform"}, + {"r", OPT_R, '-', "Show random seeding options"}, {"v", OPT_V, '-', "Show library version"}, {NULL} }; +#if defined(OPENSSL_RAND_SEED_DEVRANDOM) || defined(OPENSSL_RAND_SEED_EGD) +static void printlist(const char *prefix, const char **dev) +{ + printf("%s (", prefix); + for ( ; *dev != NULL; dev++) + printf(" \"%s\"", *dev); + printf(" )"); +} +#endif + int version_main(int argc, char **argv) { - int ret = 1, dirty = 0; + int ret = 1, dirty = 0, seed = 0; int cflags = 0, version = 0, date = 0, options = 0, platform = 0, dir = 0; int engdir = 0; char *prog; @@ -86,11 +98,14 @@ opthelp: case OPT_P: dirty = platform = 1; break; + case OPT_R: + dirty = seed = 1; + break; case OPT_V: dirty = version = 1; break; case OPT_A: - options = cflags = version = date = platform = dir = engdir = 1; + seed = cflags = version = date = platform = dir = engdir = 1; break; } } @@ -102,12 +117,11 @@ opthelp: version = 1; if (version) { - if (OpenSSL_version_num() == OPENSSL_VERSION_NUMBER) { + if (OpenSSL_version_num() == OPENSSL_VERSION_NUMBER) printf("%s\n", OpenSSL_version(OPENSSL_VERSION)); - } else { + else printf("%s (Library: %s)\n", OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION)); - } } if (date) printf("%s\n", OpenSSL_version(OPENSSL_BUILT_ON)); @@ -139,7 +153,41 @@ opthelp: printf("%s\n", OpenSSL_version(OPENSSL_DIR)); if (engdir) printf("%s\n", OpenSSL_version(OPENSSL_ENGINES_DIR)); + if (seed) { + printf("Seeding source:"); +#ifdef OPENSSL_RAND_SEED_RTDSC + printf(" rtdsc"); +#endif +#ifdef OPENSSL_RAND_SEED_RDCPU + printf(" rdrand ( rdseed rdrand )"); +#endif +#ifdef OPENSSL_RAND_SEED_LIBRANDOM + printf(" C-library-random"); +#endif +#ifdef OPENSSL_RAND_SEED_GETRANDOM + printf(" getrandom-syscall"); +#endif +#ifdef OPENSSL_RAND_SEED_DEVRANDOM + { + static const char *dev[] = { DEVRANDOM, NULL }; + printlist(" random-device", dev); + } +#endif +#ifdef OPENSSL_RAND_SEED_EGD + { + static const char *dev[] = { DEVRANDOM_EGD, NULL }; + printlist(" EGD", dev); + } +#endif +#ifdef OPENSSL_RAND_SEED_NONE + printf(" none"); +#endif +#ifdef OPENSSL_RAND_SEED_OS + printf(" os-specific"); +#endif + printf("\n"); + } ret = 0; end: - return (ret); + return ret; } diff --git a/apps/vms_term_sock.c b/apps/vms_term_sock.c index bc0c173e..9a90a1e7 100644 --- a/apps/vms_term_sock.c +++ b/apps/vms_term_sock.c @@ -1,4 +1,5 @@ /* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2016 VMS Software, Inc. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use @@ -183,7 +184,7 @@ int TerminalSocket (int FunctionCode, int *ReturnSocket) close (TerminalSocketPair[0]); if (TerminalSocketPair[1]) close (TerminalSocketPair[1]); - return (TERM_SOCK_FAILURE); + return TERM_SOCK_FAILURE; } /* @@ -196,7 +197,7 @@ int TerminalSocket (int FunctionCode, int *ReturnSocket) LogMessage ("TerminalSocket: SYS$ASSIGN () - %08X", status); close (TerminalSocketPair[0]); close (TerminalSocketPair[1]); - return (TERM_SOCK_FAILURE); + return TERM_SOCK_FAILURE; } /* @@ -215,7 +216,7 @@ int TerminalSocket (int FunctionCode, int *ReturnSocket) LogMessage ("TerminalSocket: SYS$QIO () - %08X", status); close (TerminalSocketPair[0]); close (TerminalSocketPair[1]); - return (TERM_SOCK_FAILURE); + return TERM_SOCK_FAILURE; } /* @@ -233,7 +234,7 @@ int TerminalSocket (int FunctionCode, int *ReturnSocket) LogMessage ("TerminalSocket: SYS$CANCEL () - %08X", status); close (TerminalSocketPair[0]); close (TerminalSocketPair[1]); - return (TERM_SOCK_FAILURE); + return TERM_SOCK_FAILURE; } /* @@ -244,7 +245,7 @@ int TerminalSocket (int FunctionCode, int *ReturnSocket) LogMessage ("TerminalSocket: SYS$DASSGN () - %08X", status); close (TerminalSocketPair[0]); close (TerminalSocketPair[1]); - return (TERM_SOCK_FAILURE); + return TERM_SOCK_FAILURE; } /* @@ -264,14 +265,14 @@ int TerminalSocket (int FunctionCode, int *ReturnSocket) ** Invalid function code */ LogMessage ("TerminalSocket: Invalid Function Code - %d", FunctionCode); - return (TERM_SOCK_FAILURE); + return TERM_SOCK_FAILURE; break; } /* ** Return success */ - return (TERM_SOCK_SUCCESS); + return TERM_SOCK_SUCCESS; } @@ -311,7 +312,7 @@ static int CreateSocketPair (int SocketFamily, SockDesc1 = socket (SocketFamily, SocketType, 0); if (SockDesc1 < 0) { LogMessage ("CreateSocketPair: socket () - %d", errno); - return (-1); + return -1; } /* @@ -330,7 +331,7 @@ static int CreateSocketPair (int SocketFamily, if (status < 0) { LogMessage ("CreateSocketPair: bind () - %d", errno); close (SockDesc1); - return (-1); + return -1; } /* @@ -340,7 +341,7 @@ static int CreateSocketPair (int SocketFamily, if (status < 0) { LogMessage ("CreateSocketPair: getsockname () - %d", errno); close (SockDesc1); - return (-1); + return -1; } else LocalHostPort = sin.sin_port; @@ -359,7 +360,7 @@ static int CreateSocketPair (int SocketFamily, if (! (status & 1)) { LogMessage ("CreateSocketPair: SYS$BINTIM () - %08X", status); close (SockDesc1); - return (-1); + return -1; } /* @@ -370,7 +371,7 @@ static int CreateSocketPair (int SocketFamily, if (! (status & 1)) { LogMessage ("CreateSocketPair: SYS$ASSIGN () - %08X", status); close (SockDesc1); - return (-1); + return -1; } /* @@ -392,7 +393,7 @@ static int CreateSocketPair (int SocketFamily, LogMessage ("CreateSocketPair: SYS$QIO () - %08X", status); close (SockDesc1); sys$dassgn (TcpDeviceChan); - return (-1); + return -1; } /* @@ -428,7 +429,7 @@ static int CreateSocketPair (int SocketFamily, close (SockDesc1); close (SockDesc2); sys$dassgn (TcpDeviceChan); - return (-1); + return -1; } /* @@ -447,7 +448,7 @@ static int CreateSocketPair (int SocketFamily, close (SockDesc1); close (SockDesc2); sys$dassgn (TcpDeviceChan); - return (-1); + return -1; } /* @@ -467,7 +468,7 @@ static int CreateSocketPair (int SocketFamily, close (SockDesc1); close (SockDesc2); sys$dassgn (TcpDeviceChan); - return (-1); + return -1; } /* @@ -513,7 +514,7 @@ static int TerminalDeviceAst (int astparm) strcat (TerminalDeviceBuff, "\n"); /* - ** Send the data read from the terminal device throught the socket pair + ** Send the data read from the terminal device through the socket pair */ send (TerminalSocketPair[0], TerminalDeviceBuff, TerminalDeviceIosb.iosb$w_bcnt + 1, 0); diff --git a/apps/vms_term_sock.h b/apps/vms_term_sock.h index 662fa0ad..c4d1702d 100644 --- a/apps/vms_term_sock.h +++ b/apps/vms_term_sock.h @@ -1,4 +1,5 @@ /* + * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2016 VMS Software, Inc. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use diff --git a/apps/win32_init.c b/apps/win32_init.c index ebe92bcd..df4bff41 100644 --- a/apps/win32_init.c +++ b/apps/win32_init.c @@ -302,6 +302,6 @@ void win32_utf8argv(int *argc, char **argv[]) return; } #else -void win32_utf8argv(int &argc, char **argv[]) +void win32_utf8argv(int *argc, char **argv[]) { return; } #endif diff --git a/apps/x509.c b/apps/x509.c index 7a66ea66..1bb9ceff 100644 --- a/apps/x509.c +++ b/apps/x509.c @@ -11,6 +11,7 @@ #include #include #include "apps.h" +#include "progs.h" #include #include #include @@ -33,13 +34,16 @@ static int 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, const char *section); + const EVP_MD *digest, CONF *conf, const char *section, + int preserve_dates); static int x509_certify(X509_STORE *ctx, const char *CAfile, const EVP_MD *digest, X509 *x, X509 *xca, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *sigopts, const char *serialfile, int create, int days, int clrext, CONF *conf, - const char *section, ASN1_INTEGER *sno, int reqfile); + const char *section, ASN1_INTEGER *sno, int reqfile, + int preserve_dates); static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt); +static int print_x509v3_exts(BIO *bio, X509 *x, const char *exts); typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, @@ -56,10 +60,11 @@ typedef enum OPTION_choice { OPT_CLRREJECT, OPT_ALIAS, OPT_CACREATESERIAL, OPT_CLREXT, OPT_OCSPID, OPT_SUBJECT_HASH_OLD, OPT_ISSUER_HASH_OLD, - OPT_BADSIG, OPT_MD, OPT_ENGINE, OPT_NOCERT + OPT_BADSIG, OPT_MD, OPT_ENGINE, OPT_NOCERT, OPT_PRESERVE_DATES, + OPT_R_ENUM, OPT_EXT } OPTION_CHOICE; -OPTIONS x509_options[] = { +const OPTIONS x509_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"inform", OPT_INFORM, 'f', "Input format - default PEM (one of DER, NET or PEM)"}, @@ -114,8 +119,10 @@ OPTIONS x509_options[] = { {"CAserial", OPT_CASERIAL, 's', "Serial file"}, {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"}, {"text", OPT_TEXT, '-', "Print the certificate in text form"}, + {"ext", OPT_EXT, 's', "Print various X509V3 extensions"}, {"C", OPT_C, '-', "Print out C code forms"}, {"extfile", OPT_EXTFILE, '<', "File with X509V3 extensions to add"}, + OPT_R_OPTIONS, {"extensions", OPT_EXTENSIONS, 's', "Section from config file to use"}, {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"}, {"certopt", OPT_CERTOPT, 's', "Various certificate text options"}, @@ -140,6 +147,7 @@ OPTIONS x509_options[] = { #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif + {"preserve_dates", OPT_PRESERVE_DATES, '-', "preserve existing dates when signing"}, {NULL} }; @@ -157,23 +165,23 @@ int x509_main(int argc, char **argv) X509_STORE *ctx = NULL; const EVP_MD *digest = NULL; char *CAkeyfile = NULL, *CAserial = NULL, *fkeyfile = NULL, *alias = NULL; - char *checkhost = NULL, *checkemail = NULL, *checkip = NULL; + char *checkhost = NULL, *checkemail = NULL, *checkip = NULL, *exts = NULL; char *extsect = NULL, *extfile = NULL, *passin = NULL, *passinarg = NULL; char *infile = NULL, *outfile = NULL, *keyfile = NULL, *CAfile = NULL; - char buf[256], *prog; + char *prog; int x509req = 0, days = DEF_DAYS, modulus = 0, pubkey = 0, pprint = 0; int C = 0, CAformat = FORMAT_PEM, CAkeyformat = FORMAT_PEM; - int fingerprint = 0, reqfile = 0, need_rand = 0, checkend = 0; + int fingerprint = 0, reqfile = 0, checkend = 0; int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyformat = FORMAT_PEM; int next_serial = 0, subject_hash = 0, issuer_hash = 0, ocspid = 0; int noout = 0, sign_flag = 0, CA_flag = 0, CA_createserial = 0, email = 0; int ocsp_uri = 0, trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0; int ret = 1, i, num = 0, badsig = 0, clrext = 0, nocert = 0; - int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0; + int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0, ext = 0; int enddate = 0; time_t checkoffset = 0; - unsigned long nmflag = 0, certflag = 0; - char nmflag_set = 0; + unsigned long certflag = 0; + int preserve_dates = 0; OPTION_CHOICE o; ENGINE *e = NULL; #ifndef OPENSSL_NO_MD5 @@ -224,7 +232,7 @@ int x509_main(int argc, char **argv) outfile = opt_arg(); break; case OPT_REQ: - reqfile = need_rand = 1; + reqfile = 1; break; case OPT_SIGOPT: @@ -234,6 +242,8 @@ int x509_main(int argc, char **argv) goto opthelp; break; case OPT_DAYS: + if (preserve_dates) + goto opthelp; days = atoi(opt_arg()); break; case OPT_PASSIN: @@ -242,18 +252,20 @@ int x509_main(int argc, char **argv) case OPT_EXTFILE: extfile = opt_arg(); break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; case OPT_EXTENSIONS: extsect = opt_arg(); break; case OPT_SIGNKEY: keyfile = opt_arg(); sign_flag = ++num; - need_rand = 1; break; case OPT_CA: CAfile = opt_arg(); CA_flag = ++num; - need_rand = 1; break; case OPT_CAKEY: CAkeyfile = opt_arg(); @@ -308,8 +320,7 @@ int x509_main(int argc, char **argv) goto opthelp; break; case OPT_NAMEOPT: - nmflag_set = 1; - if (!set_name_ex(&nmflag, opt_arg())) + if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_ENGINE: @@ -369,6 +380,10 @@ int x509_main(int argc, char **argv) case OPT_NOOUT: noout = ++num; break; + case OPT_EXT: + ext = ++num; + exts = opt_arg(); + break; case OPT_NOCERT: nocert = 1; break; @@ -435,6 +450,11 @@ int x509_main(int argc, char **argv) case OPT_CHECKIP: checkip = opt_arg(); break; + case OPT_PRESERVE_DATES: + if (days != DEF_DAYS) + goto opthelp; + preserve_dates = 1; + break; case OPT_MD: if (!opt_md(opt_unknown(), &digest)) goto opthelp; @@ -447,11 +467,9 @@ int x509_main(int argc, char **argv) goto opthelp; } - if (!nmflag_set) - nmflag = XN_FLAG_ONELINE; - - if (need_rand) - app_RAND_load_file(NULL, 0); + out = bio_open_default(outfile, 'w', outformat); + if (out == NULL) + goto end; if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); @@ -463,7 +481,7 @@ int x509_main(int argc, char **argv) goto end; } - if (fkeyfile) { + if (fkeyfile != NULL) { fkey = load_pubkey(fkeyfile, keyformat, 0, NULL, e, "Forced key"); if (fkey == NULL) goto end; @@ -477,13 +495,13 @@ int x509_main(int argc, char **argv) goto end; } - if (extfile) { + if (extfile != NULL) { X509V3_CTX ctx2; if ((extconf = app_load_config(extfile)) == NULL) goto end; - if (!extsect) { + if (extsect == NULL) { extsect = NCONF_get_string(extconf, "default", "extensions"); - if (!extsect) { + if (extsect == NULL) { ERR_clear_error(); extsect = "default"; } @@ -531,11 +549,12 @@ int x509_main(int argc, char **argv) BIO_printf(bio_err, "Signature did not match the certificate request\n"); goto end; - } else + } else { BIO_printf(bio_err, "Signature ok\n"); + } print_name(bio_err, "subject=", X509_REQ_get_subject_name(req), - nmflag); + get_nameopt()); if ((x = X509_new()) == NULL) goto end; @@ -548,8 +567,9 @@ int x509_main(int argc, char **argv) goto end; ASN1_INTEGER_free(sno); sno = NULL; - } else if (!X509_set_serialNumber(x, sno)) + } else if (!X509_set_serialNumber(x, sno)) { goto end; + } if (!X509_set_issuer_name(x, X509_REQ_get_subject_name(req))) goto end; @@ -558,14 +578,15 @@ int x509_main(int argc, char **argv) if (!set_cert_times(x, NULL, NULL, days)) goto end; - if (fkey) + if (fkey != NULL) { X509_set_pubkey(x, fkey); - else { + } else { pkey = X509_REQ_get0_pubkey(req); X509_set_pubkey(x, pkey); } - } else + } else { x = load_cert(infile, informat, "Certificate"); + } if (x == NULL) goto end; @@ -575,13 +596,11 @@ int x509_main(int argc, char **argv) goto end; } - out = bio_open_default(outfile, 'w', outformat); - if (out == NULL) - goto end; - - if (!noout || text || next_serial) + if (!noout || text || next_serial) { OBJ_create("2.99999.3", "SET.ex3", "SET x509v3 extension 3"); + } + if (alias) X509_alias_set1(x, (unsigned char *)alias, -1); @@ -590,7 +609,7 @@ int x509_main(int argc, char **argv) if (clrreject) X509_reject_clear(x); - if (trust) { + if (trust != NULL) { for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) { objtmp = sk_ASN1_OBJECT_value(trust, i); X509_add1_trust_object(x, objtmp); @@ -598,7 +617,7 @@ int x509_main(int argc, char **argv) objtmp = NULL; } - if (reject) { + if (reject != NULL) { for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) { objtmp = sk_ASN1_OBJECT_value(reject, i); X509_add1_reject_object(x, objtmp); @@ -616,10 +635,10 @@ int x509_main(int argc, char **argv) if (num) { for (i = 1; i <= num; i++) { if (issuer == i) { - print_name(out, "issuer=", X509_get_issuer_name(x), nmflag); + print_name(out, "issuer=", X509_get_issuer_name(x), get_nameopt()); } else if (subject == i) { print_name(out, "subject=", - X509_get_subject_name(x), nmflag); + X509_get_subject_name(x), get_nameopt()); } else if (serial == i) { BIO_printf(out, "serial="); i2a_ASN1_INTEGER(out, X509_get_serialNumber(x)); @@ -724,13 +743,10 @@ int x509_main(int argc, char **argv) char *m; int len; - X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf)); - BIO_printf(out, "/*\n" - " * Subject: %s\n", buf); - - X509_NAME_oneline(X509_get_issuer_name(x), buf, sizeof(buf)); - BIO_printf(out, " * Issuer: %s\n" - " */\n", buf); + print_name(out, "/*\n" + " * Subject: ", X509_get_subject_name(x), get_nameopt()); + print_name(out, " * Issuer: ", X509_get_issuer_name(x), get_nameopt()); + BIO_puts(out, " */\n"); len = i2d_X509(x, NULL); m = app_malloc(len, "x509 name buffer"); @@ -745,7 +761,7 @@ int x509_main(int argc, char **argv) print_array(out, "the_certificate", len, (unsigned char *)m); OPENSSL_free(m); } else if (text == i) { - X509_print_ex(out, x, nmflag, certflag); + X509_print_ex(out, x, get_nameopt(), certflag); } else if (startdate == i) { BIO_puts(out, "notBefore="); ASN1_TIME_print(out, X509_get0_notBefore(x)); @@ -760,7 +776,7 @@ int x509_main(int argc, char **argv) unsigned char md[EVP_MAX_MD_SIZE]; const EVP_MD *fdig = digest; - if (!fdig) + if (fdig == NULL) fdig = EVP_sha1(); if (!X509_digest(x, fdig, md, &n)) { @@ -785,8 +801,7 @@ int x509_main(int argc, char **argv) goto end; } - assert(need_rand); - if (!sign(x, Upkey, days, clrext, digest, extconf, extsect)) + if (!sign(x, Upkey, days, clrext, digest, extconf, extsect, preserve_dates)) goto end; } else if (CA_flag == i) { BIO_printf(bio_err, "Getting CA Private Key\n"); @@ -797,11 +812,10 @@ int x509_main(int argc, char **argv) goto end; } - assert(need_rand); if (!x509_certify(ctx, CAfile, digest, x, xca, CApkey, sigopts, CAserial, CA_createserial, days, clrext, - extconf, extsect, sno, reqfile)) + extconf, extsect, sno, reqfile, preserve_dates)) goto end; } else if (x509req == i) { EVP_PKEY *pk; @@ -826,12 +840,14 @@ int x509_main(int argc, char **argv) goto end; } if (!noout) { - X509_REQ_print(out, rq); + X509_REQ_print_ex(out, rq, get_nameopt(), X509_FLAG_COMPAT); PEM_write_bio_X509_REQ(out, rq); } noout = 1; } else if (ocspid == i) { X509_ocspid_print(out, x); + } else if (ext == i) { + print_x509v3_exts(out, x, exts); } } } @@ -856,9 +872,9 @@ int x509_main(int argc, char **argv) goto end; } - if (outformat == FORMAT_ASN1) + if (outformat == FORMAT_ASN1) { i = i2d_X509_bio(out, x); - else if (outformat == FORMAT_PEM) { + } else if (outformat == FORMAT_PEM) { if (trustout) i = PEM_write_bio_X509_AUX(out, x); else @@ -874,8 +890,6 @@ int x509_main(int argc, char **argv) } ret = 0; end: - if (need_rand) - app_RAND_write_file(NULL); NCONF_free(extconf); BIO_free_all(out); X509_STORE_free(ctx); @@ -893,33 +907,27 @@ int x509_main(int argc, char **argv) ASN1_OBJECT_free(objtmp); release_engine(e); OPENSSL_free(passin); - return (ret); + return ret; } -static ASN1_INTEGER *x509_load_serial(const char *CAfile, const char *serialfile, - int create) +static ASN1_INTEGER *x509_load_serial(const char *CAfile, + const char *serialfile, int create) { - char *buf = NULL, *p; + char *buf = NULL; ASN1_INTEGER *bs = NULL; BIGNUM *serial = NULL; - size_t len; - len = ((serialfile == NULL) - ? (strlen(CAfile) + strlen(POSTFIX) + 1) - : (strlen(serialfile))) + 1; - buf = app_malloc(len, "serial# buffer"); if (serialfile == NULL) { - OPENSSL_strlcpy(buf, CAfile, len); - for (p = buf; *p; p++) - if (*p == '.') { - *p = '\0'; - break; - } - OPENSSL_strlcat(buf, POSTFIX, len); - } else - OPENSSL_strlcpy(buf, serialfile, len); + const char *p = strchr(CAfile, '.'); + size_t len = p != NULL ? (size_t)(p - CAfile) : strlen(CAfile); - serial = load_serial(buf, create, NULL); + buf = app_malloc(len + sizeof(POSTFIX), "serial# buffer"); + memcpy(buf, CAfile, len); + memcpy(buf + len, POSTFIX, sizeof(POSTFIX)); + serialfile = buf; + } + + serial = load_serial(serialfile, create, NULL); if (serial == NULL) goto end; @@ -928,7 +936,7 @@ static ASN1_INTEGER *x509_load_serial(const char *CAfile, const char *serialfile goto end; } - if (!save_serial(buf, NULL, serial, &bs)) + if (!save_serial(serialfile, NULL, serial, &bs)) goto end; end: @@ -942,7 +950,7 @@ static int x509_certify(X509_STORE *ctx, const char *CAfile, const EVP_MD *diges STACK_OF(OPENSSL_STRING) *sigopts, const char *serialfile, int create, int days, int clrext, CONF *conf, const char *section, - ASN1_INTEGER *sno, int reqfile) + ASN1_INTEGER *sno, int reqfile, int preserve_dates) { int ret = 0; ASN1_INTEGER *bs = NULL; @@ -986,7 +994,7 @@ static int x509_certify(X509_STORE *ctx, const char *CAfile, const EVP_MD *diges if (!X509_set_serialNumber(x, bs)) goto end; - if (!set_cert_times(x, NULL, NULL, days)) + if (!preserve_dates && !set_cert_times(x, NULL, NULL, days)) goto end; if (clrext) { @@ -994,7 +1002,7 @@ static int x509_certify(X509_STORE *ctx, const char *CAfile, const EVP_MD *diges X509_delete_ext(x, 0); } - if (conf) { + if (conf != NULL) { X509V3_CTX ctx2; X509_set_version(x, 2); /* version 3 certificate */ X509V3_set_ctx(&ctx2, xca, x, NULL, NULL, 0); @@ -1050,12 +1058,13 @@ static int callb(int ok, X509_STORE_CTX *ctx) /* self sign */ static int sign(X509 *x, EVP_PKEY *pkey, int days, int clrext, - const EVP_MD *digest, CONF *conf, const char *section) + const EVP_MD *digest, CONF *conf, const char *section, + int preserve_dates) { if (!X509_set_issuer_name(x, X509_get_subject_name(x))) goto err; - if (!set_cert_times(x, NULL, NULL, days)) + if (!preserve_dates && !set_cert_times(x, NULL, NULL, days)) goto err; if (!X509_set_pubkey(x, pkey)) goto err; @@ -1063,7 +1072,7 @@ static int sign(X509 *x, EVP_PKEY *pkey, int days, int clrext, while (X509_get_ext_count(x) > 0) X509_delete_ext(x, 0); } - if (conf) { + if (conf != NULL) { X509V3_CTX ctx; X509_set_version(x, 2); /* version 3 certificate */ X509V3_set_ctx(&ctx, x, x, NULL, NULL, 0); @@ -1097,3 +1106,93 @@ static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt) } return 1; } + +static int parse_ext_names(char *names, const char **result) +{ + char *p, *q; + int cnt = 0, len = 0; + + p = q = names; + len = strlen(names); + + while (q - names <= len) { + if (*q != ',' && *q != '\0') { + q++; + continue; + } + if (p != q) { + /* found */ + if (result != NULL) { + result[cnt] = p; + *q = '\0'; + } + cnt++; + } + p = ++q; + } + + return cnt; +} + +static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names) +{ + const STACK_OF(X509_EXTENSION) *exts = NULL; + STACK_OF(X509_EXTENSION) *exts2 = NULL; + X509_EXTENSION *ext = NULL; + ASN1_OBJECT *obj; + int i, j, ret = 0, num, nn = 0; + const char *sn, **names = NULL; + char *tmp_ext_names = NULL; + + exts = X509_get0_extensions(x); + if ((num = sk_X509_EXTENSION_num(exts)) <= 0) { + BIO_printf(bio, "No extensions in certificate\n"); + ret = 1; + goto end; + } + + /* parse comma separated ext name string */ + if ((tmp_ext_names = OPENSSL_strdup(ext_names)) == NULL) + goto end; + if ((nn = parse_ext_names(tmp_ext_names, NULL)) == 0) { + BIO_printf(bio, "Invalid extension names: %s\n", ext_names); + goto end; + } + if ((names = OPENSSL_malloc(sizeof(char *) * nn)) == NULL) + goto end; + parse_ext_names(tmp_ext_names, names); + + for (i = 0; i < num; i++) { + ext = sk_X509_EXTENSION_value(exts, i); + + /* check if this ext is what we want */ + obj = X509_EXTENSION_get_object(ext); + sn = OBJ_nid2sn(OBJ_obj2nid(obj)); + if (sn == NULL || strcmp(sn, "UNDEF") == 0) + continue; + + for (j = 0; j < nn; j++) { + if (strcmp(sn, names[j]) == 0) { + /* push the extension into a new stack */ + if (exts2 == NULL + && (exts2 = sk_X509_EXTENSION_new_null()) == NULL) + goto end; + if (!sk_X509_EXTENSION_push(exts2, ext)) + goto end; + } + } + } + + if (!sk_X509_EXTENSION_num(exts2)) { + BIO_printf(bio, "No extensions matched with %s\n", ext_names); + ret = 1; + goto end; + } + + ret = X509V3_extensions_print(bio, NULL, exts2, 0, 0); + end: + sk_X509_EXTENSION_free(exts2); + OPENSSL_free(names); + OPENSSL_free(tmp_ext_names); + return ret; +} diff --git a/appveyor.yml b/appveyor.yml index 8dd6cb6f..5074a311 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,45 +1,65 @@ platform: - - x86 - x64 + - x86 environment: + fast_finish: true matrix: - VSVER: 14 configuration: - - plain - shared + - plain before_build: - ps: >- If ($env:Platform -Match "x86") { $env:VCVARS_PLATFORM="x86" - $env:TARGET="VC-WIN32" + $env:TARGET="VC-WIN32 no-asm" } Else { $env:VCVARS_PLATFORM="amd64" - $env:TARGET="VC-WIN64A" + $env:TARGET="VC-WIN64A-masm" } - ps: >- If ($env:Configuration -Match "shared") { - $env:SHARED="" + $env:SHARED="no-makedepend" } Else { - $env:SHARED="no-shared" + $env:SHARED="no-shared no-makedepend" } - ps: $env:VSCOMNTOOLS=(Get-Content ("env:VS" + "$env:VSVER" + "0COMNTOOLS")) - call "%VSCOMNTOOLS%\..\..\VC\vcvarsall.bat" %VCVARS_PLATFORM% - mkdir _build - cd _build - - perl ..\Configure %TARGET% no-asm %SHARED% + - perl ..\Configure %TARGET% %SHARED% + - perl configdata.pm --dump - cd .. + - ps: >- + if (-not $env:APPVEYOR_PULL_REQUEST_NUMBER` + -or (&git log -2 | Select-String "\[extended tests\]") ) { + $env:EXTENDED_TESTS="yes" + } build_script: - cd _build - - nmake + - ps: >- + If ($env:Configuration -Match "shared" -or $env:EXTENDED_TESTS) { + cmd /c "nmake 2>&1" + } - cd .. test_script: - cd _build - - nmake test - - mkdir ..\_install - - nmake install install_docs DESTDIR=..\_install + - ps: >- + If ($env:Configuration -Match "shared" -or $env:EXTENDED_TESTS) { + if ($env:EXTENDED_TESTS) { + cmd /c "nmake test V=1 2>&1" + } Else { + cmd /c "nmake test V=1 TESTS=-test_fuzz 2>&1" + } + } + - ps: >- + if ($env:EXTENDED_TESTS) { + mkdir ..\_install + cmd /c "nmake install install_docs DESTDIR=..\_install 2>&1" + } - cd .. diff --git a/build.info b/build.info index fa136dc4..13ca90d3 100644 --- a/build.info +++ b/build.info @@ -1,6 +1,14 @@ +{- + our $sover = $config{shlib_version_number}; + our $sover_filename = $sover; + $sover_filename =~ s|\.|_|g + if $config{target} =~ /^mingw/ || $config{target} =~ /^VC-/; + $sover_filename = + sprintf "%02d%02d", split m|\.|, $config{shlib_version_number} + if $config{target} =~ /^vms/; + ""; +-} LIBS=libcrypto libssl -ORDINALS[libcrypto]=crypto -ORDINALS[libssl]=ssl INCLUDE[libcrypto]=. crypto/include include INCLUDE[libssl]=. include DEPEND[libssl]=libcrypto @@ -16,16 +24,62 @@ GENERATE[crypto/include/internal/bn_conf.h]=crypto/include/internal/bn_conf.h.in DEPEND[crypto/include/internal/dso_conf.h]=configdata.pm GENERATE[crypto/include/internal/dso_conf.h]=crypto/include/internal/dso_conf.h.in +IF[{- defined $target{shared_defflag} -}] + IF[{- $config{target} =~ /^mingw/ -}] + GENERATE[libcrypto.def]=util/mkdef.pl crypto 32 + DEPEND[libcrypto.def]=util/libcrypto.num + GENERATE[libssl.def]=util/mkdef.pl ssl 32 + DEPEND[libssl.def]=util/libssl.num + + SHARED_SOURCE[libcrypto]=libcrypto.def + SHARED_SOURCE[libssl]=libssl.def + ELSE + GENERATE[libcrypto.map]=util/mkdef.pl crypto linux + DEPEND[libcrypto.map]=util/libcrypto.num + GENERATE[libssl.map]=util/mkdef.pl ssl linux + DEPEND[libssl.map]=util/libssl.num + + SHARED_SOURCE[libcrypto]=libcrypto.map + SHARED_SOURCE[libssl]=libssl.map + ENDIF +ENDIF +# VMS and VC don't have parametrised .def / .symvec generation, so they get +# special treatment, since we know they do use these files +IF[{- $config{target} =~ /^VC-/ -}] + GENERATE[libcrypto.def]=util/mkdef.pl crypto 32 + DEPEND[libcrypto.def]=util/libcrypto.num + GENERATE[libssl.def]=util/mkdef.pl ssl 32 + DEPEND[libssl.def]=util/libssl.num + + SHARED_SOURCE[libcrypto]=libcrypto.def + SHARED_SOURCE[libssl]=libssl.def +ELSIF[{- $config{target} =~ /^vms/ -}] + GENERATE[libcrypto.opt]=util/mkdef.pl crypto "VMS" + DEPEND[libcrypto.opt]=util/libcrypto.num + GENERATE[libssl.opt]=util/mkdef.pl ssl "VMS" + DEPEND[libssl.opt]=util/libssl.num + + SHARED_SOURCE[libcrypto]=libcrypto.opt + SHARED_SOURCE[libssl]=libssl.opt +ENDIF + +IF[{- $config{target} =~ /^(?:Cygwin|mingw|VC-)/ -}] + GENERATE[libcrypto.rc]=util/mkrc.pl libcrypto + GENERATE[libssl.rc]=util/mkrc.pl libssl + + SHARED_SOURCE[libcrypto]=libcrypto.rc + SHARED_SOURCE[libssl]=libssl.rc +ENDIF IF[{- $config{target} =~ /^Cygwin/ -}] - SHARED_NAME[libcrypto]=cygcrypto-{- $config{shlib_major}.".".$config{shlib_minor} -} - SHARED_NAME[libssl]=cygssl-{- $config{shlib_major}.".".$config{shlib_minor} -} + SHARED_NAME[libcrypto]=cygcrypto-{- $sover_filename -} + SHARED_NAME[libssl]=cygssl-{- $sover_filename -} ELSIF[{- $config{target} =~ /^mingw/ -}] - SHARED_NAME[libcrypto]=libcrypto-{- $config{shlib_major}."_".$config{shlib_minor} -}{- $config{target} eq "mingw64" ? "-x64" : "" -} - SHARED_NAME[libssl]=libssl-{- $config{shlib_major}."_".$config{shlib_minor} -}{- $config{target} eq "mingw64" ? "-x64" : "" -} + SHARED_NAME[libcrypto]=libcrypto-{- $sover_filename -}{- $config{target} eq "mingw64" ? "-x64" : "" -} + SHARED_NAME[libssl]=libssl-{- $sover_filename -}{- $config{target} eq "mingw64" ? "-x64" : "" -} ELSIF[{- $config{target} =~ /^VC-/ -}] - SHARED_NAME[libcrypto]=libcrypto-{- $config{shlib_major}."_".$config{shlib_minor} -}{- $target{multilib} -} - SHARED_NAME[libssl]=libssl-{- $config{shlib_major}."_".$config{shlib_minor} -}{- $target{multilib} -} + SHARED_NAME[libcrypto]=libcrypto-{- $sover_filename -}{- $target{multilib} -} + SHARED_NAME[libssl]=libssl-{- $sover_filename -}{- $target{multilib} -} ENDIF # VMS has a cultural standard where all libraries are prefixed. @@ -36,6 +90,6 @@ ENDIF IF[{- $config{target} =~ /^vms/ -}] RENAME[libcrypto]=ossl$libcrypto{- $target{pointer_size} -} RENAME[libssl]=ossl$libssl{- $target{pointer_size} -} - SHARED_NAME[libcrypto]=ossl$libcrypto{- sprintf "%02d%02d", $config{shlib_major}, $config{shlib_minor} -}_shr{- $target{pointer_size} -} - SHARED_NAME[libssl]=ossl$libssl{- sprintf "%02d%02d", $config{shlib_major}, $config{shlib_minor} -}_shr{- $target{pointer_size} -} + SHARED_NAME[libcrypto]=ossl$libcrypto{- $sover_filename -}_shr{- $target{pointer_size} -} + SHARED_NAME[libssl]=ossl$libssl{- $sover_filename -}_shr{- $target{pointer_size} -} ENDIF diff --git a/config b/config index 35e849a9..00f90876 100755 --- a/config +++ b/config @@ -1,5 +1,5 @@ #!/bin/sh -# Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 1998-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 @@ -35,7 +35,8 @@ See INSTALL for instructions. EOF ;; -*) options=$options" $i" ;; +*) i=`echo "$i" | sed -e "s|'|'\\\\\\''|g"` + options="$options '$i'" ;; esac done @@ -187,6 +188,10 @@ case "${SYSTEM}:${RELEASE}:${VERSION}:${MACHINE}" in echo "${MACH}-${ARCH}-freebsd${VERS}"; exit 0 ;; + DragonFly:*) + echo "${MACHINE}-whatever-dragonfly"; exit 0 + ;; + FreeBSD:*) echo "${MACHINE}-whatever-freebsd"; exit 0 ;; @@ -450,13 +455,6 @@ case "$GUESSOS" in OUT=uClinux-dist ;; mips3-sgi-irix) - #CPU=`(hinv -t cpu) 2>/dev/null | head -1 | sed 's/^CPU:[^R]*R\([0-9]*\).*/\1/'` - #CPU=${CPU:-0} - #if [ $CPU -ge 5000 ]; then - # options="$options -mips4" - #else - # options="$options -mips3" - #fi OUT="irix-mips3-$CC" ;; mips4-sgi-irix64) @@ -466,13 +464,6 @@ case "$GUESSOS" in echo " You have about 5 seconds to press Ctrl-C to abort." (trap "stty `stty -g`; exit 0" 2 0; stty -icanon min 0 time 50; read waste) <&1 fi - #CPU=`(hinv -t cpu) 2>/dev/null | head -1 | sed 's/^CPU:[^R]*R\([0-9]*\).*/\1/'` - #CPU=${CPU:-0} - #if [ $CPU -ge 5000 ]; then - # options="$options -mips4" - #else - # options="$options -mips3" - #fi OUT="irix-mips3-$CC" ;; ppc-apple-rhapsody) OUT="rhapsody-ppc-cc" ;; @@ -498,9 +489,7 @@ case "$GUESSOS" in echo " invoke 'KERNEL_BITS=64 $THERE/config $options'." if [ "$DRYRUN" = "false" -a -t 1 ]; then echo " You have about 5 seconds to press Ctrl-C to abort." - # The stty technique used elsewhere doesn't work on - # MacOS. At least, right now on this Mac. - sleep 5 + (trap "stty `stty -g`; exit 1" 2; stty -icanon min 0 time 50; read waste; exit 0) <&1 || exit fi fi if [ "$ISA64" = "1" -a "$KERNEL_BITS" = "64" ]; then @@ -509,16 +498,6 @@ case "$GUESSOS" in OUT="darwin-i386-cc" fi ;; x86_64-apple-darwin*) - if [ -z "$KERNEL_BITS" ]; then - echo "WARNING! If you wish to build 32-bit library, then you have to" - echo " invoke 'KERNEL_BITS=32 $THERE/config $options'." - if [ "$DRYRUN" = "false" -a -t 1 ]; then - echo " You have about 5 seconds to press Ctrl-C to abort." - # The stty technique used elsewhere doesn't work on - # MacOS. At least, right now on this Mac. - sleep 5 - fi - fi if [ "$KERNEL_BITS" = "32" ]; then OUT="darwin-i386-cc" else @@ -713,6 +692,7 @@ case "$GUESSOS" in powerpc64-*-*bsd*) OUT="BSD-generic64"; options="$options -DB_ENDIAN" ;; sparc64-*-*bsd*) OUT="BSD-sparc64" ;; ia64-*-*bsd*) OUT="BSD-ia64" ;; + x86_64-*-dragonfly*) OUT="BSD-x86_64" ;; amd64-*-*bsd*) OUT="BSD-x86_64" ;; *86*-*-*bsd*) # mimic ld behaviour when it's looking for libc... if [ -L /usr/lib/libc.so ]; then # [Free|Net]BSD @@ -869,7 +849,7 @@ case "$GUESSOS" in i386-*) options="$options 386" ;; esac -for i in aes bf camellia cast des dh dsa ec hmac idea md2 md5 mdc2 rc2 rc4 rc5 ripemd rsa seed sha +for i in aes aria bf camellia cast des dh dsa ec hmac idea md2 md5 mdc2 rc2 rc4 rc5 ripemd rsa seed sha sm3 sm4 do if [ ! -d $THERE/crypto/$i ] then @@ -919,15 +899,21 @@ OUT="$OUT" $PERL $THERE/Configure LIST | grep "$OUT" > /dev/null if [ $? = "0" ]; then - echo Configuring for $OUT - if [ "$VERBOSE" = "true" ]; then echo $PERL $THERE/Configure $OUT $options fi if [ "$DRYRUN" = "false" ]; then - $PERL $THERE/Configure $OUT $options + # eval to make sure quoted options, possibly with spaces inside, + # are treated right + eval $PERL $THERE/Configure $OUT $options fi else echo "This system ($OUT) is not supported. See file INSTALL for details." + exit 1 +fi + +if [ "$OUT" = "darwin64-x86_64-cc" ]; then + echo "WARNING! If you wish to build 32-bit libraries, then you have to" + echo " invoke 'KERNEL_BITS=32 $THERE/config $options'." fi ) diff --git a/crypto/LPdir_nyi.c b/crypto/LPdir_nyi.c index 049044c4..b02449f7 100644 --- a/crypto/LPdir_nyi.c +++ b/crypto/LPdir_nyi.c @@ -8,6 +8,9 @@ */ /* + * This file is dual-licensed and is also available under the following + * terms: + * * Copyright (c) 2004, Richard Levitte * All rights reserved. * diff --git a/crypto/LPdir_unix.c b/crypto/LPdir_unix.c index 1bb2940b..6648a60c 100644 --- a/crypto/LPdir_unix.c +++ b/crypto/LPdir_unix.c @@ -8,6 +8,9 @@ */ /* + * This file is dual-licensed and is also available under the following + * terms: + * * Copyright (c) 2004, Richard Levitte * All rights reserved. * diff --git a/crypto/LPdir_vms.c b/crypto/LPdir_vms.c index 1a5b60fe..e35363fd 100644 --- a/crypto/LPdir_vms.c +++ b/crypto/LPdir_vms.c @@ -8,6 +8,9 @@ */ /* + * This file is dual-licensed and is also available under the following + * terms: + * * Copyright (c) 2004, Richard Levitte * All rights reserved. * diff --git a/crypto/LPdir_win.c b/crypto/LPdir_win.c index 8f674d30..1dc1ef12 100644 --- a/crypto/LPdir_win.c +++ b/crypto/LPdir_win.c @@ -8,6 +8,9 @@ */ /* + * This file is dual-licensed and is also available under the following + * terms: + * * Copyright (c) 2004, Richard Levitte * All rights reserved. * diff --git a/crypto/LPdir_win32.c b/crypto/LPdir_win32.c index 59ed4857..edceb98d 100644 --- a/crypto/LPdir_win32.c +++ b/crypto/LPdir_win32.c @@ -8,6 +8,9 @@ */ /* + * This file is dual-licensed and is also available under the following + * terms: + * * Copyright (c) 2004, Richard Levitte * All rights reserved. * diff --git a/crypto/LPdir_wince.c b/crypto/LPdir_wince.c index dbc10529..a24e7382 100644 --- a/crypto/LPdir_wince.c +++ b/crypto/LPdir_wince.c @@ -8,6 +8,9 @@ */ /* + * This file is dual-licensed and is also available under the following + * terms: + * * Copyright (c) 2004, Richard Levitte * All rights reserved. * diff --git a/crypto/aes/aes_core.c b/crypto/aes/aes_core.c index bd5c7793..f1f11fd8 100644 --- a/crypto/aes/aes_core.c +++ b/crypto/aes/aes_core.c @@ -14,9 +14,9 @@ * * Optimised ANSI C code for the Rijndael cipher (now AES) * - * @author Vincent Rijmen - * @author Antoon Bosselaers - * @author Paulo Barreto + * @author Vincent Rijmen + * @author Antoon Bosselaers + * @author Paulo Barreto * * This code is hereby placed in the public domain. * diff --git a/crypto/aes/aes_x86core.c b/crypto/aes/aes_x86core.c index 95b49bba..1b660d71 100644 --- a/crypto/aes/aes_x86core.c +++ b/crypto/aes/aes_x86core.c @@ -7,6 +7,14 @@ * https://www.openssl.org/source/license.html */ +/* + * This is experimental x86[_64] derivative. It assumes little-endian + * byte order and expects CPU to sustain unaligned memory references. + * It is used as playground for cache-time attack mitigations and + * serves as reference C implementation for x86[_64] as well as some + * other assembly modules. + */ + /** * rijndael-alg-fst.c * @@ -14,9 +22,9 @@ * * Optimised ANSI C code for the Rijndael cipher (now AES) * - * @author Vincent Rijmen - * @author Antoon Bosselaers - * @author Paulo Barreto + * @author Vincent Rijmen + * @author Antoon Bosselaers + * @author Paulo Barreto * * This code is hereby placed in the public domain. * @@ -33,15 +41,6 @@ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* - * This is experimental x86[_64] derivative. It assumes little-endian - * byte order and expects CPU to sustain unaligned memory references. - * It is used as playground for cache-time attack mitigations and - * serves as reference C implementation for x86[_64] assembler. - * - * - */ - #include diff --git a/crypto/aes/asm/aes-586.pl b/crypto/aes/asm/aes-586.pl index 1ba35650..29059edf 100755 --- a/crypto/aes/asm/aes-586.pl +++ b/crypto/aes/asm/aes-586.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -39,7 +39,7 @@ # for scaling too, I [try to] avoid the latter by favoring off-by-2 # shifts and masking the result with 0xFF<<2 instead of "boring" 0xFF. # -# As was shown by Dean Gaudet , the above note turned +# As was shown by Dean Gaudet, the above note turned out to be # void. Performance improvement with off-by-2 shifts was observed on # intermediate implementation, which was spilling yet another register # to stack... Final offset*4 code below runs just a tad faster on P4, @@ -55,8 +55,8 @@ # better performance on most recent µ-archs... # # Third version adds AES_cbc_encrypt implementation, which resulted in -# up to 40% performance imrovement of CBC benchmark results. 40% was -# observed on P4 core, where "overall" imrovement coefficient, i.e. if +# up to 40% performance improvement of CBC benchmark results. 40% was +# observed on P4 core, where "overall" improvement coefficient, i.e. if # compared to PIC generated by GCC and in CBC mode, was observed to be # as large as 4x:-) CBC performance is virtually identical to ECB now # and on some platforms even better, e.g. 17.6 "small" cycles/byte on @@ -123,7 +123,7 @@ # words every cache-line is *guaranteed* to be accessed within ~50 # cycles window. Why just SSE? Because it's needed on hyper-threading # CPU! Which is also why it's prefetched with 64 byte stride. Best -# part is that it has no negative effect on performance:-) +# part is that it has no negative effect on performance:-) # # Version 4.3 implements switch between compact and non-compact block # functions in AES_cbc_encrypt depending on how much data was asked @@ -159,7 +159,7 @@ # combinations then attack becomes infeasible. This is why revised # AES_cbc_encrypt "dares" to switch to larger S-box when larger chunk # of data is to be processed in one stroke. The current size limit of -# 512 bytes is chosen to provide same [diminishigly low] probability +# 512 bytes is chosen to provide same [diminishingly low] probability # for cache-line to remain untouched in large chunk operation with # large S-box as for single block operation with compact S-box and # surely needs more careful consideration... @@ -171,12 +171,12 @@ # yield execution to process performing AES just before timer fires # off the scheduler, immediately regain control of CPU and analyze the # cache state. For this attack to be efficient attacker would have to -# effectively slow down the operation by several *orders* of magnitute, +# effectively slow down the operation by several *orders* of magnitude, # by ratio of time slice to duration of handful of AES rounds, which # unlikely to remain unnoticed. Not to mention that this also means -# that he would spend correspondigly more time to collect enough +# that he would spend correspondingly more time to collect enough # statistical data to mount the attack. It's probably appropriate to -# say that if adeversary reckons that this attack is beneficial and +# say that if adversary reckons that this attack is beneficial and # risks to be noticed, you probably have larger problems having him # mere opportunity. In other words suggested code design expects you # to preclude/mitigate this attack by overall system security design. @@ -202,7 +202,7 @@ $output = pop; open OUT,">$output"; *STDOUT=*OUT; -&asm_init($ARGV[0],"aes-586.pl",$x86only = $ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$x86only = $ARGV[$#ARGV] eq "386"); &static_label("AES_Te"); &static_label("AES_Td"); @@ -240,7 +240,7 @@ $small_footprint=1; # $small_footprint=1 code is ~5% slower [on # contention and in hope to "collect" 5% back # in real-life applications... -$vertical_spin=0; # shift "verticaly" defaults to 0, because of +$vertical_spin=0; # shift "vertically" defaults to 0, because of # its proof-of-concept status... # Note that there is no decvert(), as well as last encryption round is # performed with "horizontal" shifts. This is because this "vertical" @@ -585,7 +585,7 @@ sub enctransform() # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # | mm4 | mm0 | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ -# | s3 | s2 | s1 | s0 | +# | s3 | s2 | s1 | s0 | # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ # |15|14|13|12|11|10| 9| 8| 7| 6| 5| 4| 3| 2| 1| 0| # +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ @@ -805,7 +805,7 @@ sub encstep() if ($i==3) { $tmp=$s[3]; &mov ($s[2],$__s1); }##%ecx elsif($i==2){ &movz ($tmp,&HB($s[3])); }#%ebx[2] - else { &mov ($tmp,$s[3]); + else { &mov ($tmp,$s[3]); &shr ($tmp,24) } &xor ($out,&DWP(1,$te,$tmp,8)); if ($i<2) { &mov (&DWP(4+4*$i,"esp"),$out); } @@ -1558,7 +1558,7 @@ sub sse_deccompact() &pxor ("mm1","mm3"); &pxor ("mm5","mm7"); # tp4 &pshufw ("mm3","mm1",0xb1); &pshufw ("mm7","mm5",0xb1); &pxor ("mm0","mm1"); &pxor ("mm4","mm5"); # ^= tp4 - &pxor ("mm0","mm3"); &pxor ("mm4","mm7"); # ^= ROTATE(tp4,16) + &pxor ("mm0","mm3"); &pxor ("mm4","mm7"); # ^= ROTATE(tp4,16) &pxor ("mm3","mm3"); &pxor ("mm7","mm7"); &pcmpgtb("mm3","mm1"); &pcmpgtb("mm7","mm5"); @@ -1606,7 +1606,7 @@ sub decstep() # no instructions are reordered, as performance appears # optimal... or rather that all attempts to reorder didn't # result in better performance [which by the way is not a - # bit lower than ecryption]. + # bit lower than encryption]. if($i==3) { &mov ($key,$__key); } else { &mov ($out,$s[0]); } &and ($out,0xFF); @@ -2028,7 +2028,7 @@ sub declast() { # stack frame layout # -4(%esp) # return address 0(%esp) -# 0(%esp) # s0 backing store 4(%esp) +# 0(%esp) # s0 backing store 4(%esp) # 4(%esp) # s1 backing store 8(%esp) # 8(%esp) # s2 backing store 12(%esp) # 12(%esp) # s3 backing store 16(%esp) @@ -2738,7 +2738,7 @@ sub enckey() &mov (&DWP(80,"edi"),10); # setup number of rounds &xor ("eax","eax"); &jmp (&label("exit")); - + &set_label("12rounds"); &mov ("eax",&DWP(0,"esi")); # copy first 6 dwords &mov ("ebx",&DWP(4,"esi")); diff --git a/crypto/aes/asm/aes-armv4.pl b/crypto/aes/asm/aes-armv4.pl index 99815899..c6474b8a 100644 --- a/crypto/aes/asm/aes-armv4.pl +++ b/crypto/aes/asm/aes-armv4.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 2007-2018 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2007-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 @@ -203,7 +203,7 @@ AES_encrypt: adr r3,. #endif stmdb sp!,{r1,r4-r12,lr} -#if defined(__thumb2__) || defined(__APPLE__) +#ifdef __APPLE__ adr $tbl,AES_Te #else sub $tbl,r3,#AES_encrypt-AES_Te @ Te @@ -481,7 +481,7 @@ _armv4_AES_set_encrypt_key: mov lr,r1 @ bits mov $key,r2 @ key -#if defined(__thumb2__) || defined(__APPLE__) +#ifdef __APPLE__ adr $tbl,AES_Te+1024 @ Te4 #else sub $tbl,r3,#_armv4_AES_set_encrypt_key-AES_Te-1024 @ Te4 @@ -979,7 +979,7 @@ AES_decrypt: adr r3,. #endif stmdb sp!,{r1,r4-r12,lr} -#if defined(__thumb2__) || defined(__APPLE__) +#ifdef __APPLE__ adr $tbl,AES_Td #else sub $tbl,r3,#AES_decrypt-AES_Td @ Td diff --git a/crypto/aes/asm/aes-ia64.S b/crypto/aes/asm/aes-ia64.S index f7f1f63c..03f79b7a 100644 --- a/crypto/aes/asm/aes-ia64.S +++ b/crypto/aes/asm/aes-ia64.S @@ -6,7 +6,7 @@ // https://www.openssl.org/source/license.html // // ==================================================================== -// Written by Andy Polyakov for the OpenSSL +// Written by Andy Polyakov for the OpenSSL // project. Rights for redistribution and usage in source and binary // forms are granted according to the OpenSSL license. // ==================================================================== @@ -33,7 +33,7 @@ // 64 bytes line size and L2 - 128 bytes... .ident "aes-ia64.S, version 1.2" -.ident "IA-64 ISA artwork by Andy Polyakov " +.ident "IA-64 ISA artwork by Andy Polyakov " .explicit .text diff --git a/crypto/aes/asm/aes-mips.pl b/crypto/aes/asm/aes-mips.pl index 439578d9..d81d76d7 100644 --- a/crypto/aes/asm/aes-mips.pl +++ b/crypto/aes/asm/aes-mips.pl @@ -65,8 +65,8 @@ $flavour = shift || "o32"; # supported flavours are o32,n32,64,nubi32,nubi64 if ($flavour =~ /64|n32/i) { $PTR_LA="dla"; - $PTR_ADD="dadd"; # incidentally works even on n32 - $PTR_SUB="dsub"; # incidentally works even on n32 + $PTR_ADD="daddu"; # incidentally works even on n32 + $PTR_SUB="dsubu"; # incidentally works even on n32 $PTR_INS="dins"; $REG_S="sd"; $REG_L="ld"; @@ -74,8 +74,8 @@ if ($flavour =~ /64|n32/i) { $SZREG=8; } else { $PTR_LA="la"; - $PTR_ADD="add"; - $PTR_SUB="sub"; + $PTR_ADD="addu"; + $PTR_SUB="subu"; $PTR_INS="ins"; $REG_S="sw"; $REG_L="lw"; @@ -102,15 +102,9 @@ open STDOUT,">$output"; my ($MSB,$LSB)=(0,3); # automatically converted to little-endian $code.=<<___; +#include "mips_arch.h" + .text -#ifdef OPENSSL_FIPSCANISTER -# include -#endif - -#if defined(__mips_smartmips) && !defined(_MIPS_ARCH_MIPS32R2) -#define _MIPS_ARCH_MIPS32R2 -#endif - #if !defined(__mips_eabi) && (!defined(__vxworks) || defined(__pic__)) .option pic2 #endif @@ -126,7 +120,7 @@ my ($i0,$i1,$i2,$i3)=($at,$t0,$t1,$t2); my ($t0,$t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10,$t11) = map("\$$_",(12..23)); my ($key0,$cnt)=($gp,$fp); -# instuction ordering is "stolen" from output from MIPSpro assembler +# instruction ordering is "stolen" from output from MIPSpro assembler # invoked with -mips3 -O3 arguments... $code.=<<___; .align 5 @@ -146,7 +140,7 @@ _mips_AES_encrypt: xor $s2,$t2 xor $s3,$t3 - sub $cnt,1 + subu $cnt,1 #if defined(__mips_smartmips) ext $i0,$s1,16,8 .Loop_enc: @@ -218,7 +212,7 @@ _mips_AES_encrypt: xor $t2,$t6 xor $t3,$t7 - sub $cnt,1 + subu $cnt,1 $PTR_ADD $key0,16 xor $s0,$t0 xor $s1,$t1 @@ -409,7 +403,7 @@ _mips_AES_encrypt: xor $t2,$t6 xor $t3,$t7 - sub $cnt,1 + subu $cnt,1 $PTR_ADD $key0,16 xor $s0,$t0 xor $s1,$t1 @@ -657,6 +651,12 @@ $code.=<<___; .set reorder $PTR_LA $Tbl,AES_Te # PIC-ified 'load address' +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + lw $s0,0($inp) + lw $s1,4($inp) + lw $s2,8($inp) + lw $s3,12($inp) +#else lwl $s0,0+$MSB($inp) lwl $s1,4+$MSB($inp) lwl $s2,8+$MSB($inp) @@ -665,9 +665,16 @@ $code.=<<___; lwr $s1,4+$LSB($inp) lwr $s2,8+$LSB($inp) lwr $s3,12+$LSB($inp) +#endif bal _mips_AES_encrypt +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + sw $s0,0($out) + sw $s1,4($out) + sw $s2,8($out) + sw $s3,12($out) +#else swr $s0,0+$LSB($out) swr $s1,4+$LSB($out) swr $s2,8+$LSB($out) @@ -676,6 +683,7 @@ $code.=<<___; swl $s1,4+$MSB($out) swl $s2,8+$MSB($out) swl $s3,12+$MSB($out) +#endif .set noreorder $REG_L $ra,$FRAMESIZE-1*$SZREG($sp) @@ -720,7 +728,7 @@ _mips_AES_decrypt: xor $s2,$t2 xor $s3,$t3 - sub $cnt,1 + subu $cnt,1 #if defined(__mips_smartmips) ext $i0,$s3,16,8 .Loop_dec: @@ -792,7 +800,7 @@ _mips_AES_decrypt: xor $t2,$t6 xor $t3,$t7 - sub $cnt,1 + subu $cnt,1 $PTR_ADD $key0,16 xor $s0,$t0 xor $s1,$t1 @@ -985,7 +993,7 @@ _mips_AES_decrypt: xor $t2,$t6 xor $t3,$t7 - sub $cnt,1 + subu $cnt,1 $PTR_ADD $key0,16 xor $s0,$t0 xor $s1,$t1 @@ -1228,6 +1236,12 @@ $code.=<<___; .set reorder $PTR_LA $Tbl,AES_Td # PIC-ified 'load address' +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + lw $s0,0($inp) + lw $s1,4($inp) + lw $s2,8($inp) + lw $s3,12($inp) +#else lwl $s0,0+$MSB($inp) lwl $s1,4+$MSB($inp) lwl $s2,8+$MSB($inp) @@ -1236,9 +1250,16 @@ $code.=<<___; lwr $s1,4+$LSB($inp) lwr $s2,8+$LSB($inp) lwr $s3,12+$LSB($inp) +#endif bal _mips_AES_decrypt +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + sw $s0,0($out) + sw $s1,4($out) + sw $s2,8($out) + sw $s3,12($out) +#else swr $s0,0+$LSB($out) swr $s1,4+$LSB($out) swr $s2,8+$LSB($out) @@ -1247,6 +1268,7 @@ $code.=<<___; swl $s1,4+$MSB($out) swl $s2,8+$MSB($out) swl $s3,12+$MSB($out) +#endif .set noreorder $REG_L $ra,$FRAMESIZE-1*$SZREG($sp) @@ -1295,35 +1317,52 @@ _mips_AES_set_encrypt_key: $PTR_ADD $rcon,$Tbl,256 .set reorder +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + lw $rk0,0($inp) # load 128 bits + lw $rk1,4($inp) + lw $rk2,8($inp) + lw $rk3,12($inp) +#else lwl $rk0,0+$MSB($inp) # load 128 bits lwl $rk1,4+$MSB($inp) lwl $rk2,8+$MSB($inp) lwl $rk3,12+$MSB($inp) - li $at,128 lwr $rk0,0+$LSB($inp) lwr $rk1,4+$LSB($inp) lwr $rk2,8+$LSB($inp) lwr $rk3,12+$LSB($inp) +#endif + li $at,128 .set noreorder beq $bits,$at,.L128bits li $cnt,10 .set reorder +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + lw $rk4,16($inp) # load 192 bits + lw $rk5,20($inp) +#else lwl $rk4,16+$MSB($inp) # load 192 bits lwl $rk5,20+$MSB($inp) - li $at,192 lwr $rk4,16+$LSB($inp) lwr $rk5,20+$LSB($inp) +#endif + li $at,192 .set noreorder beq $bits,$at,.L192bits li $cnt,8 .set reorder +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + lw $rk6,24($inp) # load 256 bits + lw $rk7,28($inp) +#else lwl $rk6,24+$MSB($inp) # load 256 bits lwl $rk7,28+$MSB($inp) - li $at,256 lwr $rk6,24+$LSB($inp) lwr $rk7,28+$LSB($inp) +#endif + li $at,256 .set noreorder beq $bits,$at,.L256bits li $cnt,7 @@ -1353,7 +1392,7 @@ _mips_AES_set_encrypt_key: sw $rk1,4($key) sw $rk2,8($key) sw $rk3,12($key) - sub $cnt,1 + subu $cnt,1 $PTR_ADD $key,16 _bias $i0,24 @@ -1410,7 +1449,7 @@ _mips_AES_set_encrypt_key: sw $rk3,12($key) sw $rk4,16($key) sw $rk5,20($key) - sub $cnt,1 + subu $cnt,1 $PTR_ADD $key,24 _bias $i0,24 @@ -1471,7 +1510,7 @@ _mips_AES_set_encrypt_key: sw $rk5,20($key) sw $rk6,24($key) sw $rk7,28($key) - sub $cnt,1 + subu $cnt,1 _bias $i0,24 _bias $i1,16 @@ -1653,7 +1692,7 @@ $code.=<<___; lw $tp1,16($key) # modulo-scheduled lui $x80808080,0x8080 - sub $cnt,1 + subu $cnt,1 or $x80808080,0x8080 sll $cnt,2 $PTR_ADD $key,16 @@ -1716,7 +1755,7 @@ $code.=<<___; lw $tp1,4($key) # modulo-scheduled xor $tpe,$tp2 #endif - sub $cnt,1 + subu $cnt,1 sw $tpe,0($key) $PTR_ADD $key,4 bnez $cnt,.Lmix diff --git a/crypto/aes/asm/aes-parisc.pl b/crypto/aes/asm/aes-parisc.pl index 2c785bc5..b688ab30 100644 --- a/crypto/aes/asm/aes-parisc.pl +++ b/crypto/aes/asm/aes-parisc.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -1015,7 +1015,7 @@ ___ foreach (split("\n",$code)) { s/\`([^\`]*)\`/eval $1/ge; - # translate made up instructons: _ror, _srm + # translate made up instructions: _ror, _srm s/_ror(\s+)(%r[0-9]+),/shd$1$2,$2,/ or s/_srm(\s+%r[0-9]+),([0-9]+),/ diff --git a/crypto/aes/asm/aes-ppc.pl b/crypto/aes/asm/aes-ppc.pl index 1558d8e4..ca69df4c 100644 --- a/crypto/aes/asm/aes-ppc.pl +++ b/crypto/aes/asm/aes-ppc.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -1433,10 +1433,10 @@ $code.=<<___; xor $s1,$s1,$acc05 xor $s2,$s2,$acc06 xor $s3,$s3,$acc07 - xor $s0,$s0,$acc08 # ^= ROTATE(r8,8) - xor $s1,$s1,$acc09 - xor $s2,$s2,$acc10 - xor $s3,$s3,$acc11 + xor $s0,$s0,$acc08 # ^= ROTATE(r8,8) + xor $s1,$s1,$acc09 + xor $s2,$s2,$acc10 + xor $s3,$s3,$acc11 b Ldec_compact_loop .align 4 diff --git a/crypto/aes/asm/aes-s390x.pl b/crypto/aes/asm/aes-s390x.pl index fd8a7371..0c400590 100644 --- a/crypto/aes/asm/aes-s390x.pl +++ b/crypto/aes/asm/aes-s390x.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 2007-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2007-2018 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 @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -44,7 +44,7 @@ # minimize/avoid Address Generation Interlock hazard and to favour # dual-issue z10 pipeline. This gave ~25% improvement on z10 and # almost 50% on z9. The gain is smaller on z10, because being dual- -# issue z10 makes it improssible to eliminate the interlock condition: +# issue z10 makes it impossible to eliminate the interlock condition: # critial path is not long enough. Yet it spends ~24 cycles per byte # processed with 128-bit key. # @@ -129,6 +129,8 @@ sub _data_word() } $code=<<___; +#include "s390x_arch.h" + .text .type AES_Te,\@object @@ -404,7 +406,7 @@ _s390x_AES_encrypt: or $s1,$t1 or $t2,$i2 or $t3,$i3 - + srlg $i1,$s2,`8-3` # i0 srlg $i2,$s2,`16-3` # i1 nr $i1,$mask @@ -457,7 +459,7 @@ _s390x_AES_encrypt: x $s2,24($key) x $s3,28($key) - br $ra + br $ra .size _s390x_AES_encrypt,.-_s390x_AES_encrypt ___ @@ -779,7 +781,7 @@ _s390x_AES_decrypt: x $s2,24($key) x $s3,28($key) - br $ra + br $ra .size _s390x_AES_decrypt,.-_s390x_AES_decrypt ___ @@ -823,8 +825,8 @@ $code.=<<___ if (!$softonly); larl %r1,OPENSSL_s390xcap_P llihh %r0,0x8000 srlg %r0,%r0,0(%r5) - ng %r0,32(%r1) # check availability of both km... - ng %r0,48(%r1) # ...and kmc support for given key length + ng %r0,S390X_KM(%r1) # check availability of both km... + ng %r0,S390X_KMC(%r1) # ...and kmc support for given key length jz .Lekey_internal lmg %r0,%r1,0($inp) # just copy 128 bits... @@ -1084,7 +1086,7 @@ $code.=<<___ if (!$softonly); lhi $t1,16 cr $t0,$t1 jl .Lgo - oill $t0,0x80 # set "decrypt" bit + oill $t0,S390X_DECRYPT # set "decrypt" bit st $t0,240($key) br $ra ___ @@ -1223,7 +1225,7 @@ $code.=<<___ if (!$softonly); .align 16 .Lkmc_truncated: ahi $key,-1 # it's the way it's encoded in mvc - tmll %r0,0x80 + tmll %r0,S390X_DECRYPT jnz .Lkmc_truncated_dec lghi %r1,0 stg %r1,16*$SIZE_T($sp) @@ -1294,7 +1296,7 @@ $code.=<<___; .Lcbc_enc_done: l${g} $ivp,6*$SIZE_T($sp) st $s0,0($ivp) - st $s1,4($ivp) + st $s1,4($ivp) st $s2,8($ivp) st $s3,12($ivp) @@ -1403,7 +1405,61 @@ $code.=<<___ if (!$softonly); clr %r0,%r1 jl .Lctr32_software - stm${g} %r6,$s3,6*$SIZE_T($sp) + st${g} $s2,10*$SIZE_T($sp) + st${g} $s3,11*$SIZE_T($sp) + + clr $len,%r1 # does work even in 64-bit mode + jle .Lctr32_nokma # kma is slower for <= 16 blocks + + larl %r1,OPENSSL_s390xcap_P + lr $s2,%r0 + llihh $s3,0x8000 + srlg $s3,$s3,0($s2) + ng $s3,S390X_KMA(%r1) # check kma capability vector + jz .Lctr32_nokma + + l${g}hi %r1,-$stdframe-112 + l${g}r $s3,$sp + la $sp,0(%r1,$sp) # prepare parameter block + + lhi %r1,0x0600 + sllg $len,$len,4 + or %r0,%r1 # set HS and LAAD flags + + st${g} $s3,0($sp) # backchain + la %r1,$stdframe($sp) + + lmg $s2,$s3,0($key) # copy key + stg $s2,$stdframe+80($sp) + stg $s3,$stdframe+88($sp) + lmg $s2,$s3,16($key) + stg $s2,$stdframe+96($sp) + stg $s3,$stdframe+104($sp) + + lmg $s2,$s3,0($ivp) # copy iv + stg $s2,$stdframe+64($sp) + ahi $s3,-1 # kma requires counter-1 + stg $s3,$stdframe+72($sp) + st $s3,$stdframe+12($sp) # copy counter + + lghi $s2,0 # no AAD + lghi $s3,0 + + .long 0xb929a042 # kma $out,$s2,$inp + brc 1,.-4 # pay attention to "partial completion" + + stg %r0,$stdframe+80($sp) # wipe key + stg %r0,$stdframe+88($sp) + stg %r0,$stdframe+96($sp) + stg %r0,$stdframe+104($sp) + la $sp,$stdframe+112($sp) + + lm${g} $s2,$s3,10*$SIZE_T($sp) + br $ra + +.align 16 +.Lctr32_nokma: + stm${g} %r6,$s1,6*$SIZE_T($sp) slgr $out,$inp la %r1,0($key) # %r1 is permanent copy of $key @@ -1442,7 +1498,7 @@ $code.=<<___ if (!$softonly && 0);# kmctr code was measured to be ~12% slower larl %r1,OPENSSL_s390xcap_P llihh %r0,0x8000 # check if kmctr supports the function code srlg %r0,%r0,0($s0) - ng %r0,64(%r1) # check kmctr capability vector + ng %r0,S390X_KMCTR(%r1) # check kmctr capability vector lgr %r0,$s0 lgr %r1,$s1 jz .Lctr32_km_loop @@ -1567,8 +1623,8 @@ ___ } ######################################################################## -# void AES_xts_encrypt(const char *inp,char *out,size_t len, -# const AES_KEY *key1, const AES_KEY *key2, +# 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]); # { @@ -1592,7 +1648,7 @@ $code.=<<___ if(1); larl %r1,OPENSSL_s390xcap_P llihh %r0,0x8000 srlg %r0,%r0,32($s1) # check for 32+function code - ng %r0,32(%r1) # check km capability vector + ng %r0,S390X_KM(%r1) # check km capability vector lgr %r0,$s0 # restore the function code la %r1,0($key1) # restore $key1 jz .Lxts_km_vanilla @@ -1627,7 +1683,7 @@ $code.=<<___ if(1); llgc $len,2*$SIZE_T-1($sp) nill $len,0x0f # $len%=16 br $ra - + .align 16 .Lxts_km_vanilla: ___ @@ -1854,7 +1910,7 @@ $code.=<<___; xgr $s1,%r1 lrvgr $s1,$s1 # flip byte order lrvgr $s3,$s3 - srlg $s0,$s1,32 # smash the tweak to 4x32-bits + srlg $s0,$s1,32 # smash the tweak to 4x32-bits stg $s1,$tweak+0($sp) # save the tweak llgfr $s1,$s1 srlg $s2,$s3,32 @@ -1905,7 +1961,7 @@ $code.=<<___; xgr $s1,%r1 lrvgr $s1,$s1 # flip byte order lrvgr $s3,$s3 - srlg $s0,$s1,32 # smash the tweak to 4x32-bits + srlg $s0,$s1,32 # smash the tweak to 4x32-bits stg $s1,$tweak+0($sp) # save the tweak llgfr $s1,$s1 srlg $s2,$s3,32 @@ -1936,8 +1992,8 @@ $code.=<<___; br $ra .size AES_xts_encrypt,.-AES_xts_encrypt ___ -# void AES_xts_decrypt(const char *inp,char *out,size_t len, -# const AES_KEY *key1, const AES_KEY *key2, +# 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]); # $code.=<<___; @@ -2097,7 +2153,7 @@ $code.=<<___; xgr $s1,%r1 lrvgr $s1,$s1 # flip byte order lrvgr $s3,$s3 - srlg $s0,$s1,32 # smash the tweak to 4x32-bits + srlg $s0,$s1,32 # smash the tweak to 4x32-bits stg $s1,$tweak+0($sp) # save the tweak llgfr $s1,$s1 srlg $s2,$s3,32 diff --git a/crypto/aes/asm/aes-sparcv9.pl b/crypto/aes/asm/aes-sparcv9.pl index 883fae82..40d1f94c 100755 --- a/crypto/aes/asm/aes-sparcv9.pl +++ b/crypto/aes/asm/aes-sparcv9.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. Rights for redistribution and usage in source and binary # forms are granted according to the OpenSSL license. # ==================================================================== diff --git a/crypto/aes/asm/aes-x86_64.pl b/crypto/aes/asm/aes-x86_64.pl index ce4ca30b..4d1dc9c7 100755 --- a/crypto/aes/asm/aes-x86_64.pl +++ b/crypto/aes/asm/aes-x86_64.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -599,15 +599,23 @@ $code.=<<___; .hidden asm_AES_encrypt asm_AES_encrypt: AES_encrypt: +.cfi_startproc + mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 # allocate frame "above" key schedule - mov %rsp,%r10 lea -63(%rdx),%rcx # %rdx is key argument and \$-64,%rsp sub %rsp,%rcx @@ -617,7 +625,8 @@ AES_encrypt: sub \$32,%rsp mov %rsi,16(%rsp) # save out - mov %r10,24(%rsp) # save real stack pointer + mov %rax,24(%rsp) # save original stack pointer +.cfi_cfa_expression %rsp+24,deref,+8 .Lenc_prologue: mov %rdx,$key @@ -644,20 +653,29 @@ AES_encrypt: mov 16(%rsp),$out # restore out mov 24(%rsp),%rsi # restore saved stack pointer +.cfi_def_cfa %rsi,8 mov $s0,0($out) # write output vector mov $s1,4($out) mov $s2,8($out) mov $s3,12($out) - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lenc_epilogue: ret +.cfi_endproc .size AES_encrypt,.-AES_encrypt ___ @@ -1197,15 +1215,23 @@ $code.=<<___; .hidden asm_AES_decrypt asm_AES_decrypt: AES_decrypt: +.cfi_startproc + mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 # allocate frame "above" key schedule - mov %rsp,%r10 lea -63(%rdx),%rcx # %rdx is key argument and \$-64,%rsp sub %rsp,%rcx @@ -1215,7 +1241,8 @@ AES_decrypt: sub \$32,%rsp mov %rsi,16(%rsp) # save out - mov %r10,24(%rsp) # save real stack pointer + mov %rax,24(%rsp) # save original stack pointer +.cfi_cfa_expression %rsp+24,deref,+8 .Ldec_prologue: mov %rdx,$key @@ -1244,20 +1271,29 @@ AES_decrypt: mov 16(%rsp),$out # restore out mov 24(%rsp),%rsi # restore saved stack pointer +.cfi_def_cfa %rsi,8 mov $s0,0($out) # write output vector mov $s1,4($out) mov $s2,8($out) mov $s3,12($out) - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Ldec_epilogue: ret +.cfi_endproc .size AES_decrypt,.-AES_decrypt ___ #------------------------------------------------------------------# @@ -1296,22 +1332,34 @@ $code.=<<___; .type AES_set_encrypt_key,\@function,3 .align 16 AES_set_encrypt_key: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp - push %r12 # redundant, but allows to share +.cfi_push %rbp + push %r12 # redundant, but allows to share +.cfi_push %r12 push %r13 # exception handler... +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 sub \$8,%rsp +.cfi_adjust_cfa_offset 8 .Lenc_key_prologue: call _x86_64_AES_set_encrypt_key mov 40(%rsp),%rbp +.cfi_restore %rbp mov 48(%rsp),%rbx +.cfi_restore %rbx add \$56,%rsp +.cfi_adjust_cfa_offset -56 .Lenc_key_epilogue: ret +.cfi_endproc .size AES_set_encrypt_key,.-AES_set_encrypt_key .type _x86_64_AES_set_encrypt_key,\@abi-omnipotent @@ -1424,7 +1472,7 @@ $code.=<<___; xor %rax,%rax jmp .Lexit -.L14rounds: +.L14rounds: mov 0(%rsi),%rax # copy first 8 dwords mov 8(%rsi),%rbx mov 16(%rsi),%rcx @@ -1562,13 +1610,21 @@ $code.=<<___; .type AES_set_decrypt_key,\@function,3 .align 16 AES_set_decrypt_key: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 push %rdx # save key schedule +.cfi_adjust_cfa_offset 8 .Ldec_key_prologue: call _x86_64_AES_set_encrypt_key @@ -1622,14 +1678,22 @@ $code.=<<___; xor %rax,%rax .Labort: mov 8(%rsp),%r15 +.cfi_restore %r15 mov 16(%rsp),%r14 +.cfi_restore %r14 mov 24(%rsp),%r13 +.cfi_restore %r13 mov 32(%rsp),%r12 +.cfi_restore %r12 mov 40(%rsp),%rbp +.cfi_restore %rbp mov 48(%rsp),%rbx +.cfi_restore %rbx add \$56,%rsp +.cfi_adjust_cfa_offset -56 .Ldec_key_epilogue: ret +.cfi_endproc .size AES_set_decrypt_key,.-AES_set_decrypt_key ___ @@ -1660,25 +1724,32 @@ $code.=<<___; .hidden asm_AES_cbc_encrypt asm_AES_cbc_encrypt: AES_cbc_encrypt: +.cfi_startproc cmp \$0,%rdx # check length je .Lcbc_epilogue pushfq +.cfi_push 49 # %rflags push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lcbc_prologue: cld mov %r9d,%r9d # clear upper half of enc lea .LAES_Te(%rip),$sbox + lea .LAES_Td(%rip),%r10 cmp \$0,%r9 - jne .Lcbc_picked_te - lea .LAES_Td(%rip),$sbox -.Lcbc_picked_te: + cmoveq %r10,$sbox mov OPENSSL_ia32cap_P(%rip),%r10d cmp \$$speed_limit,%rdx @@ -1714,8 +1785,10 @@ AES_cbc_encrypt: .Lcbc_te_ok: xchg %rsp,$key +.cfi_def_cfa_register $key #add \$8,%rsp # reserve for return address! mov $key,$_rsp # save %rsp +.cfi_cfa_expression $_rsp,deref,+64 .Lcbc_fast_body: mov %rdi,$_inp # save copy of inp mov %rsi,$_out # save copy of out @@ -1945,7 +2018,7 @@ AES_cbc_encrypt: lea ($key,%rax),%rax mov %rax,$keyend - # pick Te4 copy which can't "overlap" with stack frame or key scdedule + # pick Te4 copy which can't "overlap" with stack frame or key schedule lea 2048($sbox),$sbox lea 768-8(%rsp),%rax sub $sbox,%rax @@ -2097,17 +2170,27 @@ AES_cbc_encrypt: .align 16 .Lcbc_exit: mov $_rsp,%rsi +.cfi_def_cfa %rsi,64 mov (%rsi),%r15 +.cfi_restore %r15 mov 8(%rsi),%r14 +.cfi_restore %r14 mov 16(%rsi),%r13 +.cfi_restore %r13 mov 24(%rsi),%r12 +.cfi_restore %r12 mov 32(%rsi),%rbp +.cfi_restore %rbp mov 40(%rsi),%rbx +.cfi_restore %rbx lea 48(%rsi),%rsp +.cfi_def_cfa %rsp,16 .Lcbc_popfq: popfq +.cfi_pop 49 # %rflags .Lcbc_epilogue: ret +.cfi_endproc .size AES_cbc_encrypt,.-AES_cbc_encrypt ___ } @@ -2580,7 +2663,6 @@ block_se_handler: jae .Lin_block_prologue mov 24(%rax),%rax # pull saved real stack pointer - lea 48(%rax),%rax # adjust... mov -8(%rax),%rbx mov -16(%rax),%rbp diff --git a/crypto/aes/asm/aesfx-sparcv9.pl b/crypto/aes/asm/aesfx-sparcv9.pl index 04b3cf71..9ddf0b4b 100644 --- a/crypto/aes/asm/aesfx-sparcv9.pl +++ b/crypto/aes/asm/aesfx-sparcv9.pl @@ -22,7 +22,7 @@ # April 2016 # # Add "teaser" CBC and CTR mode-specific subroutines. "Teaser" means -# that parallelizeable nature of CBC decrypt and CTR is not utilized +# that parallelizable nature of CBC decrypt and CTR is not utilized # yet. CBC encrypt on the other hand is as good as it can possibly # get processing one byte in 4.1 cycles with 128-bit key on SPARC64 X. # This is ~6x faster than pure software implementation... diff --git a/crypto/aes/asm/aesni-mb-x86_64.pl b/crypto/aes/asm/aesni-mb-x86_64.pl index aa2735e0..1f356d2d 100644 --- a/crypto/aes/asm/aesni-mb-x86_64.pl +++ b/crypto/aes/asm/aesni-mb-x86_64.pl @@ -105,6 +105,7 @@ $code.=<<___; .type aesni_multi_cbc_encrypt,\@function,3 .align 32 aesni_multi_cbc_encrypt: +.cfi_startproc ___ $code.=<<___ if ($avx); cmp \$2,$num @@ -118,12 +119,19 @@ $code.=<<___ if ($avx); ___ $code.=<<___; mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -134,7 +142,7 @@ $code.=<<___ if ($win64); movaps %xmm10,0x40(%rsp) movaps %xmm11,0x50(%rsp) movaps %xmm12,0x60(%rsp) - movaps %xmm13,-0x68(%rax) # not used, saved to share se_handler + movaps %xmm13,-0x68(%rax) # not used, saved to share se_handler movaps %xmm14,-0x58(%rax) movaps %xmm15,-0x48(%rax) ___ @@ -148,6 +156,7 @@ $code.=<<___; sub \$48,%rsp and \$-64,%rsp mov %rax,16(%rsp) # original %rsp +.cfi_cfa_expression %rsp+16,deref,+8 .Lenc4x_body: movdqu ($key),$zero # 0-round key @@ -308,9 +317,9 @@ $code.=<<___; movups @out[0],-16(@outptr[0],$offset) pxor @inp[0],@out[0] - movups @out[1],-16(@outptr[1],$offset) + movups @out[1],-16(@outptr[1],$offset) pxor @inp[1],@out[1] - movups @out[2],-16(@outptr[2],$offset) + movups @out[2],-16(@outptr[2],$offset) pxor @inp[2],@out[2] movups @out[3],-16(@outptr[3],$offset) pxor @inp[3],@out[3] @@ -319,6 +328,7 @@ $code.=<<___; jnz .Loop_enc4x mov 16(%rsp),%rax # original %rsp +.cfi_def_cfa %rax,8 mov 24(%rsp),$num #pxor @inp[0],@out[0] @@ -350,20 +360,29 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -48(%rax),%r15 +.cfi_restore %r15 mov -40(%rax),%r14 +.cfi_restore %r14 mov -32(%rax),%r13 +.cfi_restore %r13 mov -24(%rax),%r12 +.cfi_restore %r12 mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Lenc4x_epilogue: ret +.cfi_endproc .size aesni_multi_cbc_encrypt,.-aesni_multi_cbc_encrypt .globl aesni_multi_cbc_decrypt .type aesni_multi_cbc_decrypt,\@function,3 .align 32 aesni_multi_cbc_decrypt: +.cfi_startproc ___ $code.=<<___ if ($avx); cmp \$2,$num @@ -377,12 +396,19 @@ $code.=<<___ if ($avx); ___ $code.=<<___; mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -393,7 +419,7 @@ $code.=<<___ if ($win64); movaps %xmm10,0x40(%rsp) movaps %xmm11,0x50(%rsp) movaps %xmm12,0x60(%rsp) - movaps %xmm13,-0x68(%rax) # not used, saved to share se_handler + movaps %xmm13,-0x68(%rax) # not used, saved to share se_handler movaps %xmm14,-0x58(%rax) movaps %xmm15,-0x48(%rax) ___ @@ -407,6 +433,7 @@ $code.=<<___; sub \$48,%rsp and \$-64,%rsp mov %rax,16(%rsp) # original %rsp +.cfi_cfa_expression %rsp+16,deref,+8 .Ldec4x_body: movdqu ($key),$zero # 0-round key @@ -563,10 +590,10 @@ $code.=<<___; movups @out[0],-16(@outptr[0],$offset) movdqu (@inptr[0],$offset),@out[0] - movups @out[1],-16(@outptr[1],$offset) + movups @out[1],-16(@outptr[1],$offset) movdqu (@inptr[1],$offset),@out[1] pxor $zero,@out[0] - movups @out[2],-16(@outptr[2],$offset) + movups @out[2],-16(@outptr[2],$offset) movdqu (@inptr[2],$offset),@out[2] pxor $zero,@out[1] movups @out[3],-16(@outptr[3],$offset) @@ -578,6 +605,7 @@ $code.=<<___; jnz .Loop_dec4x mov 16(%rsp),%rax # original %rsp +.cfi_def_cfa %rax,8 mov 24(%rsp),$num lea `40*4`($inp),$inp @@ -600,14 +628,22 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -48(%rax),%r15 +.cfi_restore %r15 mov -40(%rax),%r14 +.cfi_restore %r14 mov -32(%rax),%r13 +.cfi_restore %r13 mov -24(%rax),%r12 +.cfi_restore %r12 mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Ldec4x_epilogue: ret +.cfi_endproc .size aesni_multi_cbc_decrypt,.-aesni_multi_cbc_decrypt ___ @@ -623,14 +659,22 @@ $code.=<<___; .type aesni_multi_cbc_encrypt_avx,\@function,3 .align 32 aesni_multi_cbc_encrypt_avx: +.cfi_startproc _avx_cbc_enc_shortcut: mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -657,6 +701,7 @@ $code.=<<___; sub \$192,%rsp and \$-128,%rsp mov %rax,16(%rsp) # original %rsp +.cfi_cfa_expression %rsp+16,deref,+8 .Lenc8x_body: vzeroupper @@ -835,10 +880,10 @@ $code.=<<___; vmovups @out[0],-16(@ptr[0]) # write output sub $offset,@ptr[0] # switch to input vpxor 0x00($offload),@out[0],@out[0] - vmovups @out[1],-16(@ptr[1]) + vmovups @out[1],-16(@ptr[1]) sub `64+1*8`(%rsp),@ptr[1] vpxor 0x10($offload),@out[1],@out[1] - vmovups @out[2],-16(@ptr[2]) + vmovups @out[2],-16(@ptr[2]) sub `64+2*8`(%rsp),@ptr[2] vpxor 0x20($offload),@out[2],@out[2] vmovups @out[3],-16(@ptr[3]) @@ -847,10 +892,10 @@ $code.=<<___; vmovups @out[4],-16(@ptr[4]) sub `64+4*8`(%rsp),@ptr[4] vpxor @inp[0],@out[4],@out[4] - vmovups @out[5],-16(@ptr[5]) + vmovups @out[5],-16(@ptr[5]) sub `64+5*8`(%rsp),@ptr[5] vpxor @inp[1],@out[5],@out[5] - vmovups @out[6],-16(@ptr[6]) + vmovups @out[6],-16(@ptr[6]) sub `64+6*8`(%rsp),@ptr[6] vpxor @inp[2],@out[6],@out[6] vmovups @out[7],-16(@ptr[7]) @@ -861,6 +906,7 @@ $code.=<<___; jnz .Loop_enc8x mov 16(%rsp),%rax # original %rsp +.cfi_def_cfa %rax,8 #mov 24(%rsp),$num #lea `40*8`($inp),$inp #dec $num @@ -883,27 +929,43 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -48(%rax),%r15 +.cfi_restore %r15 mov -40(%rax),%r14 +.cfi_restore %r14 mov -32(%rax),%r13 +.cfi_restore %r13 mov -24(%rax),%r12 +.cfi_restore %r12 mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Lenc8x_epilogue: ret +.cfi_endproc .size aesni_multi_cbc_encrypt_avx,.-aesni_multi_cbc_encrypt_avx .type aesni_multi_cbc_decrypt_avx,\@function,3 .align 32 aesni_multi_cbc_decrypt_avx: +.cfi_startproc _avx_cbc_dec_shortcut: mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -932,6 +994,7 @@ $code.=<<___; and \$-256,%rsp sub \$192,%rsp mov %rax,16(%rsp) # original %rsp +.cfi_cfa_expression %rsp+16,deref,+8 .Ldec8x_body: vzeroupper @@ -1128,12 +1191,12 @@ $code.=<<___; sub $offset,@ptr[0] # switch to input vmovdqu 128+0(%rsp),@out[0] vpxor 0x70($offload),@out[7],@out[7] - vmovups @out[1],-16(@ptr[1]) + vmovups @out[1],-16(@ptr[1]) sub `64+1*8`(%rsp),@ptr[1] vmovdqu @out[0],0x00($offload) vpxor $zero,@out[0],@out[0] vmovdqu 128+16(%rsp),@out[1] - vmovups @out[2],-16(@ptr[2]) + vmovups @out[2],-16(@ptr[2]) sub `64+2*8`(%rsp),@ptr[2] vmovdqu @out[1],0x10($offload) vpxor $zero,@out[1],@out[1] @@ -1149,11 +1212,11 @@ $code.=<<___; vpxor $zero,@out[3],@out[3] vmovdqu @inp[0],0x40($offload) vpxor @inp[0],$zero,@out[4] - vmovups @out[5],-16(@ptr[5]) + vmovups @out[5],-16(@ptr[5]) sub `64+5*8`(%rsp),@ptr[5] vmovdqu @inp[1],0x50($offload) vpxor @inp[1],$zero,@out[5] - vmovups @out[6],-16(@ptr[6]) + vmovups @out[6],-16(@ptr[6]) sub `64+6*8`(%rsp),@ptr[6] vmovdqu @inp[2],0x60($offload) vpxor @inp[2],$zero,@out[6] @@ -1167,6 +1230,7 @@ $code.=<<___; jnz .Loop_dec8x mov 16(%rsp),%rax # original %rsp +.cfi_def_cfa %rax,8 #mov 24(%rsp),$num #lea `40*8`($inp),$inp #dec $num @@ -1189,14 +1253,22 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -48(%rax),%r15 +.cfi_restore %r15 mov -40(%rax),%r14 +.cfi_restore %r14 mov -32(%rax),%r13 +.cfi_restore %r13 mov -24(%rax),%r12 +.cfi_restore %r12 mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Ldec8x_epilogue: ret +.cfi_endproc .size aesni_multi_cbc_decrypt_avx,.-aesni_multi_cbc_decrypt_avx ___ }}} @@ -1253,10 +1325,10 @@ se_handler: mov -48(%rax),%r15 mov %rbx,144($context) # restore context->Rbx mov %rbp,160($context) # restore context->Rbp - mov %r12,216($context) # restore cotnext->R12 - mov %r13,224($context) # restore cotnext->R13 - mov %r14,232($context) # restore cotnext->R14 - mov %r15,240($context) # restore cotnext->R15 + mov %r12,216($context) # restore context->R12 + mov %r13,224($context) # restore context->R13 + mov %r14,232($context) # restore context->R14 + mov %r15,240($context) # restore context->R15 lea -56-10*16(%rax),%rsi lea 512($context),%rdi # &context.Xmm6 diff --git a/crypto/aes/asm/aesni-sha1-x86_64.pl b/crypto/aes/asm/aesni-sha1-x86_64.pl index 33a7f0cf..b01a4c55 100644 --- a/crypto/aes/asm/aesni-sha1-x86_64.pl +++ b/crypto/aes/asm/aesni-sha1-x86_64.pl @@ -191,16 +191,24 @@ $code.=<<___; .type aesni_cbc_sha1_enc_ssse3,\@function,6 .align 32 aesni_cbc_sha1_enc_ssse3: +.cfi_startproc mov `($win64?56:8)`(%rsp),$inp # load 7th argument #shr \$6,$len # debugging artefact #jz .Lepilogue_ssse3 # debugging artefact push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 lea `-104-($win64?10*16:0)`(%rsp),%rsp +.cfi_adjust_cfa_offset `104+($win64?10*16:0)` #mov $in0,$inp # debugging artefact #lea 64(%rsp),$ctx # debugging artefact ___ @@ -726,15 +734,24 @@ $code.=<<___ if ($win64); ___ $code.=<<___; lea `104+($win64?10*16:0)`(%rsp),%rsi +.cfi_def_cfa %rsi,56 mov 0(%rsi),%r15 +.cfi_restore %r15 mov 8(%rsi),%r14 +.cfi_restore %r14 mov 16(%rsi),%r13 +.cfi_restore %r13 mov 24(%rsi),%r12 +.cfi_restore %r12 mov 32(%rsi),%rbp +.cfi_restore %rbp mov 40(%rsi),%rbx +.cfi_restore %rbx lea 48(%rsi),%rsp +.cfi_def_cfa %rsp,8 .Lepilogue_ssse3: ret +.cfi_endproc .size aesni_cbc_sha1_enc_ssse3,.-aesni_cbc_sha1_enc_ssse3 ___ @@ -798,7 +815,7 @@ sub body_00_19_dec () { # ((c^d)&b)^d sub body_20_39_dec () { # b^d^c # on entry @T[0]=b^d return &body_40_59_dec() if ($rx==39); - + my @r=@body_20_39; unshift (@r,@aes256_dec[$rx]) if (@aes256_dec[$rx]); @@ -842,14 +859,22 @@ $code.=<<___; .type aesni256_cbc_sha1_dec_ssse3,\@function,6 .align 32 aesni256_cbc_sha1_dec_ssse3: +.cfi_startproc mov `($win64?56:8)`(%rsp),$inp # load 7th argument push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 lea `-104-($win64?10*16:0)`(%rsp),%rsp +.cfi_adjust_cfa_offset `104+($win64?10*16:0)` ___ $code.=<<___ if ($win64); movaps %xmm6,96+0(%rsp) @@ -997,15 +1022,24 @@ $code.=<<___ if ($win64); ___ $code.=<<___; lea `104+($win64?10*16:0)`(%rsp),%rsi +.cfi_cfa_def %rsi,56 mov 0(%rsi),%r15 +.cfi_restore %r15 mov 8(%rsi),%r14 +.cfi_restore %r14 mov 16(%rsi),%r13 +.cfi_restore %r13 mov 24(%rsi),%r12 +.cfi_restore %r12 mov 32(%rsi),%rbp +.cfi_restore %rbp mov 40(%rsi),%rbx +.cfi_restore %rbx lea 48(%rsi),%rsp +.cfi_cfa_def %rsp,8 .Lepilogue_dec_ssse3: ret +.cfi_endproc .size aesni256_cbc_sha1_dec_ssse3,.-aesni256_cbc_sha1_dec_ssse3 ___ }}} @@ -1031,16 +1065,24 @@ $code.=<<___; .type aesni_cbc_sha1_enc_avx,\@function,6 .align 32 aesni_cbc_sha1_enc_avx: +.cfi_startproc mov `($win64?56:8)`(%rsp),$inp # load 7th argument #shr \$6,$len # debugging artefact #jz .Lepilogue_avx # debugging artefact push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 lea `-104-($win64?10*16:0)`(%rsp),%rsp +.cfi_adjust_cfa_offset `104+($win64?10*16:0)` #mov $in0,$inp # debugging artefact #lea 64(%rsp),$ctx # debugging artefact ___ @@ -1439,15 +1481,24 @@ $code.=<<___ if ($win64); ___ $code.=<<___; lea `104+($win64?10*16:0)`(%rsp),%rsi +.cfi_def_cfa %rsi,56 mov 0(%rsi),%r15 +.cfi_restore %r15 mov 8(%rsi),%r14 +.cfi_restore %r14 mov 16(%rsi),%r13 +.cfi_restore %r13 mov 24(%rsi),%r12 +.cfi_restore %r12 mov 32(%rsi),%rbp +.cfi_restore %rbp mov 40(%rsi),%rbx +.cfi_restore %rbx lea 48(%rsi),%rsp +.cfi_def_cfa %rsp,8 .Lepilogue_avx: ret +.cfi_endproc .size aesni_cbc_sha1_enc_avx,.-aesni_cbc_sha1_enc_avx ___ @@ -1496,14 +1547,22 @@ $code.=<<___; .type aesni256_cbc_sha1_dec_avx,\@function,6 .align 32 aesni256_cbc_sha1_dec_avx: +.cfi_startproc mov `($win64?56:8)`(%rsp),$inp # load 7th argument push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 lea `-104-($win64?10*16:0)`(%rsp),%rsp +.cfi_adjust_cfa_offset `104+($win64?10*16:0)` ___ $code.=<<___ if ($win64); movaps %xmm6,96+0(%rsp) @@ -1650,15 +1709,24 @@ $code.=<<___ if ($win64); ___ $code.=<<___; lea `104+($win64?10*16:0)`(%rsp),%rsi +.cfi_def_cfa %rsi,56 mov 0(%rsi),%r15 +.cfi_restore %r15 mov 8(%rsi),%r14 +.cfi_restore %r14 mov 16(%rsi),%r13 +.cfi_restore %r13 mov 24(%rsi),%r12 +.cfi_restore %r12 mov 32(%rsi),%rbp +.cfi_restore %rbp mov 40(%rsi),%rbx +.cfi_restore %rbx lea 48(%rsi),%rsp +.cfi_def_cfa %rsp,8 .Lepilogue_dec_avx: ret +.cfi_endproc .size aesni256_cbc_sha1_dec_avx,.-aesni256_cbc_sha1_dec_avx ___ }}} diff --git a/crypto/aes/asm/aesni-sha256-x86_64.pl b/crypto/aes/asm/aesni-sha256-x86_64.pl index 0e49f26f..ef460237 100644 --- a/crypto/aes/asm/aesni-sha256-x86_64.pl +++ b/crypto/aes/asm/aesni-sha256-x86_64.pl @@ -112,7 +112,7 @@ $_key="16*$SZ+3*8(%rsp)"; $_ivp="16*$SZ+4*8(%rsp)"; $_ctx="16*$SZ+5*8(%rsp)"; $_in0="16*$SZ+6*8(%rsp)"; -$_rsp="16*$SZ+7*8(%rsp)"; +$_rsp="`16*$SZ+7*8`(%rsp)"; $framesz=16*$SZ+8*8; $code=<<___; @@ -342,15 +342,23 @@ $code.=<<___; .type ${func}_xop,\@function,6 .align 64 ${func}_xop: +.cfi_startproc .Lxop_shortcut: mov `($win64?56:8)`(%rsp),$in0 # load 7th parameter + mov %rsp,%rax # copy %rsp +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 - mov %rsp,%r11 # copy %rsp +.cfi_push %r15 sub \$`$framesz+$win64*16*10`,%rsp and \$-64,%rsp # align stack frame @@ -366,7 +374,8 @@ ${func}_xop: mov $ivp,$_ivp mov $ctx,$_ctx mov $in0,$_in0 - mov %r11,$_rsp + mov %rax,$_rsp +.cfi_cfa_expression $_rsp,deref,+8 ___ $code.=<<___ if ($win64); movaps %xmm6,`$framesz+16*0`(%rsp) @@ -604,6 +613,7 @@ $code.=<<___; mov $_ivp,$ivp mov $_rsp,%rsi +.cfi_def_cfa %rsi,8 vmovdqu $iv,($ivp) # output IV vzeroall ___ @@ -620,15 +630,23 @@ $code.=<<___ if ($win64); movaps `$framesz+16*9`(%rsp),%xmm15 ___ $code.=<<___; - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_xop: ret +.cfi_endproc .size ${func}_xop,.-${func}_xop ___ ###################################################################### @@ -640,15 +658,23 @@ $code.=<<___; .type ${func}_avx,\@function,6 .align 64 ${func}_avx: +.cfi_startproc .Lavx_shortcut: mov `($win64?56:8)`(%rsp),$in0 # load 7th parameter + mov %rsp,%rax # copy %rsp +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 - mov %rsp,%r11 # copy %rsp +.cfi_push %r15 sub \$`$framesz+$win64*16*10`,%rsp and \$-64,%rsp # align stack frame @@ -664,7 +690,8 @@ ${func}_avx: mov $ivp,$_ivp mov $ctx,$_ctx mov $in0,$_in0 - mov %r11,$_rsp + mov %rax,$_rsp +.cfi_cfa_expression $_rsp,deref,+8 ___ $code.=<<___ if ($win64); movaps %xmm6,`$framesz+16*0`(%rsp) @@ -855,6 +882,7 @@ $code.=<<___; mov $_ivp,$ivp mov $_rsp,%rsi +.cfi_def_cfa %rsi,8 vmovdqu $iv,($ivp) # output IV vzeroall ___ @@ -871,15 +899,23 @@ $code.=<<___ if ($win64); movaps `$framesz+16*9`(%rsp),%xmm15 ___ $code.=<<___; - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_avx: ret +.cfi_endproc .size ${func}_avx,.-${func}_avx ___ @@ -887,7 +923,7 @@ if ($avx>1) {{ ###################################################################### # AVX2+BMI code path # -my $a5=$SZ==4?"%esi":"%rsi"; # zap $inp +my $a5=$SZ==4?"%esi":"%rsi"; # zap $inp my $PUSH8=8*2*$SZ; use integer; @@ -936,15 +972,23 @@ $code.=<<___; .type ${func}_avx2,\@function,6 .align 64 ${func}_avx2: +.cfi_startproc .Lavx2_shortcut: mov `($win64?56:8)`(%rsp),$in0 # load 7th parameter + mov %rsp,%rax # copy %rsp +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 - mov %rsp,%r11 # copy %rsp +.cfi_push %r15 sub \$`2*$SZ*$rounds+8*8+$win64*16*10`,%rsp and \$-256*$SZ,%rsp # align stack frame add \$`2*$SZ*($rounds-8)`,%rsp @@ -961,7 +1005,8 @@ ${func}_avx2: mov $ivp,$_ivp mov $ctx,$_ctx mov $in0,$_in0 - mov %r11,$_rsp + mov %rax,$_rsp +.cfi_cfa_expression $_rsp,deref,+8 ___ $code.=<<___ if ($win64); movaps %xmm6,`$framesz+16*0`(%rsp) @@ -1192,6 +1237,7 @@ $code.=<<___; lea ($Tbl),%rsp mov $_ivp,$ivp mov $_rsp,%rsi +.cfi_def_cfa %rsi,8 vmovdqu $iv,($ivp) # output IV vzeroall ___ @@ -1208,15 +1254,23 @@ $code.=<<___ if ($win64); movaps `$framesz+16*9`(%rsp),%xmm15 ___ $code.=<<___; - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_avx2: ret +.cfi_endproc .size ${func}_avx2,.-${func}_avx2 ___ }} @@ -1573,7 +1627,6 @@ ___ $code.=<<___; mov %rax,%rsi # put aside Rsp mov 16*$SZ+7*8(%rax),%rax # pull $_rsp - lea 48(%rax),%rax mov -8(%rax),%rbx mov -16(%rax),%rbp diff --git a/crypto/aes/asm/aesni-x86.pl b/crypto/aes/asm/aesni-x86.pl index ed1a47c3..b351fca2 100644 --- a/crypto/aes/asm/aesni-x86.pl +++ b/crypto/aes/asm/aesni-x86.pl @@ -62,7 +62,9 @@ # Westmere 3.77/1.37 1.37 1.52 1.27 # * Bridge 5.07/0.98 0.99 1.09 0.91 1.10 # Haswell 4.44/0.80 0.97 1.03 0.72 0.76 +# Skylake 2.68/0.65 0.65 0.66 0.64 0.66 # Silvermont 5.77/3.56 3.67 4.03 3.46 4.03 +# Goldmont 3.84/1.39 1.39 1.63 1.31 1.70 # Bulldozer 5.80/0.98 1.05 1.24 0.93 1.23 $PREFIX="aesni"; # if $PREFIX is set to "AES", the script @@ -78,7 +80,7 @@ $output = pop; open OUT,">$output"; *STDOUT=*OUT; -&asm_init($ARGV[0],$0); +&asm_init($ARGV[0]); &external_label("OPENSSL_ia32cap_P"); &static_label("key_const"); @@ -237,7 +239,7 @@ sub aesni_generate1 # fully unrolled loop # can schedule aes[enc|dec] every cycle optimal interleave factor # equals to corresponding instructions latency. 8x is optimal for # * Bridge, but it's unfeasible to accommodate such implementation -# in XMM registers addreassable in 32-bit mode and therefore maximum +# in XMM registers addressable in 32-bit mode and therefore maximum # of 6x is used instead... sub aesni_generate2 @@ -1051,7 +1053,7 @@ if ($PREFIX eq "aesni") { &set_label("ctr32_one_shortcut",16); &movups ($inout0,&QWP(0,$rounds_)); # load ivec &mov ($rounds,&DWP(240,$key)); - + &set_label("ctr32_one"); if ($inline) { &aesni_inline_generate1("enc"); } diff --git a/crypto/aes/asm/aesni-x86_64.pl b/crypto/aes/asm/aesni-x86_64.pl index 98ca1799..2a202c53 100644 --- a/crypto/aes/asm/aesni-x86_64.pl +++ b/crypto/aes/asm/aesni-x86_64.pl @@ -34,7 +34,7 @@ # ECB 4.25/4.25 1.38/1.38 1.28/1.28 1.26/1.26 1.26/1.26 # CTR 5.42/5.42 1.92/1.92 1.44/1.44 1.28/1.28 1.26/1.26 # CBC 4.38/4.43 4.15/1.43 4.07/1.32 4.07/1.29 4.06/1.28 -# CCM 5.66/9.42 4.42/5.41 4.16/4.40 4.09/4.15 4.06/4.07 +# CCM 5.66/9.42 4.42/5.41 4.16/4.40 4.09/4.15 4.06/4.07 # OFB 5.42/5.42 4.64/4.64 4.44/4.44 4.39/4.39 4.38/4.38 # CFB 5.73/5.85 5.56/5.62 5.48/5.56 5.47/5.55 5.47/5.55 # @@ -60,7 +60,7 @@ # identical to CBC, because CBC-MAC is essentially CBC encrypt without # saving output. CCM CTR "stays invisible," because it's neatly # interleaved wih CBC-MAC. This provides ~30% improvement over -# "straghtforward" CCM implementation with CTR and CBC-MAC performed +# "straightforward" CCM implementation with CTR and CBC-MAC performed # disjointly. Parallelizable modes practically achieve the theoretical # limit. # @@ -118,7 +118,7 @@ # performance is achieved by interleaving instructions working on # independent blocks. In which case asymptotic limit for such modes # can be obtained by dividing above mentioned numbers by AES -# instructions' interleave factor. Westmere can execute at most 3 +# instructions' interleave factor. Westmere can execute at most 3 # instructions at a time, meaning that optimal interleave factor is 3, # and that's where the "magic" number of 1.25 come from. "Optimal # interleave factor" means that increase of interleave factor does @@ -143,14 +143,14 @@ # asymptotic, if it can be surpassed, isn't it? What happens there? # Rewind to CBC paragraph for the answer. Yes, out-of-order execution # magic is responsible for this. Processor overlaps not only the -# additional instructions with AES ones, but even AES instuctions +# additional instructions with AES ones, but even AES instructions # processing adjacent triplets of independent blocks. In the 6x case # additional instructions still claim disproportionally small amount # of additional cycles, but in 8x case number of instructions must be # a tad too high for out-of-order logic to cope with, and AES unit # remains underutilized... As you can see 8x interleave is hardly # justifiable, so there no need to feel bad that 32-bit aesni-x86.pl -# utilizies 6x interleave because of limited register bank capacity. +# utilizes 6x interleave because of limited register bank capacity. # # Higher interleave factors do have negative impact on Westmere # performance. While for ECB mode it's negligible ~1.5%, other @@ -179,8 +179,10 @@ # Haswell 4.44/0.63 0.63 0.73 0.63 0.70 # Skylake 2.62/0.63 0.63 0.63 0.63 # Silvermont 5.75/3.54 3.56 4.12 3.87(*) 4.11 +# Knights L 2.54/0.77 0.78 0.85 - 1.50 # Goldmont 3.82/1.26 1.26 1.29 1.29 1.50 # Bulldozer 5.77/0.70 0.72 0.90 0.70 0.95 +# Ryzen 2.71/0.35 0.35 0.44 0.38 0.49 # # (*) Atom Silvermont ECB result is suboptimal because of penalties # incurred by operations on %xmm8-15. As ECB is not considered @@ -313,7 +315,7 @@ ___ # on 2x subroutine on Atom Silvermont account. For processors that # can schedule aes[enc|dec] every cycle optimal interleave factor # equals to corresponding instructions latency. 8x is optimal for -# * Bridge and "super-optimal" for other Intel CPUs... +# * Bridge and "super-optimal" for other Intel CPUs... sub aesni_generate2 { my $dir=shift; @@ -1172,7 +1174,7 @@ ___ # with zero-round key xor. { my ($in0,$in1,$in2,$in3,$in4,$in5)=map("%xmm$_",(10..15)); -my ($key0,$ctr)=("${key_}d","${ivp}d"); +my ($key0,$ctr)=("%ebp","${ivp}d"); my $frame_size = 0x80 + ($win64?160:0); $code.=<<___; @@ -1180,6 +1182,7 @@ $code.=<<___; .type aesni_ctr32_encrypt_blocks,\@function,5 .align 16 aesni_ctr32_encrypt_blocks: +.cfi_startproc cmp \$1,$len jne .Lctr32_bulk @@ -1201,26 +1204,27 @@ $code.=<<___; .align 16 .Lctr32_bulk: - lea (%rsp),%rax + lea (%rsp),$key_ # use $key_ as frame pointer +.cfi_def_cfa_register $key_ push %rbp +.cfi_push %rbp sub \$$frame_size,%rsp and \$-16,%rsp # Linux kernel stack can be incorrectly seeded ___ $code.=<<___ if ($win64); - movaps %xmm6,-0xa8(%rax) # offload everything - movaps %xmm7,-0x98(%rax) - movaps %xmm8,-0x88(%rax) - movaps %xmm9,-0x78(%rax) - movaps %xmm10,-0x68(%rax) - movaps %xmm11,-0x58(%rax) - movaps %xmm12,-0x48(%rax) - movaps %xmm13,-0x38(%rax) - movaps %xmm14,-0x28(%rax) - movaps %xmm15,-0x18(%rax) + movaps %xmm6,-0xa8($key_) # offload everything + movaps %xmm7,-0x98($key_) + movaps %xmm8,-0x88($key_) + movaps %xmm9,-0x78($key_) + movaps %xmm10,-0x68($key_) + movaps %xmm11,-0x58($key_) + movaps %xmm12,-0x48($key_) + movaps %xmm13,-0x38($key_) + movaps %xmm14,-0x28($key_) + movaps %xmm15,-0x18($key_) .Lctr32_body: ___ $code.=<<___; - lea -8(%rax),%rbp # 8 16-byte words on top of stack are counter values # xor-ed with zero-round key @@ -1272,7 +1276,7 @@ $code.=<<___; lea 7($ctr),%r9 mov %r10d,0x60+12(%rsp) bswap %r9d - mov OPENSSL_ia32cap_P+4(%rip),%r10d + mov OPENSSL_ia32cap_P+4(%rip),%r10d xor $key0,%r9d and \$`1<<26|1<<22`,%r10d # isolate XSAVE+MOVBE mov %r9d,0x70+12(%rsp) @@ -1546,13 +1550,13 @@ $code.=<<___; sub \$8,$len jnc .Lctr32_loop8 # loop if $len-=8 didn't borrow - add \$8,$len # restore real remainig $len + add \$8,$len # restore real remaining $len jz .Lctr32_done # done if ($len==0) lea -0x80($key),$key .Lctr32_tail: # note that at this point $inout0..5 are populated with - # counter values xor-ed with 0-round key + # counter values xor-ed with 0-round key lea 16($key),$key cmp \$4,$len jb .Lctr32_loop3 @@ -1663,7 +1667,7 @@ $code.=<<___; movups $inout2,0x20($out) # $len was 3, stop store .Lctr32_done: - xorps %xmm0,%xmm0 # clear regiser bank + xorps %xmm0,%xmm0 # clear register bank xor $key0,$key0 pxor %xmm1,%xmm1 pxor %xmm2,%xmm2 @@ -1692,26 +1696,26 @@ $code.=<<___ if (!$win64); pxor %xmm15,%xmm15 ___ $code.=<<___ if ($win64); - movaps -0xa0(%rbp),%xmm6 - movaps %xmm0,-0xa0(%rbp) # clear stack - movaps -0x90(%rbp),%xmm7 - movaps %xmm0,-0x90(%rbp) - movaps -0x80(%rbp),%xmm8 - movaps %xmm0,-0x80(%rbp) - movaps -0x70(%rbp),%xmm9 - movaps %xmm0,-0x70(%rbp) - movaps -0x60(%rbp),%xmm10 - movaps %xmm0,-0x60(%rbp) - movaps -0x50(%rbp),%xmm11 - movaps %xmm0,-0x50(%rbp) - movaps -0x40(%rbp),%xmm12 - movaps %xmm0,-0x40(%rbp) - movaps -0x30(%rbp),%xmm13 - movaps %xmm0,-0x30(%rbp) - movaps -0x20(%rbp),%xmm14 - movaps %xmm0,-0x20(%rbp) - movaps -0x10(%rbp),%xmm15 - movaps %xmm0,-0x10(%rbp) + movaps -0xa8($key_),%xmm6 + movaps %xmm0,-0xa8($key_) # clear stack + movaps -0x98($key_),%xmm7 + movaps %xmm0,-0x98($key_) + movaps -0x88($key_),%xmm8 + movaps %xmm0,-0x88($key_) + movaps -0x78($key_),%xmm9 + movaps %xmm0,-0x78($key_) + movaps -0x68($key_),%xmm10 + movaps %xmm0,-0x68($key_) + movaps -0x58($key_),%xmm11 + movaps %xmm0,-0x58($key_) + movaps -0x48($key_),%xmm12 + movaps %xmm0,-0x48($key_) + movaps -0x38($key_),%xmm13 + movaps %xmm0,-0x38($key_) + movaps -0x28($key_),%xmm14 + movaps %xmm0,-0x28($key_) + movaps -0x18($key_),%xmm15 + movaps %xmm0,-0x18($key_) movaps %xmm0,0x00(%rsp) movaps %xmm0,0x10(%rsp) movaps %xmm0,0x20(%rsp) @@ -1722,10 +1726,13 @@ $code.=<<___ if ($win64); movaps %xmm0,0x70(%rsp) ___ $code.=<<___; - lea (%rbp),%rsp - pop %rbp + mov -8($key_),%rbp +.cfi_restore %rbp + lea ($key_),%rsp +.cfi_def_cfa_register %rsp .Lctr32_epilogue: ret +.cfi_endproc .size aesni_ctr32_encrypt_blocks,.-aesni_ctr32_encrypt_blocks ___ } @@ -1740,32 +1747,35 @@ my @tweak=map("%xmm$_",(10..15)); my ($twmask,$twres,$twtmp)=("%xmm8","%xmm9",@tweak[4]); my ($key2,$ivp,$len_)=("%r8","%r9","%r9"); my $frame_size = 0x70 + ($win64?160:0); +my $key_ = "%rbp"; # override so that we can use %r11 as FP $code.=<<___; .globl aesni_xts_encrypt .type aesni_xts_encrypt,\@function,6 .align 16 aesni_xts_encrypt: - lea (%rsp),%rax +.cfi_startproc + lea (%rsp),%r11 # frame pointer +.cfi_def_cfa_register %r11 push %rbp +.cfi_push %rbp sub \$$frame_size,%rsp and \$-16,%rsp # Linux kernel stack can be incorrectly seeded ___ $code.=<<___ if ($win64); - movaps %xmm6,-0xa8(%rax) # offload everything - movaps %xmm7,-0x98(%rax) - movaps %xmm8,-0x88(%rax) - movaps %xmm9,-0x78(%rax) - movaps %xmm10,-0x68(%rax) - movaps %xmm11,-0x58(%rax) - movaps %xmm12,-0x48(%rax) - movaps %xmm13,-0x38(%rax) - movaps %xmm14,-0x28(%rax) - movaps %xmm15,-0x18(%rax) + movaps %xmm6,-0xa8(%r11) # offload everything + movaps %xmm7,-0x98(%r11) + movaps %xmm8,-0x88(%r11) + movaps %xmm9,-0x78(%r11) + movaps %xmm10,-0x68(%r11) + movaps %xmm11,-0x58(%r11) + movaps %xmm12,-0x48(%r11) + movaps %xmm13,-0x38(%r11) + movaps %xmm14,-0x28(%r11) + movaps %xmm15,-0x18(%r11) .Lxts_enc_body: ___ $code.=<<___; - lea -8(%rax),%rbp movups ($ivp),$inout0 # load clear-text tweak mov 240(%r8),$rounds # key2->rounds mov 240($key),$rnds_ # key1->rounds @@ -1846,7 +1856,7 @@ $code.=<<___; lea `16*6`($inp),$inp pxor $twmask,$inout5 - pxor $twres,@tweak[0] # calclulate tweaks^round[last] + pxor $twres,@tweak[0] # calculate tweaks^round[last] aesenc $rndkey1,$inout4 pxor $twres,@tweak[1] movdqa @tweak[0],`16*0`(%rsp) # put aside tweaks^round[last] @@ -2183,26 +2193,26 @@ $code.=<<___ if (!$win64); pxor %xmm15,%xmm15 ___ $code.=<<___ if ($win64); - movaps -0xa0(%rbp),%xmm6 - movaps %xmm0,-0xa0(%rbp) # clear stack - movaps -0x90(%rbp),%xmm7 - movaps %xmm0,-0x90(%rbp) - movaps -0x80(%rbp),%xmm8 - movaps %xmm0,-0x80(%rbp) - movaps -0x70(%rbp),%xmm9 - movaps %xmm0,-0x70(%rbp) - movaps -0x60(%rbp),%xmm10 - movaps %xmm0,-0x60(%rbp) - movaps -0x50(%rbp),%xmm11 - movaps %xmm0,-0x50(%rbp) - movaps -0x40(%rbp),%xmm12 - movaps %xmm0,-0x40(%rbp) - movaps -0x30(%rbp),%xmm13 - movaps %xmm0,-0x30(%rbp) - movaps -0x20(%rbp),%xmm14 - movaps %xmm0,-0x20(%rbp) - movaps -0x10(%rbp),%xmm15 - movaps %xmm0,-0x10(%rbp) + movaps -0xa8(%r11),%xmm6 + movaps %xmm0,-0xa8(%r11) # clear stack + movaps -0x98(%r11),%xmm7 + movaps %xmm0,-0x98(%r11) + movaps -0x88(%r11),%xmm8 + movaps %xmm0,-0x88(%r11) + movaps -0x78(%r11),%xmm9 + movaps %xmm0,-0x78(%r11) + movaps -0x68(%r11),%xmm10 + movaps %xmm0,-0x68(%r11) + movaps -0x58(%r11),%xmm11 + movaps %xmm0,-0x58(%r11) + movaps -0x48(%r11),%xmm12 + movaps %xmm0,-0x48(%r11) + movaps -0x38(%r11),%xmm13 + movaps %xmm0,-0x38(%r11) + movaps -0x28(%r11),%xmm14 + movaps %xmm0,-0x28(%r11) + movaps -0x18(%r11),%xmm15 + movaps %xmm0,-0x18(%r11) movaps %xmm0,0x00(%rsp) movaps %xmm0,0x10(%rsp) movaps %xmm0,0x20(%rsp) @@ -2212,10 +2222,13 @@ $code.=<<___ if ($win64); movaps %xmm0,0x60(%rsp) ___ $code.=<<___; - lea (%rbp),%rsp - pop %rbp + mov -8(%r11),%rbp +.cfi_restore %rbp + lea (%r11),%rsp +.cfi_def_cfa_register %rsp .Lxts_enc_epilogue: ret +.cfi_endproc .size aesni_xts_encrypt,.-aesni_xts_encrypt ___ @@ -2224,26 +2237,28 @@ $code.=<<___; .type aesni_xts_decrypt,\@function,6 .align 16 aesni_xts_decrypt: - lea (%rsp),%rax +.cfi_startproc + lea (%rsp),%r11 # frame pointer +.cfi_def_cfa_register %r11 push %rbp +.cfi_push %rbp sub \$$frame_size,%rsp and \$-16,%rsp # Linux kernel stack can be incorrectly seeded ___ $code.=<<___ if ($win64); - movaps %xmm6,-0xa8(%rax) # offload everything - movaps %xmm7,-0x98(%rax) - movaps %xmm8,-0x88(%rax) - movaps %xmm9,-0x78(%rax) - movaps %xmm10,-0x68(%rax) - movaps %xmm11,-0x58(%rax) - movaps %xmm12,-0x48(%rax) - movaps %xmm13,-0x38(%rax) - movaps %xmm14,-0x28(%rax) - movaps %xmm15,-0x18(%rax) + movaps %xmm6,-0xa8(%r11) # offload everything + movaps %xmm7,-0x98(%r11) + movaps %xmm8,-0x88(%r11) + movaps %xmm9,-0x78(%r11) + movaps %xmm10,-0x68(%r11) + movaps %xmm11,-0x58(%r11) + movaps %xmm12,-0x48(%r11) + movaps %xmm13,-0x38(%r11) + movaps %xmm14,-0x28(%r11) + movaps %xmm15,-0x18(%r11) .Lxts_dec_body: ___ $code.=<<___; - lea -8(%rax),%rbp movups ($ivp),$inout0 # load clear-text tweak mov 240($key2),$rounds # key2->rounds mov 240($key),$rnds_ # key1->rounds @@ -2327,7 +2342,7 @@ $code.=<<___; lea `16*6`($inp),$inp pxor $twmask,$inout5 - pxor $twres,@tweak[0] # calclulate tweaks^round[last] + pxor $twres,@tweak[0] # calculate tweaks^round[last] aesdec $rndkey1,$inout4 pxor $twres,@tweak[1] movdqa @tweak[0],`16*0`(%rsp) # put aside tweaks^last round key @@ -2687,26 +2702,26 @@ $code.=<<___ if (!$win64); pxor %xmm15,%xmm15 ___ $code.=<<___ if ($win64); - movaps -0xa0(%rbp),%xmm6 - movaps %xmm0,-0xa0(%rbp) # clear stack - movaps -0x90(%rbp),%xmm7 - movaps %xmm0,-0x90(%rbp) - movaps -0x80(%rbp),%xmm8 - movaps %xmm0,-0x80(%rbp) - movaps -0x70(%rbp),%xmm9 - movaps %xmm0,-0x70(%rbp) - movaps -0x60(%rbp),%xmm10 - movaps %xmm0,-0x60(%rbp) - movaps -0x50(%rbp),%xmm11 - movaps %xmm0,-0x50(%rbp) - movaps -0x40(%rbp),%xmm12 - movaps %xmm0,-0x40(%rbp) - movaps -0x30(%rbp),%xmm13 - movaps %xmm0,-0x30(%rbp) - movaps -0x20(%rbp),%xmm14 - movaps %xmm0,-0x20(%rbp) - movaps -0x10(%rbp),%xmm15 - movaps %xmm0,-0x10(%rbp) + movaps -0xa8(%r11),%xmm6 + movaps %xmm0,-0xa8(%r11) # clear stack + movaps -0x98(%r11),%xmm7 + movaps %xmm0,-0x98(%r11) + movaps -0x88(%r11),%xmm8 + movaps %xmm0,-0x88(%r11) + movaps -0x78(%r11),%xmm9 + movaps %xmm0,-0x78(%r11) + movaps -0x68(%r11),%xmm10 + movaps %xmm0,-0x68(%r11) + movaps -0x58(%r11),%xmm11 + movaps %xmm0,-0x58(%r11) + movaps -0x48(%r11),%xmm12 + movaps %xmm0,-0x48(%r11) + movaps -0x38(%r11),%xmm13 + movaps %xmm0,-0x38(%r11) + movaps -0x28(%r11),%xmm14 + movaps %xmm0,-0x28(%r11) + movaps -0x18(%r11),%xmm15 + movaps %xmm0,-0x18(%r11) movaps %xmm0,0x00(%rsp) movaps %xmm0,0x10(%rsp) movaps %xmm0,0x20(%rsp) @@ -2716,10 +2731,13 @@ $code.=<<___ if ($win64); movaps %xmm0,0x60(%rsp) ___ $code.=<<___; - lea (%rbp),%rsp - pop %rbp + mov -8(%r11),%rbp +.cfi_restore %rbp + lea (%r11),%rsp +.cfi_def_cfa_register %rsp .Lxts_dec_epilogue: ret +.cfi_endproc .size aesni_xts_decrypt,.-aesni_xts_decrypt ___ } @@ -2744,12 +2762,18 @@ $code.=<<___; .type aesni_ocb_encrypt,\@function,6 .align 32 aesni_ocb_encrypt: +.cfi_startproc lea (%rsp),%rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 ___ $code.=<<___ if ($win64); lea -0xa0(%rsp),%rsp @@ -2943,6 +2967,8 @@ $code.=<<___ if (!$win64); pxor %xmm13,%xmm13 pxor %xmm14,%xmm14 pxor %xmm15,%xmm15 + lea 0x28(%rsp),%rax +.cfi_def_cfa %rax,8 ___ $code.=<<___ if ($win64); movaps 0x00(%rsp),%xmm6 @@ -2967,16 +2993,23 @@ $code.=<<___ if ($win64); movaps %xmm0,0x90(%rsp) lea 0xa0+0x28(%rsp),%rax .Locb_enc_pop: - lea 0xa0(%rsp),%rsp ___ $code.=<<___; - pop %r14 - pop %r13 - pop %r12 - pop %rbp - pop %rbx + mov -40(%rax),%r14 +.cfi_restore %r14 + mov -32(%rax),%r13 +.cfi_restore %r13 + mov -24(%rax),%r12 +.cfi_restore %r12 + mov -16(%rax),%rbp +.cfi_restore %rbp + mov -8(%rax),%rbx +.cfi_restore %rbx + lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Locb_enc_epilogue: ret +.cfi_endproc .size aesni_ocb_encrypt,.-aesni_ocb_encrypt .type __ocb_encrypt6,\@abi-omnipotent @@ -3189,12 +3222,18 @@ __ocb_encrypt1: .type aesni_ocb_decrypt,\@function,6 .align 32 aesni_ocb_decrypt: +.cfi_startproc lea (%rsp),%rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 ___ $code.=<<___ if ($win64); lea -0xa0(%rsp),%rsp @@ -3410,6 +3449,8 @@ $code.=<<___ if (!$win64); pxor %xmm13,%xmm13 pxor %xmm14,%xmm14 pxor %xmm15,%xmm15 + lea 0x28(%rsp),%rax +.cfi_def_cfa %rax,8 ___ $code.=<<___ if ($win64); movaps 0x00(%rsp),%xmm6 @@ -3434,16 +3475,23 @@ $code.=<<___ if ($win64); movaps %xmm0,0x90(%rsp) lea 0xa0+0x28(%rsp),%rax .Locb_dec_pop: - lea 0xa0(%rsp),%rsp ___ $code.=<<___; - pop %r14 - pop %r13 - pop %r12 - pop %rbp - pop %rbx + mov -40(%rax),%r14 +.cfi_restore %r14 + mov -32(%rax),%r13 +.cfi_restore %r13 + mov -24(%rax),%r12 +.cfi_restore %r12 + mov -16(%rax),%rbp +.cfi_restore %rbp + mov -8(%rax),%rbx +.cfi_restore %rbx + lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Locb_dec_epilogue: ret +.cfi_endproc .size aesni_ocb_decrypt,.-aesni_ocb_decrypt .type __ocb_decrypt6,\@abi-omnipotent @@ -3650,13 +3698,13 @@ ___ { my $frame_size = 0x10 + ($win64?0xa0:0); # used in decrypt my ($iv,$in0,$in1,$in2,$in3,$in4)=map("%xmm$_",(10..15)); -my $inp_=$key_; $code.=<<___; .globl ${PREFIX}_cbc_encrypt .type ${PREFIX}_cbc_encrypt,\@function,6 .align 16 ${PREFIX}_cbc_encrypt: +.cfi_startproc test $len,$len # check length jz .Lcbc_ret @@ -3732,8 +3780,10 @@ $code.=<<___; jmp .Lcbc_ret .align 16 .Lcbc_decrypt_bulk: - lea (%rsp),%rax + lea (%rsp),%r11 # frame pointer +.cfi_def_cfa_register %r11 push %rbp +.cfi_push %rbp sub \$$frame_size,%rsp and \$-16,%rsp # Linux kernel stack can be incorrectly seeded ___ @@ -3750,8 +3800,11 @@ $code.=<<___ if ($win64); movaps %xmm15,0xa0(%rsp) .Lcbc_decrypt_body: ___ + +my $inp_=$key_="%rbp"; # reassign $key_ + $code.=<<___; - lea -8(%rax),%rbp + mov $key,$key_ # [re-]backup $key [after reassignment] movups ($ivp),$iv mov $rnds_,$rounds cmp \$0x50,$len @@ -3791,7 +3844,7 @@ $code.=<<___; pxor $rndkey0,$inout1 $movkey 0x10-0x70($key),$rndkey1 pxor $rndkey0,$inout2 - xor $inp_,$inp_ + mov \$-1,$inp_ cmp \$0x70,$len # is there at least 0x60 bytes ahead? pxor $rndkey0,$inout3 pxor $rndkey0,$inout4 @@ -3807,8 +3860,8 @@ $code.=<<___; aesdec $rndkey1,$inout4 aesdec $rndkey1,$inout5 aesdec $rndkey1,$inout6 - setnc ${inp_}b - shl \$7,$inp_ + adc \$0,$inp_ + and \$128,$inp_ aesdec $rndkey1,$inout7 add $inp,$inp_ $movkey 0x30-0x70($key),$rndkey1 @@ -4172,10 +4225,13 @@ $code.=<<___ if ($win64); movaps %xmm0,0xa0(%rsp) ___ $code.=<<___; - lea (%rbp),%rsp - pop %rbp + mov -8(%r11),%rbp +.cfi_restore %rbp + lea (%r11),%rsp +.cfi_def_cfa_register %rsp .Lcbc_ret: ret +.cfi_endproc .size ${PREFIX}_cbc_encrypt,.-${PREFIX}_cbc_encrypt ___ } @@ -4196,7 +4252,9 @@ $code.=<<___; .type ${PREFIX}_set_decrypt_key,\@abi-omnipotent .align 16 ${PREFIX}_set_decrypt_key: +.cfi_startproc .byte 0x48,0x83,0xEC,0x08 # sub rsp,8 +.cfi_adjust_cfa_offset 8 call __aesni_set_encrypt_key shl \$4,$bits # rounds-1 after _aesni_set_encrypt_key test %eax,%eax @@ -4229,15 +4287,16 @@ ${PREFIX}_set_decrypt_key: pxor %xmm0,%xmm0 .Ldec_key_ret: add \$8,%rsp +.cfi_adjust_cfa_offset -8 ret +.cfi_endproc .LSEH_end_set_decrypt_key: .size ${PREFIX}_set_decrypt_key,.-${PREFIX}_set_decrypt_key ___ -# This is based on submission by -# -# Huang Ying -# Vinodh Gopal +# This is based on submission from Intel by +# Huang Ying +# Vinodh Gopal # Kahraman Akdemir # # Aggressively optimized in respect to aeskeygenassist's critical path @@ -4265,7 +4324,9 @@ $code.=<<___; .align 16 ${PREFIX}_set_encrypt_key: __aesni_set_encrypt_key: +.cfi_startproc .byte 0x48,0x83,0xEC,0x08 # sub rsp,8 +.cfi_adjust_cfa_offset 8 mov \$-1,%rax test $inp,$inp jz .Lenc_key_ret @@ -4454,7 +4515,7 @@ __aesni_set_encrypt_key: .align 16 .L14rounds: - movups 16($inp),%xmm2 # remaning half of *userKey + movups 16($inp),%xmm2 # remaining half of *userKey mov \$13,$bits # 14 rounds for 256 lea 16(%rax),%rax cmp \$`1<<28`,%r10d # AVX, but no XOP @@ -4558,7 +4619,9 @@ __aesni_set_encrypt_key: pxor %xmm4,%xmm4 pxor %xmm5,%xmm5 add \$8,%rsp +.cfi_adjust_cfa_offset -8 ret +.cfi_endproc .LSEH_end_set_encrypt_key: .align 16 @@ -4744,13 +4807,16 @@ ctr_xts_se_handler: cmp %r10,%rbx # context->Rip>=epilogue label jae .Lcommon_seh_tail - mov 160($context),%rax # pull context->Rbp - lea -0xa0(%rax),%rsi # %xmm save area + mov 208($context),%rax # pull context->R11 + + lea -0xa8(%rax),%rsi # %xmm save area lea 512($context),%rdi # & context.Xmm6 mov \$20,%ecx # 10*sizeof(%xmm0)/sizeof(%rax) .long 0xa548f3fc # cld; rep movsq - jmp .Lcommon_rbp_tail + mov -8(%rax),%rbp # restore saved %rbp + mov %rbp,160($context) # restore context->Rbp + jmp .Lcommon_seh_tail .size ctr_xts_se_handler,.-ctr_xts_se_handler .type ocb_se_handler,\@abi-omnipotent @@ -4834,9 +4900,13 @@ cbc_se_handler: cmp %r10,%rbx # context->Rip<"prologue" label jb .Lcommon_seh_tail + mov 120($context),%rax # pull context->Rax + lea .Lcbc_decrypt_body(%rip),%r10 cmp %r10,%rbx # context->RipRsp lea .Lcbc_ret(%rip),%r10 cmp %r10,%rbx # context->Rip>="epilogue" label @@ -4847,15 +4917,10 @@ cbc_se_handler: mov \$20,%ecx # 10*sizeof(%xmm0)/sizeof(%rax) .long 0xa548f3fc # cld; rep movsq -.Lcommon_rbp_tail: - mov 160($context),%rax # pull context->Rbp - mov (%rax),%rbp # restore saved %rbp - lea 8(%rax),%rax # adjust stack pointer - mov %rbp,160($context) # restore context->Rbp - jmp .Lcommon_seh_tail + mov 208($context),%rax # pull context->R11 -.Lrestore_cbc_rax: - mov 120($context),%rax + mov -8(%rax),%rbp # restore saved %rbp + mov %rbp,160($context) # restore context->Rbp .Lcommon_seh_tail: mov 8(%rax),%rdi diff --git a/crypto/aes/asm/aesp8-ppc.pl b/crypto/aes/asm/aesp8-ppc.pl index b7e92f65..7463df6c 100755 --- a/crypto/aes/asm/aesp8-ppc.pl +++ b/crypto/aes/asm/aesp8-ppc.pl @@ -3773,7 +3773,7 @@ foreach(split("\n",$code)) { if ($flavour =~ /le$/o) { SWITCH: for($conv) { /\?inv/ && do { @bytes=map($_^0xf,@bytes); last; }; - /\?rev/ && do { @bytes=reverse(@bytes); last; }; + /\?rev/ && do { @bytes=reverse(@bytes); last; }; } } diff --git a/crypto/aes/asm/aest4-sparcv9.pl b/crypto/aes/asm/aest4-sparcv9.pl index bf479c60..54d0c588 100644 --- a/crypto/aes/asm/aest4-sparcv9.pl +++ b/crypto/aes/asm/aest4-sparcv9.pl @@ -8,9 +8,9 @@ # ==================================================================== -# Written by David S. Miller and Andy Polyakov -# . The module is licensed under 2-clause BSD -# license. October 2012. All rights reserved. +# Written by David S. Miller and Andy Polyakov. +# The module is licensed under 2-clause BSD license. October 2012. +# All rights reserved. # ==================================================================== ###################################################################### @@ -44,7 +44,7 @@ # instructions with those on critical path. Amazing! # # As with Intel AES-NI, question is if it's possible to improve -# performance of parallelizeable modes by interleaving round +# performance of parallelizable modes by interleaving round # instructions. Provided round instruction latency and throughput # optimal interleave factor is 2. But can we expect 2x performance # improvement? Well, as round instructions can be issued one per diff --git a/crypto/aes/asm/aesv8-armx.pl b/crypto/aes/asm/aesv8-armx.pl index 1782d5b4..8b37cfc4 100755 --- a/crypto/aes/asm/aesv8-armx.pl +++ b/crypto/aes/asm/aesv8-armx.pl @@ -35,6 +35,7 @@ # Cortex-A57(*) 1.95 0.85 0.93 # Denver 1.96 0.86 0.80 # Mongoose 1.33 1.20 1.20 +# Kryo 1.26 0.94 1.00 # # (*) original 3.64/1.34/1.32 results were for r0p0 revision # and are still same even for updated module; @@ -929,7 +930,7 @@ if ($flavour =~ /64/) { ######## 64-bit code s/^(\s+)v/$1/o or # strip off v prefix s/\bbx\s+lr\b/ret/o; - # fix up remainig legacy suffixes + # fix up remaining legacy suffixes s/\.[ui]?8//o; m/\],#8/o and s/\.16b/\.8b/go; s/\.[ui]?32//o and s/\.16b/\.4s/go; @@ -964,21 +965,21 @@ if ($flavour =~ /64/) { ######## 64-bit code $arg =~ m/q([0-9]+),\s*\{q([0-9]+)\},\s*q([0-9]+)/o && sprintf "vtbl.8 d%d,{q%d},d%d\n\t". - "vtbl.8 d%d,{q%d},d%d", 2*$1,$2,2*$3, 2*$1+1,$2,2*$3+1; + "vtbl.8 d%d,{q%d},d%d", 2*$1,$2,2*$3, 2*$1+1,$2,2*$3+1; } sub unvdup32 { my $arg=shift; $arg =~ m/q([0-9]+),\s*q([0-9]+)\[([0-3])\]/o && - sprintf "vdup.32 q%d,d%d[%d]",$1,2*$2+($3>>1),$3&1; + sprintf "vdup.32 q%d,d%d[%d]",$1,2*$2+($3>>1),$3&1; } sub unvmov32 { my $arg=shift; $arg =~ m/q([0-9]+)\[([0-3])\],(.*)/o && - sprintf "vmov.32 d%d[%d],%s",2*$1+($2>>1),$2&1,$3; + sprintf "vmov.32 d%d[%d],%s",2*$1+($2>>1),$2&1,$3; } foreach(split("\n",$code)) { @@ -988,7 +989,7 @@ if ($flavour =~ /64/) { ######## 64-bit code s/\bv([0-9])\.[12468]+[bsd]\b/q$1/go; # new->old registers s/\/\/\s?/@ /o; # new->old style commentary - # fix up remainig new-style suffixes + # fix up remaining new-style suffixes s/\{q([0-9]+)\},\s*\[(.+)\],#8/sprintf "{d%d},[$2]!",2*$1/eo or s/\],#[0-9]+/]!/o; diff --git a/crypto/aes/asm/bsaes-armv7.pl b/crypto/aes/asm/bsaes-armv7.pl index 7af38afc..0c5e762a 100644 --- a/crypto/aes/asm/bsaes-armv7.pl +++ b/crypto/aes/asm/bsaes-armv7.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 2012-2018 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2012-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 @@ -14,8 +14,7 @@ # details see http://www.openssl.org/~appro/cryptogams/. # # Specific modes and adaptation for Linux kernel by Ard Biesheuvel -# . Permission to use under GPL terms is -# granted. +# of Linaro. Permission to use under GPL terms is granted. # ==================================================================== # Bit-sliced AES for ARM NEON @@ -49,10 +48,7 @@ # # April-August 2013 -# -# Add CBC, CTR and XTS subroutines, adapt for kernel use. -# -# +# Add CBC, CTR and XTS subroutines and adapt for kernel use; courtesy of Ard. $flavour = shift; if ($flavour=~/\w[\w\-]*\.\w+$/) { $output=$flavour; undef $flavour; } @@ -91,7 +87,7 @@ my @s=@_[12..15]; sub InBasisChange { # input in lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb -# output in lsb > [b6, b5, b0, b3, b7, b1, b4, b2] < msb +# output in lsb > [b6, b5, b0, b3, b7, b1, b4, b2] < msb my @b=@_[0..7]; $code.=<<___; veor @b[2], @b[2], @b[1] @@ -746,7 +742,7 @@ $code.=<<___; _bsaes_decrypt8: adr $const,. vldmia $key!, {@XMM[9]} @ round 0 key -#if defined(__thumb2__) || defined(__APPLE__) +#ifdef __APPLE__ adr $const,.LM0ISR #else add $const,$const,#.LM0ISR-_bsaes_decrypt8 @@ -845,7 +841,7 @@ _bsaes_const: _bsaes_encrypt8: adr $const,. vldmia $key!, {@XMM[9]} @ round 0 key -#if defined(__thumb2__) || defined(__APPLE__) +#ifdef __APPLE__ adr $const,.LM0SR #else sub $const,$const,#_bsaes_encrypt8-.LM0SR @@ -953,7 +949,7 @@ $code.=<<___; _bsaes_key_convert: adr $const,. vld1.8 {@XMM[7]}, [$inp]! @ load round 0 key -#if defined(__thumb2__) || defined(__APPLE__) +#ifdef __APPLE__ adr $const,.LM0 #else sub $const,$const,#_bsaes_key_convert-.LM0 diff --git a/crypto/aes/asm/bsaes-x86_64.pl b/crypto/aes/asm/bsaes-x86_64.pl index 921d870e..2c79c2b6 100644 --- a/crypto/aes/asm/bsaes-x86_64.pl +++ b/crypto/aes/asm/bsaes-x86_64.pl @@ -131,7 +131,7 @@ my @s=@_[12..15]; sub InBasisChange { # input in lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb -# output in lsb > [b6, b5, b0, b3, b7, b1, b4, b2] < msb +# output in lsb > [b6, b5, b0, b3, b7, b1, b4, b2] < msb my @b=@_[0..7]; $code.=<<___; pxor @b[6], @b[5] @@ -381,7 +381,7 @@ $code.=<<___; pxor @s[0], @t[3] pxor @s[1], @t[2] pxor @s[2], @t[1] - pxor @s[3], @t[0] + pxor @s[3], @t[0] #Inv_GF16 \t0, \t1, \t2, \t3, \s0, \s1, \s2, \s3 @@ -1165,15 +1165,23 @@ $code.=<<___; .type bsaes_ecb_encrypt_blocks,\@abi-omnipotent .align 16 bsaes_ecb_encrypt_blocks: +.cfi_startproc mov %rsp, %rax .Lecb_enc_prologue: push %rbp +.cfi_push %rbp push %rbx +.cfi_push %rbx push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 lea -0x48(%rsp),%rsp +.cfi_adjust_cfa_offset 0x48 ___ $code.=<<___ if ($win64); lea -0xa0(%rsp), %rsp @@ -1191,6 +1199,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov %rsp,%rbp # backup %rsp +.cfi_def_cfa_register %rbp mov 240($arg4),%eax # rounds mov $arg1,$inp # backup arguments mov $arg2,$out @@ -1334,7 +1343,8 @@ $code.=<<___; cmp %rax, %rbp jb .Lecb_enc_bzero - lea (%rbp),%rsp # restore %rsp + lea 0x78(%rbp),%rax +.cfi_def_cfa %rax,8 ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 @@ -1347,34 +1357,50 @@ $code.=<<___ if ($win64); movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rbp), %rsp + lea 0xa0(%rax), %rax +.Lecb_enc_tail: ___ $code.=<<___; - mov 0x48(%rsp), %r15 - mov 0x50(%rsp), %r14 - mov 0x58(%rsp), %r13 - mov 0x60(%rsp), %r12 - mov 0x68(%rsp), %rbx - mov 0x70(%rsp), %rax - lea 0x78(%rsp), %rsp - mov %rax, %rbp + mov -48(%rax), %r15 +.cfi_restore %r15 + mov -40(%rax), %r14 +.cfi_restore %r14 + mov -32(%rax), %r13 +.cfi_restore %r13 + mov -24(%rax), %r12 +.cfi_restore %r12 + mov -16(%rax), %rbx +.cfi_restore %rbx + mov -8(%rax), %rbp +.cfi_restore %rbp + lea (%rax), %rsp # restore %rsp +.cfi_def_cfa_register %rsp .Lecb_enc_epilogue: ret +.cfi_endproc .size bsaes_ecb_encrypt_blocks,.-bsaes_ecb_encrypt_blocks .globl bsaes_ecb_decrypt_blocks .type bsaes_ecb_decrypt_blocks,\@abi-omnipotent .align 16 bsaes_ecb_decrypt_blocks: +.cfi_startproc mov %rsp, %rax .Lecb_dec_prologue: push %rbp +.cfi_push %rbp push %rbx +.cfi_push %rbx push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 lea -0x48(%rsp),%rsp +.cfi_adjust_cfa_offset 0x48 ___ $code.=<<___ if ($win64); lea -0xa0(%rsp), %rsp @@ -1392,6 +1418,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov %rsp,%rbp # backup %rsp +.cfi_def_cfa_register %rbp mov 240($arg4),%eax # rounds mov $arg1,$inp # backup arguments mov $arg2,$out @@ -1536,7 +1563,8 @@ $code.=<<___; cmp %rax, %rbp jb .Lecb_dec_bzero - lea (%rbp),%rsp # restore %rsp + lea 0x78(%rbp),%rax +.cfi_def_cfa %rax,8 ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 @@ -1549,19 +1577,27 @@ $code.=<<___ if ($win64); movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rbp), %rsp + lea 0xa0(%rax), %rax +.Lecb_dec_tail: ___ $code.=<<___; - mov 0x48(%rsp), %r15 - mov 0x50(%rsp), %r14 - mov 0x58(%rsp), %r13 - mov 0x60(%rsp), %r12 - mov 0x68(%rsp), %rbx - mov 0x70(%rsp), %rax - lea 0x78(%rsp), %rsp - mov %rax, %rbp + mov -48(%rax), %r15 +.cfi_restore %r15 + mov -40(%rax), %r14 +.cfi_restore %r14 + mov -32(%rax), %r13 +.cfi_restore %r13 + mov -24(%rax), %r12 +.cfi_restore %r12 + mov -16(%rax), %rbx +.cfi_restore %rbx + mov -8(%rax), %rbp +.cfi_restore %rbp + lea (%rax), %rsp # restore %rsp +.cfi_def_cfa_register %rsp .Lecb_dec_epilogue: ret +.cfi_endproc .size bsaes_ecb_decrypt_blocks,.-bsaes_ecb_decrypt_blocks ___ } @@ -1571,6 +1607,7 @@ $code.=<<___; .type bsaes_cbc_encrypt,\@abi-omnipotent .align 16 bsaes_cbc_encrypt: +.cfi_startproc ___ $code.=<<___ if ($win64); mov 48(%rsp),$arg6 # pull direction flag @@ -1584,12 +1621,19 @@ $code.=<<___; mov %rsp, %rax .Lcbc_dec_prologue: push %rbp +.cfi_push %rbp push %rbx +.cfi_push %rbx push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 lea -0x48(%rsp), %rsp +.cfi_adjust_cfa_offset 0x48 ___ $code.=<<___ if ($win64); mov 0xa0(%rsp),$arg5 # pull ivp @@ -1608,6 +1652,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov %rsp, %rbp # backup %rsp +.cfi_def_cfa_register %rbp mov 240($arg4), %eax # rounds mov $arg1, $inp # backup arguments mov $arg2, $out @@ -1826,7 +1871,8 @@ $code.=<<___; cmp %rax, %rbp ja .Lcbc_dec_bzero - lea (%rbp),%rsp # restore %rsp + lea 0x78(%rbp),%rax +.cfi_def_cfa %rax,8 ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 @@ -1839,34 +1885,50 @@ $code.=<<___ if ($win64); movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rbp), %rsp + lea 0xa0(%rax), %rax +.Lcbc_dec_tail: ___ $code.=<<___; - mov 0x48(%rsp), %r15 - mov 0x50(%rsp), %r14 - mov 0x58(%rsp), %r13 - mov 0x60(%rsp), %r12 - mov 0x68(%rsp), %rbx - mov 0x70(%rsp), %rax - lea 0x78(%rsp), %rsp - mov %rax, %rbp + mov -48(%rax), %r15 +.cfi_restore %r15 + mov -40(%rax), %r14 +.cfi_restore %r14 + mov -32(%rax), %r13 +.cfi_restore %r13 + mov -24(%rax), %r12 +.cfi_restore %r12 + mov -16(%rax), %rbx +.cfi_restore %rbx + mov -8(%rax), %rbp +.cfi_restore %rbp + lea (%rax), %rsp # restore %rsp +.cfi_def_cfa_register %rsp .Lcbc_dec_epilogue: ret +.cfi_endproc .size bsaes_cbc_encrypt,.-bsaes_cbc_encrypt .globl bsaes_ctr32_encrypt_blocks .type bsaes_ctr32_encrypt_blocks,\@abi-omnipotent .align 16 bsaes_ctr32_encrypt_blocks: +.cfi_startproc mov %rsp, %rax .Lctr_enc_prologue: push %rbp +.cfi_push %rbp push %rbx +.cfi_push %rbx push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 lea -0x48(%rsp), %rsp +.cfi_adjust_cfa_offset 0x48 ___ $code.=<<___ if ($win64); mov 0xa0(%rsp),$arg5 # pull ivp @@ -1885,6 +1947,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov %rsp, %rbp # backup %rsp +.cfi_def_cfa_register %rbp movdqu ($arg5), %xmm0 # load counter mov 240($arg4), %eax # rounds mov $arg1, $inp # backup arguments @@ -2058,7 +2121,8 @@ $code.=<<___; cmp %rax, %rbp ja .Lctr_enc_bzero - lea (%rbp),%rsp # restore %rsp + lea 0x78(%rbp),%rax +.cfi_def_cfa %rax,8 ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 @@ -2071,19 +2135,27 @@ $code.=<<___ if ($win64); movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rbp), %rsp + lea 0xa0(%rax), %rax +.Lctr_enc_tail: ___ $code.=<<___; - mov 0x48(%rsp), %r15 - mov 0x50(%rsp), %r14 - mov 0x58(%rsp), %r13 - mov 0x60(%rsp), %r12 - mov 0x68(%rsp), %rbx - mov 0x70(%rsp), %rax - lea 0x78(%rsp), %rsp - mov %rax, %rbp + mov -48(%rax), %r15 +.cfi_restore %r15 + mov -40(%rax), %r14 +.cfi_restore %r14 + mov -32(%rax), %r13 +.cfi_restore %r13 + mov -24(%rax), %r12 +.cfi_restore %r12 + mov -16(%rax), %rbx +.cfi_restore %rbx + mov -8(%rax), %rbp +.cfi_restore %rbp + lea (%rax), %rsp # restore %rsp +.cfi_def_cfa_register %rsp .Lctr_enc_epilogue: ret +.cfi_endproc .size bsaes_ctr32_encrypt_blocks,.-bsaes_ctr32_encrypt_blocks ___ ###################################################################### @@ -2099,15 +2171,23 @@ $code.=<<___; .type bsaes_xts_encrypt,\@abi-omnipotent .align 16 bsaes_xts_encrypt: +.cfi_startproc mov %rsp, %rax .Lxts_enc_prologue: push %rbp +.cfi_push %rbp push %rbx +.cfi_push %rbx push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 lea -0x48(%rsp), %rsp +.cfi_adjust_cfa_offset 0x48 ___ $code.=<<___ if ($win64); mov 0xa0(%rsp),$arg5 # pull key2 @@ -2127,6 +2207,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov %rsp, %rbp # backup %rsp +.cfi_def_cfa_register %rbp mov $arg1, $inp # backup arguments mov $arg2, $out mov $arg3, $len @@ -2448,7 +2529,8 @@ $code.=<<___; cmp %rax, %rbp ja .Lxts_enc_bzero - lea (%rbp),%rsp # restore %rsp + lea 0x78(%rbp),%rax +.cfi_def_cfa %rax,8 ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 @@ -2461,34 +2543,50 @@ $code.=<<___ if ($win64); movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rbp), %rsp + lea 0xa0(%rax), %rax +.Lxts_enc_tail: ___ $code.=<<___; - mov 0x48(%rsp), %r15 - mov 0x50(%rsp), %r14 - mov 0x58(%rsp), %r13 - mov 0x60(%rsp), %r12 - mov 0x68(%rsp), %rbx - mov 0x70(%rsp), %rax - lea 0x78(%rsp), %rsp - mov %rax, %rbp + mov -48(%rax), %r15 +.cfi_restore %r15 + mov -40(%rax), %r14 +.cfi_restore %r14 + mov -32(%rax), %r13 +.cfi_restore %r13 + mov -24(%rax), %r12 +.cfi_restore %r12 + mov -16(%rax), %rbx +.cfi_restore %rbx + mov -8(%rax), %rbp +.cfi_restore %rbp + lea (%rax), %rsp # restore %rsp +.cfi_def_cfa_register %rsp .Lxts_enc_epilogue: ret +.cfi_endproc .size bsaes_xts_encrypt,.-bsaes_xts_encrypt .globl bsaes_xts_decrypt .type bsaes_xts_decrypt,\@abi-omnipotent .align 16 bsaes_xts_decrypt: +.cfi_startproc mov %rsp, %rax .Lxts_dec_prologue: push %rbp +.cfi_push %rbp push %rbx +.cfi_push %rbx push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 lea -0x48(%rsp), %rsp +.cfi_adjust_cfa_offset 0x48 ___ $code.=<<___ if ($win64); mov 0xa0(%rsp),$arg5 # pull key2 @@ -2855,7 +2953,8 @@ $code.=<<___; cmp %rax, %rbp ja .Lxts_dec_bzero - lea (%rbp),%rsp # restore %rsp + lea 0x78(%rbp),%rax +.cfi_def_cfa %rax,8 ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 @@ -2868,19 +2967,27 @@ $code.=<<___ if ($win64); movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 - lea 0xa0(%rbp), %rsp + lea 0xa0(%rax), %rax +.Lxts_dec_tail: ___ $code.=<<___; - mov 0x48(%rsp), %r15 - mov 0x50(%rsp), %r14 - mov 0x58(%rsp), %r13 - mov 0x60(%rsp), %r12 - mov 0x68(%rsp), %rbx - mov 0x70(%rsp), %rax - lea 0x78(%rsp), %rsp - mov %rax, %rbp + mov -48(%rax), %r15 +.cfi_restore %r15 + mov -40(%rax), %r14 +.cfi_restore %r14 + mov -32(%rax), %r13 +.cfi_restore %r13 + mov -24(%rax), %r12 +.cfi_restore %r12 + mov -16(%rax), %rbx +.cfi_restore %rbx + mov -8(%rax), %rbp +.cfi_restore %rbp + lea (%rax), %rsp # restore %rsp +.cfi_def_cfa_register %rsp .Lxts_dec_epilogue: ret +.cfi_endproc .size bsaes_xts_decrypt,.-bsaes_xts_decrypt ___ } @@ -2974,31 +3081,34 @@ se_handler: mov 0(%r11),%r10d # HandlerData[0] lea (%rsi,%r10),%r10 # prologue label - cmp %r10,%rbx # context->RipRsp + cmp %r10,%rbx # context->Rip<=prologue label + jbe .Lin_prologue mov 4(%r11),%r10d # HandlerData[1] lea (%rsi,%r10),%r10 # epilogue label cmp %r10,%rbx # context->Rip>=epilogue label jae .Lin_prologue + mov 8(%r11),%r10d # HandlerData[2] + lea (%rsi,%r10),%r10 # epilogue label + cmp %r10,%rbx # context->Rip>=tail label + jae .Lin_tail + mov 160($context),%rax # pull context->Rbp lea 0x40(%rax),%rsi # %xmm save area lea 512($context),%rdi # &context.Xmm6 mov \$20,%ecx # 10*sizeof(%xmm0)/sizeof(%rax) .long 0xa548f3fc # cld; rep movsq - lea 0xa0(%rax),%rax # adjust stack pointer + lea 0xa0+0x78(%rax),%rax # adjust stack pointer - mov 0x70(%rax),%rbp - mov 0x68(%rax),%rbx - mov 0x60(%rax),%r12 - mov 0x58(%rax),%r13 - mov 0x50(%rax),%r14 - mov 0x48(%rax),%r15 - lea 0x78(%rax),%rax # adjust stack pointer +.Lin_tail: + mov -48(%rax),%rbp + mov -40(%rax),%rbx + mov -32(%rax),%r12 + mov -24(%rax),%r13 + mov -16(%rax),%r14 + mov -8(%rax),%r15 mov %rbx,144($context) # restore context->Rbx mov %rbp,160($context) # restore context->Rbp mov %r12,216($context) # restore context->R12 @@ -3079,28 +3189,40 @@ $code.=<<___ if ($ecb); .byte 9,0,0,0 .rva se_handler .rva .Lecb_enc_body,.Lecb_enc_epilogue # HandlerData[] + .rva .Lecb_enc_tail + .long 0 .Lecb_dec_info: .byte 9,0,0,0 .rva se_handler .rva .Lecb_dec_body,.Lecb_dec_epilogue # HandlerData[] + .rva .Lecb_dec_tail + .long 0 ___ $code.=<<___; .Lcbc_dec_info: .byte 9,0,0,0 .rva se_handler .rva .Lcbc_dec_body,.Lcbc_dec_epilogue # HandlerData[] + .rva .Lcbc_dec_tail + .long 0 .Lctr_enc_info: .byte 9,0,0,0 .rva se_handler .rva .Lctr_enc_body,.Lctr_enc_epilogue # HandlerData[] + .rva .Lctr_enc_tail + .long 0 .Lxts_enc_info: .byte 9,0,0,0 .rva se_handler .rva .Lxts_enc_body,.Lxts_enc_epilogue # HandlerData[] + .rva .Lxts_enc_tail + .long 0 .Lxts_dec_info: .byte 9,0,0,0 .rva se_handler .rva .Lxts_dec_body,.Lxts_dec_epilogue # HandlerData[] + .rva .Lxts_dec_tail + .long 0 ___ } diff --git a/crypto/aes/asm/vpaes-armv8.pl b/crypto/aes/asm/vpaes-armv8.pl index d6b5f561..5131e13a 100755 --- a/crypto/aes/asm/vpaes-armv8.pl +++ b/crypto/aes/asm/vpaes-armv8.pl @@ -31,7 +31,7 @@ # Apple A7(***) 22.7(**) 10.9/14.3 [8.45/10.0 ] # Mongoose(***) 26.3(**) 21.0/25.0(**) [13.3/16.8 ] # -# (*) ECB denotes approximate result for parallelizeable modes +# (*) ECB denotes approximate result for parallelizable modes # such as CBC decrypt, CTR, etc.; # (**) these results are worse than scalar compiler-generated # code, but it's constant-time and therefore preferred; @@ -137,7 +137,7 @@ _vpaes_consts: .quad 0x07E4A34047A4E300, 0x1DFEB95A5DBEF91A .quad 0x5F36B5DC83EA6900, 0x2841C2ABF49D1E77 -.asciz "Vector Permutaion AES for ARMv8, Mike Hamburg (Stanford University)" +.asciz "Vector Permutation AES for ARMv8, Mike Hamburg (Stanford University)" .size _vpaes_consts,.-_vpaes_consts .align 6 ___ @@ -769,7 +769,7 @@ _vpaes_schedule_core: ld1 {v0.16b}, [$inp] // vmovdqu 16(%rdi),%xmm0 # load key part 2 (unaligned) bl _vpaes_schedule_transform // input transform mov $inp, #7 // mov \$7, %esi - + .Loop_schedule_256: sub $inp, $inp, #1 // dec %esi bl _vpaes_schedule_mangle // output low result @@ -778,7 +778,7 @@ _vpaes_schedule_core: // high round bl _vpaes_schedule_round cbz $inp, .Lschedule_mangle_last - bl _vpaes_schedule_mangle + bl _vpaes_schedule_mangle // low round. swap xmm7 and xmm6 dup v0.4s, v0.s[3] // vpshufd \$0xFF, %xmm0, %xmm0 @@ -787,7 +787,7 @@ _vpaes_schedule_core: mov v7.16b, v6.16b // vmovdqa %xmm6, %xmm7 bl _vpaes_schedule_low_round mov v7.16b, v5.16b // vmovdqa %xmm5, %xmm7 - + b .Loop_schedule_256 ## @@ -814,7 +814,7 @@ _vpaes_schedule_core: .Lschedule_mangle_last_dec: ld1 {v20.2d-v21.2d}, [x11] // reload constants - sub $out, $out, #16 // add \$-16, %rdx + sub $out, $out, #16 // add \$-16, %rdx eor v0.16b, v0.16b, v16.16b // vpxor .Lk_s63(%rip), %xmm0, %xmm0 bl _vpaes_schedule_transform // output transform st1 {v0.2d}, [$out] // vmovdqu %xmm0, (%rdx) # save last key diff --git a/crypto/aes/asm/vpaes-ppc.pl b/crypto/aes/asm/vpaes-ppc.pl index bb38fbe6..3c771a7e 100644 --- a/crypto/aes/asm/vpaes-ppc.pl +++ b/crypto/aes/asm/vpaes-ppc.pl @@ -1075,7 +1075,7 @@ Loop_schedule_256: # high round bl _vpaes_schedule_round bdz Lschedule_mangle_last # dec %esi - bl _vpaes_schedule_mangle + bl _vpaes_schedule_mangle # low round. swap xmm7 and xmm6 ?vspltw v0, v0, 3 # vpshufd \$0xFF, %xmm0, %xmm0 @@ -1083,7 +1083,7 @@ Loop_schedule_256: vmr v7, v6 # vmovdqa %xmm6, %xmm7 bl _vpaes_schedule_low_round vmr v7, v5 # vmovdqa %xmm5, %xmm7 - + b Loop_schedule_256 ## ## .aes_schedule_mangle_last @@ -1131,7 +1131,7 @@ Lschedule_mangle_last: Lschedule_mangle_last_dec: lvx $iptlo, r11, r12 # reload $ipt lvx $ipthi, r9, r12 - addi $out, $out, -16 # add \$-16, %rdx + addi $out, $out, -16 # add \$-16, %rdx vxor v0, v0, v26 # vpxor .Lk_s63(%rip), %xmm0, %xmm0 bl _vpaes_schedule_transform # output transform @@ -1566,7 +1566,7 @@ foreach (split("\n",$code)) { if ($flavour =~ /le$/o) { SWITCH: for($conv) { /\?inv/ && do { @bytes=map($_^0xf,@bytes); last; }; - /\?rev/ && do { @bytes=reverse(@bytes); last; }; + /\?rev/ && do { @bytes=reverse(@bytes); last; }; } } diff --git a/crypto/aes/asm/vpaes-x86.pl b/crypto/aes/asm/vpaes-x86.pl index 47615c07..7d57edc0 100644 --- a/crypto/aes/asm/vpaes-x86.pl +++ b/crypto/aes/asm/vpaes-x86.pl @@ -62,7 +62,7 @@ $output = pop; open OUT,">$output"; *STDOUT=*OUT; -&asm_init($ARGV[0],"vpaes-x86.pl",$x86only = $ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$x86only = $ARGV[$#ARGV] eq "386"); $PREFIX="vpaes"; @@ -445,7 +445,7 @@ $k_dsbo=0x2c0; # decryption sbox final output ## &set_label("schedule_192",16); &movdqu ("xmm0",&QWP(8,$inp)); # load key part 2 (very unaligned) - &call ("_vpaes_schedule_transform"); # input transform + &call ("_vpaes_schedule_transform"); # input transform &movdqa ("xmm6","xmm0"); # save short part &pxor ("xmm4","xmm4"); # clear 4 &movhlps("xmm6","xmm4"); # clobber low side with zeros @@ -476,7 +476,7 @@ $k_dsbo=0x2c0; # decryption sbox final output ## &set_label("schedule_256",16); &movdqu ("xmm0",&QWP(16,$inp)); # load key part 2 (unaligned) - &call ("_vpaes_schedule_transform"); # input transform + &call ("_vpaes_schedule_transform"); # input transform &mov ($round,7); &set_label("loop_schedule_256"); @@ -487,7 +487,7 @@ $k_dsbo=0x2c0; # decryption sbox final output &call ("_vpaes_schedule_round"); &dec ($round); &jz (&label("schedule_mangle_last")); - &call ("_vpaes_schedule_mangle"); + &call ("_vpaes_schedule_mangle"); # low round. swap xmm7 and xmm6 &pshufd ("xmm0","xmm0",0xFF); @@ -610,7 +610,7 @@ $k_dsbo=0x2c0; # decryption sbox final output # subbyte &movdqa ("xmm4",&QWP($k_s0F,$const)); &movdqa ("xmm5",&QWP($k_inv,$const)); # 4 : 1/j - &movdqa ("xmm1","xmm4"); + &movdqa ("xmm1","xmm4"); &pandn ("xmm1","xmm0"); &psrld ("xmm1",4); # 1 = i &pand ("xmm0","xmm4"); # 0 = k diff --git a/crypto/aes/asm/vpaes-x86_64.pl b/crypto/aes/asm/vpaes-x86_64.pl index 422e8ee4..b715aca1 100644 --- a/crypto/aes/asm/vpaes-x86_64.pl +++ b/crypto/aes/asm/vpaes-x86_64.pl @@ -172,7 +172,7 @@ _vpaes_encrypt_core: pshufb %xmm1, %xmm0 ret .size _vpaes_encrypt_core,.-_vpaes_encrypt_core - + ## ## Decryption core ## @@ -333,7 +333,7 @@ _vpaes_schedule_core: ## .Lschedule_128: mov \$10, %esi - + .Loop_schedule_128: call _vpaes_schedule_round dec %rsi @@ -367,7 +367,7 @@ _vpaes_schedule_core: .Loop_schedule_192: call _vpaes_schedule_round - palignr \$8,%xmm6,%xmm0 + palignr \$8,%xmm6,%xmm0 call _vpaes_schedule_mangle # save key n call _vpaes_schedule_192_smear call _vpaes_schedule_mangle # save key n+1 @@ -393,7 +393,7 @@ _vpaes_schedule_core: movdqu 16(%rdi),%xmm0 # load key part 2 (unaligned) call _vpaes_schedule_transform # input transform mov \$7, %esi - + .Loop_schedule_256: call _vpaes_schedule_mangle # output low result movdqa %xmm0, %xmm6 # save cur_lo in xmm6 @@ -402,7 +402,7 @@ _vpaes_schedule_core: call _vpaes_schedule_round dec %rsi jz .Lschedule_mangle_last - call _vpaes_schedule_mangle + call _vpaes_schedule_mangle # low round. swap xmm7 and xmm6 pshufd \$0xFF, %xmm0, %xmm0 @@ -410,10 +410,10 @@ _vpaes_schedule_core: movdqa %xmm6, %xmm7 call _vpaes_schedule_low_round movdqa %xmm5, %xmm7 - + jmp .Loop_schedule_256 - + ## ## .aes_schedule_mangle_last ## @@ -512,9 +512,9 @@ _vpaes_schedule_round: # rotate pshufd \$0xFF, %xmm0, %xmm0 palignr \$1, %xmm0, %xmm0 - + # fall through... - + # low round: same as high round, but no rotation and no rcon. _vpaes_schedule_low_round: # smear xmm7 @@ -553,7 +553,7 @@ _vpaes_schedule_low_round: pxor %xmm4, %xmm0 # 0 = sbox output # add in smeared stuff - pxor %xmm7, %xmm0 + pxor %xmm7, %xmm0 movdqa %xmm0, %xmm7 ret .size _vpaes_schedule_round,.-_vpaes_schedule_round diff --git a/crypto/aes/build.info b/crypto/aes/build.info index cf6cb5ec..0f048636 100644 --- a/crypto/aes/build.info +++ b/crypto/aes/build.info @@ -5,11 +5,14 @@ SOURCE[../../libcrypto]=\ GENERATE[aes-ia64.s]=asm/aes-ia64.S -GENERATE[aes-586.s]=asm/aes-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[aes-586.s]=asm/aes-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[aes-586.s]=../perlasm/x86asm.pl -GENERATE[vpaes-x86.s]=asm/vpaes-x86.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[vpaes-x86.s]=asm/vpaes-x86.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[vpaes-586.s]=../perlasm/x86asm.pl -GENERATE[aesni-x86.s]=asm/aesni-x86.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[aesni-x86.s]=asm/aesni-x86.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[aesni-586.s]=../perlasm/x86asm.pl GENERATE[aes-x86_64.s]=asm/aes-x86_64.pl $(PERLASM_SCHEME) @@ -35,6 +38,7 @@ GENERATE[aesp8-ppc.s]=asm/aesp8-ppc.pl $(PERLASM_SCHEME) GENERATE[aes-parisc.s]=asm/aes-parisc.pl $(PERLASM_SCHEME) GENERATE[aes-mips.S]=asm/aes-mips.pl $(PERLASM_SCHEME) +INCLUDE[aes-mips.o]=.. GENERATE[aesv8-armx.S]=asm/aesv8-armx.pl $(PERLASM_SCHEME) INCLUDE[aesv8-armx.o]=.. @@ -45,6 +49,9 @@ INCLUDE[aes-armv4.o]=.. GENERATE[bsaes-armv7.S]=asm/bsaes-armv7.pl $(PERLASM_SCHEME) INCLUDE[bsaes-armv7.o]=.. +GENERATE[aes-s390x.S]=asm/aes-s390x.pl $(PERLASM_SCHEME) +INCLUDE[aes-s390x.o]=.. + BEGINRAW[Makefile] ##### AES assembler implementations diff --git a/crypto/aria/aria.c b/crypto/aria/aria.c new file mode 100644 index 00000000..293bcc72 --- /dev/null +++ b/crypto/aria/aria.c @@ -0,0 +1,1212 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2017, Oracle and/or its affiliates. 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 + */ + +/* + * Copyright (C) 2017 National Security Research Institute. All Rights Reserved. + * + * Information for ARIA + * http://210.104.33.10/ARIA/index-e.html (English) + * http://seed.kisa.or.kr/ (Korean) + * + * Public domain version is distributed above. + */ + +#include +#include "internal/aria.h" + +#include +#include + +#ifndef OPENSSL_SMALL_FOOTPRINT + +/* Begin macro */ + +/* rotation */ +#define rotl32(v, r) (((uint32_t)(v) << (r)) | ((uint32_t)(v) >> (32 - r))) +#define rotr32(v, r) (((uint32_t)(v) >> (r)) | ((uint32_t)(v) << (32 - r))) + +#define bswap32(v) \ + (((v) << 24) ^ ((v) >> 24) ^ \ + (((v) & 0x0000ff00) << 8) ^ (((v) & 0x00ff0000) >> 8)) + +#define GET_U8_BE(X, Y) ((uint8_t)((X) >> ((3 - Y) * 8))) +#define GET_U32_BE(X, Y) ( \ + ((uint32_t)((const uint8_t *)(X))[Y * 4 ] << 24) ^ \ + ((uint32_t)((const uint8_t *)(X))[Y * 4 + 1] << 16) ^ \ + ((uint32_t)((const uint8_t *)(X))[Y * 4 + 2] << 8) ^ \ + ((uint32_t)((const uint8_t *)(X))[Y * 4 + 3] ) ) + +#define PUT_U32_BE(DEST, IDX, VAL) \ + do { \ + ((uint8_t *)(DEST))[IDX * 4 ] = GET_U8_BE(VAL, 0); \ + ((uint8_t *)(DEST))[IDX * 4 + 1] = GET_U8_BE(VAL, 1); \ + ((uint8_t *)(DEST))[IDX * 4 + 2] = GET_U8_BE(VAL, 2); \ + ((uint8_t *)(DEST))[IDX * 4 + 3] = GET_U8_BE(VAL, 3); \ + } while(0) + +#define MAKE_U32(V0, V1, V2, V3) ( \ + ((uint32_t)((uint8_t)(V0)) << 24) | \ + ((uint32_t)((uint8_t)(V1)) << 16) | \ + ((uint32_t)((uint8_t)(V2)) << 8) | \ + ((uint32_t)((uint8_t)(V3)) ) ) + +/* End Macro*/ + +/* Key Constant + * 128bit : 0, 1, 2 + * 192bit : 1, 2, 3(0) + * 256bit : 2, 3(0), 4(1) + */ +static const uint32_t Key_RC[5][4] = { + { 0x517cc1b7, 0x27220a94, 0xfe13abe8, 0xfa9a6ee0 }, + { 0x6db14acc, 0x9e21c820, 0xff28b1d5, 0xef5de2b0 }, + { 0xdb92371d, 0x2126e970, 0x03249775, 0x04e8c90e }, + { 0x517cc1b7, 0x27220a94, 0xfe13abe8, 0xfa9a6ee0 }, + { 0x6db14acc, 0x9e21c820, 0xff28b1d5, 0xef5de2b0 } +}; + +/* 32bit expanded s-box */ +static const uint32_t S1[256] = { + 0x00636363, 0x007c7c7c, 0x00777777, 0x007b7b7b, + 0x00f2f2f2, 0x006b6b6b, 0x006f6f6f, 0x00c5c5c5, + 0x00303030, 0x00010101, 0x00676767, 0x002b2b2b, + 0x00fefefe, 0x00d7d7d7, 0x00ababab, 0x00767676, + 0x00cacaca, 0x00828282, 0x00c9c9c9, 0x007d7d7d, + 0x00fafafa, 0x00595959, 0x00474747, 0x00f0f0f0, + 0x00adadad, 0x00d4d4d4, 0x00a2a2a2, 0x00afafaf, + 0x009c9c9c, 0x00a4a4a4, 0x00727272, 0x00c0c0c0, + 0x00b7b7b7, 0x00fdfdfd, 0x00939393, 0x00262626, + 0x00363636, 0x003f3f3f, 0x00f7f7f7, 0x00cccccc, + 0x00343434, 0x00a5a5a5, 0x00e5e5e5, 0x00f1f1f1, + 0x00717171, 0x00d8d8d8, 0x00313131, 0x00151515, + 0x00040404, 0x00c7c7c7, 0x00232323, 0x00c3c3c3, + 0x00181818, 0x00969696, 0x00050505, 0x009a9a9a, + 0x00070707, 0x00121212, 0x00808080, 0x00e2e2e2, + 0x00ebebeb, 0x00272727, 0x00b2b2b2, 0x00757575, + 0x00090909, 0x00838383, 0x002c2c2c, 0x001a1a1a, + 0x001b1b1b, 0x006e6e6e, 0x005a5a5a, 0x00a0a0a0, + 0x00525252, 0x003b3b3b, 0x00d6d6d6, 0x00b3b3b3, + 0x00292929, 0x00e3e3e3, 0x002f2f2f, 0x00848484, + 0x00535353, 0x00d1d1d1, 0x00000000, 0x00ededed, + 0x00202020, 0x00fcfcfc, 0x00b1b1b1, 0x005b5b5b, + 0x006a6a6a, 0x00cbcbcb, 0x00bebebe, 0x00393939, + 0x004a4a4a, 0x004c4c4c, 0x00585858, 0x00cfcfcf, + 0x00d0d0d0, 0x00efefef, 0x00aaaaaa, 0x00fbfbfb, + 0x00434343, 0x004d4d4d, 0x00333333, 0x00858585, + 0x00454545, 0x00f9f9f9, 0x00020202, 0x007f7f7f, + 0x00505050, 0x003c3c3c, 0x009f9f9f, 0x00a8a8a8, + 0x00515151, 0x00a3a3a3, 0x00404040, 0x008f8f8f, + 0x00929292, 0x009d9d9d, 0x00383838, 0x00f5f5f5, + 0x00bcbcbc, 0x00b6b6b6, 0x00dadada, 0x00212121, + 0x00101010, 0x00ffffff, 0x00f3f3f3, 0x00d2d2d2, + 0x00cdcdcd, 0x000c0c0c, 0x00131313, 0x00ececec, + 0x005f5f5f, 0x00979797, 0x00444444, 0x00171717, + 0x00c4c4c4, 0x00a7a7a7, 0x007e7e7e, 0x003d3d3d, + 0x00646464, 0x005d5d5d, 0x00191919, 0x00737373, + 0x00606060, 0x00818181, 0x004f4f4f, 0x00dcdcdc, + 0x00222222, 0x002a2a2a, 0x00909090, 0x00888888, + 0x00464646, 0x00eeeeee, 0x00b8b8b8, 0x00141414, + 0x00dedede, 0x005e5e5e, 0x000b0b0b, 0x00dbdbdb, + 0x00e0e0e0, 0x00323232, 0x003a3a3a, 0x000a0a0a, + 0x00494949, 0x00060606, 0x00242424, 0x005c5c5c, + 0x00c2c2c2, 0x00d3d3d3, 0x00acacac, 0x00626262, + 0x00919191, 0x00959595, 0x00e4e4e4, 0x00797979, + 0x00e7e7e7, 0x00c8c8c8, 0x00373737, 0x006d6d6d, + 0x008d8d8d, 0x00d5d5d5, 0x004e4e4e, 0x00a9a9a9, + 0x006c6c6c, 0x00565656, 0x00f4f4f4, 0x00eaeaea, + 0x00656565, 0x007a7a7a, 0x00aeaeae, 0x00080808, + 0x00bababa, 0x00787878, 0x00252525, 0x002e2e2e, + 0x001c1c1c, 0x00a6a6a6, 0x00b4b4b4, 0x00c6c6c6, + 0x00e8e8e8, 0x00dddddd, 0x00747474, 0x001f1f1f, + 0x004b4b4b, 0x00bdbdbd, 0x008b8b8b, 0x008a8a8a, + 0x00707070, 0x003e3e3e, 0x00b5b5b5, 0x00666666, + 0x00484848, 0x00030303, 0x00f6f6f6, 0x000e0e0e, + 0x00616161, 0x00353535, 0x00575757, 0x00b9b9b9, + 0x00868686, 0x00c1c1c1, 0x001d1d1d, 0x009e9e9e, + 0x00e1e1e1, 0x00f8f8f8, 0x00989898, 0x00111111, + 0x00696969, 0x00d9d9d9, 0x008e8e8e, 0x00949494, + 0x009b9b9b, 0x001e1e1e, 0x00878787, 0x00e9e9e9, + 0x00cecece, 0x00555555, 0x00282828, 0x00dfdfdf, + 0x008c8c8c, 0x00a1a1a1, 0x00898989, 0x000d0d0d, + 0x00bfbfbf, 0x00e6e6e6, 0x00424242, 0x00686868, + 0x00414141, 0x00999999, 0x002d2d2d, 0x000f0f0f, + 0x00b0b0b0, 0x00545454, 0x00bbbbbb, 0x00161616 +}; + +static const uint32_t S2[256] = { + 0xe200e2e2, 0x4e004e4e, 0x54005454, 0xfc00fcfc, + 0x94009494, 0xc200c2c2, 0x4a004a4a, 0xcc00cccc, + 0x62006262, 0x0d000d0d, 0x6a006a6a, 0x46004646, + 0x3c003c3c, 0x4d004d4d, 0x8b008b8b, 0xd100d1d1, + 0x5e005e5e, 0xfa00fafa, 0x64006464, 0xcb00cbcb, + 0xb400b4b4, 0x97009797, 0xbe00bebe, 0x2b002b2b, + 0xbc00bcbc, 0x77007777, 0x2e002e2e, 0x03000303, + 0xd300d3d3, 0x19001919, 0x59005959, 0xc100c1c1, + 0x1d001d1d, 0x06000606, 0x41004141, 0x6b006b6b, + 0x55005555, 0xf000f0f0, 0x99009999, 0x69006969, + 0xea00eaea, 0x9c009c9c, 0x18001818, 0xae00aeae, + 0x63006363, 0xdf00dfdf, 0xe700e7e7, 0xbb00bbbb, + 0x00000000, 0x73007373, 0x66006666, 0xfb00fbfb, + 0x96009696, 0x4c004c4c, 0x85008585, 0xe400e4e4, + 0x3a003a3a, 0x09000909, 0x45004545, 0xaa00aaaa, + 0x0f000f0f, 0xee00eeee, 0x10001010, 0xeb00ebeb, + 0x2d002d2d, 0x7f007f7f, 0xf400f4f4, 0x29002929, + 0xac00acac, 0xcf00cfcf, 0xad00adad, 0x91009191, + 0x8d008d8d, 0x78007878, 0xc800c8c8, 0x95009595, + 0xf900f9f9, 0x2f002f2f, 0xce00cece, 0xcd00cdcd, + 0x08000808, 0x7a007a7a, 0x88008888, 0x38003838, + 0x5c005c5c, 0x83008383, 0x2a002a2a, 0x28002828, + 0x47004747, 0xdb00dbdb, 0xb800b8b8, 0xc700c7c7, + 0x93009393, 0xa400a4a4, 0x12001212, 0x53005353, + 0xff00ffff, 0x87008787, 0x0e000e0e, 0x31003131, + 0x36003636, 0x21002121, 0x58005858, 0x48004848, + 0x01000101, 0x8e008e8e, 0x37003737, 0x74007474, + 0x32003232, 0xca00caca, 0xe900e9e9, 0xb100b1b1, + 0xb700b7b7, 0xab00abab, 0x0c000c0c, 0xd700d7d7, + 0xc400c4c4, 0x56005656, 0x42004242, 0x26002626, + 0x07000707, 0x98009898, 0x60006060, 0xd900d9d9, + 0xb600b6b6, 0xb900b9b9, 0x11001111, 0x40004040, + 0xec00ecec, 0x20002020, 0x8c008c8c, 0xbd00bdbd, + 0xa000a0a0, 0xc900c9c9, 0x84008484, 0x04000404, + 0x49004949, 0x23002323, 0xf100f1f1, 0x4f004f4f, + 0x50005050, 0x1f001f1f, 0x13001313, 0xdc00dcdc, + 0xd800d8d8, 0xc000c0c0, 0x9e009e9e, 0x57005757, + 0xe300e3e3, 0xc300c3c3, 0x7b007b7b, 0x65006565, + 0x3b003b3b, 0x02000202, 0x8f008f8f, 0x3e003e3e, + 0xe800e8e8, 0x25002525, 0x92009292, 0xe500e5e5, + 0x15001515, 0xdd00dddd, 0xfd00fdfd, 0x17001717, + 0xa900a9a9, 0xbf00bfbf, 0xd400d4d4, 0x9a009a9a, + 0x7e007e7e, 0xc500c5c5, 0x39003939, 0x67006767, + 0xfe00fefe, 0x76007676, 0x9d009d9d, 0x43004343, + 0xa700a7a7, 0xe100e1e1, 0xd000d0d0, 0xf500f5f5, + 0x68006868, 0xf200f2f2, 0x1b001b1b, 0x34003434, + 0x70007070, 0x05000505, 0xa300a3a3, 0x8a008a8a, + 0xd500d5d5, 0x79007979, 0x86008686, 0xa800a8a8, + 0x30003030, 0xc600c6c6, 0x51005151, 0x4b004b4b, + 0x1e001e1e, 0xa600a6a6, 0x27002727, 0xf600f6f6, + 0x35003535, 0xd200d2d2, 0x6e006e6e, 0x24002424, + 0x16001616, 0x82008282, 0x5f005f5f, 0xda00dada, + 0xe600e6e6, 0x75007575, 0xa200a2a2, 0xef00efef, + 0x2c002c2c, 0xb200b2b2, 0x1c001c1c, 0x9f009f9f, + 0x5d005d5d, 0x6f006f6f, 0x80008080, 0x0a000a0a, + 0x72007272, 0x44004444, 0x9b009b9b, 0x6c006c6c, + 0x90009090, 0x0b000b0b, 0x5b005b5b, 0x33003333, + 0x7d007d7d, 0x5a005a5a, 0x52005252, 0xf300f3f3, + 0x61006161, 0xa100a1a1, 0xf700f7f7, 0xb000b0b0, + 0xd600d6d6, 0x3f003f3f, 0x7c007c7c, 0x6d006d6d, + 0xed00eded, 0x14001414, 0xe000e0e0, 0xa500a5a5, + 0x3d003d3d, 0x22002222, 0xb300b3b3, 0xf800f8f8, + 0x89008989, 0xde00dede, 0x71007171, 0x1a001a1a, + 0xaf00afaf, 0xba00baba, 0xb500b5b5, 0x81008181 +}; + +static const uint32_t X1[256] = { + 0x52520052, 0x09090009, 0x6a6a006a, 0xd5d500d5, + 0x30300030, 0x36360036, 0xa5a500a5, 0x38380038, + 0xbfbf00bf, 0x40400040, 0xa3a300a3, 0x9e9e009e, + 0x81810081, 0xf3f300f3, 0xd7d700d7, 0xfbfb00fb, + 0x7c7c007c, 0xe3e300e3, 0x39390039, 0x82820082, + 0x9b9b009b, 0x2f2f002f, 0xffff00ff, 0x87870087, + 0x34340034, 0x8e8e008e, 0x43430043, 0x44440044, + 0xc4c400c4, 0xdede00de, 0xe9e900e9, 0xcbcb00cb, + 0x54540054, 0x7b7b007b, 0x94940094, 0x32320032, + 0xa6a600a6, 0xc2c200c2, 0x23230023, 0x3d3d003d, + 0xeeee00ee, 0x4c4c004c, 0x95950095, 0x0b0b000b, + 0x42420042, 0xfafa00fa, 0xc3c300c3, 0x4e4e004e, + 0x08080008, 0x2e2e002e, 0xa1a100a1, 0x66660066, + 0x28280028, 0xd9d900d9, 0x24240024, 0xb2b200b2, + 0x76760076, 0x5b5b005b, 0xa2a200a2, 0x49490049, + 0x6d6d006d, 0x8b8b008b, 0xd1d100d1, 0x25250025, + 0x72720072, 0xf8f800f8, 0xf6f600f6, 0x64640064, + 0x86860086, 0x68680068, 0x98980098, 0x16160016, + 0xd4d400d4, 0xa4a400a4, 0x5c5c005c, 0xcccc00cc, + 0x5d5d005d, 0x65650065, 0xb6b600b6, 0x92920092, + 0x6c6c006c, 0x70700070, 0x48480048, 0x50500050, + 0xfdfd00fd, 0xeded00ed, 0xb9b900b9, 0xdada00da, + 0x5e5e005e, 0x15150015, 0x46460046, 0x57570057, + 0xa7a700a7, 0x8d8d008d, 0x9d9d009d, 0x84840084, + 0x90900090, 0xd8d800d8, 0xabab00ab, 0x00000000, + 0x8c8c008c, 0xbcbc00bc, 0xd3d300d3, 0x0a0a000a, + 0xf7f700f7, 0xe4e400e4, 0x58580058, 0x05050005, + 0xb8b800b8, 0xb3b300b3, 0x45450045, 0x06060006, + 0xd0d000d0, 0x2c2c002c, 0x1e1e001e, 0x8f8f008f, + 0xcaca00ca, 0x3f3f003f, 0x0f0f000f, 0x02020002, + 0xc1c100c1, 0xafaf00af, 0xbdbd00bd, 0x03030003, + 0x01010001, 0x13130013, 0x8a8a008a, 0x6b6b006b, + 0x3a3a003a, 0x91910091, 0x11110011, 0x41410041, + 0x4f4f004f, 0x67670067, 0xdcdc00dc, 0xeaea00ea, + 0x97970097, 0xf2f200f2, 0xcfcf00cf, 0xcece00ce, + 0xf0f000f0, 0xb4b400b4, 0xe6e600e6, 0x73730073, + 0x96960096, 0xacac00ac, 0x74740074, 0x22220022, + 0xe7e700e7, 0xadad00ad, 0x35350035, 0x85850085, + 0xe2e200e2, 0xf9f900f9, 0x37370037, 0xe8e800e8, + 0x1c1c001c, 0x75750075, 0xdfdf00df, 0x6e6e006e, + 0x47470047, 0xf1f100f1, 0x1a1a001a, 0x71710071, + 0x1d1d001d, 0x29290029, 0xc5c500c5, 0x89890089, + 0x6f6f006f, 0xb7b700b7, 0x62620062, 0x0e0e000e, + 0xaaaa00aa, 0x18180018, 0xbebe00be, 0x1b1b001b, + 0xfcfc00fc, 0x56560056, 0x3e3e003e, 0x4b4b004b, + 0xc6c600c6, 0xd2d200d2, 0x79790079, 0x20200020, + 0x9a9a009a, 0xdbdb00db, 0xc0c000c0, 0xfefe00fe, + 0x78780078, 0xcdcd00cd, 0x5a5a005a, 0xf4f400f4, + 0x1f1f001f, 0xdddd00dd, 0xa8a800a8, 0x33330033, + 0x88880088, 0x07070007, 0xc7c700c7, 0x31310031, + 0xb1b100b1, 0x12120012, 0x10100010, 0x59590059, + 0x27270027, 0x80800080, 0xecec00ec, 0x5f5f005f, + 0x60600060, 0x51510051, 0x7f7f007f, 0xa9a900a9, + 0x19190019, 0xb5b500b5, 0x4a4a004a, 0x0d0d000d, + 0x2d2d002d, 0xe5e500e5, 0x7a7a007a, 0x9f9f009f, + 0x93930093, 0xc9c900c9, 0x9c9c009c, 0xefef00ef, + 0xa0a000a0, 0xe0e000e0, 0x3b3b003b, 0x4d4d004d, + 0xaeae00ae, 0x2a2a002a, 0xf5f500f5, 0xb0b000b0, + 0xc8c800c8, 0xebeb00eb, 0xbbbb00bb, 0x3c3c003c, + 0x83830083, 0x53530053, 0x99990099, 0x61610061, + 0x17170017, 0x2b2b002b, 0x04040004, 0x7e7e007e, + 0xbaba00ba, 0x77770077, 0xd6d600d6, 0x26260026, + 0xe1e100e1, 0x69690069, 0x14140014, 0x63630063, + 0x55550055, 0x21210021, 0x0c0c000c, 0x7d7d007d +}; + +static const uint32_t X2[256] = { + 0x30303000, 0x68686800, 0x99999900, 0x1b1b1b00, + 0x87878700, 0xb9b9b900, 0x21212100, 0x78787800, + 0x50505000, 0x39393900, 0xdbdbdb00, 0xe1e1e100, + 0x72727200, 0x09090900, 0x62626200, 0x3c3c3c00, + 0x3e3e3e00, 0x7e7e7e00, 0x5e5e5e00, 0x8e8e8e00, + 0xf1f1f100, 0xa0a0a000, 0xcccccc00, 0xa3a3a300, + 0x2a2a2a00, 0x1d1d1d00, 0xfbfbfb00, 0xb6b6b600, + 0xd6d6d600, 0x20202000, 0xc4c4c400, 0x8d8d8d00, + 0x81818100, 0x65656500, 0xf5f5f500, 0x89898900, + 0xcbcbcb00, 0x9d9d9d00, 0x77777700, 0xc6c6c600, + 0x57575700, 0x43434300, 0x56565600, 0x17171700, + 0xd4d4d400, 0x40404000, 0x1a1a1a00, 0x4d4d4d00, + 0xc0c0c000, 0x63636300, 0x6c6c6c00, 0xe3e3e300, + 0xb7b7b700, 0xc8c8c800, 0x64646400, 0x6a6a6a00, + 0x53535300, 0xaaaaaa00, 0x38383800, 0x98989800, + 0x0c0c0c00, 0xf4f4f400, 0x9b9b9b00, 0xededed00, + 0x7f7f7f00, 0x22222200, 0x76767600, 0xafafaf00, + 0xdddddd00, 0x3a3a3a00, 0x0b0b0b00, 0x58585800, + 0x67676700, 0x88888800, 0x06060600, 0xc3c3c300, + 0x35353500, 0x0d0d0d00, 0x01010100, 0x8b8b8b00, + 0x8c8c8c00, 0xc2c2c200, 0xe6e6e600, 0x5f5f5f00, + 0x02020200, 0x24242400, 0x75757500, 0x93939300, + 0x66666600, 0x1e1e1e00, 0xe5e5e500, 0xe2e2e200, + 0x54545400, 0xd8d8d800, 0x10101000, 0xcecece00, + 0x7a7a7a00, 0xe8e8e800, 0x08080800, 0x2c2c2c00, + 0x12121200, 0x97979700, 0x32323200, 0xababab00, + 0xb4b4b400, 0x27272700, 0x0a0a0a00, 0x23232300, + 0xdfdfdf00, 0xefefef00, 0xcacaca00, 0xd9d9d900, + 0xb8b8b800, 0xfafafa00, 0xdcdcdc00, 0x31313100, + 0x6b6b6b00, 0xd1d1d100, 0xadadad00, 0x19191900, + 0x49494900, 0xbdbdbd00, 0x51515100, 0x96969600, + 0xeeeeee00, 0xe4e4e400, 0xa8a8a800, 0x41414100, + 0xdadada00, 0xffffff00, 0xcdcdcd00, 0x55555500, + 0x86868600, 0x36363600, 0xbebebe00, 0x61616100, + 0x52525200, 0xf8f8f800, 0xbbbbbb00, 0x0e0e0e00, + 0x82828200, 0x48484800, 0x69696900, 0x9a9a9a00, + 0xe0e0e000, 0x47474700, 0x9e9e9e00, 0x5c5c5c00, + 0x04040400, 0x4b4b4b00, 0x34343400, 0x15151500, + 0x79797900, 0x26262600, 0xa7a7a700, 0xdedede00, + 0x29292900, 0xaeaeae00, 0x92929200, 0xd7d7d700, + 0x84848400, 0xe9e9e900, 0xd2d2d200, 0xbababa00, + 0x5d5d5d00, 0xf3f3f300, 0xc5c5c500, 0xb0b0b000, + 0xbfbfbf00, 0xa4a4a400, 0x3b3b3b00, 0x71717100, + 0x44444400, 0x46464600, 0x2b2b2b00, 0xfcfcfc00, + 0xebebeb00, 0x6f6f6f00, 0xd5d5d500, 0xf6f6f600, + 0x14141400, 0xfefefe00, 0x7c7c7c00, 0x70707000, + 0x5a5a5a00, 0x7d7d7d00, 0xfdfdfd00, 0x2f2f2f00, + 0x18181800, 0x83838300, 0x16161600, 0xa5a5a500, + 0x91919100, 0x1f1f1f00, 0x05050500, 0x95959500, + 0x74747400, 0xa9a9a900, 0xc1c1c100, 0x5b5b5b00, + 0x4a4a4a00, 0x85858500, 0x6d6d6d00, 0x13131300, + 0x07070700, 0x4f4f4f00, 0x4e4e4e00, 0x45454500, + 0xb2b2b200, 0x0f0f0f00, 0xc9c9c900, 0x1c1c1c00, + 0xa6a6a600, 0xbcbcbc00, 0xececec00, 0x73737300, + 0x90909000, 0x7b7b7b00, 0xcfcfcf00, 0x59595900, + 0x8f8f8f00, 0xa1a1a100, 0xf9f9f900, 0x2d2d2d00, + 0xf2f2f200, 0xb1b1b100, 0x00000000, 0x94949400, + 0x37373700, 0x9f9f9f00, 0xd0d0d000, 0x2e2e2e00, + 0x9c9c9c00, 0x6e6e6e00, 0x28282800, 0x3f3f3f00, + 0x80808000, 0xf0f0f000, 0x3d3d3d00, 0xd3d3d300, + 0x25252500, 0x8a8a8a00, 0xb5b5b500, 0xe7e7e700, + 0x42424200, 0xb3b3b300, 0xc7c7c700, 0xeaeaea00, + 0xf7f7f700, 0x4c4c4c00, 0x11111100, 0x33333300, + 0x03030300, 0xa2a2a200, 0xacacac00, 0x60606000 +}; + +/* Key XOR Layer */ +#define ARIA_ADD_ROUND_KEY(RK, T0, T1, T2, T3) \ + do { \ + (T0) ^= (RK)->u[0]; \ + (T1) ^= (RK)->u[1]; \ + (T2) ^= (RK)->u[2]; \ + (T3) ^= (RK)->u[3]; \ + } while(0) + +/* S-Box Layer 1 + M */ +#define ARIA_SBOX_LAYER1_WITH_PRE_DIFF(T0, T1, T2, T3) \ + do { \ + (T0) = \ + S1[GET_U8_BE(T0, 0)] ^ \ + S2[GET_U8_BE(T0, 1)] ^ \ + X1[GET_U8_BE(T0, 2)] ^ \ + X2[GET_U8_BE(T0, 3)]; \ + (T1) = \ + S1[GET_U8_BE(T1, 0)] ^ \ + S2[GET_U8_BE(T1, 1)] ^ \ + X1[GET_U8_BE(T1, 2)] ^ \ + X2[GET_U8_BE(T1, 3)]; \ + (T2) = \ + S1[GET_U8_BE(T2, 0)] ^ \ + S2[GET_U8_BE(T2, 1)] ^ \ + X1[GET_U8_BE(T2, 2)] ^ \ + X2[GET_U8_BE(T2, 3)]; \ + (T3) = \ + S1[GET_U8_BE(T3, 0)] ^ \ + S2[GET_U8_BE(T3, 1)] ^ \ + X1[GET_U8_BE(T3, 2)] ^ \ + X2[GET_U8_BE(T3, 3)]; \ + } while(0) + +/* S-Box Layer 2 + M */ +#define ARIA_SBOX_LAYER2_WITH_PRE_DIFF(T0, T1, T2, T3) \ + do { \ + (T0) = \ + X1[GET_U8_BE(T0, 0)] ^ \ + X2[GET_U8_BE(T0, 1)] ^ \ + S1[GET_U8_BE(T0, 2)] ^ \ + S2[GET_U8_BE(T0, 3)]; \ + (T1) = \ + X1[GET_U8_BE(T1, 0)] ^ \ + X2[GET_U8_BE(T1, 1)] ^ \ + S1[GET_U8_BE(T1, 2)] ^ \ + S2[GET_U8_BE(T1, 3)]; \ + (T2) = \ + X1[GET_U8_BE(T2, 0)] ^ \ + X2[GET_U8_BE(T2, 1)] ^ \ + S1[GET_U8_BE(T2, 2)] ^ \ + S2[GET_U8_BE(T2, 3)]; \ + (T3) = \ + X1[GET_U8_BE(T3, 0)] ^ \ + X2[GET_U8_BE(T3, 1)] ^ \ + S1[GET_U8_BE(T3, 2)] ^ \ + S2[GET_U8_BE(T3, 3)]; \ + } while(0) + +/* Word-level diffusion */ +#define ARIA_DIFF_WORD(T0,T1,T2,T3) \ + do { \ + (T1) ^= (T2); \ + (T2) ^= (T3); \ + (T0) ^= (T1); \ + \ + (T3) ^= (T1); \ + (T2) ^= (T0); \ + (T1) ^= (T2); \ + } while(0) + +/* Byte-level diffusion */ +#define ARIA_DIFF_BYTE(T0, T1, T2, T3) \ + do { \ + (T1) = (((T1) << 8) & 0xff00ff00) ^ (((T1) >> 8) & 0x00ff00ff); \ + (T2) = rotr32(T2, 16); \ + (T3) = bswap32(T3); \ + } while(0) + +/* Odd round Substitution & Diffusion */ +#define ARIA_SUBST_DIFF_ODD(T0, T1, T2, T3) \ + do { \ + ARIA_SBOX_LAYER1_WITH_PRE_DIFF(T0, T1, T2, T3); \ + ARIA_DIFF_WORD(T0, T1, T2, T3); \ + ARIA_DIFF_BYTE(T0, T1, T2, T3); \ + ARIA_DIFF_WORD(T0, T1, T2, T3); \ + } while(0) + +/* Even round Substitution & Diffusion */ +#define ARIA_SUBST_DIFF_EVEN(T0, T1, T2, T3) \ + do { \ + ARIA_SBOX_LAYER2_WITH_PRE_DIFF(T0, T1, T2, T3); \ + ARIA_DIFF_WORD(T0, T1, T2, T3); \ + ARIA_DIFF_BYTE(T2, T3, T0, T1); \ + ARIA_DIFF_WORD(T0, T1, T2, T3); \ + } while(0) + +/* Q, R Macro expanded ARIA GSRK */ +#define _ARIA_GSRK(RK, X, Y, Q, R) \ + do { \ + (RK)->u[0] = \ + ((X)[0]) ^ \ + (((Y)[((Q) ) % 4]) >> (R)) ^ \ + (((Y)[((Q) + 3) % 4]) << (32 - (R))); \ + (RK)->u[1] = \ + ((X)[1]) ^ \ + (((Y)[((Q) + 1) % 4]) >> (R)) ^ \ + (((Y)[((Q) ) % 4]) << (32 - (R))); \ + (RK)->u[2] = \ + ((X)[2]) ^ \ + (((Y)[((Q) + 2) % 4]) >> (R)) ^ \ + (((Y)[((Q) + 1) % 4]) << (32 - (R))); \ + (RK)->u[3] = \ + ((X)[3]) ^ \ + (((Y)[((Q) + 3) % 4]) >> (R)) ^ \ + (((Y)[((Q) + 2) % 4]) << (32 - (R))); \ + } while(0) + +#define ARIA_GSRK(RK, X, Y, N) _ARIA_GSRK(RK, X, Y, 4 - ((N) / 32), (N) % 32) + +#define ARIA_DEC_DIFF_BYTE(X, Y, TMP, TMP2) \ + do { \ + (TMP) = (X); \ + (TMP2) = rotr32((TMP), 8); \ + (Y) = (TMP2) ^ rotr32((TMP) ^ (TMP2), 16); \ + } while(0) + +void aria_encrypt(const unsigned char *in, unsigned char *out, + const ARIA_KEY *key) +{ + register uint32_t reg0, reg1, reg2, reg3; + int Nr; + const ARIA_u128 *rk; + + if (in == NULL || out == NULL || key == NULL) { + return; + } + + rk = key->rd_key; + Nr = key->rounds; + + if (Nr != 12 && Nr != 14 && Nr != 16) { + return; + } + + reg0 = GET_U32_BE(in, 0); + reg1 = GET_U32_BE(in, 1); + reg2 = GET_U32_BE(in, 2); + reg3 = GET_U32_BE(in, 3); + + ARIA_ADD_ROUND_KEY(rk, reg0, reg1, reg2, reg3); + rk++; + + ARIA_SUBST_DIFF_ODD(reg0, reg1, reg2, reg3); + ARIA_ADD_ROUND_KEY(rk, reg0, reg1, reg2, reg3); + rk++; + + while(Nr -= 2){ + ARIA_SUBST_DIFF_EVEN(reg0, reg1, reg2, reg3); + ARIA_ADD_ROUND_KEY(rk, reg0, reg1, reg2, reg3); + rk++; + + ARIA_SUBST_DIFF_ODD(reg0, reg1, reg2, reg3); + ARIA_ADD_ROUND_KEY(rk, reg0, reg1, reg2, reg3); + rk++; + } + + reg0 = rk->u[0] ^ MAKE_U32( + (uint8_t)(X1[GET_U8_BE(reg0, 0)] ), + (uint8_t)(X2[GET_U8_BE(reg0, 1)] >> 8), + (uint8_t)(S1[GET_U8_BE(reg0, 2)] ), + (uint8_t)(S2[GET_U8_BE(reg0, 3)] )); + reg1 = rk->u[1] ^ MAKE_U32( + (uint8_t)(X1[GET_U8_BE(reg1, 0)] ), + (uint8_t)(X2[GET_U8_BE(reg1, 1)] >> 8), + (uint8_t)(S1[GET_U8_BE(reg1, 2)] ), + (uint8_t)(S2[GET_U8_BE(reg1, 3)] )); + reg2 = rk->u[2] ^ MAKE_U32( + (uint8_t)(X1[GET_U8_BE(reg2, 0)] ), + (uint8_t)(X2[GET_U8_BE(reg2, 1)] >> 8), + (uint8_t)(S1[GET_U8_BE(reg2, 2)] ), + (uint8_t)(S2[GET_U8_BE(reg2, 3)] )); + reg3 = rk->u[3] ^ MAKE_U32( + (uint8_t)(X1[GET_U8_BE(reg3, 0)] ), + (uint8_t)(X2[GET_U8_BE(reg3, 1)] >> 8), + (uint8_t)(S1[GET_U8_BE(reg3, 2)] ), + (uint8_t)(S2[GET_U8_BE(reg3, 3)] )); + + PUT_U32_BE(out, 0, reg0); + PUT_U32_BE(out, 1, reg1); + PUT_U32_BE(out, 2, reg2); + PUT_U32_BE(out, 3, reg3); +} + +int aria_set_encrypt_key(const unsigned char *userKey, const int bits, + ARIA_KEY *key) +{ + register uint32_t reg0, reg1, reg2, reg3; + uint32_t w0[4], w1[4], w2[4], w3[4]; + const uint32_t *ck; + + ARIA_u128 *rk; + int Nr = (bits + 256) / 32; + + if (userKey == NULL || key == NULL) { + return -1; + } + if (bits != 128 && bits != 192 && bits != 256) { + return -2; + } + + rk = key->rd_key; + key->rounds = Nr; + ck = &Key_RC[(bits - 128) / 64][0]; + + w0[0] = GET_U32_BE(userKey, 0); + w0[1] = GET_U32_BE(userKey, 1); + w0[2] = GET_U32_BE(userKey, 2); + w0[3] = GET_U32_BE(userKey, 3); + + reg0 = w0[0] ^ ck[0]; + reg1 = w0[1] ^ ck[1]; + reg2 = w0[2] ^ ck[2]; + reg3 = w0[3] ^ ck[3]; + + ARIA_SUBST_DIFF_ODD(reg0, reg1, reg2, reg3); + + if (bits > 128) { + w1[0] = GET_U32_BE(userKey, 4); + w1[1] = GET_U32_BE(userKey, 5); + if (bits > 192) { + w1[2] = GET_U32_BE(userKey, 6); + w1[3] = GET_U32_BE(userKey, 7); + } + else { + w1[2] = w1[3] = 0; + } + } + else { + w1[0] = w1[1] = w1[2] = w1[3] = 0; + } + + w1[0] ^= reg0; + w1[1] ^= reg1; + w1[2] ^= reg2; + w1[3] ^= reg3; + + reg0 = w1[0]; + reg1 = w1[1]; + reg2 = w1[2]; + reg3 = w1[3]; + + reg0 ^= ck[4]; + reg1 ^= ck[5]; + reg2 ^= ck[6]; + reg3 ^= ck[7]; + + ARIA_SUBST_DIFF_EVEN(reg0, reg1, reg2, reg3); + + reg0 ^= w0[0]; + reg1 ^= w0[1]; + reg2 ^= w0[2]; + reg3 ^= w0[3]; + + w2[0] = reg0; + w2[1] = reg1; + w2[2] = reg2; + w2[3] = reg3; + + reg0 ^= ck[8]; + reg1 ^= ck[9]; + reg2 ^= ck[10]; + reg3 ^= ck[11]; + + ARIA_SUBST_DIFF_ODD(reg0, reg1, reg2, reg3); + + w3[0] = reg0 ^ w1[0]; + w3[1] = reg1 ^ w1[1]; + w3[2] = reg2 ^ w1[2]; + w3[3] = reg3 ^ w1[3]; + + ARIA_GSRK(rk, w0, w1, 19); + rk++; + ARIA_GSRK(rk, w1, w2, 19); + rk++; + ARIA_GSRK(rk, w2, w3, 19); + rk++; + ARIA_GSRK(rk, w3, w0, 19); + + rk++; + ARIA_GSRK(rk, w0, w1, 31); + rk++; + ARIA_GSRK(rk, w1, w2, 31); + rk++; + ARIA_GSRK(rk, w2, w3, 31); + rk++; + ARIA_GSRK(rk, w3, w0, 31); + + rk++; + ARIA_GSRK(rk, w0, w1, 67); + rk++; + ARIA_GSRK(rk, w1, w2, 67); + rk++; + ARIA_GSRK(rk, w2, w3, 67); + rk++; + ARIA_GSRK(rk, w3, w0, 67); + + rk++; + ARIA_GSRK(rk, w0, w1, 97); + if (bits > 128) { + rk++; + ARIA_GSRK(rk, w1, w2, 97); + rk++; + ARIA_GSRK(rk, w2, w3, 97); + } + if (bits > 192) { + rk++; + ARIA_GSRK(rk, w3, w0, 97); + + rk++; + ARIA_GSRK(rk, w0, w1, 109); + } + + return 0; +} + +int aria_set_decrypt_key(const unsigned char *userKey, const int bits, + ARIA_KEY *key) +{ + ARIA_u128 *rk_head; + ARIA_u128 *rk_tail; + register uint32_t w1, w2; + register uint32_t reg0, reg1, reg2, reg3; + uint32_t s0, s1, s2, s3; + + const int r = aria_set_encrypt_key(userKey, bits, key); + + if (r != 0) { + return r; + } + + rk_head = key->rd_key; + rk_tail = rk_head + key->rounds; + + reg0 = rk_head->u[0]; + reg1 = rk_head->u[1]; + reg2 = rk_head->u[2]; + reg3 = rk_head->u[3]; + + memcpy(rk_head, rk_tail, ARIA_BLOCK_SIZE); + + rk_tail->u[0] = reg0; + rk_tail->u[1] = reg1; + rk_tail->u[2] = reg2; + rk_tail->u[3] = reg3; + + rk_head++; + rk_tail--; + + for (; rk_head < rk_tail; rk_head++, rk_tail--) { + ARIA_DEC_DIFF_BYTE(rk_head->u[0], reg0, w1, w2); + ARIA_DEC_DIFF_BYTE(rk_head->u[1], reg1, w1, w2); + ARIA_DEC_DIFF_BYTE(rk_head->u[2], reg2, w1, w2); + ARIA_DEC_DIFF_BYTE(rk_head->u[3], reg3, w1, w2); + + ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); + ARIA_DIFF_BYTE(reg0, reg1, reg2, reg3); + ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); + + s0 = reg0; + s1 = reg1; + s2 = reg2; + s3 = reg3; + + ARIA_DEC_DIFF_BYTE(rk_tail->u[0], reg0, w1, w2); + ARIA_DEC_DIFF_BYTE(rk_tail->u[1], reg1, w1, w2); + ARIA_DEC_DIFF_BYTE(rk_tail->u[2], reg2, w1, w2); + ARIA_DEC_DIFF_BYTE(rk_tail->u[3], reg3, w1, w2); + + ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); + ARIA_DIFF_BYTE(reg0, reg1, reg2, reg3); + ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); + + rk_head->u[0] = reg0; + rk_head->u[1] = reg1; + rk_head->u[2] = reg2; + rk_head->u[3] = reg3; + + rk_tail->u[0] = s0; + rk_tail->u[1] = s1; + rk_tail->u[2] = s2; + rk_tail->u[3] = s3; + } + ARIA_DEC_DIFF_BYTE(rk_head->u[0], reg0, w1, w2); + ARIA_DEC_DIFF_BYTE(rk_head->u[1], reg1, w1, w2); + ARIA_DEC_DIFF_BYTE(rk_head->u[2], reg2, w1, w2); + ARIA_DEC_DIFF_BYTE(rk_head->u[3], reg3, w1, w2); + + ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); + ARIA_DIFF_BYTE(reg0, reg1, reg2, reg3); + ARIA_DIFF_WORD(reg0, reg1, reg2, reg3); + + rk_tail->u[0] = reg0; + rk_tail->u[1] = reg1; + rk_tail->u[2] = reg2; + rk_tail->u[3] = reg3; + + return 0; +} + +#else + +static const unsigned char sb1[256] = { + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, + 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, + 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, + 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, + 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, + 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, + 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, + 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, + 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, + 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, + 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, + 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, + 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, + 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, + 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, + 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, + 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 +}; + +static const unsigned char sb2[256] = { + 0xe2, 0x4e, 0x54, 0xfc, 0x94, 0xc2, 0x4a, 0xcc, + 0x62, 0x0d, 0x6a, 0x46, 0x3c, 0x4d, 0x8b, 0xd1, + 0x5e, 0xfa, 0x64, 0xcb, 0xb4, 0x97, 0xbe, 0x2b, + 0xbc, 0x77, 0x2e, 0x03, 0xd3, 0x19, 0x59, 0xc1, + 0x1d, 0x06, 0x41, 0x6b, 0x55, 0xf0, 0x99, 0x69, + 0xea, 0x9c, 0x18, 0xae, 0x63, 0xdf, 0xe7, 0xbb, + 0x00, 0x73, 0x66, 0xfb, 0x96, 0x4c, 0x85, 0xe4, + 0x3a, 0x09, 0x45, 0xaa, 0x0f, 0xee, 0x10, 0xeb, + 0x2d, 0x7f, 0xf4, 0x29, 0xac, 0xcf, 0xad, 0x91, + 0x8d, 0x78, 0xc8, 0x95, 0xf9, 0x2f, 0xce, 0xcd, + 0x08, 0x7a, 0x88, 0x38, 0x5c, 0x83, 0x2a, 0x28, + 0x47, 0xdb, 0xb8, 0xc7, 0x93, 0xa4, 0x12, 0x53, + 0xff, 0x87, 0x0e, 0x31, 0x36, 0x21, 0x58, 0x48, + 0x01, 0x8e, 0x37, 0x74, 0x32, 0xca, 0xe9, 0xb1, + 0xb7, 0xab, 0x0c, 0xd7, 0xc4, 0x56, 0x42, 0x26, + 0x07, 0x98, 0x60, 0xd9, 0xb6, 0xb9, 0x11, 0x40, + 0xec, 0x20, 0x8c, 0xbd, 0xa0, 0xc9, 0x84, 0x04, + 0x49, 0x23, 0xf1, 0x4f, 0x50, 0x1f, 0x13, 0xdc, + 0xd8, 0xc0, 0x9e, 0x57, 0xe3, 0xc3, 0x7b, 0x65, + 0x3b, 0x02, 0x8f, 0x3e, 0xe8, 0x25, 0x92, 0xe5, + 0x15, 0xdd, 0xfd, 0x17, 0xa9, 0xbf, 0xd4, 0x9a, + 0x7e, 0xc5, 0x39, 0x67, 0xfe, 0x76, 0x9d, 0x43, + 0xa7, 0xe1, 0xd0, 0xf5, 0x68, 0xf2, 0x1b, 0x34, + 0x70, 0x05, 0xa3, 0x8a, 0xd5, 0x79, 0x86, 0xa8, + 0x30, 0xc6, 0x51, 0x4b, 0x1e, 0xa6, 0x27, 0xf6, + 0x35, 0xd2, 0x6e, 0x24, 0x16, 0x82, 0x5f, 0xda, + 0xe6, 0x75, 0xa2, 0xef, 0x2c, 0xb2, 0x1c, 0x9f, + 0x5d, 0x6f, 0x80, 0x0a, 0x72, 0x44, 0x9b, 0x6c, + 0x90, 0x0b, 0x5b, 0x33, 0x7d, 0x5a, 0x52, 0xf3, + 0x61, 0xa1, 0xf7, 0xb0, 0xd6, 0x3f, 0x7c, 0x6d, + 0xed, 0x14, 0xe0, 0xa5, 0x3d, 0x22, 0xb3, 0xf8, + 0x89, 0xde, 0x71, 0x1a, 0xaf, 0xba, 0xb5, 0x81 +}; + +static const unsigned char sb3[256] = { + 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, + 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, + 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, + 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, + 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, + 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, + 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, + 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, + 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, + 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, + 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, + 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, + 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, + 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, + 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, + 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, + 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, + 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, + 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, + 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, + 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, + 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, + 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, + 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, + 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, + 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, + 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, + 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, + 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, + 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, + 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d +}; + +static const unsigned char sb4[256] = { + 0x30, 0x68, 0x99, 0x1b, 0x87, 0xb9, 0x21, 0x78, + 0x50, 0x39, 0xdb, 0xe1, 0x72, 0x09, 0x62, 0x3c, + 0x3e, 0x7e, 0x5e, 0x8e, 0xf1, 0xa0, 0xcc, 0xa3, + 0x2a, 0x1d, 0xfb, 0xb6, 0xd6, 0x20, 0xc4, 0x8d, + 0x81, 0x65, 0xf5, 0x89, 0xcb, 0x9d, 0x77, 0xc6, + 0x57, 0x43, 0x56, 0x17, 0xd4, 0x40, 0x1a, 0x4d, + 0xc0, 0x63, 0x6c, 0xe3, 0xb7, 0xc8, 0x64, 0x6a, + 0x53, 0xaa, 0x38, 0x98, 0x0c, 0xf4, 0x9b, 0xed, + 0x7f, 0x22, 0x76, 0xaf, 0xdd, 0x3a, 0x0b, 0x58, + 0x67, 0x88, 0x06, 0xc3, 0x35, 0x0d, 0x01, 0x8b, + 0x8c, 0xc2, 0xe6, 0x5f, 0x02, 0x24, 0x75, 0x93, + 0x66, 0x1e, 0xe5, 0xe2, 0x54, 0xd8, 0x10, 0xce, + 0x7a, 0xe8, 0x08, 0x2c, 0x12, 0x97, 0x32, 0xab, + 0xb4, 0x27, 0x0a, 0x23, 0xdf, 0xef, 0xca, 0xd9, + 0xb8, 0xfa, 0xdc, 0x31, 0x6b, 0xd1, 0xad, 0x19, + 0x49, 0xbd, 0x51, 0x96, 0xee, 0xe4, 0xa8, 0x41, + 0xda, 0xff, 0xcd, 0x55, 0x86, 0x36, 0xbe, 0x61, + 0x52, 0xf8, 0xbb, 0x0e, 0x82, 0x48, 0x69, 0x9a, + 0xe0, 0x47, 0x9e, 0x5c, 0x04, 0x4b, 0x34, 0x15, + 0x79, 0x26, 0xa7, 0xde, 0x29, 0xae, 0x92, 0xd7, + 0x84, 0xe9, 0xd2, 0xba, 0x5d, 0xf3, 0xc5, 0xb0, + 0xbf, 0xa4, 0x3b, 0x71, 0x44, 0x46, 0x2b, 0xfc, + 0xeb, 0x6f, 0xd5, 0xf6, 0x14, 0xfe, 0x7c, 0x70, + 0x5a, 0x7d, 0xfd, 0x2f, 0x18, 0x83, 0x16, 0xa5, + 0x91, 0x1f, 0x05, 0x95, 0x74, 0xa9, 0xc1, 0x5b, + 0x4a, 0x85, 0x6d, 0x13, 0x07, 0x4f, 0x4e, 0x45, + 0xb2, 0x0f, 0xc9, 0x1c, 0xa6, 0xbc, 0xec, 0x73, + 0x90, 0x7b, 0xcf, 0x59, 0x8f, 0xa1, 0xf9, 0x2d, + 0xf2, 0xb1, 0x00, 0x94, 0x37, 0x9f, 0xd0, 0x2e, + 0x9c, 0x6e, 0x28, 0x3f, 0x80, 0xf0, 0x3d, 0xd3, + 0x25, 0x8a, 0xb5, 0xe7, 0x42, 0xb3, 0xc7, 0xea, + 0xf7, 0x4c, 0x11, 0x33, 0x03, 0xa2, 0xac, 0x60 +}; + +static const ARIA_u128 c1 = {{ + 0x51, 0x7c, 0xc1, 0xb7, 0x27, 0x22, 0x0a, 0x94, + 0xfe, 0x13, 0xab, 0xe8, 0xfa, 0x9a, 0x6e, 0xe0 +}}; + +static const ARIA_u128 c2 = {{ + 0x6d, 0xb1, 0x4a, 0xcc, 0x9e, 0x21, 0xc8, 0x20, + 0xff, 0x28, 0xb1, 0xd5, 0xef, 0x5d, 0xe2, 0xb0 +}}; + +static const ARIA_u128 c3 = {{ + 0xdb, 0x92, 0x37, 0x1d, 0x21, 0x26, 0xe9, 0x70, + 0x03, 0x24, 0x97, 0x75, 0x04, 0xe8, 0xc9, 0x0e +}}; + +/* + * Exclusive or two 128 bit values into the result. + * It is safe for the result to be the same as the either input. + */ +static void xor128(ARIA_c128 o, const ARIA_c128 x, const ARIA_u128 *y) +{ + int i; + + for (i = 0; i < ARIA_BLOCK_SIZE; i++) + o[i] = x[i] ^ y->c[i]; +} + +/* + * Generalised circular rotate right and exclusive or function. + * It is safe for the output to overlap either input. + */ +static ossl_inline void rotnr(unsigned int n, ARIA_u128 *o, + const ARIA_u128 *xor, const ARIA_u128 *z) +{ + const unsigned int bytes = n / 8, bits = n % 8; + unsigned int i; + ARIA_u128 t; + + for (i = 0; i < ARIA_BLOCK_SIZE; i++) + t.c[(i + bytes) % ARIA_BLOCK_SIZE] = z->c[i]; + for (i = 0; i < ARIA_BLOCK_SIZE; i++) + o->c[i] = ((t.c[i] >> bits) | + (t.c[i ? i - 1 : ARIA_BLOCK_SIZE - 1] << (8 - bits))) ^ + xor->c[i]; +} + +/* + * Circular rotate 19 bits right and xor. + * It is safe for the output to overlap either input. + */ +static void rot19r(ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) +{ + rotnr(19, o, xor, z); +} + +/* + * Circular rotate 31 bits right and xor. + * It is safe for the output to overlap either input. + */ +static void rot31r(ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) +{ + rotnr(31, o, xor, z); +} + +/* + * Circular rotate 61 bits left and xor. + * It is safe for the output to overlap either input. + */ +static void rot61l(ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) +{ + rotnr(8 * ARIA_BLOCK_SIZE - 61, o, xor, z); +} + +/* + * Circular rotate 31 bits left and xor. + * It is safe for the output to overlap either input. + */ +static void rot31l(ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) +{ + rotnr(8 * ARIA_BLOCK_SIZE - 31, o, xor, z); +} + +/* + * Circular rotate 19 bits left and xor. + * It is safe for the output to overlap either input. + */ +static void rot19l(ARIA_u128 *o, const ARIA_u128 *xor, const ARIA_u128 *z) +{ + rotnr(8 * ARIA_BLOCK_SIZE - 19, o, xor, z); +} + +/* + * First substitution and xor layer, used for odd steps. + * It is safe for the input and output to be the same. + */ +static void sl1(ARIA_u128 *o, const ARIA_u128 *x, const ARIA_u128 *y) +{ + unsigned int i; + for (i = 0; i < ARIA_BLOCK_SIZE; i += 4) { + o->c[i ] = sb1[x->c[i ] ^ y->c[i ]]; + o->c[i + 1] = sb2[x->c[i + 1] ^ y->c[i + 1]]; + o->c[i + 2] = sb3[x->c[i + 2] ^ y->c[i + 2]]; + o->c[i + 3] = sb4[x->c[i + 3] ^ y->c[i + 3]]; + } +} + +/* + * Second substitution and xor layer, used for even steps. + * It is safe for the input and output to be the same. + */ +static void sl2(ARIA_c128 o, const ARIA_u128 *x, const ARIA_u128 *y) +{ + unsigned int i; + for (i = 0; i < ARIA_BLOCK_SIZE; i += 4) { + o[i ] = sb3[x->c[i ] ^ y->c[i ]]; + o[i + 1] = sb4[x->c[i + 1] ^ y->c[i + 1]]; + o[i + 2] = sb1[x->c[i + 2] ^ y->c[i + 2]]; + o[i + 3] = sb2[x->c[i + 3] ^ y->c[i + 3]]; + } +} + +/* + * Diffusion layer step + * It is NOT safe for the input and output to overlap. + */ +static void a(ARIA_u128 *y, const ARIA_u128 *x) +{ + y->c[ 0] = x->c[ 3] ^ x->c[ 4] ^ x->c[ 6] ^ x->c[ 8] ^ + x->c[ 9] ^ x->c[13] ^ x->c[14]; + y->c[ 1] = x->c[ 2] ^ x->c[ 5] ^ x->c[ 7] ^ x->c[ 8] ^ + x->c[ 9] ^ x->c[12] ^ x->c[15]; + y->c[ 2] = x->c[ 1] ^ x->c[ 4] ^ x->c[ 6] ^ x->c[10] ^ + x->c[11] ^ x->c[12] ^ x->c[15]; + y->c[ 3] = x->c[ 0] ^ x->c[ 5] ^ x->c[ 7] ^ x->c[10] ^ + x->c[11] ^ x->c[13] ^ x->c[14]; + y->c[ 4] = x->c[ 0] ^ x->c[ 2] ^ x->c[ 5] ^ x->c[ 8] ^ + x->c[11] ^ x->c[14] ^ x->c[15]; + y->c[ 5] = x->c[ 1] ^ x->c[ 3] ^ x->c[ 4] ^ x->c[ 9] ^ + x->c[10] ^ x->c[14] ^ x->c[15]; + y->c[ 6] = x->c[ 0] ^ x->c[ 2] ^ x->c[ 7] ^ x->c[ 9] ^ + x->c[10] ^ x->c[12] ^ x->c[13]; + y->c[ 7] = x->c[ 1] ^ x->c[ 3] ^ x->c[ 6] ^ x->c[ 8] ^ + x->c[11] ^ x->c[12] ^ x->c[13]; + y->c[ 8] = x->c[ 0] ^ x->c[ 1] ^ x->c[ 4] ^ x->c[ 7] ^ + x->c[10] ^ x->c[13] ^ x->c[15]; + y->c[ 9] = x->c[ 0] ^ x->c[ 1] ^ x->c[ 5] ^ x->c[ 6] ^ + x->c[11] ^ x->c[12] ^ x->c[14]; + y->c[10] = x->c[ 2] ^ x->c[ 3] ^ x->c[ 5] ^ x->c[ 6] ^ + x->c[ 8] ^ x->c[13] ^ x->c[15]; + y->c[11] = x->c[ 2] ^ x->c[ 3] ^ x->c[ 4] ^ x->c[ 7] ^ + x->c[ 9] ^ x->c[12] ^ x->c[14]; + y->c[12] = x->c[ 1] ^ x->c[ 2] ^ x->c[ 6] ^ x->c[ 7] ^ + x->c[ 9] ^ x->c[11] ^ x->c[12]; + y->c[13] = x->c[ 0] ^ x->c[ 3] ^ x->c[ 6] ^ x->c[ 7] ^ + x->c[ 8] ^ x->c[10] ^ x->c[13]; + y->c[14] = x->c[ 0] ^ x->c[ 3] ^ x->c[ 4] ^ x->c[ 5] ^ + x->c[ 9] ^ x->c[11] ^ x->c[14]; + y->c[15] = x->c[ 1] ^ x->c[ 2] ^ x->c[ 4] ^ x->c[ 5] ^ + x->c[ 8] ^ x->c[10] ^ x->c[15]; +} + +/* + * Odd round function + * Apply the first substitution layer and then a diffusion step. + * It is safe for the input and output to overlap. + */ +static ossl_inline void FO(ARIA_u128 *o, const ARIA_u128 *d, + const ARIA_u128 *rk) +{ + ARIA_u128 y; + + sl1(&y, d, rk); + a(o, &y); +} + +/* + * Even round function + * Apply the second substitution layer and then a diffusion step. + * It is safe for the input and output to overlap. + */ +static ossl_inline void FE(ARIA_u128 *o, const ARIA_u128 *d, + const ARIA_u128 *rk) +{ + ARIA_u128 y; + + sl2(y.c, d, rk); + a(o, &y); +} + +/* + * Encrypt or decrypt a single block + * in and out can overlap + */ +static void do_encrypt(unsigned char *o, const unsigned char *pin, + unsigned int rounds, const ARIA_u128 *keys) +{ + ARIA_u128 p; + unsigned int i; + + memcpy(&p, pin, sizeof(p)); + for (i = 0; i < rounds - 2; i += 2) { + FO(&p, &p, &keys[i]); + FE(&p, &p, &keys[i + 1]); + } + FO(&p, &p, &keys[rounds - 2]); + sl2(o, &p, &keys[rounds - 1]); + xor128(o, o, &keys[rounds]); +} + +/* + * Encrypt a single block + * in and out can overlap + */ +void aria_encrypt(const unsigned char *in, unsigned char *out, + const ARIA_KEY *key) +{ + assert(in != NULL && out != NULL && key != NULL); + do_encrypt(out, in, key->rounds, key->rd_key); +} + + +/* + * Expand the cipher key into the encryption key schedule. + * We short circuit execution of the last two + * or four rotations based on the key size. + */ +int aria_set_encrypt_key(const unsigned char *userKey, const int bits, + ARIA_KEY *key) +{ + const ARIA_u128 *ck1, *ck2, *ck3; + ARIA_u128 kr, w0, w1, w2, w3; + + if (!userKey || !key) + return -1; + memcpy(w0.c, userKey, sizeof(w0)); + switch (bits) { + default: + return -2; + case 128: + key->rounds = 12; + ck1 = &c1; + ck2 = &c2; + ck3 = &c3; + memset(kr.c, 0, sizeof(kr)); + break; + + case 192: + key->rounds = 14; + ck1 = &c2; + ck2 = &c3; + ck3 = &c1; + memcpy(kr.c, userKey + ARIA_BLOCK_SIZE, sizeof(kr) / 2); + memset(kr.c + ARIA_BLOCK_SIZE / 2, 0, sizeof(kr) / 2); + break; + + case 256: + key->rounds = 16; + ck1 = &c3; + ck2 = &c1; + ck3 = &c2; + memcpy(kr.c, userKey + ARIA_BLOCK_SIZE, sizeof(kr)); + break; + } + + FO(&w3, &w0, ck1); xor128(w1.c, w3.c, &kr); + FE(&w3, &w1, ck2); xor128(w2.c, w3.c, &w0); + FO(&kr, &w2, ck3); xor128(w3.c, kr.c, &w1); + + rot19r(&key->rd_key[ 0], &w0, &w1); + rot19r(&key->rd_key[ 1], &w1, &w2); + rot19r(&key->rd_key[ 2], &w2, &w3); + rot19r(&key->rd_key[ 3], &w3, &w0); + + rot31r(&key->rd_key[ 4], &w0, &w1); + rot31r(&key->rd_key[ 5], &w1, &w2); + rot31r(&key->rd_key[ 6], &w2, &w3); + rot31r(&key->rd_key[ 7], &w3, &w0); + + rot61l(&key->rd_key[ 8], &w0, &w1); + rot61l(&key->rd_key[ 9], &w1, &w2); + rot61l(&key->rd_key[10], &w2, &w3); + rot61l(&key->rd_key[11], &w3, &w0); + + rot31l(&key->rd_key[12], &w0, &w1); + if (key->rounds > 12) { + rot31l(&key->rd_key[13], &w1, &w2); + rot31l(&key->rd_key[14], &w2, &w3); + + if (key->rounds > 14) { + rot31l(&key->rd_key[15], &w3, &w0); + rot19l(&key->rd_key[16], &w0, &w1); + } + } + return 0; +} + +/* + * Expand the cipher key into the decryption key schedule. + */ +int aria_set_decrypt_key(const unsigned char *userKey, const int bits, + ARIA_KEY *key) +{ + ARIA_KEY ek; + const int r = aria_set_encrypt_key(userKey, bits, &ek); + unsigned int i, rounds = ek.rounds; + + if (r == 0) { + key->rounds = rounds; + memcpy(&key->rd_key[0], &ek.rd_key[rounds], sizeof(key->rd_key[0])); + for (i = 1; i < rounds; i++) + a(&key->rd_key[i], &ek.rd_key[rounds - i]); + memcpy(&key->rd_key[rounds], &ek.rd_key[0], sizeof(key->rd_key[rounds])); + } + return r; +} + +#endif diff --git a/crypto/aria/build.info b/crypto/aria/build.info new file mode 100644 index 00000000..218d0612 --- /dev/null +++ b/crypto/aria/build.info @@ -0,0 +1,4 @@ +LIBS=../../libcrypto +SOURCE[../../libcrypto]=\ + aria.c + diff --git a/crypto/arm64cpuid.pl b/crypto/arm64cpuid.pl index caa33875..daa2b17a 100755 --- a/crypto/arm64cpuid.pl +++ b/crypto/arm64cpuid.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2015-2018 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 @@ -63,6 +63,7 @@ _armv8_sha256_probe: sha256su0 v0.4s, v0.4s ret .size _armv8_sha256_probe,.-_armv8_sha256_probe + .globl _armv8_pmull_probe .type _armv8_pmull_probe,%function _armv8_pmull_probe: @@ -70,6 +71,13 @@ _armv8_pmull_probe: ret .size _armv8_pmull_probe,.-_armv8_pmull_probe +.globl _armv8_sha512_probe +.type _armv8_sha512_probe,%function +_armv8_sha512_probe: + .long 0xcec08000 // sha512su0 v0.2d,v0.2d + ret +.size _armv8_sha512_probe,.-_armv8_sha512_probe + .globl OPENSSL_cleanse .type OPENSSL_cleanse,%function .align 5 diff --git a/crypto/arm_arch.h b/crypto/arm_arch.h index 3fc9e69b..547ec958 100644 --- a/crypto/arm_arch.h +++ b/crypto/arm_arch.h @@ -1,5 +1,5 @@ /* - * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2011-2018 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 @@ -28,7 +28,7 @@ # endif /* * Why doesn't gcc define __ARM_ARCH__? Instead it defines - * bunch of below macros. See all_architectires[] table in + * bunch of below macros. See all_architectures[] table in * gcc/config/arm/arm.c. On a side note it defines * __ARMEL__/__ARMEB__ for little-/big-endian. */ @@ -79,5 +79,6 @@ extern unsigned int OPENSSL_armcap_P; # define ARMV8_SHA1 (1<<3) # define ARMV8_SHA256 (1<<4) # define ARMV8_PMULL (1<<5) +# define ARMV8_SHA512 (1<<6) #endif diff --git a/crypto/armcap.c b/crypto/armcap.c index 432a06c0..d6707330 100644 --- a/crypto/armcap.c +++ b/crypto/armcap.c @@ -1,5 +1,5 @@ /* - * Copyright 2011-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2011-2018 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 @@ -13,6 +13,7 @@ #include #include #include +#include "internal/cryptlib.h" #include "arm_arch.h" @@ -23,7 +24,7 @@ void OPENSSL_cpuid_setup(void) { } -unsigned long OPENSSL_rdtsc(void) +uint32_t OPENSSL_rdtsc(void) { return 0; } @@ -45,9 +46,12 @@ void _armv8_aes_probe(void); void _armv8_sha1_probe(void); void _armv8_sha256_probe(void); void _armv8_pmull_probe(void); -unsigned long _armv7_tick(void); +# ifdef __aarch64__ +void _armv8_sha512_probe(void); +# endif +uint32_t _armv7_tick(void); -unsigned long OPENSSL_rdtsc(void) +uint32_t OPENSSL_rdtsc(void) { if (OPENSSL_armcap_P & ARMV7_TICK) return _armv7_tick(); @@ -93,11 +97,12 @@ static unsigned long (*getauxval) (unsigned long) = NULL; # define HWCAP_CE_PMULL (1 << 4) # define HWCAP_CE_SHA1 (1 << 5) # define HWCAP_CE_SHA256 (1 << 6) +# define HWCAP_CE_SHA512 (1 << 21) # endif void OPENSSL_cpuid_setup(void) { - char *e; + const char *e; struct sigaction ill_oact, ill_act; sigset_t oset; static int trigger = 0; @@ -162,6 +167,11 @@ void OPENSSL_cpuid_setup(void) if (hwcap & HWCAP_CE_SHA256) OPENSSL_armcap_P |= ARMV8_SHA256; + +# ifdef __aarch64__ + if (hwcap & HWCAP_CE_SHA512) + OPENSSL_armcap_P |= ARMV8_SHA512; +# endif } } else if (sigsetjmp(ill_jmp, 1) == 0) { _armv7_neon_probe(); @@ -181,6 +191,12 @@ void OPENSSL_cpuid_setup(void) _armv8_sha256_probe(); OPENSSL_armcap_P |= ARMV8_SHA256; } +# ifdef __aarch64__ + if (sigsetjmp(ill_jmp, 1) == 0) { + _armv8_sha512_probe(); + OPENSSL_armcap_P |= ARMV8_SHA512; + } +# endif } if (sigsetjmp(ill_jmp, 1) == 0) { _armv7_tick(); diff --git a/crypto/asn1/a_bitstr.c b/crypto/asn1/a_bitstr.c index b2e0fb68..bffbd160 100644 --- a/crypto/asn1/a_bitstr.c +++ b/crypto/asn1/a_bitstr.c @@ -24,7 +24,7 @@ int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp) unsigned char *p, *d; if (a == NULL) - return (0); + return 0; len = a->length; @@ -61,7 +61,7 @@ int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp) ret = 1 + len; if (pp == NULL) - return (ret); + return ret; p = *pp; @@ -73,7 +73,7 @@ int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp) p[-1] &= (0xff << bits); } *pp = p; - return (ret); + return ret; } ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a, @@ -96,7 +96,7 @@ ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a, if ((a == NULL) || ((*a) == NULL)) { if ((ret = ASN1_BIT_STRING_new()) == NULL) - return (NULL); + return NULL; } else ret = (*a); @@ -132,16 +132,16 @@ ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a, if (a != NULL) (*a) = ret; *pp = p; - return (ret); + return ret; err: ASN1err(ASN1_F_C2I_ASN1_BIT_STRING, i); if ((a == NULL) || (*a != ret)) ASN1_BIT_STRING_free(ret); - return (NULL); + return NULL; } /* - * These next 2 functions from Goetz Babin-Ebell + * These next 2 functions from Goetz Babin-Ebell. */ int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value) { @@ -161,7 +161,7 @@ int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value) if ((a->length < (w + 1)) || (a->data == NULL)) { if (!value) - return (1); /* Don't need to set */ + return 1; /* Don't need to set */ c = OPENSSL_clear_realloc(a->data, a->length, w + 1); if (c == NULL) { ASN1err(ASN1_F_ASN1_BIT_STRING_SET_BIT, ERR_R_MALLOC_FAILURE); @@ -175,7 +175,7 @@ int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value) a->data[w] = ((a->data[w]) & iv) | v; while ((a->length > 0) && (a->data[a->length - 1] == 0)) a->length--; - return (1); + return 1; } int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n) @@ -185,7 +185,7 @@ int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n) w = n / 8; v = 1 << (7 - (n & 0x07)); if ((a == NULL) || (a->length < (w + 1)) || (a->data == NULL)) - return (0); + return 0; return ((a->data[w] & v) != 0); } diff --git a/crypto/asn1/a_d2i_fp.c b/crypto/asn1/a_d2i_fp.c index e5c1d0ed..a1a17901 100644 --- a/crypto/asn1/a_d2i_fp.c +++ b/crypto/asn1/a_d2i_fp.c @@ -13,8 +13,7 @@ #include "internal/numbers.h" #include #include - -static int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb); +#include "internal/asn1_int.h" #ifndef NO_OLD_ASN1 # ifndef OPENSSL_NO_STDIO @@ -26,12 +25,12 @@ void *ASN1_d2i_fp(void *(*xnew) (void), d2i_of_void *d2i, FILE *in, void **x) if ((b = BIO_new(BIO_s_file())) == NULL) { ASN1err(ASN1_F_ASN1_D2I_FP, ERR_R_BUF_LIB); - return (NULL); + return NULL; } BIO_set_fp(b, in, BIO_NOCLOSE); ret = ASN1_d2i_bio(xnew, d2i, b, x); BIO_free(b); - return (ret); + return ret; } # endif @@ -50,7 +49,7 @@ void *ASN1_d2i_bio(void *(*xnew) (void), d2i_of_void *d2i, BIO *in, void **x) ret = d2i(x, &p, len); err: BUF_MEM_free(b); - return (ret); + return ret; } #endif @@ -70,7 +69,7 @@ void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x) ret = ASN1_item_d2i(x, &p, len, it); err: BUF_MEM_free(b); - return (ret); + return ret; } #ifndef OPENSSL_NO_STDIO @@ -81,18 +80,18 @@ void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x) if ((b = BIO_new(BIO_s_file())) == NULL) { ASN1err(ASN1_F_ASN1_ITEM_D2I_FP, ERR_R_BUF_LIB); - return (NULL); + return NULL; } BIO_set_fp(b, in, BIO_NOCLOSE); ret = ASN1_item_d2i_bio(it, b, x); BIO_free(b); - return (ret); + return ret; } #endif #define HEADER_SIZE 8 #define ASN1_CHUNK_INITIAL_SIZE (16 * 1024) -static int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb) +int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb) { BUF_MEM *b; unsigned char *p; diff --git a/crypto/asn1/a_digest.c b/crypto/asn1/a_digest.c index c84ecc9b..f4cc1f2e 100644 --- a/crypto/asn1/a_digest.c +++ b/crypto/asn1/a_digest.c @@ -29,7 +29,7 @@ int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data, i = i2d(data, NULL); if ((str = OPENSSL_malloc(i)) == NULL) { ASN1err(ASN1_F_ASN1_DIGEST, ERR_R_MALLOC_FAILURE); - return (0); + return 0; } p = str; i2d(data, &p); @@ -39,7 +39,7 @@ int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data, return 0; } OPENSSL_free(str); - return (1); + return 1; } #endif @@ -52,12 +52,12 @@ int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *asn, i = ASN1_item_i2d(asn, &str, it); if (!str) - return (0); + return 0; if (!EVP_Digest(str, i, md, len, type, NULL)) { OPENSSL_free(str); return 0; } OPENSSL_free(str); - return (1); + return 1; } diff --git a/crypto/asn1/a_dup.c b/crypto/asn1/a_dup.c index d9a57b2c..50af6b00 100644 --- a/crypto/asn1/a_dup.c +++ b/crypto/asn1/a_dup.c @@ -21,20 +21,20 @@ void *ASN1_dup(i2d_of_void *i2d, d2i_of_void *d2i, void *x) char *ret; if (x == NULL) - return (NULL); + return NULL; i = i2d(x, NULL); b = OPENSSL_malloc(i + 10); if (b == NULL) { ASN1err(ASN1_F_ASN1_DUP, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } p = b; i = i2d(x, &p); p2 = b; ret = d2i(NULL, &p2, i); OPENSSL_free(b); - return (ret); + return ret; } #endif @@ -54,15 +54,15 @@ void *ASN1_item_dup(const ASN1_ITEM *it, void *x) void *ret; if (x == NULL) - return (NULL); + return NULL; i = ASN1_item_i2d(x, &b, it); if (b == NULL) { ASN1err(ASN1_F_ASN1_ITEM_DUP, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } p = b; ret = ASN1_item_d2i(NULL, &p, i, it); OPENSSL_free(b); - return (ret); + return ret; } diff --git a/crypto/asn1/a_gentm.c b/crypto/asn1/a_gentm.c index ff1b6954..d3878d6e 100644 --- a/crypto/asn1/a_gentm.c +++ b/crypto/asn1/a_gentm.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -17,121 +17,13 @@ #include #include "asn1_locl.h" +/* This is the primary function used to parse ASN1_GENERALIZEDTIME */ 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; - + /* wrapper around asn1_time_to_tm */ 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); + return 0; + return asn1_time_to_tm(tm, d); } int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *d) @@ -146,15 +38,15 @@ int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str) 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, str, t.length)) - return 0; - s->type = V_ASN1_GENERALIZEDTIME; - } - return (1); - } else - return (0); + t.flags = 0; + + if (!ASN1_GENERALIZEDTIME_check(&t)) + return 0; + + if (s != NULL && !ASN1_STRING_copy(s, &t)) + return 0; + + return 1; } ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s, @@ -167,107 +59,24 @@ 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; - ASN1_GENERALIZEDTIME *tmps = NULL; - - if (s == NULL) - tmps = ASN1_GENERALIZEDTIME_new(); - else - tmps = s; - if (tmps == NULL) - return NULL; ts = OPENSSL_gmtime(&t, &data); if (ts == NULL) - goto err; + return NULL; if (offset_day || offset_sec) { if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec)) - goto err; + return NULL; } - p = (char *)tmps->data; - if ((p == NULL) || ((size_t)tmps->length < len)) { - p = OPENSSL_malloc(len); - if (p == NULL) { - ASN1err(ASN1_F_ASN1_GENERALIZEDTIME_ADJ, ERR_R_MALLOC_FAILURE); - goto err; - } - OPENSSL_free(tmps->data); - tmps->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); - tmps->length = strlen(p); - tmps->type = V_ASN1_GENERALIZEDTIME; -#ifdef CHARSET_EBCDIC_not - ebcdic2ascii(tmps->data, tmps->data, tmps->length); -#endif - return tmps; - err: - if (s == NULL) - ASN1_GENERALIZEDTIME_free(tmps); - return NULL; + return asn1_time_from_tm(s, ts, V_ASN1_GENERALIZEDTIME); } -const char *_asn1_mon[12] = { - "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" -}; - int ASN1_GENERALIZEDTIME_print(BIO *bp, const ASN1_GENERALIZEDTIME *tm) { - char *v; - int gmt = 0; - int i; - int y = 0, M = 0, d = 0, h = 0, m = 0, s = 0; - char *f = NULL; - int f_len = 0; - - i = tm->length; - v = (char *)tm->data; - - if (i < 12) - goto err; - if (v[i - 1] == 'Z') - gmt = 1; - for (i = 0; i < 12; i++) - if ((v[i] > '9') || (v[i] < '0')) - goto err; - y = (v[0] - '0') * 1000 + (v[1] - '0') * 100 - + (v[2] - '0') * 10 + (v[3] - '0'); - M = (v[4] - '0') * 10 + (v[5] - '0'); - if ((M > 12) || (M < 1)) - goto err; - d = (v[6] - '0') * 10 + (v[7] - '0'); - h = (v[8] - '0') * 10 + (v[9] - '0'); - m = (v[10] - '0') * 10 + (v[11] - '0'); - if (tm->length >= 14 && - (v[12] >= '0') && (v[12] <= '9') && - (v[13] >= '0') && (v[13] <= '9')) { - s = (v[12] - '0') * 10 + (v[13] - '0'); - /* Check for fractions of seconds. */ - if (tm->length >= 15 && v[14] == '.') { - int l = tm->length; - f = &v[14]; /* The decimal point. */ - f_len = 1; - while (14 + f_len < l && f[f_len] >= '0' && f[f_len] <= '9') - ++f_len; - } - } - - if (BIO_printf(bp, "%s %2d %02d:%02d:%02d%.*s %d%s", - _asn1_mon[M - 1], d, h, m, s, f_len, f, y, - (gmt) ? " GMT" : "") <= 0) - return (0); - else - return (1); - err: - BIO_write(bp, "Bad time value", 14); - return (0); + if (tm->type != V_ASN1_GENERALIZEDTIME) + return 0; + return ASN1_TIME_print(bp, tm); } diff --git a/crypto/asn1/a_i2d_fp.c b/crypto/asn1/a_i2d_fp.c index 3b3f713c..980c65a2 100644 --- a/crypto/asn1/a_i2d_fp.c +++ b/crypto/asn1/a_i2d_fp.c @@ -22,12 +22,12 @@ int ASN1_i2d_fp(i2d_of_void *i2d, FILE *out, void *x) if ((b = BIO_new(BIO_s_file())) == NULL) { ASN1err(ASN1_F_ASN1_I2D_FP, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, out, BIO_NOCLOSE); ret = ASN1_i2d_bio(i2d, b, x); BIO_free(b); - return (ret); + return ret; } # endif @@ -44,7 +44,7 @@ int ASN1_i2d_bio(i2d_of_void *i2d, BIO *out, unsigned char *x) b = OPENSSL_malloc(n); if (b == NULL) { ASN1err(ASN1_F_ASN1_I2D_BIO, ERR_R_MALLOC_FAILURE); - return (0); + return 0; } p = (unsigned char *)b; @@ -62,7 +62,7 @@ int ASN1_i2d_bio(i2d_of_void *i2d, BIO *out, unsigned char *x) n -= i; } OPENSSL_free(b); - return (ret); + return ret; } #endif @@ -75,12 +75,12 @@ int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, void *x) if ((b = BIO_new(BIO_s_file())) == NULL) { ASN1err(ASN1_F_ASN1_ITEM_I2D_FP, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, out, BIO_NOCLOSE); ret = ASN1_item_i2d_bio(it, b, x); BIO_free(b); - return (ret); + return ret; } #endif @@ -92,7 +92,7 @@ int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, void *x) n = ASN1_item_i2d(x, &b, it); if (b == NULL) { ASN1err(ASN1_F_ASN1_ITEM_I2D_BIO, ERR_R_MALLOC_FAILURE); - return (0); + return 0; } for (;;) { @@ -107,5 +107,5 @@ int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, void *x) n -= i; } OPENSSL_free(b); - return (ret); + return ret; } diff --git a/crypto/asn1/a_int.c b/crypto/asn1/a_int.c index 217650a0..70a45cb3 100644 --- a/crypto/asn1/a_int.c +++ b/crypto/asn1/a_int.c @@ -396,7 +396,7 @@ ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp, if ((a == NULL) || ((*a) == NULL)) { if ((ret = ASN1_INTEGER_new()) == NULL) - return (NULL); + return NULL; ret->type = V_ASN1_INTEGER; } else ret = (*a); @@ -438,12 +438,12 @@ ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp, if (a != NULL) (*a) = ret; *pp = p; - return (ret); + return ret; err: ASN1err(ASN1_F_D2I_ASN1_UINTEGER, i); if ((a == NULL) || (*a != ret)) ASN1_INTEGER_free(ret); - return (NULL); + return NULL; } static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai, @@ -487,7 +487,7 @@ static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai, err: if (ret != ai) ASN1_INTEGER_free(ret); - return (NULL); + return NULL; } static BIGNUM *asn1_string_to_bn(const ASN1_INTEGER *ai, BIGNUM *bn, diff --git a/crypto/asn1/a_mbstr.c b/crypto/asn1/a_mbstr.c index 7a035afb..949fe6c1 100644 --- a/crypto/asn1/a_mbstr.c +++ b/crypto/asn1/a_mbstr.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-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 @@ -8,7 +8,7 @@ */ #include -#include +#include "internal/ctype.h" #include "internal/cryptlib.h" #include @@ -22,8 +22,6 @@ 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_numeric(unsigned long value); -static int is_printable(unsigned long value); /* * These functions take a string in UTF8, ASCII or multibyte form and a mask @@ -271,13 +269,15 @@ static int out_utf8(unsigned long value, void *arg) static int type_str(unsigned long value, void *arg) { - unsigned long types; - types = *((unsigned long *)arg); - if ((types & B_ASN1_NUMERICSTRING) && !is_numeric(value)) + unsigned long types = *((unsigned long *)arg); + const int native = value > INT_MAX ? INT_MAX : ossl_fromascii(value); + + if ((types & B_ASN1_NUMERICSTRING) && !(ossl_isdigit(native) + || native == ' ')) types &= ~B_ASN1_NUMERICSTRING; - if ((types & B_ASN1_PRINTABLESTRING) && !is_printable(value)) + if ((types & B_ASN1_PRINTABLESTRING) && !ossl_isasn1print(native)) types &= ~B_ASN1_PRINTABLESTRING; - if ((types & B_ASN1_IA5STRING) && (value > 127)) + if ((types & B_ASN1_IA5STRING) && !ossl_isascii(native)) types &= ~B_ASN1_IA5STRING; if ((types & B_ASN1_T61STRING) && (value > 0xff)) types &= ~B_ASN1_T61STRING; @@ -341,55 +341,3 @@ static int cpy_utf8(unsigned long value, void *arg) *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; -} - -/* Return 1 if the character is a digit or space */ -static int is_numeric(unsigned long value) -{ - int ch; - if (value > 0x7f) - return 0; - ch = (int)value; -#ifndef CHARSET_EBCDIC - if (!isdigit(ch) && ch != ' ') - return 0; -#else - if (ch > os_toascii['9']) - return 0; - if (ch < os_toascii['0'] && ch != os_toascii[' ']) - return 0; -#endif - return 1; -} diff --git a/crypto/asn1/a_object.c b/crypto/asn1/a_object.c index 1ec7a7e1..b5e90a5a 100644 --- a/crypto/asn1/a_object.c +++ b/crypto/asn1/a_object.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,6 +9,7 @@ #include #include +#include "internal/ctype.h" #include "internal/cryptlib.h" #include #include @@ -23,7 +24,7 @@ int i2d_ASN1_OBJECT(const ASN1_OBJECT *a, unsigned char **pp) int objsize; if ((a == NULL) || (a->data == NULL)) - return (0); + return 0; objsize = ASN1_object_size(0, a->length, V_ASN1_OBJECT); if (pp == NULL || objsize == -1) @@ -35,7 +36,7 @@ int i2d_ASN1_OBJECT(const ASN1_OBJECT *a, unsigned char **pp) p += a->length; *pp = p; - return (objsize); + return objsize; } int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num) @@ -48,7 +49,7 @@ int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num) BIGNUM *bl = NULL; if (num == 0) - return (0); + return 0; else if (num == -1) num = strlen(buf); @@ -84,7 +85,7 @@ int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num) c = *(p++); if ((c == ' ') || (c == '.')) break; - if ((c < '0') || (c > '9')) { + if (!ossl_isdigit(c)) { ASN1err(ASN1_F_A2D_ASN1_OBJECT, ASN1_R_INVALID_DIGIT); goto err; } @@ -157,12 +158,12 @@ int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num) if (tmp != ftmp) OPENSSL_free(tmp); BN_free(bl); - return (len); + return len; err: if (tmp != ftmp) OPENSSL_free(tmp); BN_free(bl); - return (0); + return 0; } int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a) @@ -176,7 +177,7 @@ int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a) int i; if ((a == NULL) || (a->data == NULL)) - return (BIO_write(bp, "NULL", 4)); + return BIO_write(bp, "NULL", 4); i = i2t_ASN1_OBJECT(buf, sizeof(buf), a); if (i > (int)(sizeof(buf) - 1)) { p = OPENSSL_malloc(i + 1); @@ -192,7 +193,7 @@ int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a) BIO_write(bp, p, i); if (p != buf) OPENSSL_free(p); - return (i); + return i; } ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp, @@ -220,7 +221,7 @@ ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp, return ret; err: ASN1err(ASN1_F_D2I_ASN1_OBJECT, i); - return (NULL); + return NULL; } ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp, @@ -280,7 +281,7 @@ ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp, if ((a == NULL) || ((*a) == NULL) || !((*a)->flags & ASN1_OBJECT_FLAG_DYNAMIC)) { if ((ret = ASN1_OBJECT_new()) == NULL) - return (NULL); + return NULL; } else ret = (*a); @@ -311,12 +312,12 @@ ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp, if (a != NULL) (*a) = ret; *pp = p; - return (ret); + return ret; err: ASN1err(ASN1_F_C2I_ASN1_OBJECT, i); if ((a == NULL) || (*a != ret)) ASN1_OBJECT_free(ret); - return (NULL); + return NULL; } ASN1_OBJECT *ASN1_OBJECT_new(void) @@ -326,10 +327,10 @@ ASN1_OBJECT *ASN1_OBJECT_new(void) ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) { ASN1err(ASN1_F_ASN1_OBJECT_NEW, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } ret->flags = ASN1_OBJECT_FLAG_DYNAMIC; - return (ret); + return ret; } void ASN1_OBJECT_free(ASN1_OBJECT *a) @@ -366,5 +367,5 @@ ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len, o.length = len; o.flags = ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS | ASN1_OBJECT_FLAG_DYNAMIC_DATA; - return (OBJ_dup(&o)); + return OBJ_dup(&o); } diff --git a/crypto/asn1/a_print.c b/crypto/asn1/a_print.c index 1aafe7c8..8a373d9d 100644 --- a/crypto/asn1/a_print.c +++ b/crypto/asn1/a_print.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,7 +8,7 @@ */ #include -#include +#include "internal/ctype.h" #include "internal/cryptlib.h" #include @@ -21,34 +21,20 @@ int ASN1_PRINTABLE_type(const unsigned char *s, int len) if (len <= 0) len = -1; if (s == NULL) - return (V_ASN1_PRINTABLESTRING); + return V_ASN1_PRINTABLESTRING; while ((*s) && (len-- != 0)) { c = *(s++); -#ifndef CHARSET_EBCDIC - if (!(((c >= 'a') && (c <= 'z')) || - ((c >= 'A') && (c <= 'Z')) || - ((c >= '0') && (c <= '9')) || - (c == ' ') || (c == '\'') || - (c == '(') || (c == ')') || - (c == '+') || (c == ',') || - (c == '-') || (c == '.') || - (c == '/') || (c == ':') || (c == '=') || (c == '?'))) + if (!ossl_isasn1print(c)) ia5 = 1; - if (c & 0x80) + if (!ossl_isascii(c)) t61 = 1; -#else - if (!isalnum(c) && (c != ' ') && strchr("'()+,-./:=?", c) == NULL) - ia5 = 1; - if (os_toascii[c] & 0x80) - t61 = 1; -#endif } if (t61) - return (V_ASN1_T61STRING); + return V_ASN1_T61STRING; if (ia5) - return (V_ASN1_IA5STRING); - return (V_ASN1_PRINTABLESTRING); + return V_ASN1_IA5STRING; + return V_ASN1_PRINTABLESTRING; } int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s) @@ -57,9 +43,9 @@ int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s) unsigned char *p; if (s->type != V_ASN1_UNIVERSALSTRING) - return (0); + return 0; if ((s->length % 4) != 0) - return (0); + return 0; p = s->data; for (i = 0; i < s->length; i += 4) { if ((p[0] != '\0') || (p[1] != '\0') || (p[2] != '\0')) @@ -68,7 +54,7 @@ int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s) p += 4; } if (i < s->length) - return (0); + return 0; p = s->data; for (i = 3; i < s->length; i += 4) { *(p++) = s->data[i]; @@ -76,7 +62,7 @@ int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s) *(p) = '\0'; s->length /= 4; s->type = ASN1_PRINTABLE_type(s->data, s->length); - return (1); + return 1; } int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v) @@ -86,7 +72,7 @@ int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v) const char *p; if (v == NULL) - return (0); + return 0; n = 0; p = (const char *)v->data; for (i = 0; i < v->length; i++) { @@ -98,12 +84,12 @@ int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v) n++; if (n >= 80) { if (BIO_write(bp, buf, n) <= 0) - return (0); + return 0; n = 0; } } if (n > 0) if (BIO_write(bp, buf, n) <= 0) - return (0); - return (1); + return 0; + return 1; } diff --git a/crypto/asn1/a_sign.c b/crypto/asn1/a_sign.c index 3b261eba..130e23ea 100644 --- a/crypto/asn1/a_sign.c +++ b/crypto/asn1/a_sign.c @@ -103,7 +103,7 @@ int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, X509_ALGOR *algor2, EVP_MD_CTX_free(ctx); OPENSSL_clear_free((char *)buf_in, (unsigned int)inl); OPENSSL_clear_free((char *)buf_out, outll); - return (outl); + return outl; } #endif @@ -144,7 +144,7 @@ int ASN1_item_sign_ctx(const ASN1_ITEM *it, type = EVP_MD_CTX_md(ctx); pkey = EVP_PKEY_CTX_get0_pkey(EVP_MD_CTX_pkey_ctx(ctx)); - if (type == NULL || pkey == NULL) { + if (pkey == NULL) { ASN1err(ASN1_F_ASN1_ITEM_SIGN_CTX, ASN1_R_CONTEXT_NOT_INITIALISED); goto err; } @@ -169,10 +169,15 @@ int ASN1_item_sign_ctx(const ASN1_ITEM *it, ASN1err(ASN1_F_ASN1_ITEM_SIGN_CTX, ERR_R_EVP_LIB); if (rv <= 1) goto err; - } else + } else { rv = 2; + } if (rv == 2) { + if (type == NULL) { + ASN1err(ASN1_F_ASN1_ITEM_SIGN_CTX, ASN1_R_CONTEXT_NOT_INITIALISED); + goto err; + } if (!OBJ_find_sigid_by_algs(&signid, EVP_MD_nid(type), pkey->ameth->pkey_id)) { @@ -202,8 +207,7 @@ int ASN1_item_sign_ctx(const ASN1_ITEM *it, goto err; } - if (!EVP_DigestSignUpdate(ctx, buf_in, inl) - || !EVP_DigestSignFinal(ctx, buf_out, &outl)) { + if (!EVP_DigestSign(ctx, buf_out, &outl, buf_in, inl)) { outl = 0; ASN1err(ASN1_F_ASN1_ITEM_SIGN_CTX, ERR_R_EVP_LIB); goto err; @@ -221,5 +225,5 @@ int ASN1_item_sign_ctx(const ASN1_ITEM *it, err: OPENSSL_clear_free((char *)buf_in, (unsigned int)inl); OPENSSL_clear_free((char *)buf_out, outll); - return (outl); + return outl; } diff --git a/crypto/asn1/a_strnid.c b/crypto/asn1/a_strnid.c index ecf178e2..a7d6b0e3 100644 --- a/crypto/asn1/a_strnid.c +++ b/crypto/asn1/a_strnid.c @@ -8,7 +8,6 @@ */ #include -#include #include "internal/cryptlib.h" #include #include @@ -50,6 +49,7 @@ int ASN1_STRING_set_default_mask_asc(const char *p) { unsigned long mask; char *end; + if (strncmp(p, "MASK:", 5) == 0) { if (!p[5]) return 0; @@ -84,19 +84,20 @@ ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, ASN1_STRING *str = NULL; unsigned long mask; int ret; - if (!out) + + if (out == NULL) out = &str; tbl = ASN1_STRING_TABLE_get(nid); - if (tbl) { + if (tbl != NULL) { mask = tbl->mask; if (!(tbl->flags & STABLE_NO_MASK)) mask &= global_mask; ret = ASN1_mbstring_ncopy(out, in, inlen, inform, mask, tbl->minsize, tbl->maxsize); - } else - ret = - ASN1_mbstring_copy(out, in, inlen, inform, - DIRSTRING_TYPE & global_mask); + } else { + ret = ASN1_mbstring_copy(out, in, inlen, inform, + DIRSTRING_TYPE & global_mask); + } if (ret <= 0) return NULL; return *out; @@ -106,54 +107,7 @@ ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, * Now the tables and helper functions for the string table: */ -/* size limits: this stuff is taken straight from RFC3280 */ - -#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 -#define ub_serial_number 64 - -/* From RFC4524 */ - -#define ub_rfc822_mailbox 256 - -/* This table must be kept in NID order */ - -static const ASN1_STRING_TABLE tbl_standard[] = { - {NID_commonName, 1, ub_common_name, DIRSTRING_TYPE, 0}, - {NID_countryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, - {NID_localityName, 1, ub_locality_name, DIRSTRING_TYPE, 0}, - {NID_stateOrProvinceName, 1, ub_state_name, DIRSTRING_TYPE, 0}, - {NID_organizationName, 1, ub_organization_name, DIRSTRING_TYPE, 0}, - {NID_organizationalUnitName, 1, ub_organization_unit_name, DIRSTRING_TYPE, - 0}, - {NID_pkcs9_emailAddress, 1, ub_email_address, B_ASN1_IA5STRING, - STABLE_NO_MASK}, - {NID_pkcs9_unstructuredName, 1, -1, PKCS9STRING_TYPE, 0}, - {NID_pkcs9_challengePassword, 1, -1, PKCS9STRING_TYPE, 0}, - {NID_pkcs9_unstructuredAddress, 1, -1, DIRSTRING_TYPE, 0}, - {NID_givenName, 1, ub_name, DIRSTRING_TYPE, 0}, - {NID_surname, 1, ub_name, DIRSTRING_TYPE, 0}, - {NID_initials, 1, ub_name, DIRSTRING_TYPE, 0}, - {NID_serialNumber, 1, ub_serial_number, B_ASN1_PRINTABLESTRING, - STABLE_NO_MASK}, - {NID_friendlyName, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}, - {NID_name, 1, ub_name, DIRSTRING_TYPE, 0}, - {NID_dnQualifier, -1, -1, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, - {NID_domainComponent, 1, -1, B_ASN1_IA5STRING, STABLE_NO_MASK}, - {NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}, - {NID_rfc822Mailbox, 1, ub_rfc822_mailbox, B_ASN1_IA5STRING, - STABLE_NO_MASK}, - {NID_jurisdictionCountryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, - {NID_INN, 1, 12, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, - {NID_OGRN, 1, 13, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, - {NID_SNILS, 1, 11, B_ASN1_NUMERICSTRING, STABLE_NO_MASK} -}; +#include "tbl_standard.h" static int sk_table_cmp(const ASN1_STRING_TABLE *const *a, const ASN1_STRING_TABLE *const *b) @@ -174,6 +128,7 @@ ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid) { int idx; ASN1_STRING_TABLE fnd; + fnd.nid = nid; if (stable) { idx = sk_ASN1_STRING_TABLE_find(stable, &fnd); @@ -191,6 +146,7 @@ ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid) static ASN1_STRING_TABLE *stable_get(int nid) { ASN1_STRING_TABLE *tmp, *rv; + /* Always need a string table so allocate one if NULL */ if (stable == NULL) { stable = sk_ASN1_STRING_TABLE_new(sk_table_cmp); @@ -198,7 +154,7 @@ static ASN1_STRING_TABLE *stable_get(int nid) return NULL; } tmp = ASN1_STRING_TABLE_get(nid); - if (tmp && tmp->flags & STABLE_FLAGS_MALLOC) + if (tmp != NULL && tmp->flags & STABLE_FLAGS_MALLOC) return tmp; rv = OPENSSL_zalloc(sizeof(*rv)); if (rv == NULL) @@ -207,7 +163,7 @@ static ASN1_STRING_TABLE *stable_get(int nid) OPENSSL_free(rv); return NULL; } - if (tmp) { + if (tmp != NULL) { rv->nid = tmp->nid; rv->minsize = tmp->minsize; rv->maxsize = tmp->maxsize; @@ -227,8 +183,9 @@ int ASN1_STRING_TABLE_add(int nid, unsigned long flags) { ASN1_STRING_TABLE *tmp; + tmp = stable_get(nid); - if (!tmp) { + if (tmp == NULL) { ASN1err(ASN1_F_ASN1_STRING_TABLE_ADD, ERR_R_MALLOC_FAILURE); return 0; } @@ -246,8 +203,9 @@ int ASN1_STRING_TABLE_add(int nid, void ASN1_STRING_TABLE_cleanup(void) { STACK_OF(ASN1_STRING_TABLE) *tmp; + tmp = stable; - if (!tmp) + if (tmp == NULL) return; stable = NULL; sk_ASN1_STRING_TABLE_pop_free(tmp, st_free); @@ -258,32 +216,3 @@ static void st_free(ASN1_STRING_TABLE *tbl) if (tbl->flags & STABLE_FLAGS_MALLOC) OPENSSL_free(tbl); } - - -#ifdef STRING_TABLE_TEST - -main() -{ - ASN1_STRING_TABLE *tmp; - int i, last_nid = -1; - - for (tmp = tbl_standard, i = 0; i < OSSL_NELEM(tbl_standard); i++, tmp++) { - if (tmp->nid < last_nid) { - last_nid = 0; - break; - } - last_nid = tmp->nid; - } - - if (last_nid != 0) { - printf("Table order OK\n"); - exit(0); - } - - for (tmp = tbl_standard, i = 0; i < OSSL_NELEM(tbl_standard); i++, tmp++) - printf("Index %d, NID %d, Name=%s\n", i, tmp->nid, - OBJ_nid2ln(tmp->nid)); - -} - -#endif diff --git a/crypto/asn1/a_time.c b/crypto/asn1/a_time.c index 46f539cb..1babb963 100644 --- a/crypto/asn1/a_time.c +++ b/crypto/asn1/a_time.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-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 @@ -16,6 +16,7 @@ #include #include +#include "internal/ctype.h" #include "internal/cryptlib.h" #include #include "asn1_locl.h" @@ -24,6 +25,291 @@ IMPLEMENT_ASN1_MSTRING(ASN1_TIME, B_ASN1_TIME) IMPLEMENT_ASN1_FUNCTIONS(ASN1_TIME) +static int is_utc(const int year) +{ + if (50 <= year && year <= 149) + return 1; + return 0; +} + +static int leap_year(const int year) +{ + if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) + return 1; + return 0; +} + +/* + * Compute the day of the week and the day of the year from the year, month + * and day. The day of the year is straightforward, the day of the week uses + * a form of Zeller's congruence. For this months start with March and are + * numbered 4 through 15. + */ +static void determine_days(struct tm *tm) +{ + static const int ydays[12] = { + 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 + }; + int y = tm->tm_year + 1900; + int m = tm->tm_mon; + int d = tm->tm_mday; + int c; + + tm->tm_yday = ydays[m] + d - 1; + if (m >= 2) { + /* March and onwards can be one day further into the year */ + tm->tm_yday += leap_year(y); + m += 2; + } else { + /* Treat January and February as part of the previous year */ + m += 14; + y--; + } + c = y / 100; + y %= 100; + /* Zeller's congruance */ + tm->tm_wday = (d + (13 * m) / 5 + y + y / 4 + c / 4 + 5 * c + 6) % 7; +} + +int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *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 }; + static const int mdays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + char *a; + int n, i, i2, l, o, min_l = 11, strict = 0, end = 6, btz = 5, md; + struct tm tmp; + + /* + * ASN1_STRING_FLAG_X509_TIME is used to enforce RFC 5280 + * time string format, in which: + * + * 1. "seconds" is a 'MUST' + * 2. "Zulu" timezone is a 'MUST' + * 3. "+|-" is not allowed to indicate a time zone + */ + if (d->type == V_ASN1_UTCTIME) { + if (d->flags & ASN1_STRING_FLAG_X509_TIME) { + min_l = 13; + strict = 1; + } + } else if (d->type == V_ASN1_GENERALIZEDTIME) { + end = 7; + btz = 6; + if (d->flags & ASN1_STRING_FLAG_X509_TIME) { + min_l = 15; + strict = 1; + } else { + min_l = 13; + } + } else { + return 0; + } + + l = d->length; + a = (char *)d->data; + o = 0; + memset(&tmp, 0, sizeof(tmp)); + + /* + * 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 < min_l) + goto err; + for (i = 0; i < end; i++) { + if (!strict && (i == btz) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) { + i++; + break; + } + if (!ossl_isdigit(a[o])) + goto err; + n = a[o] - '0'; + /* incomplete 2-digital number */ + if (++o == l) + goto err; + + if (!ossl_isdigit(a[o])) + goto err; + n = (n * 10) + a[o] - '0'; + /* no more bytes to read, but we haven't seen time-zone yet */ + if (++o == l) + goto err; + + i2 = (d->type == V_ASN1_UTCTIME) ? i + 1 : i; + + if ((n < min[i2]) || (n > max[i2])) + goto err; + switch (i2) { + case 0: + /* UTC will never be here */ + tmp.tm_year = n * 100 - 1900; + break; + case 1: + if (d->type == V_ASN1_UTCTIME) + tmp.tm_year = n < 50 ? n + 100 : n; + else + tmp.tm_year += n; + break; + case 2: + tmp.tm_mon = n - 1; + break; + case 3: + /* check if tm_mday is valid in tm_mon */ + if (tmp.tm_mon == 1) { + /* it's February */ + md = mdays[1] + leap_year(tmp.tm_year + 1900); + } else { + md = mdays[tmp.tm_mon]; + } + if (n > md) + goto err; + tmp.tm_mday = n; + determine_days(&tmp); + break; + case 4: + tmp.tm_hour = n; + break; + case 5: + tmp.tm_min = n; + break; + case 6: + tmp.tm_sec = n; + break; + } + } + + /* + * Optional fractional seconds: decimal point followed by one or more + * digits. + */ + if (d->type == V_ASN1_GENERALIZEDTIME && a[o] == '.') { + if (strict) + /* RFC 5280 forbids fractional seconds */ + goto err; + if (++o == l) + goto err; + i = o; + while ((o < l) && ossl_isdigit(a[o])) + o++; + /* Must have at least one digit after decimal point */ + if (i == o) + goto err; + /* no more bytes to read, but we haven't seen time-zone yet */ + if (o == l) + goto err; + } + + /* + * 'o' will never point to '\0' at this point, the only chance + * 'o' can point to '\0' is either the subsequent if or the first + * else if is true. + */ + if (a[o] == 'Z') { + o++; + } else if (!strict && ((a[o] == '+') || (a[o] == '-'))) { + int offsign = a[o] == '-' ? 1 : -1; + int offset = 0; + + o++; + /* + * if not equal, no need to do subsequent checks + * since the following for-loop will add 'o' by 4 + * and the final return statement will check if 'l' + * and 'o' are equal. + */ + if (o + 4 != l) + goto err; + for (i = end; i < end + 2; i++) { + if (!ossl_isdigit(a[o])) + goto err; + n = a[o] - '0'; + o++; + if (!ossl_isdigit(a[o])) + goto err; + n = (n * 10) + a[o] - '0'; + i2 = (d->type == V_ASN1_UTCTIME) ? i + 1 : i; + if ((n < min[i2]) || (n > max[i2])) + goto err; + /* if tm is NULL, no need to adjust */ + if (tm != NULL) { + if (i == end) + offset = n * 3600; + else if (i == end + 1) + offset += n * 60; + } + o++; + } + if (offset && !OPENSSL_gmtime_adj(&tmp, 0, offset * offsign)) + goto err; + } else { + /* not Z, or not +/- in non-strict mode */ + goto err; + } + if (o == l) { + /* success, check if tm should be filled */ + if (tm != NULL) + *tm = tmp; + return 1; + } + err: + return 0; +} + +ASN1_TIME *asn1_time_from_tm(ASN1_TIME *s, struct tm *ts, int type) +{ + char* p; + ASN1_TIME *tmps = NULL; + const size_t len = 20; + + if (type == V_ASN1_UNDEF) { + if (is_utc(ts->tm_year)) + type = V_ASN1_UTCTIME; + else + type = V_ASN1_GENERALIZEDTIME; + } else if (type == V_ASN1_UTCTIME) { + if (!is_utc(ts->tm_year)) + goto err; + } else if (type != V_ASN1_GENERALIZEDTIME) { + goto err; + } + + if (s == NULL) + tmps = ASN1_STRING_new(); + else + tmps = s; + if (tmps == NULL) + return NULL; + + if (!ASN1_STRING_set(tmps, NULL, len)) + goto err; + + tmps->type = type; + p = (char*)tmps->data; + + if (type == V_ASN1_GENERALIZEDTIME) + tmps->length = 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); + else + tmps->length = 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); + +#ifdef CHARSET_EBCDIC_not + ebcdic2ascii(tmps->data, tmps->data, tmps->length); +#endif + return tmps; + err: + if (tmps != s) + ASN1_STRING_free(tmps); + return NULL; +} + ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t) { return ASN1_TIME_adj(s, t, 0, 0); @@ -44,9 +330,7 @@ ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t, 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); + return asn1_time_from_tm(s, ts, V_ASN1_UNDEF); } int ASN1_TIME_check(const ASN1_TIME *t) @@ -63,108 +347,207 @@ ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t, ASN1_GENERALIZEDTIME **out) { ASN1_GENERALIZEDTIME *ret = NULL; - char *str; - int newlen; + struct tm tm; - if (!ASN1_TIME_check(t)) + if (!ASN1_TIME_to_tm(t, &tm)) return NULL; - if (out == NULL || *out == NULL) { - if ((ret = ASN1_GENERALIZEDTIME_new()) == NULL) - goto err; - } else + if (out != NULL) 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; - } + ret = asn1_time_from_tm(ret, &tm, V_ASN1_GENERALIZEDTIME); - /* 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') - OPENSSL_strlcpy(str, "19", newlen); - else - OPENSSL_strlcpy(str, "20", newlen); + if (out != NULL && ret != NULL) + *out = ret; - OPENSSL_strlcat(str, (const 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; + return ret; } - int ASN1_TIME_set_string(ASN1_TIME *s, const char *str) +{ + /* Try UTC, if that fails, try GENERALIZED */ + if (ASN1_UTCTIME_set_string(s, str)) + return 1; + return ASN1_GENERALIZEDTIME_set_string(s, str); +} + +int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str) { ASN1_TIME t; + struct tm tm; + int rv = 0; t.length = strlen(str); t.data = (unsigned char *)str; - t.flags = 0; + t.flags = ASN1_STRING_FLAG_X509_TIME; t.type = V_ASN1_UTCTIME; if (!ASN1_TIME_check(&t)) { t.type = V_ASN1_GENERALIZEDTIME; if (!ASN1_TIME_check(&t)) - return 0; + goto out; } - if (s && !ASN1_STRING_copy((ASN1_STRING *)s, (ASN1_STRING *)&t)) - return 0; + /* + * Per RFC 5280 (section 4.1.2.5.), the valid input time + * strings should be encoded with the following rules: + * + * 1. UTC: YYMMDDHHMMSSZ, if YY < 50 (20YY) --> UTC: YYMMDDHHMMSSZ + * 2. UTC: YYMMDDHHMMSSZ, if YY >= 50 (19YY) --> UTC: YYMMDDHHMMSSZ + * 3. G'd: YYYYMMDDHHMMSSZ, if YYYY >= 2050 --> G'd: YYYYMMDDHHMMSSZ + * 4. G'd: YYYYMMDDHHMMSSZ, if YYYY < 2050 --> UTC: YYMMDDHHMMSSZ + * + * Only strings of the 4th rule should be reformatted, but since a + * UTC can only present [1950, 2050), so if the given time string + * is less than 1950 (e.g. 19230419000000Z), we do nothing... + */ - return 1; + if (s != NULL && t.type == V_ASN1_GENERALIZEDTIME) { + if (!asn1_time_to_tm(&tm, &t)) + goto out; + if (is_utc(tm.tm_year)) { + t.length -= 2; + /* + * it's OK to let original t.data go since that's assigned + * to a piece of memory allocated outside of this function. + * new t.data would be freed after ASN1_STRING_copy is done. + */ + t.data = OPENSSL_zalloc(t.length + 1); + if (t.data == NULL) + goto out; + memcpy(t.data, str + 2, t.length); + t.type = V_ASN1_UTCTIME; + } + } + + if (s == NULL || ASN1_STRING_copy((ASN1_STRING *)s, (ASN1_STRING *)&t)) + rv = 1; + + if (t.data != (unsigned char *)str) + OPENSSL_free(t.data); +out: + return rv; } -static int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *t) +int ASN1_TIME_to_tm(const ASN1_TIME *s, struct tm *tm) { - if (t == NULL) { + if (s == NULL) { time_t now_t; + time(&now_t); - if (OPENSSL_gmtime(&now_t, tm)) + memset(tm, 0, sizeof(*tm)); + if (OPENSSL_gmtime(&now_t, tm) != NULL) 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; + return asn1_time_to_tm(tm, s); } 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)) + + if (!ASN1_TIME_to_tm(from, &tm_from)) return 0; - if (!asn1_time_to_tm(&tm_to, to)) + if (!ASN1_TIME_to_tm(to, &tm_to)) return 0; return OPENSSL_gmtime_diff(pday, psec, &tm_from, &tm_to); } +static const char _asn1_mon[12][4] = { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" +}; + int ASN1_TIME_print(BIO *bp, const ASN1_TIME *tm) { - if (tm->type == V_ASN1_UTCTIME) - return ASN1_UTCTIME_print(bp, tm); - if (tm->type == V_ASN1_GENERALIZEDTIME) - return ASN1_GENERALIZEDTIME_print(bp, tm); + char *v; + int gmt = 0, l; + struct tm stm; + + if (!asn1_time_to_tm(&stm, tm)) { + /* asn1_time_to_tm will check the time type */ + goto err; + } + + l = tm->length; + v = (char *)tm->data; + if (v[l - 1] == 'Z') + gmt = 1; + + if (tm->type == V_ASN1_GENERALIZEDTIME) { + char *f = NULL; + int f_len = 0; + + /* + * Try to parse fractional seconds. '14' is the place of + * 'fraction point' in a GeneralizedTime string. + */ + if (tm->length > 15 && v[14] == '.') { + f = &v[14]; + f_len = 1; + while (14 + f_len < l && ossl_isdigit(f[f_len])) + ++f_len; + } + + return BIO_printf(bp, "%s %2d %02d:%02d:%02d%.*s %d%s", + _asn1_mon[stm.tm_mon], stm.tm_mday, stm.tm_hour, + stm.tm_min, stm.tm_sec, f_len, f, stm.tm_year + 1900, + (gmt ? " GMT" : "")) > 0; + } else { + return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d%s", + _asn1_mon[stm.tm_mon], stm.tm_mday, stm.tm_hour, + stm.tm_min, stm.tm_sec, stm.tm_year + 1900, + (gmt ? " GMT" : "")) > 0; + } + err: BIO_write(bp, "Bad time value", 14); - return (0); + return 0; +} + +int ASN1_TIME_cmp_time_t(const ASN1_TIME *s, time_t t) +{ + struct tm stm, ttm; + int day, sec; + + if (!ASN1_TIME_to_tm(s, &stm)) + return -2; + + if (!OPENSSL_gmtime(&t, &ttm)) + return -2; + + if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm)) + return -2; + + if (day > 0 || sec > 0) + return 1; + if (day < 0 || sec < 0) + return -1; + return 0; +} + +int ASN1_TIME_normalize(ASN1_TIME *t) +{ + struct tm tm; + + if (!ASN1_TIME_to_tm(t, &tm)) + return 0; + + return asn1_time_from_tm(t, &tm, V_ASN1_UNDEF) != NULL; +} + +int ASN1_TIME_compare(const ASN1_TIME *a, const ASN1_TIME *b) +{ + int day, sec; + + if (!ASN1_TIME_diff(&day, &sec, b, a)) + return -2; + if (day > 0 || sec > 0) + return 1; + if (day < 0 || sec < 0) + return -1; + return 0; } diff --git a/crypto/asn1/a_type.c b/crypto/asn1/a_type.c index df42360e..0c7aebe3 100644 --- a/crypto/asn1/a_type.c +++ b/crypto/asn1/a_type.c @@ -16,9 +16,9 @@ int ASN1_TYPE_get(const ASN1_TYPE *a) { if ((a->value.ptr != NULL) || (a->type == V_ASN1_NULL)) - return (a->type); + return a->type; else - return (0); + return 0; } void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value) diff --git a/crypto/asn1/a_utctm.c b/crypto/asn1/a_utctm.c index 9797aa8a..b224991a 100644 --- a/crypto/asn1/a_utctm.c +++ b/crypto/asn1/a_utctm.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -13,96 +13,13 @@ #include #include "asn1_locl.h" +/* This is the primary function used to parse ASN1_UTCTIME */ 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; - + /* wrapper around ans1_time_to_tm */ 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; + return 0; + return asn1_time_to_tm(tm, d); } int ASN1_UTCTIME_check(const ASN1_UTCTIME *d) @@ -110,6 +27,7 @@ int ASN1_UTCTIME_check(const ASN1_UTCTIME *d) return asn1_utctime_to_tm(NULL, d); } +/* Sets the string via simple copy without cleaning it up */ int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str) { ASN1_UTCTIME t; @@ -117,15 +35,15 @@ int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str) 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, str, t.length)) - return 0; - s->type = V_ASN1_UTCTIME; - } - return (1); - } else - return (0); + t.flags = 0; + + if (!ASN1_UTCTIME_check(&t)) + return 0; + + if (s != NULL && !ASN1_STRING_copy(s, &t)) + return 0; + + return 1; } ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t) @@ -136,55 +54,19 @@ 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) { - char *p; struct tm *ts; struct tm data; - size_t len = 20; - int free_s = 0; - - if (s == NULL) { - s = ASN1_UTCTIME_new(); - if (s == NULL) - goto err; - free_s = 1; - } ts = OPENSSL_gmtime(&t, &data); if (ts == NULL) - goto err; + return NULL; if (offset_day || offset_sec) { if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec)) - goto err; + return NULL; } - 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; - } - 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) - ASN1_UTCTIME_free(s); - return NULL; + return asn1_time_from_tm(s, ts, V_ASN1_UTCTIME); } int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t) @@ -195,60 +77,22 @@ int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t) if (!asn1_utctime_to_tm(&stm, s)) return -2; - if (!OPENSSL_gmtime(&t, &ttm)) + if (OPENSSL_gmtime(&t, &ttm) == NULL) return -2; if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm)) return -2; - if (day > 0) + if (day > 0 || sec > 0) return 1; - if (day < 0) - return -1; - if (sec > 0) - return 1; - if (sec < 0) + if (day < 0 || sec < 0) return -1; return 0; } int ASN1_UTCTIME_print(BIO *bp, const ASN1_UTCTIME *tm) { - const char *v; - int gmt = 0; - int i; - int y = 0, M = 0, d = 0, h = 0, m = 0, s = 0; - - i = tm->length; - v = (const char *)tm->data; - - if (i < 10) - goto err; - if (v[i - 1] == 'Z') - gmt = 1; - for (i = 0; i < 10; i++) - if ((v[i] > '9') || (v[i] < '0')) - goto err; - y = (v[0] - '0') * 10 + (v[1] - '0'); - if (y < 50) - y += 100; - M = (v[2] - '0') * 10 + (v[3] - '0'); - if ((M > 12) || (M < 1)) - goto err; - d = (v[4] - '0') * 10 + (v[5] - '0'); - h = (v[6] - '0') * 10 + (v[7] - '0'); - m = (v[8] - '0') * 10 + (v[9] - '0'); - if (tm->length >= 12 && - (v[10] >= '0') && (v[10] <= '9') && (v[11] >= '0') && (v[11] <= '9')) - s = (v[10] - '0') * 10 + (v[11] - '0'); - - if (BIO_printf(bp, "%s %2d %02d:%02d:%02d %d%s", - _asn1_mon[M - 1], d, h, m, s, y + 1900, - (gmt) ? " GMT" : "") <= 0) - return (0); - else - return (1); - err: - BIO_write(bp, "Bad time value", 14); - return (0); + if (tm->type != V_ASN1_UTCTIME) + return 0; + return ASN1_TIME_print(bp, tm); } diff --git a/crypto/asn1/a_verify.c b/crypto/asn1/a_verify.c index fb3607cb..973d50d2 100644 --- a/crypto/asn1/a_verify.c +++ b/crypto/asn1/a_verify.c @@ -76,7 +76,7 @@ int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature, ret = 1; err: EVP_MD_CTX_free(ctx); - return (ret); + return ret; } #endif @@ -86,7 +86,7 @@ int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, { EVP_MD_CTX *ctx = NULL; unsigned char *buf_in = NULL; - int ret = -1, inl; + int ret = -1, inl = 0; int mdnid, pknid; @@ -156,24 +156,15 @@ int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, goto err; } - ret = EVP_DigestVerifyUpdate(ctx, buf_in, inl); - - OPENSSL_clear_free(buf_in, (unsigned int)inl); - - if (!ret) { + ret = EVP_DigestVerify(ctx, signature->data, (size_t)signature->length, + buf_in, inl); + if (ret <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_EVP_LIB); goto err; } - ret = -1; - - if (EVP_DigestVerifyFinal(ctx, signature->data, - (size_t)signature->length) <= 0) { - ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_EVP_LIB); - ret = 0; - goto err; - } ret = 1; err: + OPENSSL_clear_free(buf_in, (unsigned int)inl); EVP_MD_CTX_free(ctx); - return (ret); + return ret; } diff --git a/crypto/asn1/ameth_lib.c b/crypto/asn1/ameth_lib.c index b8ba0678..f8171986 100644 --- a/crypto/asn1/ameth_lib.c +++ b/crypto/asn1/ameth_lib.c @@ -7,59 +7,20 @@ * https://www.openssl.org/source/license.html */ -#include +#include "e_os.h" /* for strncasecmp */ #include "internal/cryptlib.h" +#include #include #include #include #include "internal/asn1_int.h" #include "internal/evp_int.h" -/* Keep this sorted in type order !! */ -static const EVP_PKEY_ASN1_METHOD *standard_methods[] = { -#ifndef OPENSSL_NO_RSA - &rsa_asn1_meths[0], - &rsa_asn1_meths[1], -#endif -#ifndef OPENSSL_NO_DH - &dh_asn1_meth, -#endif -#ifndef OPENSSL_NO_DSA - &dsa_asn1_meths[0], - &dsa_asn1_meths[1], - &dsa_asn1_meths[2], - &dsa_asn1_meths[3], - &dsa_asn1_meths[4], -#endif -#ifndef OPENSSL_NO_EC - &eckey_asn1_meth, -#endif - &hmac_asn1_meth, -#ifndef OPENSSL_NO_CMAC - &cmac_asn1_meth, -#endif -#ifndef OPENSSL_NO_DH - &dhx_asn1_meth, -#endif -#ifndef OPENSSL_NO_EC - &ecx25519_asn1_meth -#endif -}; +#include "standard_methods.h" typedef int sk_cmp_fn_type(const char *const *a, const char *const *b); static STACK_OF(EVP_PKEY_ASN1_METHOD) *app_methods = NULL; -#ifdef TEST -void main() -{ - int i; - for (i = 0; i < OSSL_NELEM(standard_methods); i++) - fprintf(stderr, "Number %d id=%d (%s)\n", i, - standard_methods[i]->pkey_id, - OBJ_nid2sn(standard_methods[i]->pkey_id)); -} -#endif - DECLARE_OBJ_BSEARCH_CMP_FN(const EVP_PKEY_ASN1_METHOD *, const EVP_PKEY_ASN1_METHOD *, ameth); @@ -301,6 +262,10 @@ void EVP_PKEY_asn1_copy(EVP_PKEY_ASN1_METHOD *dst, dst->item_sign = src->item_sign; dst->item_verify = src->item_verify; + dst->siginf_set = src->siginf_set; + + dst->pkey_check = src->pkey_check; + } void EVP_PKEY_asn1_free(EVP_PKEY_ASN1_METHOD *ameth) @@ -409,3 +374,29 @@ void EVP_PKEY_asn1_set_item(EVP_PKEY_ASN1_METHOD *ameth, ameth->item_sign = item_sign; ameth->item_verify = item_verify; } + +void EVP_PKEY_asn1_set_siginf(EVP_PKEY_ASN1_METHOD *ameth, + int (*siginf_set) (X509_SIG_INFO *siginf, + const X509_ALGOR *alg, + const ASN1_STRING *sig)) +{ + ameth->siginf_set = siginf_set; +} + +void EVP_PKEY_asn1_set_check(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_check) (const EVP_PKEY *pk)) +{ + ameth->pkey_check = pkey_check; +} + +void EVP_PKEY_asn1_set_public_check(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_pub_check) (const EVP_PKEY *pk)) +{ + ameth->pkey_public_check = pkey_pub_check; +} + +void EVP_PKEY_asn1_set_param_check(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_param_check) (const EVP_PKEY *pk)) +{ + ameth->pkey_param_check = pkey_param_check; +} diff --git a/crypto/asn1/asn1_err.c b/crypto/asn1/asn1_err.c index 8602c408..da856b27 100644 --- a/crypto/asn1/asn1_err.c +++ b/crypto/asn1/asn1_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,251 +8,312 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* 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_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_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_DO_LOCK), "asn1_do_lock"}, - {ERR_FUNC(ASN1_F_ASN1_DUP), "ASN1_dup"}, - {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_GENERATE_V3), "ASN1_generate_v3"}, - {ERR_FUNC(ASN1_F_ASN1_GET_INT64), "asn1_get_int64"}, - {ERR_FUNC(ASN1_F_ASN1_GET_OBJECT), "ASN1_get_object"}, - {ERR_FUNC(ASN1_F_ASN1_GET_UINT64), "asn1_get_uint64"}, - {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_ITEM_D2I_FP), "ASN1_item_d2i_fp"}, - {ERR_FUNC(ASN1_F_ASN1_ITEM_DUP), "ASN1_item_dup"}, - {ERR_FUNC(ASN1_F_ASN1_ITEM_EMBED_D2I), "asn1_item_embed_d2i"}, - {ERR_FUNC(ASN1_F_ASN1_ITEM_EMBED_NEW), "asn1_item_embed_new"}, - {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_PCTX_NEW), "ASN1_PCTX_new"}, - {ERR_FUNC(ASN1_F_ASN1_SCTX_NEW), "ASN1_SCTX_new"}, - {ERR_FUNC(ASN1_F_ASN1_SIGN), "ASN1_sign"}, - {ERR_FUNC(ASN1_F_ASN1_STR2TYPE), "asn1_str2type"}, - {ERR_FUNC(ASN1_F_ASN1_STRING_GET_INT64), "asn1_string_get_int64"}, - {ERR_FUNC(ASN1_F_ASN1_STRING_GET_UINT64), "asn1_string_get_uint64"}, - {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_TO_BN), "asn1_string_to_bn"}, - {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_TYPE_GET_INT_OCTETSTRING), +static const ERR_STRING_DATA ASN1_str_functs[] = { + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_A2D_ASN1_OBJECT, 0), "a2d_ASN1_OBJECT"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_A2I_ASN1_INTEGER, 0), "a2i_ASN1_INTEGER"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_A2I_ASN1_STRING, 0), "a2i_ASN1_STRING"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_APPEND_EXP, 0), "append_exp"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_BIT_STRING_SET_BIT, 0), + "ASN1_BIT_STRING_set_bit"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_CB, 0), "asn1_cb"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_CHECK_TLEN, 0), "asn1_check_tlen"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_COLLECT, 0), "asn1_collect"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_D2I_EX_PRIMITIVE, 0), + "asn1_d2i_ex_primitive"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_D2I_FP, 0), "ASN1_d2i_fp"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_D2I_READ_BIO, 0), "asn1_d2i_read_bio"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_DIGEST, 0), "ASN1_digest"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_DO_ADB, 0), "asn1_do_adb"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_DO_LOCK, 0), "asn1_do_lock"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_DUP, 0), "ASN1_dup"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_EX_C2I, 0), "asn1_ex_c2i"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_FIND_END, 0), "asn1_find_end"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_GENERALIZEDTIME_ADJ, 0), + "ASN1_GENERALIZEDTIME_adj"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_GENERATE_V3, 0), "ASN1_generate_v3"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_GET_INT64, 0), "asn1_get_int64"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_GET_OBJECT, 0), "ASN1_get_object"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_GET_UINT64, 0), "asn1_get_uint64"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_I2D_BIO, 0), "ASN1_i2d_bio"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_I2D_FP, 0), "ASN1_i2d_fp"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_D2I_FP, 0), "ASN1_item_d2i_fp"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_DUP, 0), "ASN1_item_dup"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_EMBED_D2I, 0), + "asn1_item_embed_d2i"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_EMBED_NEW, 0), + "asn1_item_embed_new"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_I2D_BIO, 0), "ASN1_item_i2d_bio"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_I2D_FP, 0), "ASN1_item_i2d_fp"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_PACK, 0), "ASN1_item_pack"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_SIGN, 0), "ASN1_item_sign"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_SIGN_CTX, 0), + "ASN1_item_sign_ctx"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_UNPACK, 0), "ASN1_item_unpack"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_ITEM_VERIFY, 0), "ASN1_item_verify"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_MBSTRING_NCOPY, 0), + "ASN1_mbstring_ncopy"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_OBJECT_NEW, 0), "ASN1_OBJECT_new"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_OUTPUT_DATA, 0), "asn1_output_data"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_PCTX_NEW, 0), "ASN1_PCTX_new"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_SCTX_NEW, 0), "ASN1_SCTX_new"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_SIGN, 0), "ASN1_sign"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_STR2TYPE, 0), "asn1_str2type"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_STRING_GET_INT64, 0), + "asn1_string_get_int64"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_STRING_GET_UINT64, 0), + "asn1_string_get_uint64"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_STRING_SET, 0), "ASN1_STRING_set"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_STRING_TABLE_ADD, 0), + "ASN1_STRING_TABLE_add"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_STRING_TO_BN, 0), "asn1_string_to_bn"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_STRING_TYPE_NEW, 0), + "ASN1_STRING_type_new"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_TEMPLATE_EX_D2I, 0), + "asn1_template_ex_d2i"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_TEMPLATE_NEW, 0), "asn1_template_new"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, 0), + "asn1_template_noexp_d2i"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_TIME_ADJ, 0), "ASN1_TIME_adj"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_TYPE_GET_INT_OCTETSTRING, 0), "ASN1_TYPE_get_int_octetstring"}, - {ERR_FUNC(ASN1_F_ASN1_TYPE_GET_OCTETSTRING), "ASN1_TYPE_get_octetstring"}, - {ERR_FUNC(ASN1_F_ASN1_UTCTIME_ADJ), "ASN1_UTCTIME_adj"}, - {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_STRING), "bn_to_asn1_string"}, - {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_C2I_IBUF), "c2i_ibuf"}, - {ERR_FUNC(ASN1_F_C2I_UINT64_INT), "c2i_uint64_int"}, - {ERR_FUNC(ASN1_F_COLLECT_DATA), "collect_data"}, - {ERR_FUNC(ASN1_F_D2I_ASN1_OBJECT), "d2i_ASN1_OBJECT"}, - {ERR_FUNC(ASN1_F_D2I_ASN1_UINTEGER), "d2i_ASN1_UINTEGER"}, - {ERR_FUNC(ASN1_F_D2I_AUTOPRIVATEKEY), "d2i_AutoPrivateKey"}, - {ERR_FUNC(ASN1_F_D2I_PRIVATEKEY), "d2i_PrivateKey"}, - {ERR_FUNC(ASN1_F_D2I_PUBLICKEY), "d2i_PublicKey"}, - {ERR_FUNC(ASN1_F_DO_TCREATE), "do_tcreate"}, - {ERR_FUNC(ASN1_F_I2D_ASN1_BIO_STREAM), "i2d_ASN1_bio_stream"}, - {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_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_PBE2_SET_SCRYPT), "PKCS5_pbe2_set_scrypt"}, - {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_PKCS5_SCRYPT_SET), "pkcs5_scrypt_set"}, - {ERR_FUNC(ASN1_F_SMIME_READ_ASN1), "SMIME_read_ASN1"}, - {ERR_FUNC(ASN1_F_SMIME_TEXT), "SMIME_text"}, - {ERR_FUNC(ASN1_F_STBL_MODULE_INIT), "stbl_module_init"}, - {ERR_FUNC(ASN1_F_UINT32_C2I), "uint32_c2i"}, - {ERR_FUNC(ASN1_F_UINT64_C2I), "uint64_c2i"}, - {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_PKEY_NEW), "X509_PKEY_new"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_TYPE_GET_OCTETSTRING, 0), + "ASN1_TYPE_get_octetstring"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_UTCTIME_ADJ, 0), "ASN1_UTCTIME_adj"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_ASN1_VERIFY, 0), "ASN1_verify"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_B64_READ_ASN1, 0), "b64_read_asn1"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_B64_WRITE_ASN1, 0), "B64_write_ASN1"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_BIO_NEW_NDEF, 0), "BIO_new_NDEF"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_BITSTR_CB, 0), "bitstr_cb"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_BN_TO_ASN1_STRING, 0), "bn_to_asn1_string"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_C2I_ASN1_BIT_STRING, 0), + "c2i_ASN1_BIT_STRING"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_C2I_ASN1_INTEGER, 0), "c2i_ASN1_INTEGER"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_C2I_ASN1_OBJECT, 0), "c2i_ASN1_OBJECT"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_C2I_IBUF, 0), "c2i_ibuf"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_C2I_UINT64_INT, 0), "c2i_uint64_int"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_COLLECT_DATA, 0), "collect_data"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_D2I_ASN1_OBJECT, 0), "d2i_ASN1_OBJECT"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_D2I_ASN1_UINTEGER, 0), "d2i_ASN1_UINTEGER"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_D2I_AUTOPRIVATEKEY, 0), + "d2i_AutoPrivateKey"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_D2I_PRIVATEKEY, 0), "d2i_PrivateKey"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_D2I_PUBLICKEY, 0), "d2i_PublicKey"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_DO_TCREATE, 0), "do_tcreate"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_I2D_ASN1_BIO_STREAM, 0), + "i2d_ASN1_bio_stream"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_I2D_DSA_PUBKEY, 0), "i2d_DSA_PUBKEY"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_I2D_EC_PUBKEY, 0), "i2d_EC_PUBKEY"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_I2D_PRIVATEKEY, 0), "i2d_PrivateKey"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_I2D_PUBLICKEY, 0), "i2d_PublicKey"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_I2D_RSA_PUBKEY, 0), "i2d_RSA_PUBKEY"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_LONG_C2I, 0), "long_c2i"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_OID_MODULE_INIT, 0), "oid_module_init"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_PARSE_TAGGING, 0), "parse_tagging"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_PKCS5_PBE2_SET_IV, 0), "PKCS5_pbe2_set_iv"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_PKCS5_PBE2_SET_SCRYPT, 0), + "PKCS5_pbe2_set_scrypt"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_PKCS5_PBE_SET, 0), "PKCS5_pbe_set"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_PKCS5_PBE_SET0_ALGOR, 0), + "PKCS5_pbe_set0_algor"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_PKCS5_PBKDF2_SET, 0), "PKCS5_pbkdf2_set"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_PKCS5_SCRYPT_SET, 0), "pkcs5_scrypt_set"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_SMIME_READ_ASN1, 0), "SMIME_read_ASN1"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_SMIME_TEXT, 0), "SMIME_text"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_STBL_MODULE_INIT, 0), "stbl_module_init"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_UINT32_C2I, 0), "uint32_c2i"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_UINT64_C2I, 0), "uint64_c2i"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_X509_CRL_ADD0_REVOKED, 0), + "X509_CRL_add0_revoked"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_X509_INFO_NEW, 0), "X509_INFO_new"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_X509_NAME_ENCODE, 0), "x509_name_encode"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_X509_NAME_EX_D2I, 0), "x509_name_ex_d2i"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_X509_NAME_EX_NEW, 0), "x509_name_ex_new"}, + {ERR_PACK(ERR_LIB_ASN1, ASN1_F_X509_PKEY_NEW, 0), "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_OBJECT_HEADER), "bad object header"}, - {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_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_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_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_NEGATIVE_VALUE), "illegal negative value"}, - {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_PADDING), "illegal padding"}, - {ERR_REASON(ASN1_R_ILLEGAL_TAGGED_ANY), "illegal tagged any"}, - {ERR_REASON(ASN1_R_ILLEGAL_TIME_VALUE), "illegal time value"}, - {ERR_REASON(ASN1_R_ILLEGAL_ZERO_CONTENT), "illegal zero content"}, - {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_SCRYPT_PARAMETERS), - "invalid scrypt parameters"}, - {ERR_REASON(ASN1_R_INVALID_SEPARATOR), "invalid separator"}, - {ERR_REASON(ASN1_R_INVALID_STRING_TABLE_VALUE), - "invalid string table value"}, - {ERR_REASON(ASN1_R_INVALID_UNIVERSALSTRING_LENGTH), - "invalid universalstring length"}, - {ERR_REASON(ASN1_R_INVALID_UTF8STRING), "invalid utf8string"}, - {ERR_REASON(ASN1_R_INVALID_VALUE), "invalid value"}, - {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_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_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_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_LARGE), "too large"}, - {ERR_REASON(ASN1_R_TOO_LONG), "too long"}, - {ERR_REASON(ASN1_R_TOO_SMALL), "too small"}, - {ERR_REASON(ASN1_R_TYPE_NOT_CONSTRUCTED), "type not constructed"}, - {ERR_REASON(ASN1_R_TYPE_NOT_PRIMITIVE), "type not primitive"}, - {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_UNSUPPORTED_ANY_DEFINED_BY_TYPE), - "unsupported any defined by type"}, - {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_INTEGER_TYPE), "wrong integer type"}, - {ERR_REASON(ASN1_R_WRONG_PUBLIC_KEY_TYPE), "wrong public key type"}, - {ERR_REASON(ASN1_R_WRONG_TAG), "wrong tag"}, +static const ERR_STRING_DATA ASN1_str_reasons[] = { + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ADDING_OBJECT), "adding object"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ASN1_PARSE_ERROR), "asn1 parse error"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ASN1_SIG_PARSE_ERROR), + "asn1 sig parse error"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_AUX_ERROR), "aux error"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BAD_OBJECT_HEADER), "bad object header"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BMPSTRING_IS_WRONG_LENGTH), + "bmpstring is wrong length"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BN_LIB), "bn lib"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BOOLEAN_IS_WRONG_LENGTH), + "boolean is wrong length"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BUFFER_TOO_SMALL), "buffer too small"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER), + "cipher has no object identifier"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_CONTEXT_NOT_INITIALISED), + "context not initialised"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_DATA_IS_WRONG), "data is wrong"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_DECODE_ERROR), "decode error"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_DEPTH_EXCEEDED), "depth exceeded"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED), + "digest and key type not supported"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ENCODE_ERROR), "encode error"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ERROR_GETTING_TIME), + "error getting time"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ERROR_LOADING_SECTION), + "error loading section"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ERROR_SETTING_CIPHER_PARAMS), + "error setting cipher params"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_EXPECTING_AN_INTEGER), + "expecting an integer"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_EXPECTING_AN_OBJECT), + "expecting an object"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_EXPLICIT_LENGTH_MISMATCH), + "explicit length mismatch"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED), + "explicit tag not constructed"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_FIELD_MISSING), "field missing"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_FIRST_NUM_TOO_LARGE), + "first num too large"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_HEADER_TOO_LONG), "header too long"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_BITSTRING_FORMAT), + "illegal bitstring format"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_BOOLEAN), "illegal boolean"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_CHARACTERS), + "illegal characters"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_FORMAT), "illegal format"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_HEX), "illegal hex"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_IMPLICIT_TAG), + "illegal implicit tag"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_INTEGER), "illegal integer"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_NEGATIVE_VALUE), + "illegal negative value"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_NESTED_TAGGING), + "illegal nested tagging"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_NULL), "illegal null"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_NULL_VALUE), + "illegal null value"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_OBJECT), "illegal object"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_OPTIONAL_ANY), + "illegal optional any"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE), + "illegal options on item template"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_PADDING), "illegal padding"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_TAGGED_ANY), + "illegal tagged any"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_TIME_VALUE), + "illegal time value"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_ZERO_CONTENT), + "illegal zero content"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INTEGER_NOT_ASCII_FORMAT), + "integer not ascii format"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG), + "integer too large for long"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_BIT_STRING_BITS_LEFT), + "invalid bit string bits left"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_BMPSTRING_LENGTH), + "invalid bmpstring length"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_DIGIT), "invalid digit"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_MIME_TYPE), "invalid mime type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_MODIFIER), "invalid modifier"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_NUMBER), "invalid number"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_OBJECT_ENCODING), + "invalid object encoding"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_SCRYPT_PARAMETERS), + "invalid scrypt parameters"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_SEPARATOR), "invalid separator"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_STRING_TABLE_VALUE), + "invalid string table value"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_UNIVERSALSTRING_LENGTH), + "invalid universalstring length"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_UTF8STRING), + "invalid utf8string"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_VALUE), "invalid value"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_LIST_ERROR), "list error"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MIME_NO_CONTENT_TYPE), + "mime no content type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MIME_PARSE_ERROR), "mime parse error"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MIME_SIG_PARSE_ERROR), + "mime sig parse error"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MISSING_EOC), "missing eoc"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MISSING_SECOND_NUMBER), + "missing second number"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MISSING_VALUE), "missing value"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MSTRING_NOT_UNIVERSAL), + "mstring not universal"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MSTRING_WRONG_TAG), "mstring wrong tag"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NESTED_ASN1_STRING), + "nested asn1 string"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NON_HEX_CHARACTERS), + "non hex characters"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NOT_ASCII_FORMAT), "not ascii format"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NOT_ENOUGH_DATA), "not enough data"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NO_CONTENT_TYPE), "no content type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NO_MATCHING_CHOICE_TYPE), + "no matching choice type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NO_MULTIPART_BODY_FAILURE), + "no multipart body failure"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NO_MULTIPART_BOUNDARY), + "no multipart boundary"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NO_SIG_CONTENT_TYPE), + "no sig content type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NULL_IS_WRONG_LENGTH), + "null is wrong length"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_OBJECT_NOT_ASCII_FORMAT), + "object not ascii format"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ODD_NUMBER_OF_CHARS), + "odd number of chars"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SECOND_NUMBER_TOO_LARGE), + "second number too large"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SEQUENCE_LENGTH_MISMATCH), + "sequence length mismatch"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SEQUENCE_NOT_CONSTRUCTED), + "sequence not constructed"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG), + "sequence or set needs config"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SHORT_LINE), "short line"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SIG_INVALID_MIME_TYPE), + "sig invalid mime type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_STREAMING_NOT_SUPPORTED), + "streaming not supported"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_STRING_TOO_LONG), "string too long"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_STRING_TOO_SHORT), "string too short"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD), + "the asn1 object identifier is not known for this md"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TIME_NOT_ASCII_FORMAT), + "time not ascii format"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TOO_LARGE), "too large"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TOO_LONG), "too long"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TOO_SMALL), "too small"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TYPE_NOT_CONSTRUCTED), + "type not constructed"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TYPE_NOT_PRIMITIVE), + "type not primitive"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNEXPECTED_EOC), "unexpected eoc"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH), + "universalstring is wrong length"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_FORMAT), "unknown format"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM), + "unknown message digest algorithm"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_OBJECT_TYPE), + "unknown object type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE), + "unknown public key type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM), + "unknown signature algorithm"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_TAG), "unknown tag"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE), + "unsupported any defined by type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE), + "unsupported public key type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNSUPPORTED_TYPE), "unsupported type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_WRONG_INTEGER_TYPE), + "wrong integer type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_WRONG_PUBLIC_KEY_TYPE), + "wrong public key type"}, + {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_WRONG_TAG), "wrong tag"}, {0, NULL} }; @@ -261,10 +322,9 @@ static ERR_STRING_DATA ASN1_str_reasons[] = { int 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); + ERR_load_strings_const(ASN1_str_functs); + ERR_load_strings_const(ASN1_str_reasons); } #endif return 1; diff --git a/crypto/asn1/asn1_item_list.c b/crypto/asn1/asn1_item_list.c new file mode 100644 index 00000000..9798192f --- /dev/null +++ b/crypto/asn1/asn1_item_list.c @@ -0,0 +1,42 @@ +/* + * Copyright 2000-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 + */ + +#include +#include "internal/cryptlib.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "asn1_item_list.h" + +const ASN1_ITEM *ASN1_ITEM_lookup(const char *name) +{ + size_t i; + + for (i = 0; i < OSSL_NELEM(asn1_item_list); i++) { + const ASN1_ITEM *it = ASN1_ITEM_ptr(asn1_item_list[i]); + + if (strcmp(it->sname, name) == 0) + return it; + } + return NULL; +} + +const ASN1_ITEM *ASN1_ITEM_get(size_t i) +{ + if (i >= OSSL_NELEM(asn1_item_list)) + return NULL; + return ASN1_ITEM_ptr(asn1_item_list[i]); +} diff --git a/crypto/asn1/asn1_item_list.h b/crypto/asn1/asn1_item_list.h new file mode 100644 index 00000000..db8107ed --- /dev/null +++ b/crypto/asn1/asn1_item_list.h @@ -0,0 +1,178 @@ +/* + * Copyright 2000-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 + */ + +static ASN1_ITEM_EXP *asn1_item_list[] = { + + ASN1_ITEM_ref(ACCESS_DESCRIPTION), +#ifndef OPENSSL_NO_RFC3779 + ASN1_ITEM_ref(ASIdOrRange), + ASN1_ITEM_ref(ASIdentifierChoice), + ASN1_ITEM_ref(ASIdentifiers), +#endif + ASN1_ITEM_ref(ASN1_ANY), + ASN1_ITEM_ref(ASN1_BIT_STRING), + ASN1_ITEM_ref(ASN1_BMPSTRING), + ASN1_ITEM_ref(ASN1_BOOLEAN), + ASN1_ITEM_ref(ASN1_ENUMERATED), + ASN1_ITEM_ref(ASN1_FBOOLEAN), + ASN1_ITEM_ref(ASN1_GENERALIZEDTIME), + ASN1_ITEM_ref(ASN1_GENERALSTRING), + ASN1_ITEM_ref(ASN1_IA5STRING), + ASN1_ITEM_ref(ASN1_INTEGER), + ASN1_ITEM_ref(ASN1_NULL), + ASN1_ITEM_ref(ASN1_OBJECT), + ASN1_ITEM_ref(ASN1_OCTET_STRING_NDEF), + ASN1_ITEM_ref(ASN1_OCTET_STRING), + ASN1_ITEM_ref(ASN1_PRINTABLESTRING), + ASN1_ITEM_ref(ASN1_PRINTABLE), + ASN1_ITEM_ref(ASN1_SEQUENCE_ANY), + ASN1_ITEM_ref(ASN1_SEQUENCE), + ASN1_ITEM_ref(ASN1_SET_ANY), + ASN1_ITEM_ref(ASN1_T61STRING), + ASN1_ITEM_ref(ASN1_TBOOLEAN), + ASN1_ITEM_ref(ASN1_TIME), + ASN1_ITEM_ref(ASN1_UNIVERSALSTRING), + ASN1_ITEM_ref(ASN1_UTCTIME), + ASN1_ITEM_ref(ASN1_UTF8STRING), + ASN1_ITEM_ref(ASN1_VISIBLESTRING), +#ifndef OPENSSL_NO_RFC3779 + ASN1_ITEM_ref(ASRange), +#endif + ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS), + ASN1_ITEM_ref(AUTHORITY_KEYID), + ASN1_ITEM_ref(BASIC_CONSTRAINTS), + ASN1_ITEM_ref(BIGNUM), + ASN1_ITEM_ref(CBIGNUM), + ASN1_ITEM_ref(CERTIFICATEPOLICIES), +#ifndef OPENSSL_NO_CMS + ASN1_ITEM_ref(CMS_ContentInfo), + ASN1_ITEM_ref(CMS_ReceiptRequest), +#endif + ASN1_ITEM_ref(CRL_DIST_POINTS), +#ifndef OPENSSL_NO_DH + ASN1_ITEM_ref(DHparams), +#endif + ASN1_ITEM_ref(DIRECTORYSTRING), + ASN1_ITEM_ref(DISPLAYTEXT), + ASN1_ITEM_ref(DIST_POINT_NAME), + ASN1_ITEM_ref(DIST_POINT), +#ifndef OPENSSL_NO_EC + ASN1_ITEM_ref(ECPARAMETERS), + ASN1_ITEM_ref(ECPKPARAMETERS), +#endif + ASN1_ITEM_ref(EDIPARTYNAME), + ASN1_ITEM_ref(EXTENDED_KEY_USAGE), + ASN1_ITEM_ref(GENERAL_NAMES), + ASN1_ITEM_ref(GENERAL_NAME), + ASN1_ITEM_ref(GENERAL_SUBTREE), +#ifndef OPENSSL_NO_RFC3779 + ASN1_ITEM_ref(IPAddressChoice), + ASN1_ITEM_ref(IPAddressFamily), + ASN1_ITEM_ref(IPAddressOrRange), + ASN1_ITEM_ref(IPAddressRange), +#endif + ASN1_ITEM_ref(ISSUING_DIST_POINT), +#if OPENSSL_API_COMPAT < 0x10200000L + ASN1_ITEM_ref(LONG), +#endif + ASN1_ITEM_ref(NAME_CONSTRAINTS), + ASN1_ITEM_ref(NETSCAPE_CERT_SEQUENCE), + ASN1_ITEM_ref(NETSCAPE_SPKAC), + ASN1_ITEM_ref(NETSCAPE_SPKI), + ASN1_ITEM_ref(NOTICEREF), +#ifndef OPENSSL_NO_OCSP + ASN1_ITEM_ref(OCSP_BASICRESP), + ASN1_ITEM_ref(OCSP_CERTID), + ASN1_ITEM_ref(OCSP_CERTSTATUS), + ASN1_ITEM_ref(OCSP_CRLID), + ASN1_ITEM_ref(OCSP_ONEREQ), + ASN1_ITEM_ref(OCSP_REQINFO), + ASN1_ITEM_ref(OCSP_REQUEST), + ASN1_ITEM_ref(OCSP_RESPBYTES), + ASN1_ITEM_ref(OCSP_RESPDATA), + ASN1_ITEM_ref(OCSP_RESPID), + ASN1_ITEM_ref(OCSP_RESPONSE), + ASN1_ITEM_ref(OCSP_REVOKEDINFO), + ASN1_ITEM_ref(OCSP_SERVICELOC), + ASN1_ITEM_ref(OCSP_SIGNATURE), + ASN1_ITEM_ref(OCSP_SINGLERESP), +#endif + ASN1_ITEM_ref(OTHERNAME), + ASN1_ITEM_ref(PBE2PARAM), + ASN1_ITEM_ref(PBEPARAM), + ASN1_ITEM_ref(PBKDF2PARAM), + ASN1_ITEM_ref(PKCS12_AUTHSAFES), + ASN1_ITEM_ref(PKCS12_BAGS), + ASN1_ITEM_ref(PKCS12_MAC_DATA), + ASN1_ITEM_ref(PKCS12_SAFEBAGS), + ASN1_ITEM_ref(PKCS12_SAFEBAG), + ASN1_ITEM_ref(PKCS12), + ASN1_ITEM_ref(PKCS7_ATTR_SIGN), + ASN1_ITEM_ref(PKCS7_ATTR_VERIFY), + ASN1_ITEM_ref(PKCS7_DIGEST), + ASN1_ITEM_ref(PKCS7_ENCRYPT), + ASN1_ITEM_ref(PKCS7_ENC_CONTENT), + ASN1_ITEM_ref(PKCS7_ENVELOPE), + ASN1_ITEM_ref(PKCS7_ISSUER_AND_SERIAL), + ASN1_ITEM_ref(PKCS7_RECIP_INFO), + ASN1_ITEM_ref(PKCS7_SIGNED), + ASN1_ITEM_ref(PKCS7_SIGNER_INFO), + ASN1_ITEM_ref(PKCS7_SIGN_ENVELOPE), + ASN1_ITEM_ref(PKCS7), + ASN1_ITEM_ref(PKCS8_PRIV_KEY_INFO), + ASN1_ITEM_ref(PKEY_USAGE_PERIOD), + ASN1_ITEM_ref(POLICYINFO), + ASN1_ITEM_ref(POLICYQUALINFO), + ASN1_ITEM_ref(POLICY_CONSTRAINTS), + ASN1_ITEM_ref(POLICY_MAPPINGS), + ASN1_ITEM_ref(POLICY_MAPPING), + ASN1_ITEM_ref(PROXY_CERT_INFO_EXTENSION), + ASN1_ITEM_ref(PROXY_POLICY), +#ifndef OPENSSL_NO_RSA + ASN1_ITEM_ref(RSAPrivateKey), + ASN1_ITEM_ref(RSAPublicKey), + ASN1_ITEM_ref(RSA_OAEP_PARAMS), + ASN1_ITEM_ref(RSA_PSS_PARAMS), +#endif +#ifndef OPENSSL_NO_SCRYPT + ASN1_ITEM_ref(SCRYPT_PARAMS), +#endif + ASN1_ITEM_ref(SXNETID), + ASN1_ITEM_ref(SXNET), + ASN1_ITEM_ref(USERNOTICE), + ASN1_ITEM_ref(X509_ALGORS), + ASN1_ITEM_ref(X509_ALGOR), + ASN1_ITEM_ref(X509_ATTRIBUTE), + ASN1_ITEM_ref(X509_CERT_AUX), + ASN1_ITEM_ref(X509_CINF), + ASN1_ITEM_ref(X509_CRL_INFO), + ASN1_ITEM_ref(X509_CRL), + ASN1_ITEM_ref(X509_EXTENSIONS), + ASN1_ITEM_ref(X509_EXTENSION), + ASN1_ITEM_ref(X509_NAME_ENTRY), + ASN1_ITEM_ref(X509_NAME), + ASN1_ITEM_ref(X509_PUBKEY), + ASN1_ITEM_ref(X509_REQ_INFO), + ASN1_ITEM_ref(X509_REQ), + ASN1_ITEM_ref(X509_REVOKED), + ASN1_ITEM_ref(X509_SIG), + ASN1_ITEM_ref(X509_VAL), + ASN1_ITEM_ref(X509), +#if OPENSSL_API_COMPAT < 0x10200000L + ASN1_ITEM_ref(ZLONG), +#endif + ASN1_ITEM_ref(INT32), + ASN1_ITEM_ref(UINT32), + ASN1_ITEM_ref(ZINT32), + ASN1_ITEM_ref(ZUINT32), + ASN1_ITEM_ref(INT64), + ASN1_ITEM_ref(UINT64), + ASN1_ITEM_ref(ZINT64), + ASN1_ITEM_ref(ZUINT64), +}; diff --git a/crypto/asn1/asn1_lib.c b/crypto/asn1/asn1_lib.c index 8ca53b4c..88c4b539 100644 --- a/crypto/asn1/asn1_lib.c +++ b/crypto/asn1/asn1_lib.c @@ -23,12 +23,12 @@ 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); + return 1; else if ((len >= 2) && ((*p)[0] == 0) && ((*p)[1] == 0)) { (*p) += 2; - return (1); + return 1; } - return (0); + return 0; } int ASN1_check_infinite_end(unsigned char **p, long len) @@ -96,47 +96,54 @@ int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag, ret |= 0x80; } *pp = p; - return (ret | inf); + return ret | inf; err: ASN1err(ASN1_F_ASN1_GET_OBJECT, ASN1_R_HEADER_TOO_LONG); - return (0x80); + return 0x80; } +/* + * Decode a length field. + * The short form is a single byte defining a length 0 - 127. + * The long form is a byte 0 - 127 with the top bit set and this indicates + * the number of following octets that contain the length. These octets + * are stored most significant digit first. + */ 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; + int i; if (max-- < 1) return 0; if (*p == 0x80) { *inf = 1; - ret = 0; p++; } else { *inf = 0; i = *p & 0x7f; - if (*(p++) & 0x80) { - if (max < (long)i + 1) + if (*p++ & 0x80) { + if (max < i + 1) return 0; /* Skip leading zeroes */ - while (i && *p == 0) { + while (i > 0 && *p == 0) { p++; i--; } - if (i > sizeof(long)) + if (i > (int)sizeof(long)) return 0; - while (i-- > 0) { - ret <<= 8L; - ret |= *(p++); + while (i > 0) { + ret <<= 8; + ret |= *p++; + i--; } + if (ret > LONG_MAX) + return 0; } else ret = i; } - if (ret > LONG_MAX) - return 0; *pp = p; *rl = (long)ret; return 1; @@ -268,7 +275,7 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, int len) if (len < 0) { if (data == NULL) - return (0); + return 0; else len = strlen(data); } @@ -278,7 +285,7 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, int len) if (str->data == NULL) { ASN1err(ASN1_F_ASN1_STRING_SET, ERR_R_MALLOC_FAILURE); str->data = c; - return (0); + return 0; } } str->length = len; @@ -287,7 +294,7 @@ int ASN1_STRING_set(ASN1_STRING *str, const void *_data, int len) /* an allowance for strings :-) */ str->data[len] = '\0'; } - return (1); + return 1; } void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len) @@ -299,7 +306,7 @@ void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len) ASN1_STRING *ASN1_STRING_new(void) { - return (ASN1_STRING_type_new(V_ASN1_OCTET_STRING)); + return ASN1_STRING_type_new(V_ASN1_OCTET_STRING); } ASN1_STRING *ASN1_STRING_type_new(int type) @@ -309,10 +316,10 @@ ASN1_STRING *ASN1_STRING_type_new(int type) ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) { ASN1err(ASN1_F_ASN1_STRING_TYPE_NEW, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } ret->type = type; - return (ret); + return ret; } void asn1_string_embed_free(ASN1_STRING *a, int embed) @@ -349,11 +356,11 @@ int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b) if (i == 0) { i = memcmp(a->data, b->data, a->length); if (i == 0) - return (a->type - b->type); + return a->type - b->type; else - return (i); + return i; } else - return (i); + return i; } int ASN1_STRING_length(const ASN1_STRING *x) diff --git a/crypto/asn1/asn1_locl.h b/crypto/asn1/asn1_locl.h index 9a47b1ef..cec14172 100644 --- a/crypto/asn1/asn1_locl.h +++ b/crypto/asn1/asn1_locl.h @@ -9,6 +9,7 @@ /* Internal ASN1 structures and functions: not for application use */ +int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *d); int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d); int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d); @@ -42,9 +43,6 @@ DEFINE_STACK_OF(MIME_PARAM) typedef struct mime_header_st MIME_HEADER; DEFINE_STACK_OF(MIME_HEADER) -/* Month values for printing out times */ -extern const char *_asn1_mon[12]; - void asn1_string_embed_free(ASN1_STRING *a, int embed); int asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it); @@ -81,3 +79,5 @@ ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp, /* Internal functions used by x_int64.c */ int c2i_uint64_int(uint64_t *ret, int *neg, const unsigned char **pp, long len); int i2c_uint64_int(unsigned char *p, uint64_t r, int neg); + +ASN1_TIME *asn1_time_from_tm(ASN1_TIME *s, struct tm *ts, int type); diff --git a/crypto/asn1/asn1_par.c b/crypto/asn1/asn1_par.c index fabc8d6f..4b60c615 100644 --- a/crypto/asn1/asn1_par.c +++ b/crypto/asn1/asn1_par.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -50,20 +50,20 @@ static int asn1_print_info(BIO *bp, int tag, int xclass, int constructed, if (BIO_printf(bp, fmt, p) <= 0) goto err; - return (1); + return 1; err: - return (0); + 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)); + 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)); + return asn1_parse2(bp, &pp, len, 0, 0, indent, dump); } static int asn1_parse2(BIO *bp, const unsigned char **pp, long length, @@ -342,7 +342,7 @@ static int asn1_parse2(BIO *bp, const unsigned char **pp, long length, ASN1_OBJECT_free(o); ASN1_OCTET_STRING_free(os); *pp = p; - return (ret); + return ret; } const char *ASN1_tag2str(int tag) diff --git a/crypto/asn1/asn_mime.c b/crypto/asn1/asn_mime.c index 84475e94..7f4db6a2 100644 --- a/crypto/asn1/asn_mime.c +++ b/crypto/asn1/asn_mime.c @@ -8,7 +8,7 @@ */ #include -#include +#include "internal/ctype.h" #include "internal/cryptlib.h" #include #include @@ -635,7 +635,7 @@ static STACK_OF(MIME_HEADER) *mime_parse_hdr(BIO *bio) 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])) + if (mhdr && ossl_isspace(linebuf[0])) state = MIME_NAME; else state = MIME_START; @@ -759,7 +759,7 @@ static char *strip_start(char *name) /* Else null string */ return NULL; } - if (!isspace((unsigned char)c)) + if (!ossl_isspace(c)) return p; } return NULL; @@ -780,7 +780,7 @@ static char *strip_end(char *name) *p = 0; return name; } - if (isspace((unsigned char)c)) + if (ossl_isspace(c)) *p = 0; else return name; @@ -792,29 +792,18 @@ static MIME_HEADER *mime_hdr_new(const char *name, const char *value) { MIME_HEADER *mhdr = NULL; char *tmpname = NULL, *tmpval = NULL, *p; - int c; if (name) { if ((tmpname = OPENSSL_strdup(name)) == NULL) return NULL; - for (p = tmpname; *p; p++) { - c = (unsigned char)*p; - if (isupper(c)) { - c = tolower(c); - *p = c; - } - } + for (p = tmpname; *p; p++) + *p = ossl_tolower(*p); } if (value) { if ((tmpval = OPENSSL_strdup(value)) == NULL) goto err; - for (p = tmpval; *p; p++) { - c = (unsigned char)*p; - if (isupper(c)) { - c = tolower(c); - *p = c; - } - } + for (p = tmpval; *p; p++) + *p = ossl_tolower(*p); } mhdr = OPENSSL_malloc(sizeof(*mhdr)); if (mhdr == NULL) @@ -835,19 +824,14 @@ static MIME_HEADER *mime_hdr_new(const char *name, const char *value) static int mime_hdr_addparam(MIME_HEADER *mhdr, const char *name, const char *value) { char *tmpname = NULL, *tmpval = NULL, *p; - int c; MIME_PARAM *mparam = NULL; + if (name) { tmpname = OPENSSL_strdup(name); if (!tmpname) goto err; - for (p = tmpname; *p; p++) { - c = (unsigned char)*p; - if (isupper(c)) { - c = tolower(c); - *p = c; - } - } + for (p = tmpname; *p; p++) + *p = ossl_tolower(*p); } if (value) { tmpval = OPENSSL_strdup(value); @@ -876,7 +860,7 @@ static int mime_hdr_cmp(const MIME_HEADER *const *a, if (!(*a)->name || !(*b)->name) return ! !(*a)->name - ! !(*b)->name; - return (strcmp((*a)->name, (*b)->name)); + return strcmp((*a)->name, (*b)->name); } static int mime_param_cmp(const MIME_PARAM *const *a, @@ -884,7 +868,7 @@ static int mime_param_cmp(const MIME_PARAM *const *a, { if (!(*a)->param_name || !(*b)->param_name) return ! !(*a)->param_name - ! !(*b)->param_name; - return (strcmp((*a)->param_name, (*b)->param_name)); + return strcmp((*a)->param_name, (*b)->param_name); } /* Find a header with a given name (if possible) */ @@ -966,7 +950,7 @@ static int strip_eol(char *linebuf, int *plen, int flags) 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') diff --git a/crypto/asn1/asn_moid.c b/crypto/asn1/asn_moid.c index 8176b760..ed8517c3 100644 --- a/crypto/asn1/asn_moid.c +++ b/crypto/asn1/asn_moid.c @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2002-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 @@ -8,7 +8,7 @@ */ #include -#include +#include "internal/ctype.h" #include #include "internal/cryptlib.h" #include @@ -72,7 +72,7 @@ static int do_create(const char *value, const char *name) ostr = p + 1; if (!*ostr) return 0; - while (isspace((unsigned char)*ostr)) + while (ossl_isspace(*ostr)) ostr++; } @@ -83,10 +83,10 @@ static int do_create(const char *value, const char *name) if (p) { ln = value; - while (isspace((unsigned char)*ln)) + while (ossl_isspace(*ln)) ln++; p--; - while (isspace((unsigned char)*p)) { + while (ossl_isspace(*p)) { if (p == ln) return 0; p--; diff --git a/crypto/asn1/asn_mstbl.c b/crypto/asn1/asn_mstbl.c index 82609390..ddcbcd07 100644 --- a/crypto/asn1/asn_mstbl.c +++ b/crypto/asn1/asn_mstbl.c @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2012-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 @@ -8,7 +8,6 @@ */ #include -#include #include #include "internal/cryptlib.h" #include diff --git a/crypto/asn1/bio_asn1.c b/crypto/asn1/bio_asn1.c index 2a8a41f5..3c7c1229 100644 --- a/crypto/asn1/bio_asn1.c +++ b/crypto/asn1/bio_asn1.c @@ -14,8 +14,9 @@ */ #include -#include +#include "internal/bio.h" #include +#include "internal/cryptlib.h" /* Must be large enough for biggest tag+length */ #define DEFAULT_ASN1_BUF_SIZE 20 @@ -78,7 +79,11 @@ static int asn1_bio_setup_ex(BIO *b, BIO_ASN1_BUF_CTX *ctx, static const BIO_METHOD methods_asn1 = { BIO_TYPE_ASN1, "asn1", + /* TODO: Convert to new style write function */ + bwrite_conv, asn1_bio_write, + /* TODO: Convert to new style read function */ + bread_conv, asn1_bio_read, asn1_bio_puts, asn1_bio_gets, @@ -90,7 +95,7 @@ static const BIO_METHOD methods_asn1 = { const BIO_METHOD *BIO_f_asn1(void) { - return (&methods_asn1); + return &methods_asn1; } static int asn1_bio_new(BIO *b) @@ -157,7 +162,6 @@ static int asn1_bio_write(BIO *b, const char *in, int inl) for (;;) { switch (ctx->state) { - /* Setup prefix data, call it */ case ASN1_STATE_START: if (!asn1_bio_setup_ex(b, ctx, ctx->prefix, @@ -178,7 +182,8 @@ static int asn1_bio_write(BIO *b, const char *in, int inl) case ASN1_STATE_HEADER: ctx->buflen = ASN1_object_size(0, inl, ctx->asn1_tag) - inl; - OPENSSL_assert(ctx->buflen <= ctx->bufsize); + if (!ossl_assert(ctx->buflen <= ctx->bufsize)) + return 0; p = ctx->buf; ASN1_put_object(&p, 0, inl, ctx->asn1_tag, ctx->asn1_class); ctx->copylen = inl; @@ -223,7 +228,8 @@ static int asn1_bio_write(BIO *b, const char *in, int inl) break; - default: + case ASN1_STATE_POST_COPY: + case ASN1_STATE_DONE: BIO_clear_retry_flags(b); return 0; diff --git a/crypto/asn1/build.info b/crypto/asn1/build.info index c1afb71a..d3e92c81 100644 --- a/crypto/asn1/build.info +++ b/crypto/asn1/build.info @@ -13,4 +13,4 @@ SOURCE[../../libcrypto]=\ x_pkey.c bio_asn1.c bio_ndef.c asn_mime.c \ asn1_gen.c asn1_par.c asn1_lib.c asn1_err.c a_strnid.c \ evp_asn1.c asn_pack.c p5_pbe.c p5_pbev2.c p5_scrypt.c p8_pkey.c \ - asn_moid.c asn_mstbl.c + asn_moid.c asn_mstbl.c asn1_item_list.c diff --git a/crypto/asn1/charmap.h b/crypto/asn1/charmap.h index 2a75925c..bfccac2c 100644 --- a/crypto/asn1/charmap.h +++ b/crypto/asn1/charmap.h @@ -2,7 +2,7 @@ * WARNING: do not edit! * Generated by crypto/asn1/charmap.pl * - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-2018 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 diff --git a/crypto/asn1/charmap.pl b/crypto/asn1/charmap.pl index 26ca3252..fbab1f3b 100644 --- a/crypto/asn1/charmap.pl +++ b/crypto/asn1/charmap.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2000-2018 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 @@ -82,12 +82,14 @@ $arr[ord("?")] |= $PSTRING_CHAR; # Now generate the C code +# Output year depends on the year of the script. +my $YEAR = [localtime([stat($0)]->[9])]->[5] + 1900; print <type != V_ASN1_OCTET_STRING) || (a->value.octet_string == NULL)) { ASN1err(ASN1_F_ASN1_TYPE_GET_OCTETSTRING, ASN1_R_DATA_IS_WRONG); - return (-1); + return -1; } p = ASN1_STRING_get0_data(a->value.octet_string); ret = ASN1_STRING_length(a->value.octet_string); @@ -43,16 +43,16 @@ int ASN1_TYPE_get_octetstring(const ASN1_TYPE *a, unsigned char *data, int max_l else num = max_len; memcpy(data, p, num); - return (ret); + return ret; } typedef struct { - long num; + int32_t num; ASN1_OCTET_STRING *oct; } asn1_int_oct; ASN1_SEQUENCE(asn1_int_oct) = { - ASN1_SIMPLE(asn1_int_oct, num, LONG), + ASN1_EMBED(asn1_int_oct, num, INT32), ASN1_SIMPLE(asn1_int_oct, oct, ASN1_OCTET_STRING) } static_ASN1_SEQUENCE_END(asn1_int_oct) diff --git a/crypto/asn1/f_int.c b/crypto/asn1/f_int.c index ec556c92..6d6bddc6 100644 --- a/crypto/asn1/f_int.c +++ b/crypto/asn1/f_int.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,7 +8,7 @@ */ #include -#include +#include "internal/ctype.h" #include "internal/cryptlib.h" #include #include @@ -20,7 +20,7 @@ int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a) char buf[2]; if (a == NULL) - return (0); + return 0; if (a->type & V_ASN1_NEG) { if (BIO_write(bp, "-", 1) != 1) @@ -46,9 +46,9 @@ int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a) n += 2; } } - return (n); + return n; err: - return (-1); + return -1; } int a2i_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *bs, char *buf, int size) @@ -76,18 +76,7 @@ int a2i_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *bs, char *buf, int size) again = (buf[i - 1] == '\\'); for (j = 0; j < i; j++) { -#ifndef CHARSET_EBCDIC - if (!(((buf[j] >= '0') && (buf[j] <= '9')) || - ((buf[j] >= 'a') && (buf[j] <= 'f')) || - ((buf[j] >= 'A') && (buf[j] <= 'F')))) -#else - /* - * This #ifdef is not strictly necessary, since the characters - * A...F a...f 0...9 are contiguous (yes, even in EBCDIC - but - * not the whole alphabet). Nevertheless, isxdigit() is faster. - */ - if (!isxdigit(buf[j])) -#endif + if (!ossl_isxdigit(buf[j])) { i = j; break; diff --git a/crypto/asn1/f_string.c b/crypto/asn1/f_string.c index b9258bba..f893489a 100644 --- a/crypto/asn1/f_string.c +++ b/crypto/asn1/f_string.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,7 +8,7 @@ */ #include -#include +#include "internal/ctype.h" #include "internal/cryptlib.h" #include #include @@ -20,7 +20,7 @@ int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type) char buf[2]; if (a == NULL) - return (0); + return 0; if (a->length == 0) { if (BIO_write(bp, "0", 1) != 1) @@ -40,14 +40,14 @@ int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type) n += 2; } } - return (n); + return n; err: - return (-1); + return -1; } int a2i_ASN1_STRING(BIO *bp, ASN1_STRING *bs, char *buf, int size) { - int i, j, k, m, n, again, bufsize, spec_char; + int i, j, k, m, n, again, bufsize; unsigned char *s = NULL, *sp; unsigned char *bufp; int num = 0, slen = 0, first = 1; @@ -74,19 +74,7 @@ int a2i_ASN1_STRING(BIO *bp, ASN1_STRING *bs, char *buf, int size) again = (buf[i - 1] == '\\'); for (j = i - 1; j > 0; j--) { -#ifndef CHARSET_EBCDIC - spec_char = (!(((buf[j] >= '0') && (buf[j] <= '9')) || - ((buf[j] >= 'a') && (buf[j] <= 'f')) || - ((buf[j] >= 'A') && (buf[j] <= 'F')))); -#else - /* - * This #ifdef is not strictly necessary, since the characters - * A...F a...f 0...9 are contiguous (yes, even in EBCDIC - but - * not the whole alphabet). Nevertheless, isxdigit() is faster. - */ - spec_char = (!isxdigit(buf[j])); -#endif - if (spec_char) { + if (!ossl_isxdigit(buf[j])) { i = j; break; } diff --git a/crypto/asn1/n_pkey.c b/crypto/asn1/n_pkey.c index 267ce601..d1fb8a14 100644 --- a/crypto/asn1/n_pkey.c +++ b/crypto/asn1/n_pkey.c @@ -23,7 +23,7 @@ NON_EMPTY_TRANSLATION_UNIT # ifndef OPENSSL_NO_RC4 typedef struct netscape_pkey_st { - long version; + int32_t version; X509_ALGOR *algor; ASN1_OCTET_STRING *private_key; } NETSCAPE_PKEY; @@ -48,7 +48,7 @@ DECLARE_ASN1_ENCODE_FUNCTIONS_const(NETSCAPE_ENCRYPTED_PKEY,NETSCAPE_ENCRYPTED_P IMPLEMENT_ASN1_FUNCTIONS_const(NETSCAPE_ENCRYPTED_PKEY) ASN1_SEQUENCE(NETSCAPE_PKEY) = { - ASN1_SIMPLE(NETSCAPE_PKEY, version, LONG), + ASN1_EMBED(NETSCAPE_PKEY, version, INT32), ASN1_SIMPLE(NETSCAPE_PKEY, algor, X509_ALGOR), ASN1_SIMPLE(NETSCAPE_PKEY, private_key, ASN1_OCTET_STRING) } static_ASN1_SEQUENCE_END(NETSCAPE_PKEY) diff --git a/crypto/asn1/p5_scrypt.c b/crypto/asn1/p5_scrypt.c index 4cb78374..c556d017 100644 --- a/crypto/asn1/p5_scrypt.c +++ b/crypto/asn1/p5_scrypt.c @@ -18,24 +18,15 @@ #ifndef OPENSSL_NO_SCRYPT /* PKCS#5 scrypt password based encryption structures */ -typedef struct { - ASN1_OCTET_STRING *salt; - ASN1_INTEGER *costParameter; - ASN1_INTEGER *blockSize; - ASN1_INTEGER *parallelizationParameter; - ASN1_INTEGER *keyLength; -} SCRYPT_PARAMS; - ASN1_SEQUENCE(SCRYPT_PARAMS) = { ASN1_SIMPLE(SCRYPT_PARAMS, salt, ASN1_OCTET_STRING), ASN1_SIMPLE(SCRYPT_PARAMS, costParameter, ASN1_INTEGER), ASN1_SIMPLE(SCRYPT_PARAMS, blockSize, ASN1_INTEGER), ASN1_SIMPLE(SCRYPT_PARAMS, parallelizationParameter, ASN1_INTEGER), ASN1_OPT(SCRYPT_PARAMS, keyLength, ASN1_INTEGER), -} static_ASN1_SEQUENCE_END(SCRYPT_PARAMS) +} ASN1_SEQUENCE_END(SCRYPT_PARAMS) -DECLARE_ASN1_ALLOC_FUNCTIONS(SCRYPT_PARAMS) -IMPLEMENT_ASN1_ALLOC_FUNCTIONS(SCRYPT_PARAMS) +IMPLEMENT_ASN1_FUNCTIONS(SCRYPT_PARAMS) static X509_ALGOR *pkcs5_scrypt_set(const unsigned char *salt, size_t saltlen, size_t keylen, uint64_t N, uint64_t r, diff --git a/crypto/asn1/standard_methods.h b/crypto/asn1/standard_methods.h new file mode 100644 index 00000000..d366aa09 --- /dev/null +++ b/crypto/asn1/standard_methods.h @@ -0,0 +1,56 @@ +/* + * Copyright 2006-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 + */ + +/* + * This table MUST be kept in ascending order of the NID each method + * represents (corresponding to the pkey_id field) as OBJ_bsearch + * is used to search it. + */ +static const EVP_PKEY_ASN1_METHOD *standard_methods[] = { +#ifndef OPENSSL_NO_RSA + &rsa_asn1_meths[0], + &rsa_asn1_meths[1], +#endif +#ifndef OPENSSL_NO_DH + &dh_asn1_meth, +#endif +#ifndef OPENSSL_NO_DSA + &dsa_asn1_meths[0], + &dsa_asn1_meths[1], + &dsa_asn1_meths[2], + &dsa_asn1_meths[3], + &dsa_asn1_meths[4], +#endif +#ifndef OPENSSL_NO_EC + &eckey_asn1_meth, +#endif + &hmac_asn1_meth, +#ifndef OPENSSL_NO_CMAC + &cmac_asn1_meth, +#endif +#ifndef OPENSSL_NO_RSA + &rsa_pss_asn1_meth, +#endif +#ifndef OPENSSL_NO_DH + &dhx_asn1_meth, +#endif +#ifndef OPENSSL_NO_EC + &ecx25519_asn1_meth, +#endif +#ifndef OPENSSL_NO_POLY1305 + &poly1305_asn1_meth, +#endif +#ifndef OPENSSL_NO_SIPHASH + &siphash_asn1_meth, +#endif +#ifndef OPENSSL_NO_EC + &ed25519_asn1_meth, +#endif +}; + diff --git a/crypto/asn1/tasn_dec.c b/crypto/asn1/tasn_dec.c index af8641e3..8667bec7 100644 --- a/crypto/asn1/tasn_dec.c +++ b/crypto/asn1/tasn_dec.c @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-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 @@ -17,18 +17,9 @@ #include "internal/numbers.h" #include "asn1_locl.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_item_embed_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); + int tag, int aclass, char opt, ASN1_TLC *ctx); static int asn1_check_eoc(const unsigned char **in, long len); static int asn1_find_end(const unsigned char **in, long len, char inf); @@ -46,11 +37,11 @@ static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, - ASN1_TLC *ctx, int depth); + ASN1_TLC *ctx); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, - ASN1_TLC *ctx, int depth); + ASN1_TLC *ctx); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, @@ -120,7 +111,7 @@ int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, int tag, int aclass, char opt, ASN1_TLC *ctx) { int rv; - rv = asn1_item_embed_d2i(pval, in, len, it, tag, aclass, opt, ctx, 0); + rv = asn1_item_embed_d2i(pval, in, len, it, tag, aclass, opt, ctx); if (rv <= 0) ASN1_item_ex_free(pval, it); return rv; @@ -133,8 +124,7 @@ int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, static int asn1_item_embed_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) + int tag, int aclass, char opt, ASN1_TLC *ctx) { const ASN1_TEMPLATE *tt, *errtt = NULL; const ASN1_EXTERN_FUNCS *ef; @@ -155,11 +145,6 @@ static int asn1_item_embed_d2i(ASN1_VALUE **pval, const unsigned char **in, else asn1_cb = 0; - if (++depth > ASN1_MAX_CONSTRUCTED_NEST) { - ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_NESTED_TOO_DEEP); - goto err; - } - switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { @@ -175,7 +160,7 @@ static int asn1_item_embed_d2i(ASN1_VALUE **pval, const unsigned char **in, goto err; } return asn1_template_ex_d2i(pval, in, len, - it->templates, opt, ctx, depth); + it->templates, opt, ctx); } return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt, ctx); @@ -236,7 +221,7 @@ static int asn1_item_embed_d2i(ASN1_VALUE **pval, const unsigned char **in, /* * We mark field as OPTIONAL so its absence can be recognised. */ - ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx, depth); + ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx); /* If field not present, try the next one */ if (ret == -1) continue; @@ -359,8 +344,7 @@ static int asn1_item_embed_d2i(ASN1_VALUE **pval, const unsigned char **in, * attempt to read in field, allowing each to be OPTIONAL */ - ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx, - depth); + ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx); if (!ret) { errtt = seqtt; goto err; @@ -436,7 +420,7 @@ static int asn1_item_embed_d2i(ASN1_VALUE **pval, const unsigned char **in, static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in, long inlen, const ASN1_TEMPLATE *tt, char opt, - ASN1_TLC *ctx, int depth) + ASN1_TLC *ctx) { int flags, aclass; int ret; @@ -471,7 +455,7 @@ static int asn1_template_ex_d2i(ASN1_VALUE **val, 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, depth); + ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR); return 0; @@ -495,7 +479,7 @@ static int asn1_template_ex_d2i(ASN1_VALUE **val, } } } else - return asn1_template_noexp_d2i(val, in, inlen, tt, opt, ctx, depth); + return asn1_template_noexp_d2i(val, in, inlen, tt, opt, ctx); *in = p; return 1; @@ -507,7 +491,7 @@ static int asn1_template_ex_d2i(ASN1_VALUE **val, static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, - ASN1_TLC *ctx, int depth) + ASN1_TLC *ctx) { int flags, aclass; int ret; @@ -554,7 +538,7 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val, } else if (ret == -1) return -1; if (!*val) - *val = (ASN1_VALUE *)OPENSSL_sk_new_null(); + *val = (ASN1_VALUE *)sk_ASN1_VALUE_new_null(); else { /* * We've got a valid STACK: free up any items present @@ -589,8 +573,7 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val, } skfield = NULL; if (!asn1_item_embed_d2i(&skfield, &p, len, - ASN1_ITEM_ptr(tt->item), -1, 0, 0, ctx, - depth)) { + ASN1_ITEM_ptr(tt->item), -1, 0, 0, ctx)) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR); /* |skfield| may be partially allocated despite failure. */ @@ -612,7 +595,7 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val, /* IMPLICIT tagging */ ret = asn1_item_embed_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), tt->tag, aclass, opt, - ctx, depth); + ctx); if (!ret) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; @@ -621,7 +604,7 @@ static int asn1_template_noexp_d2i(ASN1_VALUE **val, } else { /* Nothing special */ ret = asn1_item_embed_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), - -1, 0, opt, ctx, depth); + -1, 0, opt, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; diff --git a/crypto/asn1/tasn_prn.c b/crypto/asn1/tasn_prn.c index 53a9ee8e..1fb66f10 100644 --- a/crypto/asn1/tasn_prn.c +++ b/crypto/asn1/tasn_prn.c @@ -315,7 +315,8 @@ static int asn1_template_print_ctx(BIO *out, ASN1_VALUE **fld, int indent, pctx)) return 0; } - if (!i && BIO_printf(out, "%*s\n", indent + 2, "") <= 0) + if (i == 0 && BIO_printf(out, "%*s<%s>\n", indent + 2, "", + stack == NULL ? "ABSENT" : "EMPTY") <= 0) return 0; if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SEQUENCE) { if (BIO_printf(out, "%*s}\n", indent, "") <= 0) diff --git a/crypto/asn1/tasn_utl.c b/crypto/asn1/tasn_utl.c index f79d7d6b..cf434aa2 100644 --- a/crypto/asn1/tasn_utl.c +++ b/crypto/asn1/tasn_utl.c @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-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 @@ -9,7 +9,8 @@ #include #include -#include +#include "internal/cryptlib.h" +#include "internal/refcount.h" #include #include #include diff --git a/crypto/asn1/tbl_standard.h b/crypto/asn1/tbl_standard.h new file mode 100644 index 00000000..777a7344 --- /dev/null +++ b/crypto/asn1/tbl_standard.h @@ -0,0 +1,61 @@ +/* + * Copyright 1999-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 + */ + +/* size limits: this stuff is taken straight from RFC3280 */ + +#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 +#define ub_serial_number 64 + +/* From RFC4524 */ + +#define ub_rfc822_mailbox 256 + +/* This table must be kept in NID order */ + +static const ASN1_STRING_TABLE tbl_standard[] = { + {NID_commonName, 1, ub_common_name, DIRSTRING_TYPE, 0}, + {NID_countryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, + {NID_localityName, 1, ub_locality_name, DIRSTRING_TYPE, 0}, + {NID_stateOrProvinceName, 1, ub_state_name, DIRSTRING_TYPE, 0}, + {NID_organizationName, 1, ub_organization_name, DIRSTRING_TYPE, 0}, + {NID_organizationalUnitName, 1, ub_organization_unit_name, DIRSTRING_TYPE, + 0}, + {NID_pkcs9_emailAddress, 1, ub_email_address, B_ASN1_IA5STRING, + STABLE_NO_MASK}, + {NID_pkcs9_unstructuredName, 1, -1, PKCS9STRING_TYPE, 0}, + {NID_pkcs9_challengePassword, 1, -1, PKCS9STRING_TYPE, 0}, + {NID_pkcs9_unstructuredAddress, 1, -1, DIRSTRING_TYPE, 0}, + {NID_givenName, 1, ub_name, DIRSTRING_TYPE, 0}, + {NID_surname, 1, ub_name, DIRSTRING_TYPE, 0}, + {NID_initials, 1, ub_name, DIRSTRING_TYPE, 0}, + {NID_serialNumber, 1, ub_serial_number, B_ASN1_PRINTABLESTRING, + STABLE_NO_MASK}, + {NID_friendlyName, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}, + {NID_name, 1, ub_name, DIRSTRING_TYPE, 0}, + {NID_dnQualifier, -1, -1, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, + {NID_domainComponent, 1, -1, B_ASN1_IA5STRING, STABLE_NO_MASK}, + {NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}, + {NID_rfc822Mailbox, 1, ub_rfc822_mailbox, B_ASN1_IA5STRING, + STABLE_NO_MASK}, + {NID_jurisdictionCountryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, + {NID_INN, 1, 12, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, + {NID_OGRN, 1, 13, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, + {NID_SNILS, 1, 11, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, + {NID_countryCode3c, 3, 3, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, + {NID_countryCode3n, 3, 3, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, + {NID_dnsName, 0, -1, B_ASN1_UTF8STRING, STABLE_NO_MASK} +}; + diff --git a/crypto/asn1/x_algor.c b/crypto/asn1/x_algor.c index 72378db9..853d45b8 100644 --- a/crypto/asn1/x_algor.c +++ b/crypto/asn1/x_algor.c @@ -28,18 +28,19 @@ IMPLEMENT_ASN1_DUP_FUNCTION(X509_ALGOR) int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype, void *pval) { - if (!alg) + if (alg == NULL) return 0; + if (ptype != V_ASN1_UNDEF) { if (alg->parameter == NULL) alg->parameter = ASN1_TYPE_new(); if (alg->parameter == NULL) return 0; } - if (alg) { - ASN1_OBJECT_free(alg->algorithm); - alg->algorithm = aobj; - } + + ASN1_OBJECT_free(alg->algorithm); + alg->algorithm = aobj; + if (ptype == 0) return 1; if (ptype == V_ASN1_UNDEF) { diff --git a/crypto/asn1/x_int64.c b/crypto/asn1/x_int64.c index 4433167a..714e2f70 100644 --- a/crypto/asn1/x_int64.c +++ b/crypto/asn1/x_int64.c @@ -9,8 +9,8 @@ #include #include "internal/cryptlib.h" -#include "internal/asn1t.h" #include "internal/numbers.h" +#include #include #include "asn1_locl.h" @@ -102,8 +102,8 @@ static int uint64_print(BIO *out, ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx) { if ((it->size & INTxx_FLAG_SIGNED) == INTxx_FLAG_SIGNED) - return BIO_printf(out, "%"BIO_PRI64"d\n", **(int64_t **)pval); - return BIO_printf(out, "%"BIO_PRI64"u\n", **(uint64_t **)pval); + return BIO_printf(out, "%jd\n", **(int64_t **)pval); + return BIO_printf(out, "%ju\n", **(uint64_t **)pval); } /* 32-bit variants */ diff --git a/crypto/asn1/x_long.c b/crypto/asn1/x_long.c index 5895345f..bf9371ef 100644 --- a/crypto/asn1/x_long.c +++ b/crypto/asn1/x_long.c @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-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 @@ -11,6 +11,12 @@ #include "internal/cryptlib.h" #include +#if !(OPENSSL_API_COMPAT < 0x10200000L) +NON_EMPTY_TRANSLATION_UNIT +#else + +#define COPY_SIZE(a, b) (sizeof(a) < sizeof(b) ? sizeof(a) : sizeof(b)) + /* * Custom primitive type for long handling. This converts between an * ASN1_INTEGER and a long directly. @@ -46,13 +52,13 @@ ASN1_ITEM_end(ZLONG) static int long_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { - *(long *)pval = it->size; + memcpy(pval, &it->size, COPY_SIZE(*pval, it->size)); return 1; } static void long_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { - *(long *)pval = it->size; + memcpy(pval, &it->size, COPY_SIZE(*pval, it->size)); } /* @@ -86,12 +92,8 @@ static int long_i2c(ASN1_VALUE **pval, unsigned char *cont, int *putype, long ltmp; unsigned long utmp, sign; int clen, pad, i; - /* this exists to bypass broken gcc optimization */ - char *cp = (char *)pval; - - /* use memcpy, because we may not be long aligned */ - memcpy(<mp, cp, sizeof(long)); + memcpy(<mp, pval, COPY_SIZE(*pval, ltmp)); if (ltmp == it->size) return -1; /* @@ -133,7 +135,6 @@ static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int i; long ltmp; unsigned long utmp = 0, sign = 0x100; - char *cp = (char *)pval; if (len > 1) { /* @@ -185,12 +186,16 @@ static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, ASN1err(ASN1_F_LONG_C2I, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG); return 0; } - memcpy(cp, <mp, sizeof(long)); + memcpy(pval, <mp, COPY_SIZE(*pval, ltmp)); return 1; } static int long_print(BIO *out, ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx) { - return BIO_printf(out, "%ld\n", *(long *)pval); + long l; + + memcpy(&l, pval, COPY_SIZE(*pval, l)); + return BIO_printf(out, "%ld\n", l); } +#endif diff --git a/crypto/asn1/x_spki.c b/crypto/asn1/x_spki.c index c45400b4..0d72a3f3 100644 --- a/crypto/asn1/x_spki.c +++ b/crypto/asn1/x_spki.c @@ -7,11 +7,6 @@ * https://www.openssl.org/source/license.html */ - /* - * This module was send to me my Pat Richards who wrote it. - * It is under my Copyright with his permission - */ - #include #include "internal/cryptlib.h" #include diff --git a/crypto/async/arch/async_posix.h b/crypto/async/arch/async_posix.h index 76937a9e..b07c2cb0 100644 --- a/crypto/async/arch/async_posix.h +++ b/crypto/async/arch/async_posix.h @@ -26,7 +26,6 @@ # include # include -# include "e_os.h" typedef struct async_fibre_st { ucontext_t fibre; diff --git a/crypto/async/async.c b/crypto/async/async.c index 9a4e6b26..28747907 100644 --- a/crypto/async/async.c +++ b/crypto/async/async.c @@ -19,7 +19,7 @@ #include "async_locl.h" #include -#include +#include "internal/cryptlib_int.h" #include #define ASYNC_JOB_RUNNING 0 @@ -36,7 +36,7 @@ static async_ctx *async_ctx_new(void) { async_ctx *nctx = NULL; - nctx = OPENSSL_malloc(sizeof(async_ctx)); + nctx = OPENSSL_malloc(sizeof(*nctx)); if (nctx == NULL) { ASYNCerr(ASYNC_F_ASYNC_CTX_NEW, ERR_R_MALLOC_FAILURE); goto err; @@ -81,7 +81,7 @@ static ASYNC_JOB *async_job_new(void) { ASYNC_JOB *job = NULL; - job = OPENSSL_zalloc(sizeof(ASYNC_JOB)); + job = OPENSSL_zalloc(sizeof(*job)); if (job == NULL) { ASYNCerr(ASYNC_F_ASYNC_JOB_NEW, ERR_R_MALLOC_FAILURE); return NULL; @@ -336,7 +336,7 @@ int ASYNC_init_thread(size_t max_size, size_t init_size) return 0; } - pool->jobs = sk_ASYNC_JOB_new_null(); + pool->jobs = sk_ASYNC_JOB_new_reserve(NULL, init_size); if (pool->jobs == NULL) { ASYNCerr(ASYNC_F_ASYNC_INIT_THREAD, ERR_R_MALLOC_FAILURE); OPENSSL_free(pool); @@ -358,7 +358,7 @@ int ASYNC_init_thread(size_t max_size, size_t init_size) break; } job->funcargs = NULL; - sk_ASYNC_JOB_push(pool->jobs, job); + sk_ASYNC_JOB_push(pool->jobs, job); /* Cannot fail due to reserve */ curr_size++; } pool->curr_size = curr_size; diff --git a/crypto/async/async_err.c b/crypto/async/async_err.c index ae97e965..d2d1011c 100644 --- a/crypto/async/async_err.c +++ b/crypto/async/async_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,31 +8,30 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_ASYNC,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_ASYNC,0,reason) - -static ERR_STRING_DATA ASYNC_str_functs[] = { - {ERR_FUNC(ASYNC_F_ASYNC_CTX_NEW), "async_ctx_new"}, - {ERR_FUNC(ASYNC_F_ASYNC_INIT_THREAD), "ASYNC_init_thread"}, - {ERR_FUNC(ASYNC_F_ASYNC_JOB_NEW), "async_job_new"}, - {ERR_FUNC(ASYNC_F_ASYNC_PAUSE_JOB), "ASYNC_pause_job"}, - {ERR_FUNC(ASYNC_F_ASYNC_START_FUNC), "async_start_func"}, - {ERR_FUNC(ASYNC_F_ASYNC_START_JOB), "ASYNC_start_job"}, +static const ERR_STRING_DATA ASYNC_str_functs[] = { + {ERR_PACK(ERR_LIB_ASYNC, ASYNC_F_ASYNC_CTX_NEW, 0), "async_ctx_new"}, + {ERR_PACK(ERR_LIB_ASYNC, ASYNC_F_ASYNC_INIT_THREAD, 0), + "ASYNC_init_thread"}, + {ERR_PACK(ERR_LIB_ASYNC, ASYNC_F_ASYNC_JOB_NEW, 0), "async_job_new"}, + {ERR_PACK(ERR_LIB_ASYNC, ASYNC_F_ASYNC_PAUSE_JOB, 0), "ASYNC_pause_job"}, + {ERR_PACK(ERR_LIB_ASYNC, ASYNC_F_ASYNC_START_FUNC, 0), "async_start_func"}, + {ERR_PACK(ERR_LIB_ASYNC, ASYNC_F_ASYNC_START_JOB, 0), "ASYNC_start_job"}, {0, NULL} }; -static ERR_STRING_DATA ASYNC_str_reasons[] = { - {ERR_REASON(ASYNC_R_FAILED_TO_SET_POOL), "failed to set pool"}, - {ERR_REASON(ASYNC_R_FAILED_TO_SWAP_CONTEXT), "failed to swap context"}, - {ERR_REASON(ASYNC_R_INIT_FAILED), "init failed"}, - {ERR_REASON(ASYNC_R_INVALID_POOL_SIZE), "invalid pool size"}, +static const ERR_STRING_DATA ASYNC_str_reasons[] = { + {ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_FAILED_TO_SET_POOL), + "failed to set pool"}, + {ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_FAILED_TO_SWAP_CONTEXT), + "failed to swap context"}, + {ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_INIT_FAILED), "init failed"}, + {ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_INVALID_POOL_SIZE), + "invalid pool size"}, {0, NULL} }; @@ -41,10 +40,9 @@ static ERR_STRING_DATA ASYNC_str_reasons[] = { int ERR_load_ASYNC_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(ASYNC_str_functs[0].error) == NULL) { - ERR_load_strings(0, ASYNC_str_functs); - ERR_load_strings(0, ASYNC_str_reasons); + ERR_load_strings_const(ASYNC_str_functs); + ERR_load_strings_const(ASYNC_str_reasons); } #endif return 1; diff --git a/crypto/async/async_locl.h b/crypto/async/async_locl.h index f0ac05a3..d7790293 100644 --- a/crypto/async/async_locl.h +++ b/crypto/async/async_locl.h @@ -20,7 +20,7 @@ # include #endif -#include +#include "internal/async.h" #include typedef struct async_ctx_st async_ctx; diff --git a/crypto/async/async_wait.c b/crypto/async/async_wait.c index 0a0bf873..d6d46952 100644 --- a/crypto/async/async_wait.c +++ b/crypto/async/async_wait.c @@ -145,6 +145,7 @@ int ASYNC_WAIT_CTX_clear_fd(ASYNC_WAIT_CTX *ctx, const void *key) while (curr != NULL) { if (curr->del == 1) { /* This one has been marked deleted already so do nothing */ + prev = curr; curr = curr->next; continue; } diff --git a/crypto/bf/asm/bf-586.pl b/crypto/bf/asm/bf-586.pl index ebc24f48..4e913aec 100644 --- a/crypto/bf/asm/bf-586.pl +++ b/crypto/bf/asm/bf-586.pl @@ -15,7 +15,7 @@ require "cbc.pl"; $output = pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"bf-586.pl",$ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$ARGV[$#ARGV] eq "386"); $BF_ROUNDS=16; $BF_OFF=($BF_ROUNDS+2)*4; diff --git a/crypto/bf/bf_cbc.c b/crypto/bf/bf_cbc.c deleted file mode 100644 index 6ed62578..00000000 --- a/crypto/bf/bf_cbc.c +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 1995-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 - */ - -#include -#include "bf_locl.h" - -void BF_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, - const BF_KEY *schedule, unsigned char *ivec, int encrypt) -{ - register BF_LONG tin0, tin1; - register BF_LONG tout0, tout1, xor0, xor1; - register long l = length; - BF_LONG tin[2]; - - if (encrypt) { - n2l(ivec, tout0); - n2l(ivec, tout1); - ivec -= 8; - for (l -= 8; l >= 0; l -= 8) { - n2l(in, tin0); - n2l(in, tin1); - tin0 ^= tout0; - tin1 ^= tout1; - tin[0] = tin0; - tin[1] = tin1; - BF_encrypt(tin, schedule); - tout0 = tin[0]; - tout1 = tin[1]; - l2n(tout0, out); - l2n(tout1, out); - } - if (l != -8) { - n2ln(in, tin0, tin1, l + 8); - tin0 ^= tout0; - tin1 ^= tout1; - tin[0] = tin0; - tin[1] = tin1; - BF_encrypt(tin, schedule); - tout0 = tin[0]; - tout1 = tin[1]; - l2n(tout0, out); - l2n(tout1, out); - } - l2n(tout0, ivec); - l2n(tout1, ivec); - } else { - n2l(ivec, xor0); - n2l(ivec, xor1); - ivec -= 8; - for (l -= 8; l >= 0; l -= 8) { - n2l(in, tin0); - n2l(in, tin1); - tin[0] = tin0; - tin[1] = tin1; - BF_decrypt(tin, schedule); - tout0 = tin[0] ^ xor0; - tout1 = tin[1] ^ xor1; - l2n(tout0, out); - l2n(tout1, out); - xor0 = tin0; - xor1 = tin1; - } - if (l != -8) { - n2l(in, tin0); - n2l(in, tin1); - tin[0] = tin0; - tin[1] = tin1; - BF_decrypt(tin, schedule); - tout0 = tin[0] ^ xor0; - tout1 = tin[1] ^ xor1; - l2nn(tout0, tout1, out, l + 8); - xor0 = tin0; - xor1 = tin1; - } - l2n(xor0, ivec); - l2n(xor1, ivec); - } - tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; - tin[0] = tin[1] = 0; -} diff --git a/crypto/bf/bf_ecb.c b/crypto/bf/bf_ecb.c index aa73540f..dc1becdb 100644 --- a/crypto/bf/bf_ecb.c +++ b/crypto/bf/bf_ecb.c @@ -19,7 +19,7 @@ const char *BF_options(void) { - return ("blowfish(ptr)"); + return "blowfish(ptr)"; } void BF_ecb_encrypt(const unsigned char *in, unsigned char *out, diff --git a/crypto/bf/bf_enc.c b/crypto/bf/bf_enc.c index 9f80c56d..67c0d78a 100644 --- a/crypto/bf/bf_enc.c +++ b/crypto/bf/bf_enc.c @@ -60,8 +60,6 @@ void BF_encrypt(BF_LONG *data, const BF_KEY *key) data[0] = r & 0xffffffffU; } -#ifndef BF_DEFAULT_OPTIONS - void BF_decrypt(BF_LONG *data, const BF_KEY *key) { register BF_LONG l, r; @@ -175,5 +173,3 @@ void BF_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; tin[0] = tin[1] = 0; } - -#endif diff --git a/crypto/bf/build.info b/crypto/bf/build.info index 37a004ea..29adc8ce 100644 --- a/crypto/bf/build.info +++ b/crypto/bf/build.info @@ -2,5 +2,6 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=bf_skey.c bf_ecb.c bf_cfb64.c bf_ofb64.c \ {- $target{bf_asm_src} -} -GENERATE[bf-586.s]=asm/bf-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[bf-586.s]=asm/bf-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[bf-586.s]=../perlasm/x86asm.pl ../perlasm/cbc.pl diff --git a/crypto/bio/b_addr.c b/crypto/bio/b_addr.c index aea843a7..ca9a7102 100644 --- a/crypto/bio/b_addr.c +++ b/crypto/bio/b_addr.c @@ -1,5 +1,5 @@ /* - * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-2018 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 @@ -7,6 +7,7 @@ * https://www.openssl.org/source/license.html */ +#include #include #include "bio_lcl.h" @@ -15,8 +16,7 @@ #ifndef OPENSSL_NO_SOCK #include #include -#include -#include +#include "internal/thread_once.h" CRYPTO_RWLOCK *bio_lookup_lock; static CRYPTO_ONCE bio_lookup_init = CRYPTO_ONCE_STATIC_INIT; @@ -565,8 +565,6 @@ static int addrinfo_wrap(int family, int socktype, unsigned short port, BIO_ADDRINFO **bai) { - OPENSSL_assert(bai != NULL); - *bai = OPENSSL_zalloc(sizeof(**bai)); if (*bai == NULL) return 0; @@ -609,8 +607,15 @@ DEFINE_RUN_ONCE_STATIC(do_bio_lookup_init) return bio_lookup_lock != NULL; } +int BIO_lookup(const char *host, const char *service, + enum BIO_lookup_type lookup_type, + int family, int socktype, BIO_ADDRINFO **res) +{ + return BIO_lookup_ex(host, service, lookup_type, family, socktype, 0, res); +} + /*- - * BIO_lookup - look up the node and service you want to connect to. + * BIO_lookup_ex - look up the node and service you want to connect to. * @node: the node you want to connect to. * @service: the service you want to connect to. * @lookup_type: declare intent with the result, client or server. @@ -618,6 +623,10 @@ DEFINE_RUN_ONCE_STATIC(do_bio_lookup_init) * AF_INET, AF_INET6 or AF_UNIX. * @socktype: The socket type you want to use. Can be SOCK_STREAM, SOCK_DGRAM * or 0 for all. + * @protocol: The protocol to use, e.g. IPPROTO_TCP or IPPROTO_UDP or 0 for all. + * Note that some platforms may not return IPPROTO_SCTP without + * explicitly requesting it (i.e. IPPROTO_SCTP may not be returned + * with 0 for the protocol) * @res: Storage place for the resulting list of returned addresses * * This will do a lookup of the node and service that you want to connect to. @@ -627,9 +636,8 @@ DEFINE_RUN_ONCE_STATIC(do_bio_lookup_init) * * The return value is 1 on success or 0 in case of error. */ -int BIO_lookup(const char *host, const char *service, - enum BIO_lookup_type lookup_type, - int family, int socktype, BIO_ADDRINFO **res) +int BIO_lookup_ex(const char *host, const char *service, int lookup_type, + int family, int socktype, int protocol, BIO_ADDRINFO **res) { int ret = 0; /* Assume failure */ @@ -646,7 +654,7 @@ int BIO_lookup(const char *host, const char *service, #endif break; default: - BIOerr(BIO_F_BIO_LOOKUP, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY); + BIOerr(BIO_F_BIO_LOOKUP_EX, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY); return 0; } @@ -655,7 +663,7 @@ int BIO_lookup(const char *host, const char *service, if (addrinfo_wrap(family, socktype, host, strlen(host), 0, res)) return 1; else - BIOerr(BIO_F_BIO_LOOKUP, ERR_R_MALLOC_FAILURE); + BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_MALLOC_FAILURE); return 0; } #endif @@ -672,6 +680,7 @@ int BIO_lookup(const char *host, const char *service, hints.ai_family = family; hints.ai_socktype = socktype; + hints.ai_protocol = protocol; if (lookup_type == BIO_LOOKUP_SERVER) hints.ai_flags |= AI_PASSIVE; @@ -683,14 +692,14 @@ int BIO_lookup(const char *host, const char *service, # ifdef EAI_SYSTEM case EAI_SYSTEM: SYSerr(SYS_F_GETADDRINFO, get_last_socket_error()); - BIOerr(BIO_F_BIO_LOOKUP, ERR_R_SYS_LIB); + BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_SYS_LIB); break; # endif case 0: ret = 1; /* Success */ break; default: - BIOerr(BIO_F_BIO_LOOKUP, ERR_R_SYS_LIB); + BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_SYS_LIB); ERR_add_error_data(1, gai_strerror(gai_ret)); break; } @@ -732,7 +741,7 @@ int BIO_lookup(const char *host, const char *service, #endif if (!RUN_ONCE(&bio_lookup_init, do_bio_lookup_init)) { - BIOerr(BIO_F_BIO_LOOKUP, ERR_R_MALLOC_FAILURE); + BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_MALLOC_FAILURE); ret = 0; goto err; } @@ -749,8 +758,11 @@ int BIO_lookup(const char *host, const char *service, he_fallback_address = INADDR_ANY; break; default: - OPENSSL_assert(("We forgot to handle a lookup type!" == 0)); - break; + /* We forgot to handle a lookup type! */ + assert("We forgot to handle a lookup type!" == NULL); + BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_INTERNAL_ERROR); + ret = 0; + goto err; } } else { he = gethostbyname(host); @@ -809,7 +821,7 @@ int BIO_lookup(const char *host, const char *service, if (endp != service && *endp == '\0' && portnum > 0 && portnum < 65536) { - se_fallback.s_port = htons(portnum); + se_fallback.s_port = htons((unsigned short)portnum); se_fallback.s_proto = proto; se = &se_fallback; } else if (endp == service) { @@ -824,7 +836,7 @@ int BIO_lookup(const char *host, const char *service, goto err; } } else { - BIOerr(BIO_F_BIO_LOOKUP, BIO_R_MALFORMED_HOST_OR_SERVICE); + BIOerr(BIO_F_BIO_LOOKUP_EX, BIO_R_MALFORMED_HOST_OR_SERVICE); goto err; } } @@ -866,7 +878,7 @@ int BIO_lookup(const char *host, const char *service, addrinfo_malloc_err: BIO_ADDRINFO_free(*res); *res = NULL; - BIOerr(BIO_F_BIO_LOOKUP, ERR_R_MALLOC_FAILURE); + BIOerr(BIO_F_BIO_LOOKUP_EX, ERR_R_MALLOC_FAILURE); ret = 0; goto err; } diff --git a/crypto/bio/b_dump.c b/crypto/bio/b_dump.c index 424195e1..0d06414e 100644 --- a/crypto/bio/b_dump.c +++ b/crypto/bio/b_dump.c @@ -15,7 +15,9 @@ #include "bio_lcl.h" #define DUMP_WIDTH 16 -#define DUMP_WIDTH_LESS_INDENT(i) (DUMP_WIDTH-((i-(i>6?6:i)+3)/4)) +#define DUMP_WIDTH_LESS_INDENT(i) (DUMP_WIDTH - ((i - (i > 6 ? 6 : i) + 3) / 4)) + +#define SPACE(buf, pos, n) (sizeof(buf) - (pos) > (n)) int BIO_dump_cb(int (*cb) (const void *data, size_t len, void *u), void *u, const char *s, int len) @@ -27,60 +29,63 @@ 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; + char buf[288 + 1]; + int i, j, rows, n; unsigned char ch; int dump_width; if (indent < 0) indent = 0; - if (indent) { - if (indent > 128) - indent = 128; - memset(str, ' ', indent); - } - str[indent] = '\0'; + else if (indent > 128) + indent = 128; dump_width = DUMP_WIDTH_LESS_INDENT(indent); - rows = (len / dump_width); + rows = len / dump_width; if ((rows * dump_width) < len) rows++; for (i = 0; i < rows; i++) { - OPENSSL_strlcpy(buf, str, sizeof(buf)); - BIO_snprintf(tmp, sizeof(tmp), "%04x - ", i * dump_width); - OPENSSL_strlcat(buf, tmp, sizeof(buf)); + n = BIO_snprintf(buf, sizeof(buf), "%*s%04x - ", indent, "", + i * dump_width); for (j = 0; j < dump_width; j++) { - if (((i * dump_width) + j) >= len) { - OPENSSL_strlcat(buf, " ", sizeof(buf)); - } else { - ch = ((unsigned char)*(s + i * dump_width + j)) & 0xff; - BIO_snprintf(tmp, sizeof(tmp), "%02x%c", ch, - j == 7 ? '-' : ' '); - OPENSSL_strlcat(buf, tmp, sizeof(buf)); + if (SPACE(buf, n, 3)) { + if (((i * dump_width) + j) >= len) { + strcpy(buf + n, " "); + } else { + ch = ((unsigned char)*(s + i * dump_width + j)) & 0xff; + BIO_snprintf(buf + n, 4, "%02x%c", ch, + j == 7 ? '-' : ' '); + } + n += 3; } } - OPENSSL_strlcat(buf, " ", sizeof(buf)); + if (SPACE(buf, n, 2)) { + strcpy(buf + n, " "); + n += 2; + } for (j = 0; j < dump_width; j++) { if (((i * dump_width) + j) >= len) break; - ch = ((unsigned char)*(s + i * dump_width + j)) & 0xff; + if (SPACE(buf, n, 1)) { + ch = ((unsigned char)*(s + i * dump_width + j)) & 0xff; #ifndef CHARSET_EBCDIC - BIO_snprintf(tmp, sizeof(tmp), "%c", - ((ch >= ' ') && (ch <= '~')) ? ch : '.'); + buf[n++] = ((ch >= ' ') && (ch <= '~')) ? ch : '.'; #else - BIO_snprintf(tmp, sizeof(tmp), "%c", - ((ch >= os_toascii[' ']) && (ch <= os_toascii['~'])) - ? os_toebcdic[ch] - : '.'); + buf[n++] = ((ch >= os_toascii[' ']) && (ch <= os_toascii['~'])) + ? os_toebcdic[ch] + : '.'; #endif - OPENSSL_strlcat(buf, tmp, sizeof(buf)); + buf[n] = '\0'; + } + } + if (SPACE(buf, n, 1)) { + buf[n++] = '\n'; + buf[n] = '\0'; } - OPENSSL_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); + ret += cb((void *)buf, n, u); } return ret; } diff --git a/crypto/bio/b_print.c b/crypto/bio/b_print.c index cdfe05f9..1ef85479 100644 --- a/crypto/bio/b_print.c +++ b/crypto/bio/b_print.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,9 +9,9 @@ #include #include -#include -#include "internal/numbers.h" #include "internal/cryptlib.h" +#include "internal/ctype.h" +#include "internal/numbers.h" #include /* @@ -69,6 +69,7 @@ static int _dopr(char **sbuffer, char **buffer, #define DP_C_LONG 2 #define DP_C_LDOUBLE 3 #define DP_C_LLONG 4 +#define DP_C_SIZE 5 /* Floating point formats */ #define F_FORMAT 0 @@ -110,7 +111,7 @@ _dopr(char **sbuffer, if (ch == '%') state = DP_S_FLAGS; else - if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, ch)) + if (!doapr_outch(sbuffer, buffer, &currlen, maxlen, ch)) return 0; ch = *format++; break; @@ -142,7 +143,7 @@ _dopr(char **sbuffer, } break; case DP_S_MIN: - if (isdigit((unsigned char)ch)) { + if (ossl_isdigit(ch)) { min = 10 * min + char_to_int(ch); ch = *format++; } else if (ch == '*') { @@ -160,7 +161,7 @@ _dopr(char **sbuffer, state = DP_S_MOD; break; case DP_S_MAX: - if (isdigit((unsigned char)ch)) { + if (ossl_isdigit(ch)) { if (max < 0) max = 0; max = 10 * max + char_to_int(ch); @@ -187,6 +188,7 @@ _dopr(char **sbuffer, ch = *format++; break; case 'q': + case 'j': cflags = DP_C_LLONG; ch = *format++; break; @@ -194,6 +196,10 @@ _dopr(char **sbuffer, cflags = DP_C_LDOUBLE; ch = *format++; break; + case 'z': + cflags = DP_C_SIZE; + ch = *format++; + break; default: break; } @@ -213,6 +219,9 @@ _dopr(char **sbuffer, case DP_C_LLONG: value = va_arg(args, int64_t); break; + case DP_C_SIZE: + value = va_arg(args, ossl_ssize_t); + break; default: value = va_arg(args, int); break; @@ -238,6 +247,9 @@ _dopr(char **sbuffer, case DP_C_LLONG: value = va_arg(args, uint64_t); break; + case DP_C_SIZE: + value = va_arg(args, size_t); + break; default: value = va_arg(args, unsigned int); break; @@ -281,8 +293,8 @@ _dopr(char **sbuffer, return 0; break; case 'c': - if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, - va_arg(args, int))) + if (!doapr_outch(sbuffer, buffer, &currlen, maxlen, + va_arg(args, int))) return 0; break; case 's': @@ -303,27 +315,15 @@ _dopr(char **sbuffer, 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 = 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 */ - int64_t *num; - num = va_arg(args, int64_t *); - *num = (int64_t)currlen; - } else { + case 'n': + { int *num; num = va_arg(args, int *); *num = currlen; } break; case '%': - if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, ch)) + if (!doapr_outch(sbuffer, buffer, &currlen, maxlen, ch)) return 0; break; case 'w': @@ -354,7 +354,7 @@ _dopr(char **sbuffer, if (*truncated) currlen = *maxlen - 1; } - if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, '\0')) + if (!doapr_outch(sbuffer, buffer, &currlen, maxlen, '\0')) return 0; *retlen = currlen - 1; return 1; @@ -392,19 +392,19 @@ fmtstr(char **sbuffer, padlen = -padlen; while ((padlen > 0) && (max < 0 || cnt < max)) { - if(!doapr_outch(sbuffer, buffer, currlen, maxlen, ' ')) + if (!doapr_outch(sbuffer, buffer, currlen, maxlen, ' ')) return 0; --padlen; ++cnt; } while (strln > 0 && (max < 0 || cnt < max)) { - if(!doapr_outch(sbuffer, buffer, currlen, maxlen, *value++)) + if (!doapr_outch(sbuffer, buffer, currlen, maxlen, *value++)) return 0; --strln; ++cnt; } while ((padlen < 0) && (max < 0 || cnt < max)) { - if(!doapr_outch(sbuffer, buffer, currlen, maxlen, ' ')) + if (!doapr_outch(sbuffer, buffer, currlen, maxlen, ' ')) return 0; ++padlen; ++cnt; @@ -472,19 +472,19 @@ fmtint(char **sbuffer, /* spaces */ while (spadlen > 0) { - if(!doapr_outch(sbuffer, buffer, currlen, maxlen, ' ')) + if (!doapr_outch(sbuffer, buffer, currlen, maxlen, ' ')) return 0; --spadlen; } /* sign */ if (signvalue) - if(!doapr_outch(sbuffer, buffer, currlen, maxlen, signvalue)) + if (!doapr_outch(sbuffer, buffer, currlen, maxlen, signvalue)) return 0; /* prefix */ while (*prefix) { - if(!doapr_outch(sbuffer, buffer, currlen, maxlen, *prefix)) + if (!doapr_outch(sbuffer, buffer, currlen, maxlen, *prefix)) return 0; prefix++; } @@ -492,7 +492,7 @@ fmtint(char **sbuffer, /* zeros */ if (zpadlen > 0) { while (zpadlen > 0) { - if(!doapr_outch(sbuffer, buffer, currlen, maxlen, '0')) + if (!doapr_outch(sbuffer, buffer, currlen, maxlen, '0')) return 0; --zpadlen; } @@ -758,8 +758,8 @@ fmtfp(char **sbuffer, return 0; while (fplace > 0) { - if(!doapr_outch(sbuffer, buffer, currlen, maxlen, - fconvert[--fplace])) + if (!doapr_outch(sbuffer, buffer, currlen, maxlen, + fconvert[--fplace])) return 0; } } @@ -805,11 +805,13 @@ 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 */ - OPENSSL_assert(*sbuffer != NULL || buffer != NULL); + /* If we haven't at least one buffer, someone has done a big booboo */ + if (!ossl_assert(*sbuffer != NULL || buffer != NULL)) + return 0; /* |currlen| must always be <= |*maxlen| */ - OPENSSL_assert(*currlen <= *maxlen); + if (!ossl_assert(*currlen <= *maxlen)) + return 0; if (buffer && *currlen == *maxlen) { if (*maxlen > INT_MAX - BUFFER_INC) @@ -821,7 +823,8 @@ doapr_outch(char **sbuffer, if (*buffer == NULL) return 0; if (*currlen > 0) { - OPENSSL_assert(*sbuffer != NULL); + if (!ossl_assert(*sbuffer != NULL)) + return 0; memcpy(*buffer, *sbuffer, *currlen); } *sbuffer = NULL; @@ -856,7 +859,7 @@ int BIO_printf(BIO *bio, const char *format, ...) ret = BIO_vprintf(bio, format, args); va_end(args); - return (ret); + return ret; } int BIO_vprintf(BIO *bio, const char *format, va_list args) @@ -883,7 +886,7 @@ int BIO_vprintf(BIO *bio, const char *format, va_list args) } else { ret = BIO_write(bio, hugebuf, (int)retlen); } - return (ret); + return ret; } /* @@ -902,7 +905,7 @@ int BIO_snprintf(char *buf, size_t n, const char *format, ...) ret = BIO_vsnprintf(buf, n, format, args); va_end(args); - return (ret); + return ret; } int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args) @@ -910,7 +913,7 @@ 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)) + if (!_dopr(&buf, NULL, &n, &retlen, &truncated, format, args)) return -1; if (truncated) diff --git a/crypto/bio/b_sock.c b/crypto/bio/b_sock.c index 97dcc700..740ff174 100644 --- a/crypto/bio/b_sock.c +++ b/crypto/bio/b_sock.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -11,10 +11,6 @@ #include #include #include "bio_lcl.h" -#if defined(NETWARE_CLIB) -# include -NETDB_DEFINE_CONTEXT -#endif #ifndef OPENSSL_NO_SOCK # define SOCKET_PROTOCOL IPPROTO_TCP # ifdef SO_MAXCONN @@ -43,14 +39,13 @@ int BIO_get_host_ip(const char *str, unsigned char *ip) if (BIO_ADDRINFO_family(res) != AF_INET) { BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET); - } else { - BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), NULL, &l); - /* Because only AF_INET addresses will reach this far, - we can assert that l should be 4 */ - OPENSSL_assert(l == 4); - - BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), ip, &l); - ret = 1; + } else if (BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), NULL, &l)) { + /* + * Because only AF_INET addresses will reach this far, we can assert + * that l should be 4 + */ + if (ossl_assert(l == 4)) + ret = BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), ip, &l); } BIO_ADDRINFO_free(res); } else { @@ -67,7 +62,7 @@ int BIO_get_port(const char *str, unsigned short *port_ptr) if (str == NULL) { BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_DEFINED); - return (0); + return 0; } if (BIO_sock_init() != 1) @@ -103,9 +98,9 @@ int BIO_sock_error(int sock) */ i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, &size); if (i < 0) - return (get_last_socket_error()); + return get_last_socket_error(); else - return (j); + return j; } # if OPENSSL_API_COMPAT < 0x10100000L @@ -115,11 +110,7 @@ struct hostent *BIO_gethostbyname(const char *name) * Caching gethostbyname() results forever is wrong, so we have to let * the true gethostbyname() worry about this */ -# if (defined(NETWARE_BSDSOCK) && !defined(__NOVELL_LIBC__)) - return gethostbyname((char *)name); -# else return gethostbyname(name); -# endif } # endif @@ -143,7 +134,7 @@ int BIO_sock_init(void) err = WSAGetLastError(); SYSerr(SYS_F_WSASTARTUP, err); BIOerr(BIO_F_BIO_SOCK_INIT, BIO_R_WSASTARTUP); - return (-1); + return -1; } } # endif /* OPENSSL_SYS_WINDOWS */ @@ -151,10 +142,10 @@ int BIO_sock_init(void) extern int _watt_do_exit; _watt_do_exit = 0; /* don't make sock_init() call exit() */ if (sock_init()) - return (-1); + return -1; # endif - return (1); + return 1; } void bio_sock_cleanup_int(void) @@ -202,7 +193,7 @@ int BIO_socket_ioctl(int fd, long type, void *arg) # endif /* __DJGPP__ */ if (i < 0) SYSerr(SYS_F_IOCTLSOCKET, get_last_socket_error()); - return (i); + return i; } # if OPENSSL_API_COMPAT < 0x10100000L diff --git a/crypto/bio/b_sock2.c b/crypto/bio/b_sock2.c index d8b49d02..823732d6 100644 --- a/crypto/bio/b_sock2.c +++ b/crypto/bio/b_sock2.c @@ -76,7 +76,7 @@ int BIO_socket(int domain, int socktype, int protocol, int options) */ int BIO_connect(int sock, const BIO_ADDR *addr, int options) { - int on = 1; + const int on = 1; if (sock == -1) { BIOerr(BIO_F_BIO_CONNECT, BIO_R_INVALID_SOCKET); @@ -87,7 +87,8 @@ int BIO_connect(int sock, const BIO_ADDR *addr, int options) return 0; if (options & BIO_SOCK_KEEPALIVE) { - if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) != 0) { + if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, + (const void *)&on, sizeof(on)) != 0) { SYSerr(SYS_F_SETSOCKOPT, get_last_socket_error()); BIOerr(BIO_F_BIO_CONNECT, BIO_R_UNABLE_TO_KEEPALIVE); return 0; @@ -95,7 +96,8 @@ int BIO_connect(int sock, const BIO_ADDR *addr, int options) } if (options & BIO_SOCK_NODELAY) { - if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) != 0) { + if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, + (const void *)&on, sizeof(on)) != 0) { SYSerr(SYS_F_SETSOCKOPT, get_last_socket_error()); BIOerr(BIO_F_BIO_CONNECT, BIO_R_UNABLE_TO_NODELAY); return 0; @@ -113,6 +115,55 @@ int BIO_connect(int sock, const BIO_ADDR *addr, int options) return 1; } +/*- + * BIO_bind - bind socket to address + * @sock: the socket to set + * @addr: local address to bind to + * @options: BIO socket options + * + * Binds to the address using the given socket and options. + * + * Options can be a combination of the following: + * - BIO_SOCK_REUSEADDR: Try to reuse the address and port combination + * for a recently closed port. + * + * When restarting the program it could be that the port is still in use. If + * you set to BIO_SOCK_REUSEADDR option it will try to reuse the port anyway. + * It's recommended that you use this. + */ +int BIO_bind(int sock, const BIO_ADDR *addr, int options) +{ + int on = 1; + + if (sock == -1) { + BIOerr(BIO_F_BIO_BIND, BIO_R_INVALID_SOCKET); + return 0; + } + +# ifndef OPENSSL_SYS_WINDOWS + /* + * SO_REUSEADDR has different behavior on Windows than on + * other operating systems, don't set it there. + */ + if (options & BIO_SOCK_REUSEADDR) { + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + (const void *)&on, sizeof(on)) != 0) { + SYSerr(SYS_F_SETSOCKOPT, get_last_socket_error()); + BIOerr(BIO_F_BIO_BIND, BIO_R_UNABLE_TO_REUSEADDR); + return 0; + } + } +# endif + + if (bind(sock, BIO_ADDR_sockaddr(addr), BIO_ADDR_sockaddr_size(addr)) != 0) { + SYSerr(SYS_F_BIND, get_last_socket_error()); + BIOerr(BIO_F_BIO_BIND, BIO_R_UNABLE_TO_BIND_SOCKET); + return 0; + } + + return 1; +} + /*- * BIO_listen - Creates a listen socket * @sock: the socket to listen with @@ -161,7 +212,8 @@ int BIO_listen(int sock, const BIO_ADDR *addr, int options) return 0; } - if (getsockopt(sock, SOL_SOCKET, SO_TYPE, &socktype, &socktype_len) != 0 + if (getsockopt(sock, SOL_SOCKET, SO_TYPE, + (void *)&socktype, &socktype_len) != 0 || socktype_len != sizeof(socktype)) { SYSerr(SYS_F_GETSOCKOPT, get_last_socket_error()); BIOerr(BIO_F_BIO_LISTEN, BIO_R_GETTING_SOCKTYPE); @@ -171,22 +223,9 @@ int BIO_listen(int sock, const BIO_ADDR *addr, int options) if (!BIO_socket_nbio(sock, (options & BIO_SOCK_NONBLOCK) != 0)) return 0; -# ifndef OPENSSL_SYS_WINDOWS - /* - * SO_REUSEADDR has different behavior on Windows than on - * other operating systems, don't set it there. - */ - if (options & BIO_SOCK_REUSEADDR) { - if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) != 0) { - SYSerr(SYS_F_SETSOCKOPT, get_last_socket_error()); - BIOerr(BIO_F_BIO_LISTEN, BIO_R_UNABLE_TO_REUSEADDR); - return 0; - } - } -# endif - if (options & BIO_SOCK_KEEPALIVE) { - if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) != 0) { + if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, + (const void *)&on, sizeof(on)) != 0) { SYSerr(SYS_F_SETSOCKOPT, get_last_socket_error()); BIOerr(BIO_F_BIO_LISTEN, BIO_R_UNABLE_TO_KEEPALIVE); return 0; @@ -194,7 +233,8 @@ int BIO_listen(int sock, const BIO_ADDR *addr, int options) } if (options & BIO_SOCK_NODELAY) { - if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) != 0) { + if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, + (const void *)&on, sizeof(on)) != 0) { SYSerr(SYS_F_SETSOCKOPT, get_last_socket_error()); BIOerr(BIO_F_BIO_LISTEN, BIO_R_UNABLE_TO_NODELAY); return 0; @@ -208,7 +248,8 @@ int BIO_listen(int sock, const BIO_ADDR *addr, int options) * Therefore we always have to use setsockopt here. */ on = options & BIO_SOCK_V6_ONLY ? 1 : 0; - if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) != 0) { + if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, + (const void *)&on, sizeof(on)) != 0) { SYSerr(SYS_F_SETSOCKOPT, get_last_socket_error()); BIOerr(BIO_F_BIO_LISTEN, BIO_R_LISTEN_V6_ONLY); return 0; @@ -216,11 +257,8 @@ int BIO_listen(int sock, const BIO_ADDR *addr, int options) } # endif - if (bind(sock, BIO_ADDR_sockaddr(addr), BIO_ADDR_sockaddr_size(addr)) != 0) { - SYSerr(SYS_F_BIND, get_last_socket_error()); - BIOerr(BIO_F_BIO_LISTEN, BIO_R_UNABLE_TO_BIND_SOCKET); + if (!BIO_bind(sock, addr, options)) return 0; - } if (socktype != SOCK_DGRAM && listen(sock, MAX_LISTEN) == -1) { SYSerr(SYS_F_LISTEN, get_last_socket_error()); diff --git a/crypto/bio/bf_buff.c b/crypto/bio/bf_buff.c index 85099561..8e87a629 100644 --- a/crypto/bio/bf_buff.c +++ b/crypto/bio/bf_buff.c @@ -25,7 +25,11 @@ static long buffer_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static const BIO_METHOD methods_buffer = { BIO_TYPE_BUFFER, "buffer", + /* TODO: Convert to new style write function */ + bwrite_conv, buffer_write, + /* TODO: Convert to new style read function */ + bread_conv, buffer_read, buffer_puts, buffer_gets, @@ -37,7 +41,7 @@ static const BIO_METHOD methods_buffer = { const BIO_METHOD *BIO_f_buffer(void) { - return (&methods_buffer); + return &methods_buffer; } static int buffer_new(BIO *bi) @@ -45,25 +49,25 @@ static int buffer_new(BIO *bi) BIO_F_BUFFER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) - return (0); + return 0; ctx->ibuf_size = DEFAULT_BUFFER_SIZE; ctx->ibuf = OPENSSL_malloc(DEFAULT_BUFFER_SIZE); if (ctx->ibuf == NULL) { OPENSSL_free(ctx); - return (0); + return 0; } ctx->obuf_size = DEFAULT_BUFFER_SIZE; ctx->obuf = OPENSSL_malloc(DEFAULT_BUFFER_SIZE); if (ctx->obuf == NULL) { OPENSSL_free(ctx->ibuf); OPENSSL_free(ctx); - return (0); + return 0; } bi->init = 1; bi->ptr = (char *)ctx; bi->flags = 0; - return (1); + return 1; } static int buffer_free(BIO *a) @@ -71,7 +75,7 @@ static int buffer_free(BIO *a) BIO_F_BUFFER_CTX *b; if (a == NULL) - return (0); + return 0; b = (BIO_F_BUFFER_CTX *)a->ptr; OPENSSL_free(b->ibuf); OPENSSL_free(b->obuf); @@ -79,7 +83,7 @@ static int buffer_free(BIO *a) a->ptr = NULL; a->init = 0; a->flags = 0; - return (1); + return 1; } static int buffer_read(BIO *b, char *out, int outl) @@ -88,11 +92,11 @@ static int buffer_read(BIO *b, char *out, int outl) BIO_F_BUFFER_CTX *ctx; if (out == NULL) - return (0); + return 0; ctx = (BIO_F_BUFFER_CTX *)b->ptr; if ((ctx == NULL) || (b->next_bio == NULL)) - return (0); + return 0; num = 0; BIO_clear_retry_flags(b); @@ -107,7 +111,7 @@ static int buffer_read(BIO *b, char *out, int outl) ctx->ibuf_len -= i; num += i; if (outl == i) - return (num); + return num; outl -= i; out += i; } @@ -126,11 +130,11 @@ static int buffer_read(BIO *b, char *out, int outl) if (i < 0) return ((num > 0) ? num : i); if (i == 0) - return (num); + return num; } num += i; if (outl == i) - return (num); + return num; out += i; outl -= i; } @@ -144,7 +148,7 @@ static int buffer_read(BIO *b, char *out, int outl) if (i < 0) return ((num > 0) ? num : i); if (i == 0) - return (num); + return num; } ctx->ibuf_off = 0; ctx->ibuf_len = i; @@ -159,10 +163,10 @@ static int buffer_write(BIO *b, const char *in, int inl) BIO_F_BUFFER_CTX *ctx; if ((in == NULL) || (inl <= 0)) - return (0); + return 0; ctx = (BIO_F_BUFFER_CTX *)b->ptr; if ((ctx == NULL) || (b->next_bio == NULL)) - return (0); + return 0; BIO_clear_retry_flags(b); start: @@ -193,7 +197,7 @@ static int buffer_write(BIO *b, const char *in, int inl) if (i < 0) return ((num > 0) ? num : i); if (i == 0) - return (num); + return num; } ctx->obuf_off += i; ctx->obuf_len -= i; @@ -215,13 +219,13 @@ static int buffer_write(BIO *b, const char *in, int inl) if (i < 0) return ((num > 0) ? num : i); if (i == 0) - return (num); + return num; } num += i; in += i; inl -= i; if (inl == 0) - return (num); + return num; } /* @@ -248,7 +252,12 @@ static long buffer_ctrl(BIO *b, int cmd, long num, void *ptr) ctx->obuf_off = 0; ctx->obuf_len = 0; if (b->next_bio == NULL) - return (0); + return 0; + ret = BIO_ctrl(b->next_bio, cmd, num, ptr); + break; + case BIO_CTRL_EOF: + if (ctx->ibuf_len > 0) + return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; case BIO_CTRL_INFO: @@ -266,7 +275,7 @@ static long buffer_ctrl(BIO *b, int cmd, long num, void *ptr) ret = (long)ctx->obuf_len; if (ret == 0) { if (b->next_bio == NULL) - return (0); + return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } break; @@ -274,7 +283,7 @@ static long buffer_ctrl(BIO *b, int cmd, long num, void *ptr) ret = (long)ctx->ibuf_len; if (ret == 0) { if (b->next_bio == NULL) - return (0); + return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } break; @@ -338,7 +347,7 @@ static long buffer_ctrl(BIO *b, int cmd, long num, void *ptr) break; case BIO_C_DO_STATE_MACHINE: if (b->next_bio == NULL) - return (0); + return 0; BIO_clear_retry_flags(b); ret = BIO_ctrl(b->next_bio, cmd, num, ptr); BIO_copy_next_retry(b); @@ -346,7 +355,7 @@ static long buffer_ctrl(BIO *b, int cmd, long num, void *ptr) case BIO_CTRL_FLUSH: if (b->next_bio == NULL) - return (0); + return 0; if (ctx->obuf_len <= 0) { ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; @@ -359,7 +368,7 @@ static long buffer_ctrl(BIO *b, int cmd, long num, void *ptr) &(ctx->obuf[ctx->obuf_off]), ctx->obuf_len); BIO_copy_next_retry(b); if (r <= 0) - return ((long)r); + return (long)r; ctx->obuf_off += r; ctx->obuf_len -= r; } else { @@ -376,16 +385,27 @@ static long buffer_ctrl(BIO *b, int cmd, long num, void *ptr) !BIO_set_write_buffer_size(dbio, ctx->obuf_size)) ret = 0; break; + case BIO_CTRL_PEEK: + /* Ensure there's stuff in the input buffer */ + { + char fake_buf[1]; + (void)buffer_read(b, fake_buf, 0); + } + if (num > ctx->ibuf_len) + num = ctx->ibuf_len; + memcpy(ptr, &(ctx->ibuf[ctx->ibuf_off]), num); + ret = num; + break; default: if (b->next_bio == NULL) - return (0); + return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } - return (ret); + return ret; malloc_error: BIOerr(BIO_F_BUFFER_CTRL, ERR_R_MALLOC_FAILURE); - return (0); + return 0; } static long buffer_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) @@ -393,13 +413,13 @@ static long buffer_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) long ret = 1; if (b->next_bio == NULL) - return (0); + return 0; switch (cmd) { default: ret = BIO_callback_ctrl(b->next_bio, cmd, fp); break; } - return (ret); + return ret; } static int buffer_gets(BIO *b, char *buf, int size) @@ -430,7 +450,7 @@ static int buffer_gets(BIO *b, char *buf, int size) ctx->ibuf_off += i; if (flag || size == 0) { *buf = '\0'; - return (num); + return num; } } else { /* read another chunk */ @@ -441,7 +461,7 @@ static int buffer_gets(BIO *b, char *buf, int size) if (i < 0) return ((num > 0) ? num : i); if (i == 0) - return (num); + return num; } ctx->ibuf_len = i; ctx->ibuf_off = 0; @@ -451,5 +471,5 @@ static int buffer_gets(BIO *b, char *buf, int size) static int buffer_puts(BIO *b, const char *str) { - return (buffer_write(b, str, strlen(str))); + return buffer_write(b, str, strlen(str)); } diff --git a/crypto/bio/bf_lbuf.c b/crypto/bio/bf_lbuf.c index a80f899a..2dac3d72 100644 --- a/crypto/bio/bf_lbuf.c +++ b/crypto/bio/bf_lbuf.c @@ -30,7 +30,11 @@ static long linebuffer_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static const BIO_METHOD methods_linebuffer = { BIO_TYPE_LINEBUFFER, "linebuffer", + /* TODO: Convert to new style write function */ + bwrite_conv, linebuffer_write, + /* TODO: Convert to new style read function */ + bread_conv, linebuffer_read, linebuffer_puts, linebuffer_gets, @@ -42,7 +46,7 @@ static const BIO_METHOD methods_linebuffer = { const BIO_METHOD *BIO_f_linebuffer(void) { - return (&methods_linebuffer); + return &methods_linebuffer; } typedef struct bio_linebuffer_ctx_struct { @@ -57,11 +61,11 @@ static int linebuffer_new(BIO *bi) ctx = OPENSSL_malloc(sizeof(*ctx)); if (ctx == NULL) - return (0); + return 0; ctx->obuf = OPENSSL_malloc(DEFAULT_LINEBUFFER_SIZE); if (ctx->obuf == NULL) { OPENSSL_free(ctx); - return (0); + return 0; } ctx->obuf_size = DEFAULT_LINEBUFFER_SIZE; ctx->obuf_len = 0; @@ -69,7 +73,7 @@ static int linebuffer_new(BIO *bi) bi->init = 1; bi->ptr = (char *)ctx; bi->flags = 0; - return (1); + return 1; } static int linebuffer_free(BIO *a) @@ -77,14 +81,14 @@ static int linebuffer_free(BIO *a) BIO_LINEBUFFER_CTX *b; if (a == NULL) - return (0); + return 0; b = (BIO_LINEBUFFER_CTX *)a->ptr; OPENSSL_free(b->obuf); OPENSSL_free(a->ptr); a->ptr = NULL; a->init = 0; a->flags = 0; - return (1); + return 1; } static int linebuffer_read(BIO *b, char *out, int outl) @@ -92,13 +96,13 @@ static int linebuffer_read(BIO *b, char *out, int outl) int ret = 0; if (out == NULL) - return (0); + return 0; if (b->next_bio == NULL) - return (0); + return 0; ret = BIO_read(b->next_bio, out, outl); BIO_clear_retry_flags(b); BIO_copy_next_retry(b); - return (ret); + return ret; } static int linebuffer_write(BIO *b, const char *in, int inl) @@ -107,10 +111,10 @@ static int linebuffer_write(BIO *b, const char *in, int inl) BIO_LINEBUFFER_CTX *ctx; if ((in == NULL) || (inl <= 0)) - return (0); + return 0; ctx = (BIO_LINEBUFFER_CTX *)b->ptr; if ((ctx == NULL) || (b->next_bio == NULL)) - return (0); + return 0; BIO_clear_retry_flags(b); @@ -157,7 +161,7 @@ static int linebuffer_write(BIO *b, const char *in, int inl) if (i < 0) return ((num > 0) ? num : i); if (i == 0) - return (num); + return num; } if (i < ctx->obuf_len) memmove(ctx->obuf, ctx->obuf + i, ctx->obuf_len - i); @@ -175,7 +179,7 @@ static int linebuffer_write(BIO *b, const char *in, int inl) if (i < 0) return ((num > 0) ? num : i); if (i == 0) - return (num); + return num; } num += i; in += i; @@ -211,7 +215,7 @@ static long linebuffer_ctrl(BIO *b, int cmd, long num, void *ptr) case BIO_CTRL_RESET: ctx->obuf_len = 0; if (b->next_bio == NULL) - return (0); + return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; case BIO_CTRL_INFO: @@ -221,7 +225,7 @@ static long linebuffer_ctrl(BIO *b, int cmd, long num, void *ptr) ret = (long)ctx->obuf_len; if (ret == 0) { if (b->next_bio == NULL) - return (0); + return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } break; @@ -245,7 +249,7 @@ static long linebuffer_ctrl(BIO *b, int cmd, long num, void *ptr) break; case BIO_C_DO_STATE_MACHINE: if (b->next_bio == NULL) - return (0); + return 0; BIO_clear_retry_flags(b); ret = BIO_ctrl(b->next_bio, cmd, num, ptr); BIO_copy_next_retry(b); @@ -253,7 +257,7 @@ static long linebuffer_ctrl(BIO *b, int cmd, long num, void *ptr) case BIO_CTRL_FLUSH: if (b->next_bio == NULL) - return (0); + return 0; if (ctx->obuf_len <= 0) { ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; @@ -265,7 +269,7 @@ static long linebuffer_ctrl(BIO *b, int cmd, long num, void *ptr) r = BIO_write(b->next_bio, ctx->obuf, ctx->obuf_len); BIO_copy_next_retry(b); if (r <= 0) - return ((long)r); + return (long)r; if (r < ctx->obuf_len) memmove(ctx->obuf, ctx->obuf + r, ctx->obuf_len - r); ctx->obuf_len -= r; @@ -283,14 +287,14 @@ static long linebuffer_ctrl(BIO *b, int cmd, long num, void *ptr) break; default: if (b->next_bio == NULL) - return (0); + return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } - return (ret); + return ret; malloc_error: BIOerr(BIO_F_LINEBUFFER_CTRL, ERR_R_MALLOC_FAILURE); - return (0); + return 0; } static long linebuffer_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) @@ -298,23 +302,23 @@ static long linebuffer_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) long ret = 1; if (b->next_bio == NULL) - return (0); + return 0; switch (cmd) { default: ret = BIO_callback_ctrl(b->next_bio, cmd, fp); break; } - return (ret); + return ret; } static int linebuffer_gets(BIO *b, char *buf, int size) { if (b->next_bio == NULL) - return (0); - return (BIO_gets(b->next_bio, buf, size)); + return 0; + return BIO_gets(b->next_bio, buf, size); } static int linebuffer_puts(BIO *b, const char *str) { - return (linebuffer_write(b, str, strlen(str))); + return linebuffer_write(b, str, strlen(str)); } diff --git a/crypto/bio/bf_nbio.c b/crypto/bio/bf_nbio.c index 3328506d..c41b5d58 100644 --- a/crypto/bio/bf_nbio.c +++ b/crypto/bio/bf_nbio.c @@ -34,7 +34,11 @@ typedef struct nbio_test_st { static const BIO_METHOD methods_nbiof = { BIO_TYPE_NBIO_TEST, "non-blocking IO test filter", + /* TODO: Convert to new style write function */ + bwrite_conv, nbiof_write, + /* TODO: Convert to new style read function */ + bread_conv, nbiof_read, nbiof_puts, nbiof_gets, @@ -46,7 +50,7 @@ static const BIO_METHOD methods_nbiof = { const BIO_METHOD *BIO_f_nbio_test(void) { - return (&methods_nbiof); + return &methods_nbiof; } static int nbiof_new(BIO *bi) @@ -54,23 +58,23 @@ static int nbiof_new(BIO *bi) NBIO_TEST *nt; if ((nt = OPENSSL_zalloc(sizeof(*nt))) == NULL) - return (0); + return 0; nt->lrn = -1; nt->lwn = -1; bi->ptr = (char *)nt; bi->init = 1; - return (1); + return 1; } static int nbiof_free(BIO *a) { if (a == NULL) - return (0); + return 0; OPENSSL_free(a->ptr); a->ptr = NULL; a->init = 0; a->flags = 0; - return (1); + return 1; } static int nbiof_read(BIO *b, char *out, int outl) @@ -80,9 +84,9 @@ static int nbiof_read(BIO *b, char *out, int outl) unsigned char n; if (out == NULL) - return (0); + return 0; if (b->next_bio == NULL) - return (0); + return 0; BIO_clear_retry_flags(b); if (RAND_bytes(&n, 1) <= 0) @@ -100,7 +104,7 @@ static int nbiof_read(BIO *b, char *out, int outl) if (ret < 0) BIO_copy_next_retry(b); } - return (ret); + return ret; } static int nbiof_write(BIO *b, const char *in, int inl) @@ -111,9 +115,9 @@ static int nbiof_write(BIO *b, const char *in, int inl) unsigned char n; if ((in == NULL) || (inl <= 0)) - return (0); + return 0; if (b->next_bio == NULL) - return (0); + return 0; nt = (NBIO_TEST *)b->ptr; BIO_clear_retry_flags(b); @@ -140,7 +144,7 @@ static int nbiof_write(BIO *b, const char *in, int inl) nt->lwn = inl; } } - return (ret); + return ret; } static long nbiof_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -148,7 +152,7 @@ static long nbiof_ctrl(BIO *b, int cmd, long num, void *ptr) long ret; if (b->next_bio == NULL) - return (0); + return 0; switch (cmd) { case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); @@ -162,7 +166,7 @@ static long nbiof_ctrl(BIO *b, int cmd, long num, void *ptr) ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } - return (ret); + return ret; } static long nbiof_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) @@ -170,25 +174,25 @@ static long nbiof_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) long ret = 1; if (b->next_bio == NULL) - return (0); + return 0; switch (cmd) { default: ret = BIO_callback_ctrl(b->next_bio, cmd, fp); break; } - return (ret); + return ret; } static int nbiof_gets(BIO *bp, char *buf, int size) { if (bp->next_bio == NULL) - return (0); - return (BIO_gets(bp->next_bio, buf, size)); + return 0; + return BIO_gets(bp->next_bio, buf, size); } static int nbiof_puts(BIO *bp, const char *str) { if (bp->next_bio == NULL) - return (0); - return (BIO_puts(bp->next_bio, str)); + return 0; + return BIO_puts(bp->next_bio, str); } diff --git a/crypto/bio/bf_null.c b/crypto/bio/bf_null.c index 6b86aa55..613fb2e0 100644 --- a/crypto/bio/bf_null.c +++ b/crypto/bio/bf_null.c @@ -25,7 +25,11 @@ static long nullf_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static const BIO_METHOD methods_nullf = { BIO_TYPE_NULL_FILTER, "NULL filter", + /* TODO: Convert to new style write function */ + bwrite_conv, nullf_write, + /* TODO: Convert to new style read function */ + bread_conv, nullf_read, nullf_puts, nullf_gets, @@ -37,7 +41,7 @@ static const BIO_METHOD methods_nullf = { const BIO_METHOD *BIO_f_null(void) { - return (&methods_nullf); + return &methods_nullf; } static int nullf_read(BIO *b, char *out, int outl) @@ -45,13 +49,13 @@ static int nullf_read(BIO *b, char *out, int outl) int ret = 0; if (out == NULL) - return (0); + return 0; if (b->next_bio == NULL) - return (0); + return 0; ret = BIO_read(b->next_bio, out, outl); BIO_clear_retry_flags(b); BIO_copy_next_retry(b); - return (ret); + return ret; } static int nullf_write(BIO *b, const char *in, int inl) @@ -59,13 +63,13 @@ static int nullf_write(BIO *b, const char *in, int inl) int ret = 0; if ((in == NULL) || (inl <= 0)) - return (0); + return 0; if (b->next_bio == NULL) - return (0); + return 0; ret = BIO_write(b->next_bio, in, inl); BIO_clear_retry_flags(b); BIO_copy_next_retry(b); - return (ret); + return ret; } static long nullf_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -73,7 +77,7 @@ static long nullf_ctrl(BIO *b, int cmd, long num, void *ptr) long ret; if (b->next_bio == NULL) - return (0); + return 0; switch (cmd) { case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); @@ -86,7 +90,7 @@ static long nullf_ctrl(BIO *b, int cmd, long num, void *ptr) default: ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } - return (ret); + return ret; } static long nullf_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) @@ -94,25 +98,25 @@ static long nullf_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) long ret = 1; if (b->next_bio == NULL) - return (0); + return 0; switch (cmd) { default: ret = BIO_callback_ctrl(b->next_bio, cmd, fp); break; } - return (ret); + return ret; } static int nullf_gets(BIO *bp, char *buf, int size) { if (bp->next_bio == NULL) - return (0); - return (BIO_gets(bp->next_bio, buf, size)); + return 0; + return BIO_gets(bp->next_bio, buf, size); } static int nullf_puts(BIO *bp, const char *str) { if (bp->next_bio == NULL) - return (0); - return (BIO_puts(bp->next_bio, str)); + return 0; + return BIO_puts(bp->next_bio, str); } diff --git a/crypto/bio/bio_cb.c b/crypto/bio/bio_cb.c index 412387b6..1154c233 100644 --- a/crypto/bio/bio_cb.c +++ b/crypto/bio/bio_cb.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -21,8 +21,7 @@ long BIO_debug_callback(BIO *bio, int cmd, const char *argp, char buf[256]; char *p; long r = 1; - int len; - size_t p_maxlen; + int len, left; if (BIO_CB_RETURN & cmd) r = ret; @@ -33,58 +32,58 @@ long BIO_debug_callback(BIO *bio, int cmd, const char *argp, if (len < 0) len = 0; p = buf + len; - p_maxlen = sizeof(buf) - len; + left = sizeof(buf) - len; switch (cmd) { case BIO_CB_FREE: - BIO_snprintf(p, p_maxlen, "Free - %s\n", bio->method->name); + BIO_snprintf(p, left, "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_snprintf(p, left, "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); + BIO_snprintf(p, left, "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_snprintf(p, left, "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_snprintf(p, left, "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); + BIO_snprintf(p, left, "puts() - %s\n", bio->method->name); break; case BIO_CB_GETS: - BIO_snprintf(p, p_maxlen, "gets(%lu) - %s\n", (unsigned long)argi, + BIO_snprintf(p, left, "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_snprintf(p, left, "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); + BIO_snprintf(p, left, "read return %ld\n", ret); break; case BIO_CB_RETURN | BIO_CB_WRITE: - BIO_snprintf(p, p_maxlen, "write return %ld\n", ret); + BIO_snprintf(p, left, "write return %ld\n", ret); break; case BIO_CB_RETURN | BIO_CB_GETS: - BIO_snprintf(p, p_maxlen, "gets return %ld\n", ret); + BIO_snprintf(p, left, "gets return %ld\n", ret); break; case BIO_CB_RETURN | BIO_CB_PUTS: - BIO_snprintf(p, p_maxlen, "puts return %ld\n", ret); + BIO_snprintf(p, left, "puts return %ld\n", ret); break; case BIO_CB_RETURN | BIO_CB_CTRL: - BIO_snprintf(p, p_maxlen, "ctrl return %ld\n", ret); + BIO_snprintf(p, left, "ctrl return %ld\n", ret); break; default: - BIO_snprintf(p, p_maxlen, "bio callback - unknown type (%d)\n", cmd); + BIO_snprintf(p, left, "bio callback - unknown type (%d)\n", cmd); break; } @@ -95,5 +94,5 @@ long BIO_debug_callback(BIO *bio, int cmd, const char *argp, else fputs(buf, stderr); #endif - return (r); + return r; } diff --git a/crypto/bio/bio_err.c b/crypto/bio/bio_err.c index c914dcff..594013dd 100644 --- a/crypto/bio/bio_err.c +++ b/crypto/bio/bio_err.c @@ -8,106 +8,118 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_BIO,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_BIO,0,reason) - -static ERR_STRING_DATA BIO_str_functs[] = { - {ERR_FUNC(BIO_F_ACPT_STATE), "acpt_state"}, - {ERR_FUNC(BIO_F_ADDR_STRINGS), "addr_strings"}, - {ERR_FUNC(BIO_F_BIO_ACCEPT), "BIO_accept"}, - {ERR_FUNC(BIO_F_BIO_ACCEPT_EX), "BIO_accept_ex"}, - {ERR_FUNC(BIO_F_BIO_ADDR_NEW), "BIO_ADDR_new"}, - {ERR_FUNC(BIO_F_BIO_CALLBACK_CTRL), "BIO_callback_ctrl"}, - {ERR_FUNC(BIO_F_BIO_CONNECT), "BIO_connect"}, - {ERR_FUNC(BIO_F_BIO_CTRL), "BIO_ctrl"}, - {ERR_FUNC(BIO_F_BIO_GETS), "BIO_gets"}, - {ERR_FUNC(BIO_F_BIO_GET_HOST_IP), "BIO_get_host_ip"}, - {ERR_FUNC(BIO_F_BIO_GET_NEW_INDEX), "BIO_get_new_index"}, - {ERR_FUNC(BIO_F_BIO_GET_PORT), "BIO_get_port"}, - {ERR_FUNC(BIO_F_BIO_LISTEN), "BIO_listen"}, - {ERR_FUNC(BIO_F_BIO_LOOKUP), "BIO_lookup"}, - {ERR_FUNC(BIO_F_BIO_MAKE_PAIR), "bio_make_pair"}, - {ERR_FUNC(BIO_F_BIO_METH_NEW), "BIO_meth_new"}, - {ERR_FUNC(BIO_F_BIO_NEW), "BIO_new"}, - {ERR_FUNC(BIO_F_BIO_NEW_FILE), "BIO_new_file"}, - {ERR_FUNC(BIO_F_BIO_NEW_MEM_BUF), "BIO_new_mem_buf"}, - {ERR_FUNC(BIO_F_BIO_NREAD), "BIO_nread"}, - {ERR_FUNC(BIO_F_BIO_NREAD0), "BIO_nread0"}, - {ERR_FUNC(BIO_F_BIO_NWRITE), "BIO_nwrite"}, - {ERR_FUNC(BIO_F_BIO_NWRITE0), "BIO_nwrite0"}, - {ERR_FUNC(BIO_F_BIO_PARSE_HOSTSERV), "BIO_parse_hostserv"}, - {ERR_FUNC(BIO_F_BIO_PUTS), "BIO_puts"}, - {ERR_FUNC(BIO_F_BIO_READ), "BIO_read"}, - {ERR_FUNC(BIO_F_BIO_SOCKET), "BIO_socket"}, - {ERR_FUNC(BIO_F_BIO_SOCKET_NBIO), "BIO_socket_nbio"}, - {ERR_FUNC(BIO_F_BIO_SOCK_INFO), "BIO_sock_info"}, - {ERR_FUNC(BIO_F_BIO_SOCK_INIT), "BIO_sock_init"}, - {ERR_FUNC(BIO_F_BIO_WRITE), "BIO_write"}, - {ERR_FUNC(BIO_F_BUFFER_CTRL), "buffer_ctrl"}, - {ERR_FUNC(BIO_F_CONN_CTRL), "conn_ctrl"}, - {ERR_FUNC(BIO_F_CONN_STATE), "conn_state"}, - {ERR_FUNC(BIO_F_DGRAM_SCTP_READ), "dgram_sctp_read"}, - {ERR_FUNC(BIO_F_DGRAM_SCTP_WRITE), "dgram_sctp_write"}, - {ERR_FUNC(BIO_F_FILE_CTRL), "file_ctrl"}, - {ERR_FUNC(BIO_F_FILE_READ), "file_read"}, - {ERR_FUNC(BIO_F_LINEBUFFER_CTRL), "linebuffer_ctrl"}, - {ERR_FUNC(BIO_F_MEM_WRITE), "mem_write"}, - {ERR_FUNC(BIO_F_SSL_NEW), "SSL_new"}, +static const ERR_STRING_DATA BIO_str_functs[] = { + {ERR_PACK(ERR_LIB_BIO, BIO_F_ACPT_STATE, 0), "acpt_state"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_ADDR_STRINGS, 0), "addr_strings"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_ACCEPT, 0), "BIO_accept"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_ACCEPT_EX, 0), "BIO_accept_ex"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_ADDR_NEW, 0), "BIO_ADDR_new"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_BIND, 0), "BIO_bind"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_CALLBACK_CTRL, 0), "BIO_callback_ctrl"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_CONNECT, 0), "BIO_connect"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_CTRL, 0), "BIO_ctrl"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_GETS, 0), "BIO_gets"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_GET_HOST_IP, 0), "BIO_get_host_ip"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_GET_NEW_INDEX, 0), "BIO_get_new_index"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_GET_PORT, 0), "BIO_get_port"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_LISTEN, 0), "BIO_listen"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_LOOKUP, 0), "BIO_lookup"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_LOOKUP_EX, 0), "BIO_lookup_ex"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_MAKE_PAIR, 0), "bio_make_pair"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_METH_NEW, 0), "BIO_meth_new"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_NEW, 0), "BIO_new"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_NEW_DGRAM_SCTP, 0), "BIO_new_dgram_sctp"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_NEW_FILE, 0), "BIO_new_file"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_NEW_MEM_BUF, 0), "BIO_new_mem_buf"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_NREAD, 0), "BIO_nread"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_NREAD0, 0), "BIO_nread0"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_NWRITE, 0), "BIO_nwrite"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_NWRITE0, 0), "BIO_nwrite0"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_PARSE_HOSTSERV, 0), "BIO_parse_hostserv"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_PUTS, 0), "BIO_puts"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_READ, 0), "BIO_read"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_READ_EX, 0), "BIO_read_ex"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_READ_INTERN, 0), "bio_read_intern"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_SOCKET, 0), "BIO_socket"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_SOCKET_NBIO, 0), "BIO_socket_nbio"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_SOCK_INFO, 0), "BIO_sock_info"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_SOCK_INIT, 0), "BIO_sock_init"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_WRITE, 0), "BIO_write"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_WRITE_EX, 0), "BIO_write_ex"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BIO_WRITE_INTERN, 0), "bio_write_intern"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_BUFFER_CTRL, 0), "buffer_ctrl"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_CONN_CTRL, 0), "conn_ctrl"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_CONN_STATE, 0), "conn_state"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_DGRAM_SCTP_READ, 0), "dgram_sctp_read"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_DGRAM_SCTP_WRITE, 0), "dgram_sctp_write"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_FILE_CTRL, 0), "file_ctrl"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_FILE_READ, 0), "file_read"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_LINEBUFFER_CTRL, 0), "linebuffer_ctrl"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_MEM_WRITE, 0), "mem_write"}, + {ERR_PACK(ERR_LIB_BIO, BIO_F_SSL_NEW, 0), "SSL_new"}, {0, NULL} }; -static ERR_STRING_DATA BIO_str_reasons[] = { - {ERR_REASON(BIO_R_ACCEPT_ERROR), "accept error"}, - {ERR_REASON(BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET), - "addrinfo addr is not af inet"}, - {ERR_REASON(BIO_R_AMBIGUOUS_HOST_OR_SERVICE), - "ambiguous host or service"}, - {ERR_REASON(BIO_R_BAD_FOPEN_MODE), "bad fopen mode"}, - {ERR_REASON(BIO_R_BROKEN_PIPE), "broken pipe"}, - {ERR_REASON(BIO_R_CONNECT_ERROR), "connect error"}, - {ERR_REASON(BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET), - "gethostbyname addr is not af inet"}, - {ERR_REASON(BIO_R_GETSOCKNAME_ERROR), "getsockname error"}, - {ERR_REASON(BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS), - "getsockname truncated address"}, - {ERR_REASON(BIO_R_GETTING_SOCKTYPE), "getting socktype"}, - {ERR_REASON(BIO_R_INVALID_ARGUMENT), "invalid argument"}, - {ERR_REASON(BIO_R_INVALID_SOCKET), "invalid socket"}, - {ERR_REASON(BIO_R_IN_USE), "in use"}, - {ERR_REASON(BIO_R_LISTEN_V6_ONLY), "listen v6 only"}, - {ERR_REASON(BIO_R_LOOKUP_RETURNED_NOTHING), "lookup returned nothing"}, - {ERR_REASON(BIO_R_MALFORMED_HOST_OR_SERVICE), - "malformed host or service"}, - {ERR_REASON(BIO_R_NBIO_CONNECT_ERROR), "nbio connect error"}, - {ERR_REASON(BIO_R_NO_ACCEPT_ADDR_OR_SERVICE_SPECIFIED), - "no accept addr or service specified"}, - {ERR_REASON(BIO_R_NO_HOSTNAME_OR_SERVICE_SPECIFIED), - "no hostname or service specified"}, - {ERR_REASON(BIO_R_NO_PORT_DEFINED), "no port defined"}, - {ERR_REASON(BIO_R_NO_SUCH_FILE), "no such file"}, - {ERR_REASON(BIO_R_NULL_PARAMETER), "null parameter"}, - {ERR_REASON(BIO_R_UNABLE_TO_BIND_SOCKET), "unable to bind socket"}, - {ERR_REASON(BIO_R_UNABLE_TO_CREATE_SOCKET), "unable to create socket"}, - {ERR_REASON(BIO_R_UNABLE_TO_KEEPALIVE), "unable to keepalive"}, - {ERR_REASON(BIO_R_UNABLE_TO_LISTEN_SOCKET), "unable to listen socket"}, - {ERR_REASON(BIO_R_UNABLE_TO_NODELAY), "unable to nodelay"}, - {ERR_REASON(BIO_R_UNABLE_TO_REUSEADDR), "unable to reuseaddr"}, - {ERR_REASON(BIO_R_UNAVAILABLE_IP_FAMILY), "unavailable ip family"}, - {ERR_REASON(BIO_R_UNINITIALIZED), "uninitialized"}, - {ERR_REASON(BIO_R_UNKNOWN_INFO_TYPE), "unknown info type"}, - {ERR_REASON(BIO_R_UNSUPPORTED_IP_FAMILY), "unsupported ip family"}, - {ERR_REASON(BIO_R_UNSUPPORTED_METHOD), "unsupported method"}, - {ERR_REASON(BIO_R_UNSUPPORTED_PROTOCOL_FAMILY), - "unsupported protocol family"}, - {ERR_REASON(BIO_R_WRITE_TO_READ_ONLY_BIO), "write to read only BIO"}, - {ERR_REASON(BIO_R_WSASTARTUP), "WSAStartup"}, +static const ERR_STRING_DATA BIO_str_reasons[] = { + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_ACCEPT_ERROR), "accept error"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET), + "addrinfo addr is not af inet"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_AMBIGUOUS_HOST_OR_SERVICE), + "ambiguous host or service"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_BAD_FOPEN_MODE), "bad fopen mode"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_BROKEN_PIPE), "broken pipe"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_CONNECT_ERROR), "connect error"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET), + "gethostbyname addr is not af inet"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_GETSOCKNAME_ERROR), "getsockname error"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS), + "getsockname truncated address"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_GETTING_SOCKTYPE), "getting socktype"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_INVALID_ARGUMENT), "invalid argument"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_INVALID_SOCKET), "invalid socket"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_IN_USE), "in use"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_LENGTH_TOO_LONG), "length too long"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_LISTEN_V6_ONLY), "listen v6 only"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_LOOKUP_RETURNED_NOTHING), + "lookup returned nothing"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_MALFORMED_HOST_OR_SERVICE), + "malformed host or service"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NBIO_CONNECT_ERROR), "nbio connect error"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NO_ACCEPT_ADDR_OR_SERVICE_SPECIFIED), + "no accept addr or service specified"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NO_HOSTNAME_OR_SERVICE_SPECIFIED), + "no hostname or service specified"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NO_PORT_DEFINED), "no port defined"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NO_SUCH_FILE), "no such file"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NULL_PARAMETER), "null parameter"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_BIND_SOCKET), + "unable to bind socket"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_CREATE_SOCKET), + "unable to create socket"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_KEEPALIVE), + "unable to keepalive"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_LISTEN_SOCKET), + "unable to listen socket"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_NODELAY), "unable to nodelay"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_REUSEADDR), + "unable to reuseaddr"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNAVAILABLE_IP_FAMILY), + "unavailable ip family"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNINITIALIZED), "uninitialized"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNKNOWN_INFO_TYPE), "unknown info type"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNSUPPORTED_IP_FAMILY), + "unsupported ip family"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNSUPPORTED_METHOD), "unsupported method"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY), + "unsupported protocol family"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_WRITE_TO_READ_ONLY_BIO), + "write to read only BIO"}, + {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_WSASTARTUP), "WSAStartup"}, {0, NULL} }; @@ -116,10 +128,9 @@ static ERR_STRING_DATA BIO_str_reasons[] = { int ERR_load_BIO_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(BIO_str_functs[0].error) == NULL) { - ERR_load_strings(0, BIO_str_functs); - ERR_load_strings(0, BIO_str_reasons); + ERR_load_strings_const(BIO_str_functs); + ERR_load_strings_const(BIO_str_reasons); } #endif return 1; diff --git a/crypto/bio/bio_lcl.h b/crypto/bio/bio_lcl.h index 39178cf5..e2c05a20 100644 --- a/crypto/bio/bio_lcl.h +++ b/crypto/bio/bio_lcl.h @@ -7,8 +7,9 @@ * https://www.openssl.org/source/license.html */ -#define USE_SOCKETS #include "e_os.h" +#include "internal/sockets.h" +#include "internal/refcount.h" /* BEGIN BIO_ADDRINFO/BIO_ADDR stuff. */ @@ -86,7 +87,7 @@ union bio_addr_st { /* END BIO_ADDRINFO/BIO_ADDR stuff. */ #include "internal/cryptlib.h" -#include +#include "internal/bio.h" typedef struct bio_f_buffer_ctx_struct { /*- @@ -114,7 +115,8 @@ typedef struct bio_f_buffer_ctx_struct { struct bio_st { const BIO_METHOD *method; /* bio, mode, argp, argi, argl, ret */ - long (*callback) (struct bio_st *, int, const char *, int, long, long); + BIO_callback_fn callback; + BIO_callback_fn_ex callback_ex; char *cb_arg; /* first argument for the callback */ int init; int shutdown; @@ -124,7 +126,7 @@ struct bio_st { void *ptr; struct bio_st *next_bio; /* used by filter BIOs */ struct bio_st *prev_bio; /* used by filter BIOs */ - int references; + CRYPTO_REF_COUNT references; uint64_t num_read; uint64_t num_write; CRYPTO_EX_DATA ex_data; diff --git a/crypto/bio/bio_lib.c b/crypto/bio/bio_lib.c index 7b98dc93..557d609c 100644 --- a/crypto/bio/bio_lib.c +++ b/crypto/bio/bio_lib.c @@ -13,13 +13,69 @@ #include "bio_lcl.h" #include "internal/cryptlib.h" + +/* + * Helper macro for the callback to determine whether an operator expects a + * len parameter or not + */ +#define HAS_LEN_OPER(o) ((o) == BIO_CB_READ || (o) == BIO_CB_WRITE || \ + (o) == BIO_CB_GETS) + +/* + * Helper function to work out whether to call the new style callback or the old + * one, and translate between the two. + * + * This has a long return type for consistency with the old callback. Similarly + * for the "long" used for "inret" + */ +static long bio_call_callback(BIO *b, int oper, const char *argp, size_t len, + int argi, long argl, long inret, size_t *processed) +{ + long ret; + int bareoper; + + if (b->callback_ex != NULL) { + return b->callback_ex(b, oper, argp, len, argi, argl, inret, processed); + } + + /* Strip off any BIO_CB_RETURN flag */ + bareoper = oper & ~BIO_CB_RETURN; + + /* + * We have an old style callback, so we will have to do nasty casts and + * check for overflows. + */ + if (HAS_LEN_OPER(bareoper)) { + /* In this case |len| is set, and should be used instead of |argi| */ + if (len > INT_MAX) + return -1; + + argi = (int)len; + + if (inret && (oper & BIO_CB_RETURN)) { + if (*processed > INT_MAX) + return -1; + inret = *processed; + } + } + + ret = b->callback(b, oper, argp, argi, argl, inret); + + if (ret >= 0 && (HAS_LEN_OPER(bareoper) || bareoper == BIO_CB_PUTS)) { + *processed = (size_t)ret; + ret = 1; + } + + return ret; +} + BIO *BIO_new(const BIO_METHOD *method) { BIO *bio = OPENSSL_zalloc(sizeof(*bio)); if (bio == NULL) { BIOerr(BIO_F_BIO_NEW, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } bio->method = method; @@ -54,21 +110,24 @@ err: int BIO_free(BIO *a) { - int i; + int ret; if (a == NULL) return 0; - if (CRYPTO_atomic_add(&a->references, -1, &i, a->lock) <= 0) + if (CRYPTO_DOWN_REF(&a->references, &ret, a->lock) <= 0) return 0; REF_PRINT_COUNT("BIO", a); - if (i > 0) + if (ret > 0) return 1; - REF_ASSERT_ISNT(i < 0); - if ((a->callback != NULL) && - ((i = (int)a->callback(a, BIO_CB_FREE, NULL, 0, 0L, 1L)) <= 0)) - return i; + REF_ASSERT_ISNT(ret < 0); + + if (a->callback != NULL || a->callback_ex != NULL) { + ret = (int)bio_call_callback(a, BIO_CB_FREE, NULL, 0, 0, 0L, 1L, NULL); + if (ret <= 0) + return ret; + } if ((a->method != NULL) && (a->method->destroy != NULL)) a->method->destroy(a); @@ -121,7 +180,7 @@ int BIO_up_ref(BIO *a) { int i; - if (CRYPTO_atomic_add(&a->references, 1, &i, a->lock) <= 0) + if (CRYPTO_UP_REF(&a->references, &i, a->lock) <= 0) return 0; REF_PRINT_COUNT("BIO", a); @@ -144,18 +203,26 @@ void BIO_set_flags(BIO *b, int flags) b->flags |= flags; } -long (*BIO_get_callback(const BIO *b)) (struct bio_st *, int, const char *, - int, long, long) { +BIO_callback_fn BIO_get_callback(const BIO *b) +{ return b->callback; } -void BIO_set_callback(BIO *b, - long (*cb) (struct bio_st *, int, const char *, int, - long, long)) +void BIO_set_callback(BIO *b, BIO_callback_fn cb) { b->callback = cb; } +BIO_callback_fn_ex BIO_get_callback_ex(const BIO *b) +{ + return b->callback_ex; +} + +void BIO_set_callback_ex(BIO *b, BIO_callback_fn_ex cb) +{ + b->callback_ex = cb; +} + void BIO_set_callback_arg(BIO *b, char *arg) { b->cb_arg = arg; @@ -176,124 +243,239 @@ int BIO_method_type(const BIO *b) return b->method->type; } -int BIO_read(BIO *b, void *out, int outl) +/* + * This is essentially the same as BIO_read_ex() except that it allows + * 0 or a negative value to indicate failure (retryable or not) in the return. + * This is for compatibility with the old style BIO_read(), where existing code + * may make assumptions about the return value that it might get. + */ +static int bio_read_intern(BIO *b, void *data, size_t dlen, size_t *readbytes) { - int i; - long (*cb) (BIO *, int, const char *, int, long, long); + int ret; if ((b == NULL) || (b->method == NULL) || (b->method->bread == NULL)) { - BIOerr(BIO_F_BIO_READ, BIO_R_UNSUPPORTED_METHOD); - return (-2); + BIOerr(BIO_F_BIO_READ_INTERN, BIO_R_UNSUPPORTED_METHOD); + return -2; } - cb = b->callback; - if ((cb != NULL) && - ((i = (int)cb(b, BIO_CB_READ, out, outl, 0L, 1L)) <= 0)) - return (i); + if ((b->callback != NULL || b->callback_ex != NULL) && + ((ret = (int)bio_call_callback(b, BIO_CB_READ, data, dlen, 0, 0L, 1L, + readbytes)) <= 0)) + return ret; if (!b->init) { - BIOerr(BIO_F_BIO_READ, BIO_R_UNINITIALIZED); - return (-2); + BIOerr(BIO_F_BIO_READ_INTERN, BIO_R_UNINITIALIZED); + return -2; } - i = b->method->bread(b, out, outl); + ret = b->method->bread(b, data, dlen, readbytes); - if (i > 0) - b->num_read += (uint64_t)i; + if (ret > 0) + b->num_read += (uint64_t)*readbytes; - if (cb != NULL) - i = (int)cb(b, BIO_CB_READ | BIO_CB_RETURN, out, outl, 0L, (long)i); - return (i); + if (b->callback != NULL || b->callback_ex != NULL) + ret = (int)bio_call_callback(b, BIO_CB_READ | BIO_CB_RETURN, data, + dlen, 0, 0L, ret, readbytes); + + /* Shouldn't happen */ + if (ret > 0 && *readbytes > dlen) { + BIOerr(BIO_F_BIO_READ_INTERN, ERR_R_INTERNAL_ERROR); + return -1; + } + + return ret; } -int BIO_write(BIO *b, const void *in, int inl) +int BIO_read(BIO *b, void *data, int dlen) { - int i; - long (*cb) (BIO *, int, const char *, int, long, long); + size_t readbytes; + int ret; + + if (dlen < 0) + return 0; + + ret = bio_read_intern(b, data, (size_t)dlen, &readbytes); + + if (ret > 0) { + /* *readbytes should always be <= dlen */ + ret = (int)readbytes; + } + + return ret; +} + +int BIO_read_ex(BIO *b, void *data, size_t dlen, size_t *readbytes) +{ + int ret; + + ret = bio_read_intern(b, data, dlen, readbytes); + + if (ret > 0) + ret = 1; + else + ret = 0; + + return ret; +} + +static int bio_write_intern(BIO *b, const void *data, size_t dlen, + size_t *written) +{ + int ret; if (b == NULL) - return (0); + return 0; - cb = b->callback; if ((b->method == NULL) || (b->method->bwrite == NULL)) { - BIOerr(BIO_F_BIO_WRITE, BIO_R_UNSUPPORTED_METHOD); - return (-2); + BIOerr(BIO_F_BIO_WRITE_INTERN, BIO_R_UNSUPPORTED_METHOD); + return -2; } - if ((cb != NULL) && - ((i = (int)cb(b, BIO_CB_WRITE, in, inl, 0L, 1L)) <= 0)) - return (i); + if ((b->callback != NULL || b->callback_ex != NULL) && + ((ret = (int)bio_call_callback(b, BIO_CB_WRITE, data, dlen, 0, 0L, 1L, + written)) <= 0)) + return ret; if (!b->init) { - BIOerr(BIO_F_BIO_WRITE, BIO_R_UNINITIALIZED); - return (-2); + BIOerr(BIO_F_BIO_WRITE_INTERN, BIO_R_UNINITIALIZED); + return -2; } - i = b->method->bwrite(b, in, inl); + ret = b->method->bwrite(b, data, dlen, written); - if (i > 0) - b->num_write += (uint64_t)i; + if (ret > 0) + b->num_write += (uint64_t)*written; - if (cb != NULL) - i = (int)cb(b, BIO_CB_WRITE | BIO_CB_RETURN, in, inl, 0L, (long)i); - return (i); + if (b->callback != NULL || b->callback_ex != NULL) + ret = (int)bio_call_callback(b, BIO_CB_WRITE | BIO_CB_RETURN, data, + dlen, 0, 0L, ret, written); + + return ret; } -int BIO_puts(BIO *b, const char *in) +int BIO_write(BIO *b, const void *data, int dlen) { - int i; - long (*cb) (BIO *, int, const char *, int, long, long); + size_t written; + int ret; + + if (dlen < 0) + return 0; + + ret = bio_write_intern(b, data, (size_t)dlen, &written); + + if (ret > 0) { + /* *written should always be <= dlen */ + ret = (int)written; + } + + return ret; +} + +int BIO_write_ex(BIO *b, const void *data, size_t dlen, size_t *written) +{ + int ret; + + ret = bio_write_intern(b, data, dlen, written); + + if (ret > 0) + ret = 1; + else + ret = 0; + + return ret; +} + +int BIO_puts(BIO *b, const char *buf) +{ + int ret; + size_t written = 0; if ((b == NULL) || (b->method == NULL) || (b->method->bputs == NULL)) { BIOerr(BIO_F_BIO_PUTS, BIO_R_UNSUPPORTED_METHOD); - return (-2); + return -2; } - cb = b->callback; - - if ((cb != NULL) && ((i = (int)cb(b, BIO_CB_PUTS, in, 0, 0L, 1L)) <= 0)) - return (i); + if (b->callback != NULL || b->callback_ex != NULL) { + ret = (int)bio_call_callback(b, BIO_CB_PUTS, buf, 0, 0, 0L, 1L, NULL); + if (ret <= 0) + return ret; + } if (!b->init) { BIOerr(BIO_F_BIO_PUTS, BIO_R_UNINITIALIZED); - return (-2); + return -2; } - i = b->method->bputs(b, in); + ret = b->method->bputs(b, buf); - if (i > 0) - b->num_write += (uint64_t)i; + if (ret > 0) { + b->num_write += (uint64_t)ret; + written = ret; + ret = 1; + } - if (cb != NULL) - i = (int)cb(b, BIO_CB_PUTS | BIO_CB_RETURN, in, 0, 0L, (long)i); - return (i); + if (b->callback != NULL || b->callback_ex != NULL) + ret = (int)bio_call_callback(b, BIO_CB_PUTS | BIO_CB_RETURN, buf, 0, 0, + 0L, ret, &written); + + if (ret > 0) { + if (written > INT_MAX) { + BIOerr(BIO_F_BIO_PUTS, BIO_R_LENGTH_TOO_LONG); + ret = -1; + } else { + ret = (int)written; + } + } + + return ret; } -int BIO_gets(BIO *b, char *in, int inl) +int BIO_gets(BIO *b, char *buf, int size) { - int i; - long (*cb) (BIO *, int, const char *, int, long, long); + int ret; + size_t readbytes = 0; if ((b == NULL) || (b->method == NULL) || (b->method->bgets == NULL)) { BIOerr(BIO_F_BIO_GETS, BIO_R_UNSUPPORTED_METHOD); - return (-2); + return -2; } - cb = b->callback; + if (size < 0) { + BIOerr(BIO_F_BIO_GETS, BIO_R_INVALID_ARGUMENT); + return 0; + } - if ((cb != NULL) && ((i = (int)cb(b, BIO_CB_GETS, in, inl, 0L, 1L)) <= 0)) - return (i); + if (b->callback != NULL || b->callback_ex != NULL) { + ret = (int)bio_call_callback(b, BIO_CB_GETS, buf, size, 0, 0L, 1, NULL); + if (ret <= 0) + return ret; + } if (!b->init) { BIOerr(BIO_F_BIO_GETS, BIO_R_UNINITIALIZED); - return (-2); + return -2; } - i = b->method->bgets(b, in, inl); + ret = b->method->bgets(b, buf, size); - if (cb != NULL) - i = (int)cb(b, BIO_CB_GETS | BIO_CB_RETURN, in, inl, 0L, (long)i); - return (i); + if (ret > 0) { + readbytes = ret; + ret = 1; + } + + if (b->callback != NULL || b->callback_ex != NULL) + ret = (int)bio_call_callback(b, BIO_CB_GETS | BIO_CB_RETURN, buf, size, + 0, 0L, ret, &readbytes); + + if (ret > 0) { + /* Shouldn't happen */ + if (readbytes > (size_t)size) + ret = -1; + else + ret = (int)readbytes; + } + + return ret; } int BIO_indent(BIO *b, int indent, int max) @@ -313,7 +495,7 @@ long BIO_int_ctrl(BIO *b, int cmd, long larg, int iarg) int i; i = iarg; - return (BIO_ctrl(b, cmd, larg, (char *)&i)); + return BIO_ctrl(b, cmd, larg, (char *)&i); } void *BIO_ptr_ctrl(BIO *b, int cmd, long larg) @@ -321,61 +503,64 @@ void *BIO_ptr_ctrl(BIO *b, int cmd, long larg) void *p = NULL; if (BIO_ctrl(b, cmd, larg, (char *)&p) <= 0) - return (NULL); + return NULL; else - return (p); + return p; } long BIO_ctrl(BIO *b, int cmd, long larg, void *parg) { long ret; - long (*cb) (BIO *, int, const char *, int, long, long); if (b == NULL) - return (0); + return 0; if ((b->method == NULL) || (b->method->ctrl == NULL)) { BIOerr(BIO_F_BIO_CTRL, BIO_R_UNSUPPORTED_METHOD); - return (-2); + return -2; } - cb = b->callback; - - if ((cb != NULL) && - ((ret = cb(b, BIO_CB_CTRL, parg, cmd, larg, 1L)) <= 0)) - return (ret); + if (b->callback != NULL || b->callback_ex != NULL) { + ret = bio_call_callback(b, BIO_CB_CTRL, parg, 0, cmd, larg, 1L, NULL); + if (ret <= 0) + return ret; + } ret = b->method->ctrl(b, cmd, larg, parg); - if (cb != NULL) - ret = cb(b, BIO_CB_CTRL | BIO_CB_RETURN, parg, cmd, larg, ret); - return (ret); + if (b->callback != NULL || b->callback_ex != NULL) + ret = bio_call_callback(b, BIO_CB_CTRL | BIO_CB_RETURN, parg, 0, cmd, + larg, ret, NULL); + + return ret; } long BIO_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { long ret; - long (*cb) (BIO *, int, const char *, int, long, long); if (b == NULL) - return (0); + return 0; if ((b->method == NULL) || (b->method->callback_ctrl == NULL)) { BIOerr(BIO_F_BIO_CALLBACK_CTRL, BIO_R_UNSUPPORTED_METHOD); - return (-2); + return -2; } - cb = b->callback; - - if ((cb != NULL) && - ((ret = cb(b, BIO_CB_CTRL, (void *)&fp, cmd, 0, 1L)) <= 0)) - return (ret); + if (b->callback != NULL || b->callback_ex != NULL) { + ret = bio_call_callback(b, BIO_CB_CTRL, (void *)&fp, 0, cmd, 0, 1L, + NULL); + if (ret <= 0) + return ret; + } ret = b->method->callback_ctrl(b, cmd, fp); - if (cb != NULL) - ret = cb(b, BIO_CB_CTRL | BIO_CB_RETURN, (void *)&fp, cmd, 0, ret); - return (ret); + if (b->callback != NULL || b->callback_ex != NULL) + ret = bio_call_callback(b, BIO_CB_CTRL | BIO_CB_RETURN, (void *)&fp, 0, + cmd, 0, ret, NULL); + + return ret; } /* @@ -399,7 +584,7 @@ BIO *BIO_push(BIO *b, BIO *bio) BIO *lb; if (b == NULL) - return (bio); + return bio; lb = b; while (lb->next_bio != NULL) lb = lb->next_bio; @@ -408,7 +593,7 @@ BIO *BIO_push(BIO *b, BIO *bio) bio->prev_bio = lb; /* called to do internal processing */ BIO_ctrl(b, BIO_CTRL_PUSH, 0, lb); - return (b); + return b; } /* Remove the first and return the rest */ @@ -417,7 +602,7 @@ BIO *BIO_pop(BIO *b) BIO *ret; if (b == NULL) - return (NULL); + return NULL; ret = b->next_bio; BIO_ctrl(b, BIO_CTRL_POP, 0, b); @@ -429,7 +614,7 @@ BIO *BIO_pop(BIO *b) b->next_bio = NULL; b->prev_bio = NULL; - return (ret); + return ret; } BIO *BIO_get_retry_BIO(BIO *bio, int *reason) @@ -447,12 +632,12 @@ BIO *BIO_get_retry_BIO(BIO *bio, int *reason) } if (reason != NULL) *reason = last->retry_reason; - return (last); + return last; } int BIO_get_retry_reason(BIO *bio) { - return (bio->retry_reason); + return bio->retry_reason; } void BIO_set_retry_reason(BIO *bio, int reason) @@ -473,13 +658,13 @@ BIO *BIO_find_type(BIO *bio, int type) if (!mask) { if (mt & type) - return (bio); + return bio; } else if (mt == type) - return (bio); + return bio; } bio = bio->next_bio; } while (bio != NULL); - return (NULL); + return NULL; } BIO *BIO_next(BIO *b) @@ -518,6 +703,7 @@ BIO *BIO_dup_chain(BIO *in) if ((new_bio = BIO_new(bio->method)) == NULL) goto err; new_bio->callback = bio->callback; + new_bio->callback_ex = bio->callback_ex; new_bio->cb_arg = bio->cb_arg; new_bio->init = bio->init; new_bio->shutdown = bio->shutdown; @@ -546,11 +732,11 @@ BIO *BIO_dup_chain(BIO *in) eoc = new_bio; } } - return (ret); + return ret; err: BIO_free_all(ret); - return (NULL); + return NULL; } void BIO_copy_next_retry(BIO *b) @@ -561,12 +747,12 @@ void BIO_copy_next_retry(BIO *b) int BIO_set_ex_data(BIO *bio, int idx, void *data) { - return (CRYPTO_set_ex_data(&(bio->ex_data), idx, data)); + return CRYPTO_set_ex_data(&(bio->ex_data), idx, data); } void *BIO_get_ex_data(BIO *bio, int idx) { - return (CRYPTO_get_ex_data(&(bio->ex_data), idx)); + return CRYPTO_get_ex_data(&(bio->ex_data), idx); } uint64_t BIO_number_read(BIO *bio) diff --git a/crypto/bio/bio_meth.c b/crypto/bio/bio_meth.c index 1e785d34..4c157c07 100644 --- a/crypto/bio/bio_meth.c +++ b/crypto/bio/bio_meth.c @@ -8,7 +8,7 @@ */ #include "bio_lcl.h" -#include +#include "internal/thread_once.h" CRYPTO_RWLOCK *bio_type_lock = NULL; static CRYPTO_ONCE bio_type_init = CRYPTO_ONCE_STATIC_INIT; @@ -21,14 +21,14 @@ DEFINE_RUN_ONCE_STATIC(do_bio_type_init) int BIO_get_new_index() { - static int bio_count = BIO_TYPE_START; + static CRYPTO_REF_COUNT bio_count = BIO_TYPE_START; int newval; if (!RUN_ONCE(&bio_type_init, do_bio_type_init)) { BIOerr(BIO_F_BIO_GET_NEW_INDEX, ERR_R_MALLOC_FAILURE); return -1; } - if (!CRYPTO_atomic_add(&bio_count, 1, &newval, bio_type_lock)) + if (!CRYPTO_UP_REF(&bio_count, &newval, bio_type_lock)) return -1; return newval; } @@ -43,6 +43,7 @@ BIO_METHOD *BIO_meth_new(int type, const char *name) BIOerr(BIO_F_BIO_METH_NEW, ERR_R_MALLOC_FAILURE); return NULL; } + biom->type = type; return biom; } @@ -55,25 +56,94 @@ void BIO_meth_free(BIO_METHOD *biom) } int (*BIO_meth_get_write(BIO_METHOD *biom)) (BIO *, const char *, int) +{ + return biom->bwrite_old; +} + +int (*BIO_meth_get_write_ex(BIO_METHOD *biom)) (BIO *, const char *, size_t, + size_t *) { return biom->bwrite; } +/* Conversion for old style bwrite to new style */ +int bwrite_conv(BIO *bio, const char *data, size_t datal, size_t *written) +{ + int ret; + + if (datal > INT_MAX) + datal = INT_MAX; + + ret = bio->method->bwrite_old(bio, data, (int)datal); + + if (ret <= 0) { + *written = 0; + return ret; + } + + *written = (size_t)ret; + + return 1; +} + int BIO_meth_set_write(BIO_METHOD *biom, int (*bwrite) (BIO *, const char *, int)) { + biom->bwrite_old = bwrite; + biom->bwrite = bwrite_conv; + return 1; +} + +int BIO_meth_set_write_ex(BIO_METHOD *biom, + int (*bwrite) (BIO *, const char *, size_t, size_t *)) +{ + biom->bwrite_old = NULL; biom->bwrite = bwrite; return 1; } int (*BIO_meth_get_read(BIO_METHOD *biom)) (BIO *, char *, int) +{ + return biom->bread_old; +} + +int (*BIO_meth_get_read_ex(BIO_METHOD *biom)) (BIO *, char *, size_t, size_t *) { return biom->bread; } +/* Conversion for old style bread to new style */ +int bread_conv(BIO *bio, char *data, size_t datal, size_t *readbytes) +{ + int ret; + + if (datal > INT_MAX) + datal = INT_MAX; + + ret = bio->method->bread_old(bio, data, (int)datal); + + if (ret <= 0) { + *readbytes = 0; + return ret; + } + + *readbytes = (size_t)ret; + + return 1; +} + int BIO_meth_set_read(BIO_METHOD *biom, int (*bread) (BIO *, char *, int)) { + biom->bread_old = bread; + biom->bread = bread_conv; + return 1; +} + +int BIO_meth_set_read_ex(BIO_METHOD *biom, + int (*bread) (BIO *, char *, size_t, size_t *)) +{ + biom->bread_old = NULL; biom->bread = bread; return 1; } diff --git a/crypto/bio/bss_acpt.c b/crypto/bio/bss_acpt.c index 21d21c16..b7ec0c0d 100644 --- a/crypto/bio/bss_acpt.c +++ b/crypto/bio/bss_acpt.c @@ -54,7 +54,11 @@ static void BIO_ACCEPT_free(BIO_ACCEPT *a); static const BIO_METHOD methods_acceptp = { BIO_TYPE_ACCEPT, "socket accept", + /* TODO: Convert to new style write function */ + bwrite_conv, acpt_write, + /* TODO: Convert to new style read function */ + bread_conv, acpt_read, acpt_puts, NULL, /* connect_gets, */ @@ -66,7 +70,7 @@ static const BIO_METHOD methods_acceptp = { const BIO_METHOD *BIO_s_accept(void) { - return (&methods_acceptp); + return &methods_acceptp; } static int acpt_new(BIO *bi) @@ -77,11 +81,11 @@ static int acpt_new(BIO *bi) bi->num = (int)INVALID_SOCKET; bi->flags = 0; if ((ba = BIO_ACCEPT_new()) == NULL) - return (0); + return 0; bi->ptr = (char *)ba; ba->state = ACPT_S_BEFORE; bi->shutdown = 1; - return (1); + return 1; } static BIO_ACCEPT *BIO_ACCEPT_new(void) @@ -89,10 +93,10 @@ static BIO_ACCEPT *BIO_ACCEPT_new(void) BIO_ACCEPT *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) - return (NULL); + return NULL; ret->accept_family = BIO_FAMILY_IPANY; ret->accept_sock = (int)INVALID_SOCKET; - return (ret); + return ret; } static void BIO_ACCEPT_free(BIO_ACCEPT *a) @@ -129,7 +133,7 @@ static int acpt_free(BIO *a) BIO_ACCEPT *data; if (a == NULL) - return (0); + return 0; data = (BIO_ACCEPT *)a->ptr; if (a->shutdown) { @@ -139,7 +143,7 @@ static int acpt_free(BIO *a) a->flags = 0; a->init = 0; } - return (1); + return 1; } static int acpt_state(BIO *b, BIO_ACCEPT *c) @@ -360,12 +364,12 @@ static int acpt_read(BIO *b, char *out, int outl) while (b->next_bio == NULL) { ret = acpt_state(b, data); if (ret <= 0) - return (ret); + return ret; } ret = BIO_read(b->next_bio, out, outl); BIO_copy_next_retry(b); - return (ret); + return ret; } static int acpt_write(BIO *b, const char *in, int inl) @@ -379,12 +383,12 @@ static int acpt_write(BIO *b, const char *in, int inl) while (b->next_bio == NULL) { ret = acpt_state(b, data); if (ret <= 0) - return (ret); + return ret; } ret = BIO_write(b->next_bio, in, inl); BIO_copy_next_retry(b); - return (ret); + return ret; } static long acpt_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -451,7 +455,6 @@ static long acpt_ctrl(BIO *b, int cmd, long num, void *ptr) data->accepted_mode &= ~BIO_SOCK_NONBLOCK; break; case BIO_C_SET_FD: - b->init = 1; b->num = *((int *)ptr); data->accept_sock = b->num; data->state = ACPT_S_ACCEPT; @@ -522,19 +525,13 @@ static long acpt_ctrl(BIO *b, int cmd, long num, void *ptr) ret = (long)data->bind_mode; break; case BIO_CTRL_DUP: -/*- dbio=(BIO *)ptr; - if (data->param_port) EAY EAY - BIO_set_port(dbio,data->param_port); - if (data->param_hostname) - BIO_set_hostname(dbio,data->param_hostname); - BIO_set_nbio(dbio,data->nbio); */ break; default: ret = 0; break; } - return (ret); + return ret; } static int acpt_puts(BIO *bp, const char *str) @@ -543,7 +540,7 @@ static int acpt_puts(BIO *bp, const char *str) n = strlen(str); ret = acpt_write(bp, str, n); - return (ret); + return ret; } BIO *BIO_new_accept(const char *str) @@ -552,11 +549,11 @@ BIO *BIO_new_accept(const char *str) ret = BIO_new(BIO_s_accept()); if (ret == NULL) - return (NULL); + return NULL; if (BIO_set_accept_name(ret, str)) - return (ret); + return ret; BIO_free(ret); - return (NULL); + return NULL; } #endif diff --git a/crypto/bio/bss_bio.c b/crypto/bio/bss_bio.c index de34f6bf..e34382c5 100644 --- a/crypto/bio/bss_bio.c +++ b/crypto/bio/bss_bio.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-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 @@ -15,6 +15,7 @@ * See ssl/ssltest.c for some hints on how this can be used. */ +#include "e_os.h" #include #include #include @@ -24,8 +25,6 @@ #include #include -#include "e_os.h" - static int bio_new(BIO *bio); static int bio_free(BIO *bio); static int bio_read(BIO *bio, char *buf, int size); @@ -39,7 +38,11 @@ static void bio_destroy_pair(BIO *bio); static const BIO_METHOD methods_biop = { BIO_TYPE_BIO, "BIO pair", + /* TODO: Convert to new style write function */ + bwrite_conv, bio_write, + /* TODO: Convert to new style read function */ + bread_conv, bio_read, bio_puts, NULL /* no bio_gets */ , diff --git a/crypto/bio/bss_conn.c b/crypto/bio/bss_conn.c index e343bcdd..5c461ae7 100644 --- a/crypto/bio/bss_conn.c +++ b/crypto/bio/bss_conn.c @@ -58,7 +58,11 @@ void BIO_CONNECT_free(BIO_CONNECT *a); static const BIO_METHOD methods_connectp = { BIO_TYPE_CONNECT, "socket connect", + /* TODO: Convert to new style write function */ + bwrite_conv, conn_write, + /* TODO: Convert to new style read function */ + bread_conv, conn_read, conn_puts, NULL, /* conn_gets, */ @@ -212,7 +216,7 @@ static int conn_state(BIO *b, BIO_CONNECT *c) if (cb != NULL) ret = cb((BIO *)b, c->state, ret); end: - return (ret); + return ret; } BIO_CONNECT *BIO_CONNECT_new(void) @@ -220,10 +224,10 @@ BIO_CONNECT *BIO_CONNECT_new(void) BIO_CONNECT *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) - return (NULL); + return NULL; ret->state = BIO_CONN_S_BEFORE; ret->connect_family = BIO_FAMILY_IPANY; - return (ret); + return ret; } void BIO_CONNECT_free(BIO_CONNECT *a) @@ -239,7 +243,7 @@ void BIO_CONNECT_free(BIO_CONNECT *a) const BIO_METHOD *BIO_s_connect(void) { - return (&methods_connectp); + return &methods_connectp; } static int conn_new(BIO *bi) @@ -248,9 +252,9 @@ static int conn_new(BIO *bi) bi->num = (int)INVALID_SOCKET; bi->flags = 0; if ((bi->ptr = (char *)BIO_CONNECT_new()) == NULL) - return (0); + return 0; else - return (1); + return 1; } static void conn_close_socket(BIO *bio) @@ -272,7 +276,7 @@ static int conn_free(BIO *a) BIO_CONNECT *data; if (a == NULL) - return (0); + return 0; data = (BIO_CONNECT *)a->ptr; if (a->shutdown) { @@ -282,7 +286,7 @@ static int conn_free(BIO *a) a->flags = 0; a->init = 0; } - return (1); + return 1; } static int conn_read(BIO *b, char *out, int outl) @@ -294,7 +298,7 @@ static int conn_read(BIO *b, char *out, int outl) if (data->state != BIO_CONN_S_OK) { ret = conn_state(b, data); if (ret <= 0) - return (ret); + return ret; } if (out != NULL) { @@ -306,7 +310,7 @@ static int conn_read(BIO *b, char *out, int outl) BIO_set_retry_read(b); } } - return (ret); + return ret; } static int conn_write(BIO *b, const char *in, int inl) @@ -318,7 +322,7 @@ static int conn_write(BIO *b, const char *in, int inl) if (data->state != BIO_CONN_S_OK) { ret = conn_state(b, data); if (ret <= 0) - return (ret); + return ret; } clear_socket_error(); @@ -328,7 +332,7 @@ static int conn_write(BIO *b, const char *in, int inl) if (BIO_sock_should_retry(ret)) BIO_set_retry_write(b); } - return (ret); + return ret; } static long conn_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -473,15 +477,7 @@ static long conn_ctrl(BIO *b, int cmd, long num, void *ptr) } 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 - } + ret = 0; /* use callback ctrl */ break; case BIO_CTRL_GET_CALLBACK: { @@ -495,7 +491,7 @@ static long conn_ctrl(BIO *b, int cmd, long num, void *ptr) ret = 0; break; } - return (ret); + return ret; } static long conn_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) @@ -515,7 +511,7 @@ static long conn_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) ret = 0; break; } - return (ret); + return ret; } static int conn_puts(BIO *bp, const char *str) @@ -524,7 +520,7 @@ static int conn_puts(BIO *bp, const char *str) n = strlen(str); ret = conn_write(bp, str, n); - return (ret); + return ret; } BIO *BIO_new_connect(const char *str) @@ -533,11 +529,11 @@ BIO *BIO_new_connect(const char *str) ret = BIO_new(BIO_s_connect()); if (ret == NULL) - return (NULL); + return NULL; if (BIO_set_conn_hostname(ret, str)) - return (ret); + return ret; BIO_free(ret); - return (NULL); + return NULL; } #endif diff --git a/crypto/bio/bss_dgram.c b/crypto/bio/bss_dgram.c index c772d956..90b250eb 100644 --- a/crypto/bio/bss_dgram.c +++ b/crypto/bio/bss_dgram.c @@ -1,5 +1,5 @@ /* - * Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2005-2018 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 @@ -13,13 +13,6 @@ #include "bio_lcl.h" #ifndef OPENSSL_NO_DGRAM -# if !(defined(_WIN32) || defined(OPENSSL_SYS_VMS)) -# include -# endif -# if defined(OPENSSL_SYS_VMS) -# include -# endif - # ifndef OPENSSL_NO_SCTP # include # include @@ -73,7 +66,11 @@ static void get_current_time(struct timeval *t); static const BIO_METHOD methods_dgramp = { BIO_TYPE_DGRAM, "datagram socket", + /* TODO: Convert to new style write function */ + bwrite_conv, dgram_write, + /* TODO: Convert to new style read function */ + bread_conv, dgram_read, dgram_puts, NULL, /* dgram_gets, */ @@ -87,7 +84,11 @@ static const BIO_METHOD methods_dgramp = { static const BIO_METHOD methods_dgramp_sctp = { BIO_TYPE_DGRAM_SCTP, "datagram sctp socket", + /* TODO: Convert to new style write function */ + bwrite_conv, dgram_sctp_write, + /* TODO: Convert to new style write function */ + bread_conv, dgram_sctp_read, dgram_sctp_puts, NULL, /* dgram_gets, */ @@ -135,7 +136,7 @@ typedef struct bio_dgram_sctp_data_st { const BIO_METHOD *BIO_s_datagram(void) { - return (&methods_dgramp); + return &methods_dgramp; } BIO *BIO_new_dgram(int fd, int close_flag) @@ -144,9 +145,9 @@ BIO *BIO_new_dgram(int fd, int close_flag) ret = BIO_new(BIO_s_datagram()); if (ret == NULL) - return (NULL); + return NULL; BIO_set_fd(ret, fd, close_flag); - return (ret); + return ret; } static int dgram_new(BIO *bi) @@ -156,7 +157,7 @@ static int dgram_new(BIO *bi) if (data == NULL) return 0; bi->ptr = data; - return (1); + return 1; } static int dgram_free(BIO *a) @@ -164,20 +165,20 @@ static int dgram_free(BIO *a) bio_dgram_data *data; if (a == NULL) - return (0); + return 0; if (!dgram_clear(a)) return 0; data = (bio_dgram_data *)a->ptr; OPENSSL_free(data); - return (1); + return 1; } static int dgram_clear(BIO *a) { if (a == NULL) - return (0); + return 0; if (a->shutdown) { if (a->init) { BIO_closesocket(a->num); @@ -185,7 +186,7 @@ static int dgram_clear(BIO *a) a->init = 0; a->flags = 0; } - return (1); + return 1; } static void dgram_adjust_rcv_timeout(BIO *b) @@ -324,7 +325,7 @@ static int dgram_read(BIO *b, char *out, int outl) dgram_reset_rcv_timeout(b); } - return (ret); + return ret; } static int dgram_write(BIO *b, const char *in, int inl) @@ -338,13 +339,8 @@ static int dgram_write(BIO *b, const char *in, int inl) else { int peerlen = BIO_ADDR_sockaddr_size(&data->peer); -# if defined(NETWARE_CLIB) && defined(NETWARE_BSDSOCK) - ret = sendto(b->num, (char *)in, inl, 0, - BIO_ADDR_sockaddr(&data->peer), peerlen); -# else ret = sendto(b->num, in, inl, 0, BIO_ADDR_sockaddr(&data->peer), peerlen); -# endif } BIO_clear_retry_flags(b); @@ -354,7 +350,7 @@ static int dgram_write(BIO *b, const char *in, int inl) data->_errno = get_last_socket_error(); } } - return (ret); + return ret; } static long dgram_get_mtu_overhead(bio_dgram_data *data) @@ -798,7 +794,7 @@ static long dgram_ctrl(BIO *b, int cmd, long num, void *ptr) ret = 0; break; } - return (ret); + return ret; } static int dgram_puts(BIO *bp, const char *str) @@ -807,13 +803,13 @@ static int dgram_puts(BIO *bp, const char *str) n = strlen(str); ret = dgram_write(bp, str, n); - return (ret); + return ret; } # ifndef OPENSSL_NO_SCTP const BIO_METHOD *BIO_s_datagram_sctp(void) { - return (&methods_dgramp_sctp); + return &methods_dgramp_sctp; } BIO *BIO_new_dgram_sctp(int fd, int close_flag) @@ -835,7 +831,7 @@ BIO *BIO_new_dgram_sctp(int fd, int close_flag) bio = BIO_new(BIO_s_datagram_sctp()); if (bio == NULL) - return (NULL); + return NULL; BIO_set_fd(bio, fd, close_flag); /* Activate SCTP-AUTH for DATA and FORWARD-TSN chunks */ @@ -845,7 +841,9 @@ BIO *BIO_new_dgram_sctp(int fd, int close_flag) sizeof(struct sctp_authchunk)); if (ret < 0) { BIO_vfree(bio); - return (NULL); + BIOerr(BIO_F_BIO_NEW_DGRAM_SCTP, ERR_R_SYS_LIB); + ERR_add_error_data(1, "Ensure SCTP AUTH chunks are enabled in kernel"); + return NULL; } auth.sauth_chunk = OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE; ret = @@ -853,26 +851,29 @@ BIO *BIO_new_dgram_sctp(int fd, int close_flag) sizeof(struct sctp_authchunk)); if (ret < 0) { BIO_vfree(bio); - return (NULL); + BIOerr(BIO_F_BIO_NEW_DGRAM_SCTP, ERR_R_SYS_LIB); + ERR_add_error_data(1, "Ensure SCTP AUTH chunks are enabled in kernel"); + return NULL; } /* * Test if activation was successful. When using accept(), SCTP-AUTH has * to be activated for the listening socket already, otherwise the - * connected socket won't use it. + * connected socket won't use it. Similarly with connect(): the socket + * prior to connection must be activated for SCTP-AUTH */ sockopt_len = (socklen_t) (sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t)); authchunks = OPENSSL_zalloc(sockopt_len); if (authchunks == NULL) { BIO_vfree(bio); - return (NULL); + return NULL; } ret = getsockopt(fd, IPPROTO_SCTP, SCTP_LOCAL_AUTH_CHUNKS, authchunks, &sockopt_len); if (ret < 0) { OPENSSL_free(authchunks); BIO_vfree(bio); - return (NULL); + return NULL; } for (p = (unsigned char *)authchunks->gauth_chunks; @@ -886,8 +887,14 @@ BIO *BIO_new_dgram_sctp(int fd, int close_flag) OPENSSL_free(authchunks); - OPENSSL_assert(auth_data); - OPENSSL_assert(auth_forward); + if (!auth_data || !auth_forward) { + BIO_vfree(bio); + BIOerr(BIO_F_BIO_NEW_DGRAM_SCTP, ERR_R_SYS_LIB); + ERR_add_error_data(1, + "Ensure SCTP AUTH chunks are enabled on the " + "underlying socket"); + return NULL; + } # ifdef SCTP_AUTHENTICATION_EVENT # ifdef SCTP_EVENT @@ -900,14 +907,14 @@ BIO *BIO_new_dgram_sctp(int fd, int close_flag) sizeof(struct sctp_event)); if (ret < 0) { BIO_vfree(bio); - return (NULL); + return NULL; } # else sockopt_len = (socklen_t) sizeof(struct sctp_event_subscribe); ret = getsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event, &sockopt_len); if (ret < 0) { BIO_vfree(bio); - return (NULL); + return NULL; } event.sctp_authentication_event = 1; @@ -917,7 +924,7 @@ BIO *BIO_new_dgram_sctp(int fd, int close_flag) sizeof(struct sctp_event_subscribe)); if (ret < 0) { BIO_vfree(bio); - return (NULL); + return NULL; } # endif # endif @@ -931,10 +938,10 @@ BIO *BIO_new_dgram_sctp(int fd, int close_flag) sizeof(optval)); if (ret < 0) { BIO_vfree(bio); - return (NULL); + return NULL; } - return (bio); + return bio; } int BIO_dgram_is_sctp(BIO *bio) @@ -957,7 +964,7 @@ static int dgram_sctp_new(BIO *bi) bi->ptr = data; bi->flags = 0; - return (1); + return 1; } static int dgram_sctp_free(BIO *a) @@ -965,7 +972,7 @@ static int dgram_sctp_free(BIO *a) bio_dgram_sctp_data *data; if (a == NULL) - return (0); + return 0; if (!dgram_clear(a)) return 0; @@ -973,7 +980,7 @@ static int dgram_sctp_free(BIO *a) if (data != NULL) OPENSSL_free(data); - return (1); + return 1; } # ifdef SCTP_AUTHENTICATION_EVENT @@ -1210,7 +1217,7 @@ static int dgram_sctp_read(BIO *b, char *out, int outl) data->peer_auth_tested = 1; } } - return (ret); + return ret; } /* @@ -1326,7 +1333,7 @@ static int dgram_sctp_write(BIO *b, const char *in, int inl) data->_errno = get_last_socket_error(); } } - return (ret); + return ret; } static long dgram_sctp_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -1562,7 +1569,7 @@ static long dgram_sctp_ctrl(BIO *b, int cmd, long num, void *ptr) ret = dgram_ctrl(b, cmd, num, ptr); break; } - return (ret); + return ret; } int BIO_dgram_sctp_notification_cb(BIO *b, @@ -1819,7 +1826,7 @@ static int dgram_sctp_puts(BIO *bp, const char *str) n = strlen(str); ret = dgram_sctp_write(bp, str, n); - return (ret); + return ret; } # endif @@ -1838,9 +1845,9 @@ static int BIO_dgram_should_retry(int i) */ # endif - return (BIO_dgram_non_fatal_error(err)); + return BIO_dgram_non_fatal_error(err); } - return (0); + return 0; } int BIO_dgram_non_fatal_error(int err) @@ -1884,12 +1891,11 @@ int BIO_dgram_non_fatal_error(int err) case EALREADY: # endif - return (1); - /* break; */ + return 1; default: break; } - return (0); + return 0; } static void get_current_time(struct timeval *t) @@ -1910,11 +1916,6 @@ static void get_current_time(struct timeval *t) # 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 diff --git a/crypto/bio/bss_fd.c b/crypto/bio/bss_fd.c index 2bd3517d..5bc539c9 100644 --- a/crypto/bio/bss_fd.c +++ b/crypto/bio/bss_fd.c @@ -60,7 +60,11 @@ int BIO_fd_should_retry(int s); static const BIO_METHOD methods_fdp = { BIO_TYPE_FD, "file descriptor", + /* TODO: Convert to new style write function */ + bwrite_conv, fd_write, + /* TODO: Convert to new style read function */ + bread_conv, fd_read, fd_puts, fd_gets, @@ -72,7 +76,7 @@ static const BIO_METHOD methods_fdp = { const BIO_METHOD *BIO_s_fd(void) { - return (&methods_fdp); + return &methods_fdp; } BIO *BIO_new_fd(int fd, int close_flag) @@ -80,9 +84,9 @@ BIO *BIO_new_fd(int fd, int close_flag) BIO *ret; ret = BIO_new(BIO_s_fd()); if (ret == NULL) - return (NULL); + return NULL; BIO_set_fd(ret, fd, close_flag); - return (ret); + return ret; } static int fd_new(BIO *bi) @@ -91,13 +95,13 @@ static int fd_new(BIO *bi) bi->num = -1; bi->ptr = NULL; bi->flags = BIO_FLAGS_UPLINK; /* essentially redundant */ - return (1); + return 1; } static int fd_free(BIO *a) { if (a == NULL) - return (0); + return 0; if (a->shutdown) { if (a->init) { UP_close(a->num); @@ -105,7 +109,7 @@ static int fd_free(BIO *a) a->init = 0; a->flags = BIO_FLAGS_UPLINK; } - return (1); + return 1; } static int fd_read(BIO *b, char *out, int outl) @@ -121,7 +125,7 @@ static int fd_read(BIO *b, char *out, int outl) BIO_set_retry_read(b); } } - return (ret); + return ret; } static int fd_write(BIO *b, const char *in, int inl) @@ -134,7 +138,7 @@ static int fd_write(BIO *b, const char *in, int inl) if (BIO_fd_should_retry(ret)) BIO_set_retry_write(b); } - return (ret); + return ret; } static long fd_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -186,7 +190,7 @@ static long fd_ctrl(BIO *b, int cmd, long num, void *ptr) ret = 0; break; } - return (ret); + return ret; } static int fd_puts(BIO *bp, const char *str) @@ -195,7 +199,7 @@ static int fd_puts(BIO *bp, const char *str) n = strlen(str); ret = fd_write(bp, str, n); - return (ret); + return ret; } static int fd_gets(BIO *bp, char *buf, int size) @@ -204,14 +208,16 @@ static int fd_gets(BIO *bp, char *buf, int size) char *ptr = buf; char *end = buf + size - 1; - while ((ptr < end) && (fd_read(bp, ptr, 1) > 0) && (ptr[0] != '\n')) - ptr++; + while (ptr < end && fd_read(bp, ptr, 1) > 0) { + if (*ptr++ == '\n') + break; + } ptr[0] = '\0'; if (buf[0] != '\0') ret = strlen(buf); - return (ret); + return ret; } int BIO_fd_should_retry(int i) @@ -221,9 +227,9 @@ int BIO_fd_should_retry(int i) if ((i == 0) || (i == -1)) { err = get_last_sys_error(); - return (BIO_fd_non_fatal_error(err)); + return BIO_fd_non_fatal_error(err); } - return (0); + return 0; } int BIO_fd_non_fatal_error(int err) @@ -265,11 +271,10 @@ int BIO_fd_non_fatal_error(int err) # ifdef EALREADY case EALREADY: # endif - return (1); - /* break; */ + return 1; default: break; } - return (0); + return 0; } #endif diff --git a/crypto/bio/bss_file.c b/crypto/bio/bss_file.c index 2edf2448..8de23912 100644 --- a/crypto/bio/bss_file.c +++ b/crypto/bio/bss_file.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -7,12 +7,6 @@ * https://www.openssl.org/source/license.html */ -/*- - * 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 @@ -51,7 +45,11 @@ static int file_free(BIO *data); static const BIO_METHOD methods_filep = { BIO_TYPE_FILE, "FILE pointer", + /* TODO: Convert to new style write function */ + bwrite_conv, file_write, + /* TODO: Convert to new style read function */ + bread_conv, file_read, file_puts, file_gets, @@ -81,17 +79,17 @@ BIO *BIO_new_file(const char *filename, const char *mode) BIOerr(BIO_F_BIO_NEW_FILE, BIO_R_NO_SUCH_FILE); else BIOerr(BIO_F_BIO_NEW_FILE, ERR_R_SYS_LIB); - return (NULL); + return NULL; } if ((ret = BIO_new(BIO_s_file())) == NULL) { fclose(file); - return (NULL); + return NULL; } BIO_clear_flags(ret, BIO_FLAGS_UPLINK); /* we did fopen -> we disengage * UPLINK */ BIO_set_fp(ret, file, fp_flags); - return (ret); + return ret; } BIO *BIO_new_fp(FILE *stream, int close_flag) @@ -99,17 +97,17 @@ BIO *BIO_new_fp(FILE *stream, int close_flag) BIO *ret; if ((ret = BIO_new(BIO_s_file())) == NULL) - return (NULL); + return NULL; /* redundant flag, left for documentation purposes */ BIO_set_flags(ret, BIO_FLAGS_UPLINK); BIO_set_fp(ret, stream, close_flag); - return (ret); + return ret; } const BIO_METHOD *BIO_s_file(void) { - return (&methods_filep); + return &methods_filep; } static int file_new(BIO *bi) @@ -118,13 +116,13 @@ static int file_new(BIO *bi) bi->num = 0; bi->ptr = NULL; bi->flags = BIO_FLAGS_UPLINK; /* default to UPLINK */ - return (1); + return 1; } static int file_free(BIO *a) { if (a == NULL) - return (0); + return 0; if (a->shutdown) { if ((a->init) && (a->ptr != NULL)) { if (a->flags & BIO_FLAGS_UPLINK) @@ -136,7 +134,7 @@ static int file_free(BIO *a) } a->init = 0; } - return (1); + return 1; } static int file_read(BIO *b, char *out, int outl) @@ -156,7 +154,7 @@ static int file_read(BIO *b, char *out, int outl) ret = -1; } } - return (ret); + return ret; } static int file_write(BIO *b, const char *in, int inl) @@ -172,12 +170,12 @@ static int file_write(BIO *b, const char *in, int inl) ret = inl; /* ret=fwrite(in,1,(int)inl,(FILE *)b->ptr); */ /* - * according to Tim Hudson , the commented out + * according to Tim Hudson , the commented out * version above can cause 'inl' write calls under some stupid stdio * implementations (VMS) */ } - return (ret); + return ret; } static long file_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -283,9 +281,9 @@ static long file_ctrl(BIO *b, int cmd, long num, void *ptr) } # if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32_CYGWIN) if (!(num & BIO_FP_TEXT)) - strcat(p, "b"); + OPENSSL_strlcat(p, "b", sizeof(p)); else - strcat(p, "t"); + OPENSSL_strlcat(p, "t", sizeof(p)); # endif fp = openssl_fopen(ptr, p); if (fp == NULL) { @@ -335,7 +333,7 @@ static long file_ctrl(BIO *b, int cmd, long num, void *ptr) ret = 0; break; } - return (ret); + return ret; } static int file_gets(BIO *bp, char *buf, int size) @@ -353,7 +351,7 @@ static int file_gets(BIO *bp, char *buf, int size) if (buf[0] != '\0') ret = strlen(buf); err: - return (ret); + return ret; } static int file_puts(BIO *bp, const char *str) @@ -362,7 +360,7 @@ static int file_puts(BIO *bp, const char *str) n = strlen(str); ret = file_write(bp, str, n); - return (ret); + return ret; } #else @@ -399,7 +397,11 @@ static int file_free(BIO *a) static const BIO_METHOD methods_filep = { BIO_TYPE_FILE, "FILE pointer", + /* TODO: Convert to new style write function */ + bwrite_conv, file_write, + /* TODO: Convert to new style read function */ + bread_conv, file_read, file_puts, file_gets, @@ -411,7 +413,7 @@ static const BIO_METHOD methods_filep = { const BIO_METHOD *BIO_s_file(void) { - return (&methods_filep); + return &methods_filep; } BIO *BIO_new_file(const char *filename, const char *mode) diff --git a/crypto/bio/bss_log.c b/crypto/bio/bss_log.c index 5221acc2..b04f7bbf 100644 --- a/crypto/bio/bss_log.c +++ b/crypto/bio/bss_log.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-2018 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 @@ -39,8 +39,6 @@ void *_malloc32(__size_t); # endif /* __INITIAL_POINTER_SIZE == 64 */ # endif /* __INITIAL_POINTER_SIZE && defined * _ANSI_C_SOURCE */ -#elif defined(OPENSSL_SYS_NETWARE) -# define NO_SYSLOG #elif (!defined(MSDOS) || defined(WATT32)) && !defined(OPENSSL_SYS_VXWORKS) && !defined(NO_SYSLOG) # include #endif @@ -87,10 +85,13 @@ static void xcloselog(BIO *bp); static const BIO_METHOD methods_slg = { BIO_TYPE_MEM, "syslog", + /* TODO: Convert to new style write function */ + bwrite_conv, slg_write, + NULL, /* slg_write_old, */ NULL, /* slg_read, */ slg_puts, - NULL, /* slg_gets, */ + NULL, slg_ctrl, slg_new, slg_free, @@ -99,7 +100,7 @@ static const BIO_METHOD methods_slg = { const BIO_METHOD *BIO_s_log(void) { - return (&methods_slg); + return &methods_slg; } static int slg_new(BIO *bi) @@ -108,15 +109,15 @@ static int slg_new(BIO *bi) bi->num = 0; bi->ptr = NULL; xopenlog(bi, "application", LOG_DAEMON); - return (1); + return 1; } static int slg_free(BIO *a) { if (a == NULL) - return (0); + return 0; xcloselog(a); - return (1); + return 1; } static int slg_write(BIO *b, const char *in, int inl) @@ -194,7 +195,7 @@ static int slg_write(BIO *b, const char *in, int inl) }; if ((buf = OPENSSL_malloc(inl + 1)) == NULL) { - return (0); + return 0; } strncpy(buf, in, inl); buf[inl] = '\0'; @@ -208,7 +209,7 @@ static int slg_write(BIO *b, const char *in, int inl) xsyslog(b, priority, pp); OPENSSL_free(buf); - return (ret); + return ret; } static long slg_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -221,7 +222,7 @@ static long slg_ctrl(BIO *b, int cmd, long num, void *ptr) default: break; } - return (0); + return 0; } static int slg_puts(BIO *bp, const char *str) @@ -230,7 +231,7 @@ static int slg_puts(BIO *bp, const char *str) n = strlen(str); ret = slg_write(bp, str, n); - return (ret); + return ret; } # if defined(OPENSSL_SYS_WIN32) diff --git a/crypto/bio/bss_mem.c b/crypto/bio/bss_mem.c index ff9a3ebb..7678a1df 100644 --- a/crypto/bio/bss_mem.c +++ b/crypto/bio/bss_mem.c @@ -26,7 +26,11 @@ static int mem_buf_sync(BIO *h); static const BIO_METHOD mem_method = { BIO_TYPE_MEM, "memory buffer", + /* TODO: Convert to new style write function */ + bwrite_conv, mem_write, + /* TODO: Convert to new style read function */ + bread_conv, mem_read, mem_puts, mem_gets, @@ -39,7 +43,11 @@ static const BIO_METHOD mem_method = { static const BIO_METHOD secmem_method = { BIO_TYPE_MEM, "secure memory buffer", + /* TODO: Convert to new style write function */ + bwrite_conv, mem_write, + /* TODO: Convert to new style read function */ + bread_conv, mem_read, mem_puts, mem_gets, @@ -62,7 +70,7 @@ typedef struct bio_buf_mem_st { const BIO_METHOD *BIO_s_mem(void) { - return (&mem_method); + return &mem_method; } const BIO_METHOD *BIO_s_secmem(void) @@ -122,42 +130,38 @@ static int mem_init(BIO *bi, unsigned long flags) static int mem_new(BIO *bi) { - return (mem_init(bi, 0L)); + return mem_init(bi, 0L); } static int secmem_new(BIO *bi) { - return (mem_init(bi, BUF_MEM_FLAG_SECURE)); + return mem_init(bi, BUF_MEM_FLAG_SECURE); } static int mem_free(BIO *a) { - return (mem_buf_free(a, 1)); + return mem_buf_free(a, 1); } static int mem_buf_free(BIO *a, int free_all) { if (a == NULL) - return (0); - if (a->shutdown) { - if ((a->init) && (a->ptr != NULL)) { - BUF_MEM *b; - BIO_BUF_MEM *bb = (BIO_BUF_MEM *)a->ptr; + return 0; - if (bb != NULL) { - b = bb->buf; - if (a->flags & BIO_FLAGS_MEM_RDONLY) - b->data = NULL; - BUF_MEM_free(b); - if (free_all) { - OPENSSL_free(bb->readp); - OPENSSL_free(bb); - } - } - a->ptr = NULL; + if (a->shutdown && a->init && a->ptr != NULL) { + BIO_BUF_MEM *bb = (BIO_BUF_MEM *)a->ptr; + BUF_MEM *b = bb->buf; + + if (a->flags & BIO_FLAGS_MEM_RDONLY) + b->data = NULL; + BUF_MEM_free(b); + if (free_all) { + OPENSSL_free(bb->readp); + OPENSSL_free(bb); } + a->ptr = NULL; } - return (1); + return 1; } /* @@ -174,7 +178,7 @@ static int mem_buf_sync(BIO *b) bbm->readp->data = bbm->buf->data; } } - return (0); + return 0; } static int mem_read(BIO *b, char *out, int outl) @@ -194,7 +198,7 @@ static int mem_read(BIO *b, char *out, int outl) if (ret != 0) BIO_set_retry_read(b); } - return (ret); + return ret; } static int mem_write(BIO *b, const char *in, int inl) @@ -220,7 +224,7 @@ static int mem_write(BIO *b, const char *in, int inl) *bbm->readp = *bbm->buf; ret = inl; end: - return (ret); + return ret; } static long mem_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -297,7 +301,7 @@ static long mem_ctrl(BIO *b, int cmd, long num, void *ptr) ret = 0; break; } - return (ret); + return ret; } static int mem_gets(BIO *bp, char *buf, int size) @@ -333,7 +337,7 @@ static int mem_gets(BIO *bp, char *buf, int size) if (i > 0) buf[i] = '\0'; ret = i; - return (ret); + return ret; } static int mem_puts(BIO *bp, const char *str) @@ -343,5 +347,5 @@ static int mem_puts(BIO *bp, const char *str) n = strlen(str); ret = mem_write(bp, str, n); /* memory semantics is that it will always work */ - return (ret); + return ret; } diff --git a/crypto/bio/bss_null.c b/crypto/bio/bss_null.c index 56f95f9f..08f1d2bc 100644 --- a/crypto/bio/bss_null.c +++ b/crypto/bio/bss_null.c @@ -20,7 +20,11 @@ static long null_ctrl(BIO *h, int cmd, long arg1, void *arg2); static const BIO_METHOD null_method = { BIO_TYPE_NULL, "NULL", + /* TODO: Convert to new style write function */ + bwrite_conv, null_write, + /* TODO: Convert to new style read function */ + bread_conv, null_read, null_puts, null_gets, @@ -32,17 +36,17 @@ static const BIO_METHOD null_method = { const BIO_METHOD *BIO_s_null(void) { - return (&null_method); + return &null_method; } static int null_read(BIO *b, char *out, int outl) { - return (0); + return 0; } static int null_write(BIO *b, const char *in, int inl) { - return (inl); + return inl; } static long null_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -67,17 +71,17 @@ static long null_ctrl(BIO *b, int cmd, long num, void *ptr) ret = 0; break; } - return (ret); + return ret; } static int null_gets(BIO *bp, char *buf, int size) { - return (0); + return 0; } static int null_puts(BIO *bp, const char *str) { if (str == NULL) - return (0); - return (strlen(str)); + return 0; + return strlen(str); } diff --git a/crypto/bio/bss_sock.c b/crypto/bio/bss_sock.c index 992266dc..ad384532 100644 --- a/crypto/bio/bss_sock.c +++ b/crypto/bio/bss_sock.c @@ -9,7 +9,6 @@ #include #include -#define USE_SOCKETS #include "bio_lcl.h" #include "internal/cryptlib.h" @@ -38,7 +37,11 @@ int BIO_sock_should_retry(int s); static const BIO_METHOD methods_sockp = { BIO_TYPE_SOCKET, "socket", + /* TODO: Convert to new style write function */ + bwrite_conv, sock_write, + /* TODO: Convert to new style read function */ + bread_conv, sock_read, sock_puts, NULL, /* sock_gets, */ @@ -50,7 +53,7 @@ static const BIO_METHOD methods_sockp = { const BIO_METHOD *BIO_s_socket(void) { - return (&methods_sockp); + return &methods_sockp; } BIO *BIO_new_socket(int fd, int close_flag) @@ -59,9 +62,9 @@ BIO *BIO_new_socket(int fd, int close_flag) ret = BIO_new(BIO_s_socket()); if (ret == NULL) - return (NULL); + return NULL; BIO_set_fd(ret, fd, close_flag); - return (ret); + return ret; } static int sock_new(BIO *bi) @@ -70,13 +73,13 @@ static int sock_new(BIO *bi) bi->num = 0; bi->ptr = NULL; bi->flags = 0; - return (1); + return 1; } static int sock_free(BIO *a) { if (a == NULL) - return (0); + return 0; if (a->shutdown) { if (a->init) { BIO_closesocket(a->num); @@ -84,7 +87,7 @@ static int sock_free(BIO *a) a->init = 0; a->flags = 0; } - return (1); + return 1; } static int sock_read(BIO *b, char *out, int outl) @@ -100,7 +103,7 @@ static int sock_read(BIO *b, char *out, int outl) BIO_set_retry_read(b); } } - return (ret); + return ret; } static int sock_write(BIO *b, const char *in, int inl) @@ -114,7 +117,7 @@ static int sock_write(BIO *b, const char *in, int inl) if (BIO_sock_should_retry(ret)) BIO_set_retry_write(b); } - return (ret); + return ret; } static long sock_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -152,7 +155,7 @@ static long sock_ctrl(BIO *b, int cmd, long num, void *ptr) ret = 0; break; } - return (ret); + return ret; } static int sock_puts(BIO *bp, const char *str) @@ -161,7 +164,7 @@ static int sock_puts(BIO *bp, const char *str) n = strlen(str); ret = sock_write(bp, str, n); - return (ret); + return ret; } int BIO_sock_should_retry(int i) @@ -171,9 +174,9 @@ int BIO_sock_should_retry(int i) if ((i == 0) || (i == -1)) { err = get_last_socket_error(); - return (BIO_sock_non_fatal_error(err)); + return BIO_sock_non_fatal_error(err); } - return (0); + return 0; } int BIO_sock_non_fatal_error(int err) @@ -220,12 +223,11 @@ int BIO_sock_non_fatal_error(int err) # ifdef EALREADY case EALREADY: # endif - return (1); - /* break; */ + return 1; default: break; } - return (0); + return 0; } #endif /* #ifndef OPENSSL_NO_SOCK */ diff --git a/crypto/blake2/blake2_impl.h b/crypto/blake2/blake2_impl.h index 8fe5c959..80b717e7 100644 --- a/crypto/blake2/blake2_impl.h +++ b/crypto/blake2/blake2_impl.h @@ -1,5 +1,5 @@ /* - * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-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 @@ -15,7 +15,6 @@ */ #include -#include "e_os.h" static ossl_inline uint32_t load32(const uint8_t *src) { diff --git a/crypto/blake2/blake2_locl.h b/crypto/blake2/blake2_locl.h index fb7beb97..926bae94 100644 --- a/crypto/blake2/blake2_locl.h +++ b/crypto/blake2/blake2_locl.h @@ -1,5 +1,5 @@ /* - * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-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 @@ -15,7 +15,6 @@ */ #include -#include "e_os.h" #define BLAKE2S_BLOCKBYTES 64 #define BLAKE2S_OUTBYTES 32 diff --git a/crypto/blake2/blake2b.c b/crypto/blake2/blake2b.c index e77bd9ac..829ba5b5 100644 --- a/crypto/blake2/blake2b.c +++ b/crypto/blake2/blake2b.c @@ -1,5 +1,5 @@ /* - * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-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 @@ -17,7 +17,6 @@ #include #include #include -#include "e_os.h" #include "blake2_locl.h" #include "blake2_impl.h" diff --git a/crypto/blake2/blake2s.c b/crypto/blake2/blake2s.c index 0b3503e4..8211374d 100644 --- a/crypto/blake2/blake2s.c +++ b/crypto/blake2/blake2s.c @@ -1,5 +1,5 @@ /* - * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-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 @@ -17,7 +17,6 @@ #include #include #include -#include "e_os.h" #include "blake2_locl.h" #include "blake2_impl.h" @@ -219,7 +218,7 @@ int BLAKE2s_Update(BLAKE2S_CTX *c, const void *data, size_t datalen) in += fill; datalen -= fill; } - if (datalen > BLAKE2S_BLOCKBYTES) { + if (datalen > BLAKE2S_BLOCKBYTES) { size_t stashlen = datalen % BLAKE2S_BLOCKBYTES; /* * If |datalen| is a multiple of the blocksize, stash diff --git a/crypto/blake2/m_blake2b.c b/crypto/blake2/m_blake2b.c index 82c6f6bd..c493648c 100644 --- a/crypto/blake2/m_blake2b.c +++ b/crypto/blake2/m_blake2b.c @@ -54,6 +54,6 @@ static const EVP_MD blake2b_md = { const EVP_MD *EVP_blake2b512(void) { - return (&blake2b_md); + return &blake2b_md; } #endif diff --git a/crypto/blake2/m_blake2s.c b/crypto/blake2/m_blake2s.c index 467e91a8..83b2811e 100644 --- a/crypto/blake2/m_blake2s.c +++ b/crypto/blake2/m_blake2s.c @@ -54,6 +54,6 @@ static const EVP_MD blake2s_md = { const EVP_MD *EVP_blake2s256(void) { - return (&blake2s_md); + return &blake2s_md; } #endif diff --git a/crypto/bn/README.pod b/crypto/bn/README.pod index 109ab0d9..706a1403 100644 --- a/crypto/bn/README.pod +++ b/crypto/bn/README.pod @@ -6,7 +6,7 @@ bn_mul_words, bn_mul_add_words, bn_sqr_words, bn_div_words, bn_add_words, bn_sub_words, bn_mul_comba4, bn_mul_comba8, bn_sqr_comba4, bn_sqr_comba8, bn_cmp_words, bn_mul_normal, bn_mul_low_normal, bn_mul_recursive, bn_mul_part_recursive, -bn_mul_low_recursive, bn_mul_high, bn_sqr_normal, bn_sqr_recursive, +bn_mul_low_recursive, bn_sqr_normal, bn_sqr_recursive, bn_expand, bn_wexpand, bn_expand2, bn_fix_top, bn_check_top, bn_print, bn_dump, bn_set_max, bn_set_high, bn_set_low - BIGNUM library internal functions @@ -41,8 +41,6 @@ library internal functions int n, int tna, int tnb, BN_ULONG *tmp); void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, BN_ULONG *tmp); - void bn_mul_high(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, BN_ULONG *l, - int n2, BN_ULONG *tmp); void bn_sqr_normal(BN_ULONG *r, BN_ULONG *a, int n, BN_ULONG *tmp); void bn_sqr_recursive(BN_ULONG *r, BN_ULONG *a, int n2, BN_ULONG *tmp); @@ -178,10 +176,6 @@ bn_mul_low_recursive(B, B, B, B, B) operates on the B word arrays B and B and the B/2 word arrays B and B. -bn_mul_high(B, B, B, B, B, B) operates on the -B word arrays B, B, B and B (?) and the 3*B word -array B. - BN_mul() calls bn_mul_normal(), or an optimized implementation if the factors have the same size: bn_mul_comba8() is used if they are 8 words long, bn_mul_recursive() if they are larger than diff --git a/crypto/bn/asm/alpha-mont.pl b/crypto/bn/asm/alpha-mont.pl index 1d68d6d0..cd0e1fb8 100644 --- a/crypto/bn/asm/alpha-mont.pl +++ b/crypto/bn/asm/alpha-mont.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. diff --git a/crypto/bn/asm/armv4-gf2m.pl b/crypto/bn/asm/armv4-gf2m.pl index 0bb54330..7a0cdb2e 100644 --- a/crypto/bn/asm/armv4-gf2m.pl +++ b/crypto/bn/asm/armv4-gf2m.pl @@ -36,7 +36,7 @@ # # Câmara, D.; Gouvêa, C. P. L.; López, J. & Dahab, R.: Fast Software # Polynomial Multiplication on ARM Processors using the NEON Engine. -# +# # http://conradoplg.cryptoland.net/files/2010/12/mocrysen13.pdf $flavour = shift; diff --git a/crypto/bn/asm/armv4-mont.pl b/crypto/bn/asm/armv4-mont.pl index 0dc4fe95..75a36f62 100644 --- a/crypto/bn/asm/armv4-mont.pl +++ b/crypto/bn/asm/armv4-mont.pl @@ -23,7 +23,7 @@ # [depending on key length, less for longer keys] on ARM920T, and # +115-80% on Intel IXP425. This is compared to pre-bn_mul_mont code # base and compiler generated code with in-lined umull and even umlal -# instructions. The latter means that this code didn't really have an +# instructions. The latter means that this code didn't really have an # "advantage" of utilizing some "secret" instruction. # # The code is interoperable with Thumb ISA and is rather compact, less diff --git a/crypto/bn/asm/bn-586.pl b/crypto/bn/asm/bn-586.pl index 1ca1bbf7..58effc88 100644 --- a/crypto/bn/asm/bn-586.pl +++ b/crypto/bn/asm/bn-586.pl @@ -14,7 +14,7 @@ require "x86asm.pl"; $output = pop; open STDOUT,">$output"; -&asm_init($ARGV[0],$0); +&asm_init($ARGV[0]); $sse2=0; for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } @@ -54,7 +54,7 @@ sub bn_mul_add_words &movd("mm0",&wparam(3)); # mm0 = w &pxor("mm1","mm1"); # mm1 = carry_in &jmp(&label("maw_sse2_entry")); - + &set_label("maw_sse2_unrolled",16); &movd("mm3",&DWP(0,$r,"",0)); # mm3 = r[0] &paddq("mm1","mm3"); # mm1 = carry_in + r[0] @@ -675,20 +675,20 @@ sub bn_sub_part_words &adc($c,0); &mov(&DWP($i*4,$r,"",0),$tmp1); # *r } - + &comment(""); &add($b,32); &add($r,32); &sub($num,8); &jnz(&label("pw_neg_loop")); - + &set_label("pw_neg_finish",0); &mov($tmp2,&wparam(4)); # get dl &mov($num,0); &sub($num,$tmp2); &and($num,7); &jz(&label("pw_end")); - + for ($i=0; $i<7; $i++) { &comment("dl<0 Tail Round $i"); @@ -705,9 +705,9 @@ sub bn_sub_part_words } &jmp(&label("pw_end")); - + &set_label("pw_pos",0); - + &and($num,0xfffffff8); # num / 8 &jz(&label("pw_pos_finish")); @@ -722,18 +722,18 @@ sub bn_sub_part_words &mov(&DWP($i*4,$r,"",0),$tmp1); # *r &jnc(&label("pw_nc".$i)); } - + &comment(""); &add($a,32); &add($r,32); &sub($num,8); &jnz(&label("pw_pos_loop")); - + &set_label("pw_pos_finish",0); &mov($num,&wparam(4)); # get dl &and($num,7); &jz(&label("pw_end")); - + for ($i=0; $i<7; $i++) { &comment("dl>0 Tail Round $i"); @@ -754,17 +754,17 @@ sub bn_sub_part_words &mov(&DWP($i*4,$r,"",0),$tmp1); # *r &set_label("pw_nc".$i,0); } - + &comment(""); &add($a,32); &add($r,32); &sub($num,8); &jnz(&label("pw_nc_loop")); - + &mov($num,&wparam(4)); # get dl &and($num,7); &jz(&label("pw_nc_end")); - + for ($i=0; $i<7; $i++) { &mov($tmp1,&DWP($i*4,$a,"",0)); # *a diff --git a/crypto/bn/asm/c64xplus-gf2m.pl b/crypto/bn/asm/c64xplus-gf2m.pl index c0e54008..9c46da3a 100644 --- a/crypto/bn/asm/c64xplus-gf2m.pl +++ b/crypto/bn/asm/c64xplus-gf2m.pl @@ -43,7 +43,7 @@ $code.=<<___; SHRU $A,16, $Ahi ; smash $A to two halfwords || EXTU $A,16,16,$Alo - XORMPY $Alo,$B_2,$Alox2 ; 16x8 bits muliplication + XORMPY $Alo,$B_2,$Alox2 ; 16x8 bits multiplication || XORMPY $Ahi,$B_2,$Ahix2 || EXTU $B,16,24,$B_1 XORMPY $Alo,$B_0,$Alox0 diff --git a/crypto/bn/asm/co-586.pl b/crypto/bn/asm/co-586.pl index 60d03636..97f5e3a1 100644 --- a/crypto/bn/asm/co-586.pl +++ b/crypto/bn/asm/co-586.pl @@ -13,7 +13,7 @@ require "x86asm.pl"; $output = pop; open STDOUT,">$output"; -&asm_init($ARGV[0],$0); +&asm_init($ARGV[0]); &bn_mul_comba("bn_mul_comba8",8); &bn_mul_comba("bn_mul_comba4",4); @@ -47,7 +47,7 @@ sub mul_add_c &mov("edx",&DWP(($nb)*4,$b,"",0)) if $pos == 1; # laod next b ### &adc($c2,0); - # is pos > 1, it means it is the last loop + # is pos > 1, it means it is the last loop &mov(&DWP($i*4,"eax","",0),$c0) if $pos > 0; # save r[]; &mov("eax",&DWP(($na)*4,$a,"",0)) if $pos == 1; # laod next a } @@ -76,7 +76,7 @@ sub sqr_add_c &mov("edx",&DWP(($nb)*4,$a,"",0)) if ($pos == 1) && ($na != $nb); ### &adc($c2,0); - # is pos > 1, it means it is the last loop + # is pos > 1, it means it is the last loop &mov(&DWP($i*4,$r,"",0),$c0) if $pos > 0; # save r[]; &mov("eax",&DWP(($na)*4,$a,"",0)) if $pos == 1; # load next b } @@ -127,7 +127,7 @@ sub bn_mul_comba $c2="ebp"; $a="esi"; $b="edi"; - + $as=0; $ae=0; $bs=0; @@ -142,9 +142,9 @@ sub bn_mul_comba &push("ebx"); &xor($c0,$c0); - &mov("eax",&DWP(0,$a,"",0)); # load the first word + &mov("eax",&DWP(0,$a,"",0)); # load the first word &xor($c1,$c1); - &mov("edx",&DWP(0,$b,"",0)); # load the first second + &mov("edx",&DWP(0,$b,"",0)); # load the first second for ($i=0; $i<$tot; $i++) { @@ -152,7 +152,7 @@ sub bn_mul_comba $bi=$bs; $end=$be+1; - &comment("################## Calculate word $i"); + &comment("################## Calculate word $i"); for ($j=$bs; $j<$end; $j++) { diff --git a/crypto/bn/asm/ia64-mont.pl b/crypto/bn/asm/ia64-mont.pl index 5cc5c599..9d1ecf6a 100644 --- a/crypto/bn/asm/ia64-mont.pl +++ b/crypto/bn/asm/ia64-mont.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -80,7 +80,7 @@ $code=<<___; // int bn_mul_mont (BN_ULONG *rp,const BN_ULONG *ap, // const BN_ULONG *bp,const BN_ULONG *np, -// const BN_ULONG *n0p,int num); +// const BN_ULONG *n0p,int num); .align 64 .global bn_mul_mont# .proc bn_mul_mont# @@ -203,7 +203,7 @@ bn_mul_mont_general: { .mmi; .pred.rel "mutex",p39,p41 (p39) add topbit=r0,r0 (p41) add topbit=r0,r0,1 - nop.i 0 } + nop.i 0 } { .mmi; st8 [tp_1]=n[0] add tptr=16,sp add tp_1=8,sp };; diff --git a/crypto/bn/asm/ia64.S b/crypto/bn/asm/ia64.S index f2404a3c..d235c45e 100644 --- a/crypto/bn/asm/ia64.S +++ b/crypto/bn/asm/ia64.S @@ -1,9 +1,9 @@ .explicit .text .ident "ia64.S, Version 2.1" -.ident "IA-64 ISA artwork by Andy Polyakov " +.ident "IA-64 ISA artwork by Andy Polyakov " -// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +// Copyright 2001-2018 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 @@ -12,7 +12,7 @@ // // ==================================================================== -// Written by Andy Polyakov for the OpenSSL +// Written by Andy Polyakov for the OpenSSL // project. // // Rights for redistribution and usage in source and binary forms are @@ -20,7 +20,7 @@ // disclaimed. // ==================================================================== // -// Version 2.x is Itanium2 re-tune. Few words about how Itanum2 is +// Version 2.x is Itanium2 re-tune. Few words about how Itanium2 is // different from Itanium to this module viewpoint. Most notably, is it // "wider" than Itanium? Can you experience loop scalability as // discussed in commentary sections? Not really:-( Itanium2 has 6 @@ -141,7 +141,7 @@ // User Mask I want to excuse the kernel from preserving upper // (f32-f128) FP register bank over process context switch, thus // minimizing bus bandwidth consumption during the switch (i.e. -// after PKI opration completes and the program is off doing +// after PKI operation completes and the program is off doing // something else like bulk symmetric encryption). Having said // this, I also want to point out that it might be good idea // to compile the whole toolkit (as well as majority of the @@ -157,12 +157,15 @@ #else #define ADDP add #endif +#ifdef __VMS +.alias abort, "decc$abort" +#endif #if 1 // // bn_[add|sub]_words routines. // -// Loops are spinning in 2*(n+5) ticks on Itanuim (provided that the +// Loops are spinning in 2*(n+5) ticks on Itanium (provided that the // data reside in L1 cache, i.e. 2 ticks away). It's possible to // compress the epilogue and get down to 2*n+6, but at the cost of // scalability (the neat feature of this implementation is that it @@ -500,7 +503,7 @@ bn_sqr_words: // possible to compress the epilogue (I'm getting tired to write this // comment over and over) and get down to 2*n+16 at the cost of // scalability. The decision will very likely be reconsidered after the -// benchmark program is profiled. I.e. if perfomance gain on Itanium +// benchmark program is profiled. I.e. if performance gain on Itanium // will appear larger than loss on "wider" IA-64, then the loop should // be explicitly split and the epilogue compressed. .L_bn_sqr_words_ctop: @@ -936,7 +939,7 @@ bn_mul_comba8: xma.hu f118=f39,f127,f117 } { .mfi; xma.lu f117=f39,f127,f117 };;// //-------------------------------------------------// -// Leaving muliplier's heaven... Quite a ride, huh? +// Leaving multiplier's heaven... Quite a ride, huh? { .mii; getf.sig r31=f47 add r25=r25,r24 @@ -1428,6 +1431,7 @@ bn_div_words: mov ar.ec=0 // don't rotate at exit mov pr.rot=0 } { .mii; mov L=r33 // save l + mov r25=r0 // needed if abort is called on VMS mov r36=r0 };; .L_divw_shift: // -vv- note signed comparison @@ -1529,9 +1533,8 @@ bn_div_words: // output: f8 = (int)(a/b) // clobbered: f8,f9,f10,f11,pred pred=p15 -// One can argue that this snippet is copyrighted to Intel -// Corporation, as it's essentially identical to one of those -// found in "Divide, Square Root and Remainder" section at +// This snippet is based on text found in the "Divide, Square +// Root and Remainder" section at // http://www.intel.com/software/products/opensource/libraries/num.htm. // Yes, I admit that the referred code was used as template, // but after I realized that there hardly is any other instruction diff --git a/crypto/bn/asm/mips-mont.pl b/crypto/bn/asm/mips-mont.pl index a907571b..56d42028 100644 --- a/crypto/bn/asm/mips-mont.pl +++ b/crypto/bn/asm/mips-mont.pl @@ -56,14 +56,14 @@ $flavour = shift || "o32"; # supported flavours are o32,n32,64,nubi32,nubi64 if ($flavour =~ /64|n32/i) { - $PTR_ADD="dadd"; # incidentally works even on n32 - $PTR_SUB="dsub"; # incidentally works even on n32 + $PTR_ADD="daddu"; # incidentally works even on n32 + $PTR_SUB="dsubu"; # incidentally works even on n32 $REG_S="sd"; $REG_L="ld"; $SZREG=8; } else { - $PTR_ADD="add"; - $PTR_SUB="sub"; + $PTR_ADD="addu"; + $PTR_SUB="subu"; $REG_S="sw"; $REG_L="lw"; $SZREG=4; @@ -121,6 +121,8 @@ $m1=$s11; $FRAMESIZE=14; $code=<<___; +#include "mips_arch.h" + .text .set noat @@ -183,27 +185,27 @@ $code.=<<___; $PTR_SUB $sp,$num and $sp,$at - $MULTU $aj,$bi - $LD $alo,$BNSZ($ap) - $LD $nlo,$BNSZ($np) - mflo $lo0 - mfhi $hi0 - $MULTU $lo0,$n0 - mflo $m1 + $MULTU ($aj,$bi) + $LD $ahi,$BNSZ($ap) + $LD $nhi,$BNSZ($np) + mflo ($lo0,$aj,$bi) + mfhi ($hi0,$aj,$bi) + $MULTU ($lo0,$n0) + mflo ($m1,$lo0,$n0) - $MULTU $alo,$bi - mflo $alo - mfhi $ahi + $MULTU ($ahi,$bi) + mflo ($alo,$ahi,$bi) + mfhi ($ahi,$ahi,$bi) - $MULTU $nj,$m1 - mflo $lo1 - mfhi $hi1 - $MULTU $nlo,$m1 + $MULTU ($nj,$m1) + mflo ($lo1,$nj,$m1) + mfhi ($hi1,$nj,$m1) + $MULTU ($nhi,$m1) $ADDU $lo1,$lo0 sltu $at,$lo1,$lo0 $ADDU $hi1,$at - mflo $nlo - mfhi $nhi + mflo ($nlo,$nhi,$m1) + mfhi ($nhi,$nhi,$m1) move $tp,$sp li $j,2*$BNSZ @@ -215,25 +217,25 @@ $code.=<<___; $LD $aj,($aj) $LD $nj,($nj) - $MULTU $aj,$bi + $MULTU ($aj,$bi) $ADDU $lo0,$alo,$hi0 $ADDU $lo1,$nlo,$hi1 sltu $at,$lo0,$hi0 sltu $t0,$lo1,$hi1 $ADDU $hi0,$ahi,$at $ADDU $hi1,$nhi,$t0 - mflo $alo - mfhi $ahi + mflo ($alo,$aj,$bi) + mfhi ($ahi,$aj,$bi) $ADDU $lo1,$lo0 sltu $at,$lo1,$lo0 - $MULTU $nj,$m1 + $MULTU ($nj,$m1) $ADDU $hi1,$at addu $j,$BNSZ $ST $lo1,($tp) sltu $t0,$j,$num - mflo $nlo - mfhi $nhi + mflo ($nlo,$nj,$m1) + mfhi ($nhi,$nj,$m1) bnez $t0,.L1st $PTR_ADD $tp,$BNSZ @@ -263,34 +265,34 @@ $code.=<<___; $PTR_ADD $bi,$bp,$i $LD $bi,($bi) $LD $aj,($ap) - $LD $alo,$BNSZ($ap) + $LD $ahi,$BNSZ($ap) $LD $tj,($sp) - $MULTU $aj,$bi + $MULTU ($aj,$bi) $LD $nj,($np) - $LD $nlo,$BNSZ($np) - mflo $lo0 - mfhi $hi0 + $LD $nhi,$BNSZ($np) + mflo ($lo0,$aj,$bi) + mfhi ($hi0,$aj,$bi) $ADDU $lo0,$tj - $MULTU $lo0,$n0 + $MULTU ($lo0,$n0) sltu $at,$lo0,$tj $ADDU $hi0,$at - mflo $m1 + mflo ($m1,$lo0,$n0) - $MULTU $alo,$bi - mflo $alo - mfhi $ahi + $MULTU ($ahi,$bi) + mflo ($alo,$ahi,$bi) + mfhi ($ahi,$ahi,$bi) - $MULTU $nj,$m1 - mflo $lo1 - mfhi $hi1 + $MULTU ($nj,$m1) + mflo ($lo1,$nj,$m1) + mfhi ($hi1,$nj,$m1) - $MULTU $nlo,$m1 + $MULTU ($nhi,$m1) $ADDU $lo1,$lo0 sltu $at,$lo1,$lo0 $ADDU $hi1,$at - mflo $nlo - mfhi $nhi + mflo ($nlo,$nhi,$m1) + mfhi ($nhi,$nhi,$m1) move $tp,$sp li $j,2*$BNSZ @@ -303,19 +305,19 @@ $code.=<<___; $LD $aj,($aj) $LD $nj,($nj) - $MULTU $aj,$bi + $MULTU ($aj,$bi) $ADDU $lo0,$alo,$hi0 $ADDU $lo1,$nlo,$hi1 sltu $at,$lo0,$hi0 sltu $t0,$lo1,$hi1 $ADDU $hi0,$ahi,$at $ADDU $hi1,$nhi,$t0 - mflo $alo - mfhi $ahi + mflo ($alo,$aj,$bi) + mfhi ($ahi,$aj,$bi) $ADDU $lo0,$tj addu $j,$BNSZ - $MULTU $nj,$m1 + $MULTU ($nj,$m1) sltu $at,$lo0,$tj $ADDU $lo1,$lo0 $ADDU $hi0,$at @@ -323,8 +325,8 @@ $code.=<<___; $LD $tj,2*$BNSZ($tp) $ADDU $hi1,$t0 sltu $at,$j,$num - mflo $nlo - mfhi $nhi + mflo ($nlo,$nj,$m1) + mfhi ($nhi,$nj,$m1) $ST $lo1,($tp) bnez $at,.Linner $PTR_ADD $tp,$BNSZ diff --git a/crypto/bn/asm/mips.pl b/crypto/bn/asm/mips.pl index 420f01f3..da35ec1b 100644 --- a/crypto/bn/asm/mips.pl +++ b/crypto/bn/asm/mips.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. # # Rights for redistribution and usage in source and binary forms are @@ -42,7 +42,7 @@ # Performance improvement is astonishing! 'apps/openssl speed rsa dsa' # goes way over 3 times faster! # -# +# # October 2010 # @@ -109,6 +109,22 @@ $gp=$v1 if ($flavour =~ /nubi/i); $minus4=$v1; $code.=<<___; +#include "mips_arch.h" + +#if defined(_MIPS_ARCH_MIPS64R6) +# define ddivu(rs,rt) +# define mfqt(rd,rs,rt) ddivu rd,rs,rt +# define mfrm(rd,rs,rt) dmodu rd,rs,rt +#elif defined(_MIPS_ARCH_MIPS32R6) +# define divu(rs,rt) +# define mfqt(rd,rs,rt) divu rd,rs,rt +# define mfrm(rd,rs,rt) modu rd,rs,rt +#else +# define $DIVU(rs,rt) $DIVU $zero,rs,rt +# define mfqt(rd,rs,rt) mflo rd +# define mfrm(rd,rs,rt) mfhi rd +#endif + .rdata .asciiz "mips3.s, Version 1.2" .asciiz "MIPS II/III/IV ISA artwork by Andy Polyakov " @@ -151,7 +167,7 @@ $code.=<<___; .L_bn_mul_add_words_loop: $LD $t0,0($a1) - $MULTU $t0,$a3 + $MULTU ($t0,$a3) $LD $t1,0($a0) $LD $t2,$BNSZ($a1) $LD $t3,$BNSZ($a0) @@ -161,11 +177,11 @@ $code.=<<___; sltu $v0,$t1,$v0 # All manuals say it "compares 32-bit # values", but it seems to work fine # even on 64-bit registers. - mflo $at - mfhi $t0 + mflo ($at,$t0,$a3) + mfhi ($t0,$t0,$a3) $ADDU $t1,$at $ADDU $v0,$t0 - $MULTU $t2,$a3 + $MULTU ($t2,$a3) sltu $at,$t1,$at $ST $t1,0($a0) $ADDU $v0,$at @@ -174,11 +190,11 @@ $code.=<<___; $LD $ta3,3*$BNSZ($a0) $ADDU $t3,$v0 sltu $v0,$t3,$v0 - mflo $at - mfhi $t2 + mflo ($at,$t2,$a3) + mfhi ($t2,$t2,$a3) $ADDU $t3,$at $ADDU $v0,$t2 - $MULTU $ta0,$a3 + $MULTU ($ta0,$a3) sltu $at,$t3,$at $ST $t3,$BNSZ($a0) $ADDU $v0,$at @@ -188,11 +204,11 @@ $code.=<<___; $PTR_ADD $a1,4*$BNSZ $ADDU $ta1,$v0 sltu $v0,$ta1,$v0 - mflo $at - mfhi $ta0 + mflo ($at,$ta0,$a3) + mfhi ($ta0,$ta0,$a3) $ADDU $ta1,$at $ADDU $v0,$ta0 - $MULTU $ta2,$a3 + $MULTU ($ta2,$a3) sltu $at,$ta1,$at $ST $ta1,-2*$BNSZ($a0) $ADDU $v0,$at @@ -201,8 +217,8 @@ $code.=<<___; and $ta0,$a2,$minus4 $ADDU $ta3,$v0 sltu $v0,$ta3,$v0 - mflo $at - mfhi $ta2 + mflo ($at,$ta2,$a3) + mfhi ($ta2,$ta2,$a3) $ADDU $ta3,$at $ADDU $v0,$ta2 sltu $at,$ta3,$at @@ -217,13 +233,13 @@ $code.=<<___; .L_bn_mul_add_words_tail: .set reorder $LD $t0,0($a1) - $MULTU $t0,$a3 + $MULTU ($t0,$a3) $LD $t1,0($a0) subu $a2,1 $ADDU $t1,$v0 sltu $v0,$t1,$v0 - mflo $at - mfhi $t0 + mflo ($at,$t0,$a3) + mfhi ($t0,$t0,$a3) $ADDU $t1,$at $ADDU $v0,$t0 sltu $at,$t1,$at @@ -232,13 +248,13 @@ $code.=<<___; beqz $a2,.L_bn_mul_add_words_return $LD $t0,$BNSZ($a1) - $MULTU $t0,$a3 + $MULTU ($t0,$a3) $LD $t1,$BNSZ($a0) subu $a2,1 $ADDU $t1,$v0 sltu $v0,$t1,$v0 - mflo $at - mfhi $t0 + mflo ($at,$t0,$a3) + mfhi ($t0,$t0,$a3) $ADDU $t1,$at $ADDU $v0,$t0 sltu $at,$t1,$at @@ -247,12 +263,12 @@ $code.=<<___; beqz $a2,.L_bn_mul_add_words_return $LD $t0,2*$BNSZ($a1) - $MULTU $t0,$a3 + $MULTU ($t0,$a3) $LD $t1,2*$BNSZ($a0) $ADDU $t1,$v0 sltu $v0,$t1,$v0 - mflo $at - mfhi $t0 + mflo ($at,$t0,$a3) + mfhi ($t0,$t0,$a3) $ADDU $t1,$at $ADDU $v0,$t0 sltu $at,$t1,$at @@ -310,40 +326,40 @@ $code.=<<___; .L_bn_mul_words_loop: $LD $t0,0($a1) - $MULTU $t0,$a3 + $MULTU ($t0,$a3) $LD $t2,$BNSZ($a1) $LD $ta0,2*$BNSZ($a1) $LD $ta2,3*$BNSZ($a1) - mflo $at - mfhi $t0 + mflo ($at,$t0,$a3) + mfhi ($t0,$t0,$a3) $ADDU $v0,$at sltu $t1,$v0,$at - $MULTU $t2,$a3 + $MULTU ($t2,$a3) $ST $v0,0($a0) $ADDU $v0,$t1,$t0 subu $a2,4 $PTR_ADD $a0,4*$BNSZ $PTR_ADD $a1,4*$BNSZ - mflo $at - mfhi $t2 + mflo ($at,$t2,$a3) + mfhi ($t2,$t2,$a3) $ADDU $v0,$at sltu $t3,$v0,$at - $MULTU $ta0,$a3 + $MULTU ($ta0,$a3) $ST $v0,-3*$BNSZ($a0) $ADDU $v0,$t3,$t2 - mflo $at - mfhi $ta0 + mflo ($at,$ta0,$a3) + mfhi ($ta0,$ta0,$a3) $ADDU $v0,$at sltu $ta1,$v0,$at - $MULTU $ta2,$a3 + $MULTU ($ta2,$a3) $ST $v0,-2*$BNSZ($a0) $ADDU $v0,$ta1,$ta0 and $ta0,$a2,$minus4 - mflo $at - mfhi $ta2 + mflo ($at,$ta2,$a3) + mfhi ($ta2,$ta2,$a3) $ADDU $v0,$at sltu $ta3,$v0,$at $ST $v0,-$BNSZ($a0) @@ -357,10 +373,10 @@ $code.=<<___; .L_bn_mul_words_tail: .set reorder $LD $t0,0($a1) - $MULTU $t0,$a3 + $MULTU ($t0,$a3) subu $a2,1 - mflo $at - mfhi $t0 + mflo ($at,$t0,$a3) + mfhi ($t0,$t0,$a3) $ADDU $v0,$at sltu $t1,$v0,$at $ST $v0,0($a0) @@ -368,10 +384,10 @@ $code.=<<___; beqz $a2,.L_bn_mul_words_return $LD $t0,$BNSZ($a1) - $MULTU $t0,$a3 + $MULTU ($t0,$a3) subu $a2,1 - mflo $at - mfhi $t0 + mflo ($at,$t0,$a3) + mfhi ($t0,$t0,$a3) $ADDU $v0,$at sltu $t1,$v0,$at $ST $v0,$BNSZ($a0) @@ -379,9 +395,9 @@ $code.=<<___; beqz $a2,.L_bn_mul_words_return $LD $t0,2*$BNSZ($a1) - $MULTU $t0,$a3 - mflo $at - mfhi $t0 + $MULTU ($t0,$a3) + mflo ($at,$t0,$a3) + mfhi ($t0,$t0,$a3) $ADDU $v0,$at sltu $t1,$v0,$at $ST $v0,2*$BNSZ($a0) @@ -438,35 +454,35 @@ $code.=<<___; .L_bn_sqr_words_loop: $LD $t0,0($a1) - $MULTU $t0,$t0 + $MULTU ($t0,$t0) $LD $t2,$BNSZ($a1) $LD $ta0,2*$BNSZ($a1) $LD $ta2,3*$BNSZ($a1) - mflo $t1 - mfhi $t0 + mflo ($t1,$t0,$t0) + mfhi ($t0,$t0,$t0) $ST $t1,0($a0) $ST $t0,$BNSZ($a0) - $MULTU $t2,$t2 + $MULTU ($t2,$t2) subu $a2,4 $PTR_ADD $a0,8*$BNSZ $PTR_ADD $a1,4*$BNSZ - mflo $t3 - mfhi $t2 + mflo ($t3,$t2,$t2) + mfhi ($t2,$t2,$t2) $ST $t3,-6*$BNSZ($a0) $ST $t2,-5*$BNSZ($a0) - $MULTU $ta0,$ta0 - mflo $ta1 - mfhi $ta0 + $MULTU ($ta0,$ta0) + mflo ($ta1,$ta0,$ta0) + mfhi ($ta0,$ta0,$ta0) $ST $ta1,-4*$BNSZ($a0) $ST $ta0,-3*$BNSZ($a0) - $MULTU $ta2,$ta2 + $MULTU ($ta2,$ta2) and $ta0,$a2,$minus4 - mflo $ta3 - mfhi $ta2 + mflo ($ta3,$ta2,$ta2) + mfhi ($ta2,$ta2,$ta2) $ST $ta3,-2*$BNSZ($a0) .set noreorder @@ -479,27 +495,27 @@ $code.=<<___; .L_bn_sqr_words_tail: .set reorder $LD $t0,0($a1) - $MULTU $t0,$t0 + $MULTU ($t0,$t0) subu $a2,1 - mflo $t1 - mfhi $t0 + mflo ($t1,$t0,$t0) + mfhi ($t0,$t0,$t0) $ST $t1,0($a0) $ST $t0,$BNSZ($a0) beqz $a2,.L_bn_sqr_words_return $LD $t0,$BNSZ($a1) - $MULTU $t0,$t0 + $MULTU ($t0,$t0) subu $a2,1 - mflo $t1 - mfhi $t0 + mflo ($t1,$t0,$t0) + mfhi ($t0,$t0,$t0) $ST $t1,2*$BNSZ($a0) $ST $t0,3*$BNSZ($a0) beqz $a2,.L_bn_sqr_words_return $LD $t0,2*$BNSZ($a1) - $MULTU $t0,$t0 - mflo $t1 - mfhi $t0 + $MULTU ($t0,$t0) + mflo ($t1,$t0,$t0) + mfhi ($t0,$t0,$t0) $ST $t1,4*$BNSZ($a0) $ST $t0,5*$BNSZ($a0) @@ -587,13 +603,13 @@ $code.=<<___; sltu $v0,$t2,$ta2 $ST $t2,-2*$BNSZ($a0) $ADDU $v0,$t8 - + $ADDU $ta3,$t3 sltu $t9,$ta3,$t3 $ADDU $t3,$ta3,$v0 sltu $v0,$t3,$ta3 $ST $t3,-$BNSZ($a0) - + .set noreorder bgtz $at,.L_bn_add_words_loop $ADDU $v0,$t9 @@ -792,7 +808,7 @@ bn_div_3_words: # so that we can save two arguments # and return address in registers # instead of stack:-) - + $LD $a0,($a3) move $ta2,$a1 bne $a0,$a2,bn_div_3_words_internal @@ -823,11 +839,11 @@ $code.=<<___; move $ta3,$ra bal bn_div_words_internal move $ra,$ta3 - $MULTU $ta2,$v0 + $MULTU ($ta2,$v0) $LD $t2,-2*$BNSZ($a3) move $ta0,$zero - mfhi $t1 - mflo $t0 + mfhi ($t1,$ta2,$v0) + mflo ($t0,$ta2,$v0) sltu $t8,$t1,$a1 .L_bn_div_3_words_inner_loop: bnez $t8,.L_bn_div_3_words_inner_loop_done @@ -930,15 +946,15 @@ $code.=<<___; $SRL $HH,$a0,4*$BNSZ # bits $SRL $QT,4*$BNSZ # q=0xffffffff beq $DH,$HH,.L_bn_div_words_skip_div1 - $DIVU $zero,$a0,$DH - mflo $QT + $DIVU ($a0,$DH) + mfqt ($QT,$a0,$DH) .L_bn_div_words_skip_div1: - $MULTU $a2,$QT + $MULTU ($a2,$QT) $SLL $t3,$a0,4*$BNSZ # bits $SRL $at,$a1,4*$BNSZ # bits or $t3,$at - mflo $t0 - mfhi $t1 + mflo ($t0,$a2,$QT) + mfhi ($t1,$a2,$QT) .L_bn_div_words_inner_loop1: sltu $t2,$t3,$t0 seq $t8,$HH,$t1 @@ -963,15 +979,15 @@ $code.=<<___; $SRL $HH,$a0,4*$BNSZ # bits $SRL $QT,4*$BNSZ # q=0xffffffff beq $DH,$HH,.L_bn_div_words_skip_div2 - $DIVU $zero,$a0,$DH - mflo $QT + $DIVU ($a0,$DH) + mfqt ($QT,$a0,$DH) .L_bn_div_words_skip_div2: - $MULTU $a2,$QT + $MULTU ($a2,$QT) $SLL $t3,$a0,4*$BNSZ # bits $SRL $at,$a1,4*$BNSZ # bits or $t3,$at - mflo $t0 - mfhi $t1 + mflo ($t0,$a2,$QT) + mfhi ($t1,$a2,$QT) .L_bn_div_words_inner_loop2: sltu $t2,$t3,$t0 seq $t8,$HH,$t1 @@ -1070,592 +1086,592 @@ $code.=<<___; $LD $b_0,0($a2) $LD $a_1,$BNSZ($a1) $LD $a_2,2*$BNSZ($a1) - $MULTU $a_0,$b_0 # mul_add_c(a[0],b[0],c1,c2,c3); + $MULTU ($a_0,$b_0) # mul_add_c(a[0],b[0],c1,c2,c3); $LD $a_3,3*$BNSZ($a1) $LD $b_1,$BNSZ($a2) $LD $b_2,2*$BNSZ($a2) $LD $b_3,3*$BNSZ($a2) - mflo $c_1 - mfhi $c_2 + mflo ($c_1,$a_0,$b_0) + mfhi ($c_2,$a_0,$b_0) $LD $a_4,4*$BNSZ($a1) $LD $a_5,5*$BNSZ($a1) - $MULTU $a_0,$b_1 # mul_add_c(a[0],b[1],c2,c3,c1); + $MULTU ($a_0,$b_1) # mul_add_c(a[0],b[1],c2,c3,c1); $LD $a_6,6*$BNSZ($a1) $LD $a_7,7*$BNSZ($a1) $LD $b_4,4*$BNSZ($a2) $LD $b_5,5*$BNSZ($a2) - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_0,$b_1) + mfhi ($t_2,$a_0,$b_1) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_1,$b_0 # mul_add_c(a[1],b[0],c2,c3,c1); + $MULTU ($a_1,$b_0) # mul_add_c(a[1],b[0],c2,c3,c1); $ADDU $c_3,$t_2,$at $LD $b_6,6*$BNSZ($a2) $LD $b_7,7*$BNSZ($a2) $ST $c_1,0($a0) # r[0]=c1; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_0) + mfhi ($t_2,$a_1,$b_0) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_2,$b_0 # mul_add_c(a[2],b[0],c3,c1,c2); + $MULTU ($a_2,$b_0) # mul_add_c(a[2],b[0],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $c_1,$c_3,$t_2 $ST $c_2,$BNSZ($a0) # r[1]=c2; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_0) + mfhi ($t_2,$a_2,$b_0) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_1,$b_1 # mul_add_c(a[1],b[1],c3,c1,c2); + $MULTU ($a_1,$b_1) # mul_add_c(a[1],b[1],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_1) + mfhi ($t_2,$a_1,$b_1) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_0,$b_2 # mul_add_c(a[0],b[2],c3,c1,c2); + $MULTU ($a_0,$b_2) # mul_add_c(a[0],b[2],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $c_2,$c_1,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_0,$b_2) + mfhi ($t_2,$a_0,$b_2) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_0,$b_3 # mul_add_c(a[0],b[3],c1,c2,c3); + $MULTU ($a_0,$b_3) # mul_add_c(a[0],b[3],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at $ST $c_3,2*$BNSZ($a0) # r[2]=c3; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_0,$b_3) + mfhi ($t_2,$a_0,$b_3) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_1,$b_2 # mul_add_c(a[1],b[2],c1,c2,c3); + $MULTU ($a_1,$b_2) # mul_add_c(a[1],b[2],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $c_3,$c_2,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_2) + mfhi ($t_2,$a_1,$b_2) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_2,$b_1 # mul_add_c(a[2],b[1],c1,c2,c3); + $MULTU ($a_2,$b_1) # mul_add_c(a[2],b[1],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_1) + mfhi ($t_2,$a_2,$b_1) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_3,$b_0 # mul_add_c(a[3],b[0],c1,c2,c3); + $MULTU ($a_3,$b_0) # mul_add_c(a[3],b[0],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_0) + mfhi ($t_2,$a_3,$b_0) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_4,$b_0 # mul_add_c(a[4],b[0],c2,c3,c1); + $MULTU ($a_4,$b_0) # mul_add_c(a[4],b[0],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at $ST $c_1,3*$BNSZ($a0) # r[3]=c1; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_4,$b_0) + mfhi ($t_2,$a_4,$b_0) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_3,$b_1 # mul_add_c(a[3],b[1],c2,c3,c1); + $MULTU ($a_3,$b_1) # mul_add_c(a[3],b[1],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $c_1,$c_3,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_1) + mfhi ($t_2,$a_3,$b_1) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_2,$b_2 # mul_add_c(a[2],b[2],c2,c3,c1); + $MULTU ($a_2,$b_2) # mul_add_c(a[2],b[2],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_2) + mfhi ($t_2,$a_2,$b_2) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_1,$b_3 # mul_add_c(a[1],b[3],c2,c3,c1); + $MULTU ($a_1,$b_3) # mul_add_c(a[1],b[3],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_3) + mfhi ($t_2,$a_1,$b_3) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_0,$b_4 # mul_add_c(a[0],b[4],c2,c3,c1); + $MULTU ($a_0,$b_4) # mul_add_c(a[0],b[4],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_0,$b_4) + mfhi ($t_2,$a_0,$b_4) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_0,$b_5 # mul_add_c(a[0],b[5],c3,c1,c2); + $MULTU ($a_0,$b_5) # mul_add_c(a[0],b[5],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at $ST $c_2,4*$BNSZ($a0) # r[4]=c2; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_0,$b_5) + mfhi ($t_2,$a_0,$b_5) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_1,$b_4 # mul_add_c(a[1],b[4],c3,c1,c2); + $MULTU ($a_1,$b_4) # mul_add_c(a[1],b[4],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $c_2,$c_1,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_4) + mfhi ($t_2,$a_1,$b_4) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_2,$b_3 # mul_add_c(a[2],b[3],c3,c1,c2); + $MULTU ($a_2,$b_3) # mul_add_c(a[2],b[3],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_3) + mfhi ($t_2,$a_2,$b_3) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_3,$b_2 # mul_add_c(a[3],b[2],c3,c1,c2); + $MULTU ($a_3,$b_2) # mul_add_c(a[3],b[2],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_2) + mfhi ($t_2,$a_3,$b_2) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_4,$b_1 # mul_add_c(a[4],b[1],c3,c1,c2); + $MULTU ($a_4,$b_1) # mul_add_c(a[4],b[1],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_4,$b_1) + mfhi ($t_2,$a_4,$b_1) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_5,$b_0 # mul_add_c(a[5],b[0],c3,c1,c2); + $MULTU ($a_5,$b_0) # mul_add_c(a[5],b[0],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_5,$b_0) + mfhi ($t_2,$a_5,$b_0) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_6,$b_0 # mul_add_c(a[6],b[0],c1,c2,c3); + $MULTU ($a_6,$b_0) # mul_add_c(a[6],b[0],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at $ST $c_3,5*$BNSZ($a0) # r[5]=c3; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_6,$b_0) + mfhi ($t_2,$a_6,$b_0) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_5,$b_1 # mul_add_c(a[5],b[1],c1,c2,c3); + $MULTU ($a_5,$b_1) # mul_add_c(a[5],b[1],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $c_3,$c_2,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_5,$b_1) + mfhi ($t_2,$a_5,$b_1) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_4,$b_2 # mul_add_c(a[4],b[2],c1,c2,c3); + $MULTU ($a_4,$b_2) # mul_add_c(a[4],b[2],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_4,$b_2) + mfhi ($t_2,$a_4,$b_2) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_3,$b_3 # mul_add_c(a[3],b[3],c1,c2,c3); + $MULTU ($a_3,$b_3) # mul_add_c(a[3],b[3],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_3) + mfhi ($t_2,$a_3,$b_3) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_2,$b_4 # mul_add_c(a[2],b[4],c1,c2,c3); + $MULTU ($a_2,$b_4) # mul_add_c(a[2],b[4],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_4) + mfhi ($t_2,$a_2,$b_4) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_1,$b_5 # mul_add_c(a[1],b[5],c1,c2,c3); + $MULTU ($a_1,$b_5) # mul_add_c(a[1],b[5],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_5) + mfhi ($t_2,$a_1,$b_5) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_0,$b_6 # mul_add_c(a[0],b[6],c1,c2,c3); + $MULTU ($a_0,$b_6) # mul_add_c(a[0],b[6],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_0,$b_6) + mfhi ($t_2,$a_0,$b_6) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_0,$b_7 # mul_add_c(a[0],b[7],c2,c3,c1); + $MULTU ($a_0,$b_7) # mul_add_c(a[0],b[7],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at $ST $c_1,6*$BNSZ($a0) # r[6]=c1; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_0,$b_7) + mfhi ($t_2,$a_0,$b_7) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_1,$b_6 # mul_add_c(a[1],b[6],c2,c3,c1); + $MULTU ($a_1,$b_6) # mul_add_c(a[1],b[6],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $c_1,$c_3,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_6) + mfhi ($t_2,$a_1,$b_6) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_2,$b_5 # mul_add_c(a[2],b[5],c2,c3,c1); + $MULTU ($a_2,$b_5) # mul_add_c(a[2],b[5],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_5) + mfhi ($t_2,$a_2,$b_5) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_3,$b_4 # mul_add_c(a[3],b[4],c2,c3,c1); + $MULTU ($a_3,$b_4) # mul_add_c(a[3],b[4],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_4) + mfhi ($t_2,$a_3,$b_4) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_4,$b_3 # mul_add_c(a[4],b[3],c2,c3,c1); + $MULTU ($a_4,$b_3) # mul_add_c(a[4],b[3],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_4,$b_3) + mfhi ($t_2,$a_4,$b_3) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_5,$b_2 # mul_add_c(a[5],b[2],c2,c3,c1); + $MULTU ($a_5,$b_2) # mul_add_c(a[5],b[2],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_5,$b_2) + mfhi ($t_2,$a_5,$b_2) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_6,$b_1 # mul_add_c(a[6],b[1],c2,c3,c1); + $MULTU ($a_6,$b_1) # mul_add_c(a[6],b[1],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_6,$b_1) + mfhi ($t_2,$a_6,$b_1) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_7,$b_0 # mul_add_c(a[7],b[0],c2,c3,c1); + $MULTU ($a_7,$b_0) # mul_add_c(a[7],b[0],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_7,$b_0) + mfhi ($t_2,$a_7,$b_0) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_7,$b_1 # mul_add_c(a[7],b[1],c3,c1,c2); + $MULTU ($a_7,$b_1) # mul_add_c(a[7],b[1],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at $ST $c_2,7*$BNSZ($a0) # r[7]=c2; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_7,$b_1) + mfhi ($t_2,$a_7,$b_1) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_6,$b_2 # mul_add_c(a[6],b[2],c3,c1,c2); + $MULTU ($a_6,$b_2) # mul_add_c(a[6],b[2],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $c_2,$c_1,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_6,$b_2) + mfhi ($t_2,$a_6,$b_2) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_5,$b_3 # mul_add_c(a[5],b[3],c3,c1,c2); + $MULTU ($a_5,$b_3) # mul_add_c(a[5],b[3],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_5,$b_3) + mfhi ($t_2,$a_5,$b_3) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_4,$b_4 # mul_add_c(a[4],b[4],c3,c1,c2); + $MULTU ($a_4,$b_4) # mul_add_c(a[4],b[4],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_4,$b_4) + mfhi ($t_2,$a_4,$b_4) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_3,$b_5 # mul_add_c(a[3],b[5],c3,c1,c2); + $MULTU ($a_3,$b_5) # mul_add_c(a[3],b[5],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_5) + mfhi ($t_2,$a_3,$b_5) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_2,$b_6 # mul_add_c(a[2],b[6],c3,c1,c2); + $MULTU ($a_2,$b_6) # mul_add_c(a[2],b[6],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_6) + mfhi ($t_2,$a_2,$b_6) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_1,$b_7 # mul_add_c(a[1],b[7],c3,c1,c2); + $MULTU ($a_1,$b_7) # mul_add_c(a[1],b[7],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_7) + mfhi ($t_2,$a_1,$b_7) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_2,$b_7 # mul_add_c(a[2],b[7],c1,c2,c3); + $MULTU ($a_2,$b_7) # mul_add_c(a[2],b[7],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at $ST $c_3,8*$BNSZ($a0) # r[8]=c3; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_7) + mfhi ($t_2,$a_2,$b_7) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_3,$b_6 # mul_add_c(a[3],b[6],c1,c2,c3); + $MULTU ($a_3,$b_6) # mul_add_c(a[3],b[6],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $c_3,$c_2,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_6) + mfhi ($t_2,$a_3,$b_6) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_4,$b_5 # mul_add_c(a[4],b[5],c1,c2,c3); + $MULTU ($a_4,$b_5) # mul_add_c(a[4],b[5],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_4,$b_5) + mfhi ($t_2,$a_4,$b_5) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_5,$b_4 # mul_add_c(a[5],b[4],c1,c2,c3); + $MULTU ($a_5,$b_4) # mul_add_c(a[5],b[4],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_5,$b_4) + mfhi ($t_2,$a_5,$b_4) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_6,$b_3 # mul_add_c(a[6],b[3],c1,c2,c3); + $MULTU ($a_6,$b_3) # mul_add_c(a[6],b[3],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_6,$b_3) + mfhi ($t_2,$a_6,$b_3) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_7,$b_2 # mul_add_c(a[7],b[2],c1,c2,c3); + $MULTU ($a_7,$b_2) # mul_add_c(a[7],b[2],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_7,$b_2) + mfhi ($t_2,$a_7,$b_2) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_7,$b_3 # mul_add_c(a[7],b[3],c2,c3,c1); + $MULTU ($a_7,$b_3) # mul_add_c(a[7],b[3],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at $ST $c_1,9*$BNSZ($a0) # r[9]=c1; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_7,$b_3) + mfhi ($t_2,$a_7,$b_3) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_6,$b_4 # mul_add_c(a[6],b[4],c2,c3,c1); + $MULTU ($a_6,$b_4) # mul_add_c(a[6],b[4],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $c_1,$c_3,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_6,$b_4) + mfhi ($t_2,$a_6,$b_4) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_5,$b_5 # mul_add_c(a[5],b[5],c2,c3,c1); + $MULTU ($a_5,$b_5) # mul_add_c(a[5],b[5],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_5,$b_5) + mfhi ($t_2,$a_5,$b_5) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_4,$b_6 # mul_add_c(a[4],b[6],c2,c3,c1); + $MULTU ($a_4,$b_6) # mul_add_c(a[4],b[6],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_4,$b_6) + mfhi ($t_2,$a_4,$b_6) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_3,$b_7 # mul_add_c(a[3],b[7],c2,c3,c1); + $MULTU ($a_3,$b_7) # mul_add_c(a[3],b[7],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_7) + mfhi ($t_2,$a_3,$b_7) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_4,$b_7 # mul_add_c(a[4],b[7],c3,c1,c2); + $MULTU ($a_4,$b_7) # mul_add_c(a[4],b[7],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at $ST $c_2,10*$BNSZ($a0) # r[10]=c2; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_4,$b_7) + mfhi ($t_2,$a_4,$b_7) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_5,$b_6 # mul_add_c(a[5],b[6],c3,c1,c2); + $MULTU ($a_5,$b_6) # mul_add_c(a[5],b[6],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $c_2,$c_1,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_5,$b_6) + mfhi ($t_2,$a_5,$b_6) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_6,$b_5 # mul_add_c(a[6],b[5],c3,c1,c2); + $MULTU ($a_6,$b_5) # mul_add_c(a[6],b[5],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_6,$b_5) + mfhi ($t_2,$a_6,$b_5) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_7,$b_4 # mul_add_c(a[7],b[4],c3,c1,c2); + $MULTU ($a_7,$b_4) # mul_add_c(a[7],b[4],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_7,$b_4) + mfhi ($t_2,$a_7,$b_4) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_7,$b_5 # mul_add_c(a[7],b[5],c1,c2,c3); + $MULTU ($a_7,$b_5) # mul_add_c(a[7],b[5],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at $ST $c_3,11*$BNSZ($a0) # r[11]=c3; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_7,$b_5) + mfhi ($t_2,$a_7,$b_5) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_6,$b_6 # mul_add_c(a[6],b[6],c1,c2,c3); + $MULTU ($a_6,$b_6) # mul_add_c(a[6],b[6],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $c_3,$c_2,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_6,$b_6) + mfhi ($t_2,$a_6,$b_6) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_5,$b_7 # mul_add_c(a[5],b[7],c1,c2,c3); + $MULTU ($a_5,$b_7) # mul_add_c(a[5],b[7],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_5,$b_7) + mfhi ($t_2,$a_5,$b_7) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_6,$b_7 # mul_add_c(a[6],b[7],c2,c3,c1); + $MULTU ($a_6,$b_7) # mul_add_c(a[6],b[7],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at $ST $c_1,12*$BNSZ($a0) # r[12]=c1; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_6,$b_7) + mfhi ($t_2,$a_6,$b_7) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_7,$b_6 # mul_add_c(a[7],b[6],c2,c3,c1); + $MULTU ($a_7,$b_6) # mul_add_c(a[7],b[6],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $c_1,$c_3,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_7,$b_6) + mfhi ($t_2,$a_7,$b_6) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_7,$b_7 # mul_add_c(a[7],b[7],c3,c1,c2); + $MULTU ($a_7,$b_7) # mul_add_c(a[7],b[7],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at $ST $c_2,13*$BNSZ($a0) # r[13]=c2; - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_7,$b_7) + mfhi ($t_2,$a_7,$b_7) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 $ADDU $t_2,$at @@ -1716,144 +1732,144 @@ $code.=<<___; $LD $b_0,0($a2) $LD $a_1,$BNSZ($a1) $LD $a_2,2*$BNSZ($a1) - $MULTU $a_0,$b_0 # mul_add_c(a[0],b[0],c1,c2,c3); + $MULTU ($a_0,$b_0) # mul_add_c(a[0],b[0],c1,c2,c3); $LD $a_3,3*$BNSZ($a1) $LD $b_1,$BNSZ($a2) $LD $b_2,2*$BNSZ($a2) $LD $b_3,3*$BNSZ($a2) - mflo $c_1 - mfhi $c_2 + mflo ($c_1,$a_0,$b_0) + mfhi ($c_2,$a_0,$b_0) $ST $c_1,0($a0) - $MULTU $a_0,$b_1 # mul_add_c(a[0],b[1],c2,c3,c1); - mflo $t_1 - mfhi $t_2 + $MULTU ($a_0,$b_1) # mul_add_c(a[0],b[1],c2,c3,c1); + mflo ($t_1,$a_0,$b_1) + mfhi ($t_2,$a_0,$b_1) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_1,$b_0 # mul_add_c(a[1],b[0],c2,c3,c1); + $MULTU ($a_1,$b_0) # mul_add_c(a[1],b[0],c2,c3,c1); $ADDU $c_3,$t_2,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_0) + mfhi ($t_2,$a_1,$b_0) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_2,$b_0 # mul_add_c(a[2],b[0],c3,c1,c2); + $MULTU ($a_2,$b_0) # mul_add_c(a[2],b[0],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $c_1,$c_3,$t_2 $ST $c_2,$BNSZ($a0) - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_0) + mfhi ($t_2,$a_2,$b_0) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_1,$b_1 # mul_add_c(a[1],b[1],c3,c1,c2); + $MULTU ($a_1,$b_1) # mul_add_c(a[1],b[1],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_1) + mfhi ($t_2,$a_1,$b_1) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_0,$b_2 # mul_add_c(a[0],b[2],c3,c1,c2); + $MULTU ($a_0,$b_2) # mul_add_c(a[0],b[2],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $c_2,$c_1,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_0,$b_2) + mfhi ($t_2,$a_0,$b_2) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_0,$b_3 # mul_add_c(a[0],b[3],c1,c2,c3); + $MULTU ($a_0,$b_3) # mul_add_c(a[0],b[3],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at $ST $c_3,2*$BNSZ($a0) - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_0,$b_3) + mfhi ($t_2,$a_0,$b_3) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_1,$b_2 # mul_add_c(a[1],b[2],c1,c2,c3); + $MULTU ($a_1,$b_2) # mul_add_c(a[1],b[2],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $c_3,$c_2,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_2) + mfhi ($t_2,$a_1,$b_2) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_2,$b_1 # mul_add_c(a[2],b[1],c1,c2,c3); + $MULTU ($a_2,$b_1) # mul_add_c(a[2],b[1],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_1) + mfhi ($t_2,$a_2,$b_1) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_3,$b_0 # mul_add_c(a[3],b[0],c1,c2,c3); + $MULTU ($a_3,$b_0) # mul_add_c(a[3],b[0],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_0) + mfhi ($t_2,$a_3,$b_0) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_3,$b_1 # mul_add_c(a[3],b[1],c2,c3,c1); + $MULTU ($a_3,$b_1) # mul_add_c(a[3],b[1],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at $ST $c_1,3*$BNSZ($a0) - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_1) + mfhi ($t_2,$a_3,$b_1) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_2,$b_2 # mul_add_c(a[2],b[2],c2,c3,c1); + $MULTU ($a_2,$b_2) # mul_add_c(a[2],b[2],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $c_1,$c_3,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_2) + mfhi ($t_2,$a_2,$b_2) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_1,$b_3 # mul_add_c(a[1],b[3],c2,c3,c1); + $MULTU ($a_1,$b_3) # mul_add_c(a[1],b[3],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_1,$b_3) + mfhi ($t_2,$a_1,$b_3) $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_2,$b_3 # mul_add_c(a[2],b[3],c3,c1,c2); + $MULTU ($a_2,$b_3) # mul_add_c(a[2],b[3],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at $ST $c_2,4*$BNSZ($a0) - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_2,$b_3) + mfhi ($t_2,$a_2,$b_3) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_3,$b_2 # mul_add_c(a[3],b[2],c3,c1,c2); + $MULTU ($a_3,$b_2) # mul_add_c(a[3],b[2],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $c_2,$c_1,$t_2 - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_2) + mfhi ($t_2,$a_3,$b_2) $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_3,$b_3 # mul_add_c(a[3],b[3],c1,c2,c3); + $MULTU ($a_3,$b_3) # mul_add_c(a[3],b[3],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at $ST $c_3,5*$BNSZ($a0) - mflo $t_1 - mfhi $t_2 + mflo ($t_1,$a_3,$b_3) + mfhi ($t_2,$a_3,$b_3) $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 $ADDU $t_2,$at @@ -1888,11 +1904,9 @@ my ($hi,$lo,$c0,$c1,$c2, # commented as "forward multiplication" below]; )=@_; $code.=<<___; - mflo $lo - mfhi $hi $ADDU $c0,$lo sltu $at,$c0,$lo - $MULTU $an,$bn # forward multiplication + $MULTU ($an,$bn) # forward multiplication $ADDU $c0,$lo $ADDU $at,$hi sltu $lo,$c0,$lo @@ -1902,15 +1916,17 @@ ___ $code.=<<___ if (!$warm); sltu $c2,$c1,$at $ADDU $c1,$hi - sltu $hi,$c1,$hi - $ADDU $c2,$hi ___ $code.=<<___ if ($warm); sltu $at,$c1,$at $ADDU $c1,$hi $ADDU $c2,$at +___ +$code.=<<___; sltu $hi,$c1,$hi $ADDU $c2,$hi + mflo ($lo,$an,$bn) + mfhi ($hi,$an,$bn) ___ } @@ -1940,21 +1956,21 @@ $code.=<<___; $LD $a_2,2*$BNSZ($a1) $LD $a_3,3*$BNSZ($a1) - $MULTU $a_0,$a_0 # mul_add_c(a[0],b[0],c1,c2,c3); + $MULTU ($a_0,$a_0) # mul_add_c(a[0],b[0],c1,c2,c3); $LD $a_4,4*$BNSZ($a1) $LD $a_5,5*$BNSZ($a1) $LD $a_6,6*$BNSZ($a1) $LD $a_7,7*$BNSZ($a1) - mflo $c_1 - mfhi $c_2 + mflo ($c_1,$a_0,$a_0) + mfhi ($c_2,$a_0,$a_0) $ST $c_1,0($a0) - $MULTU $a_0,$a_1 # mul_add_c2(a[0],b[1],c2,c3,c1); - mflo $t_1 - mfhi $t_2 + $MULTU ($a_0,$a_1) # mul_add_c2(a[0],b[1],c2,c3,c1); + mflo ($t_1,$a_0,$a_1) + mfhi ($t_2,$a_0,$a_1) slt $c_1,$t_2,$zero $SLL $t_2,1 - $MULTU $a_2,$a_0 # mul_add_c2(a[2],b[0],c3,c1,c2); + $MULTU ($a_2,$a_0) # mul_add_c2(a[2],b[0],c3,c1,c2); slt $a2,$t_1,$zero $ADDU $t_2,$a2 $SLL $t_1,1 @@ -1962,20 +1978,22 @@ $code.=<<___; sltu $at,$c_2,$t_1 $ADDU $c_3,$t_2,$at $ST $c_2,$BNSZ($a0) + mflo ($t_1,$a_2,$a_0) + mfhi ($t_2,$a_2,$a_0) ___ &add_c2($t_2,$t_1,$c_3,$c_1,$c_2,0, $a_1,$a_1); # mul_add_c(a[1],b[1],c3,c1,c2); $code.=<<___; - mflo $t_1 - mfhi $t_2 $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_0,$a_3 # mul_add_c2(a[0],b[3],c1,c2,c3); + $MULTU ($a_0,$a_3) # mul_add_c2(a[0],b[3],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at $ST $c_3,2*$BNSZ($a0) + mflo ($t_1,$a_0,$a_3) + mfhi ($t_2,$a_0,$a_3) ___ &add_c2($t_2,$t_1,$c_1,$c_2,$c_3,0, $a_1,$a_2); # mul_add_c2(a[1],b[2],c1,c2,c3); @@ -1989,16 +2007,16 @@ ___ &add_c2($t_2,$t_1,$c_2,$c_3,$c_1,1, $a_2,$a_2); # mul_add_c(a[2],b[2],c2,c3,c1); $code.=<<___; - mflo $t_1 - mfhi $t_2 $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_0,$a_5 # mul_add_c2(a[0],b[5],c3,c1,c2); + $MULTU ($a_0,$a_5) # mul_add_c2(a[0],b[5],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at $ST $c_2,4*$BNSZ($a0) + mflo ($t_1,$a_0,$a_5) + mfhi ($t_2,$a_0,$a_5) ___ &add_c2($t_2,$t_1,$c_3,$c_1,$c_2,0, $a_1,$a_4); # mul_add_c2(a[1],b[4],c3,c1,c2); @@ -2016,16 +2034,16 @@ ___ &add_c2($t_2,$t_1,$c_1,$c_2,$c_3,1, $a_3,$a_3); # mul_add_c(a[3],b[3],c1,c2,c3); $code.=<<___; - mflo $t_1 - mfhi $t_2 $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_0,$a_7 # mul_add_c2(a[0],b[7],c2,c3,c1); + $MULTU ($a_0,$a_7) # mul_add_c2(a[0],b[7],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at $ST $c_1,6*$BNSZ($a0) + mflo ($t_1,$a_0,$a_7) + mfhi ($t_2,$a_0,$a_7) ___ &add_c2($t_2,$t_1,$c_2,$c_3,$c_1,0, $a_1,$a_6); # mul_add_c2(a[1],b[6],c2,c3,c1); @@ -2045,16 +2063,16 @@ ___ &add_c2($t_2,$t_1,$c_3,$c_1,$c_2,1, $a_4,$a_4); # mul_add_c(a[4],b[4],c3,c1,c2); $code.=<<___; - mflo $t_1 - mfhi $t_2 $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_2,$a_7 # mul_add_c2(a[2],b[7],c1,c2,c3); + $MULTU ($a_2,$a_7) # mul_add_c2(a[2],b[7],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at $ST $c_3,8*$BNSZ($a0) + mflo ($t_1,$a_2,$a_7) + mfhi ($t_2,$a_2,$a_7) ___ &add_c2($t_2,$t_1,$c_1,$c_2,$c_3,0, $a_3,$a_6); # mul_add_c2(a[3],b[6],c1,c2,c3); @@ -2070,16 +2088,16 @@ ___ &add_c2($t_2,$t_1,$c_2,$c_3,$c_1,1, $a_5,$a_5); # mul_add_c(a[5],b[5],c2,c3,c1); $code.=<<___; - mflo $t_1 - mfhi $t_2 $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_4,$a_7 # mul_add_c2(a[4],b[7],c3,c1,c2); + $MULTU ($a_4,$a_7) # mul_add_c2(a[4],b[7],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at $ST $c_2,10*$BNSZ($a0) + mflo ($t_1,$a_4,$a_7) + mfhi ($t_2,$a_4,$a_7) ___ &add_c2($t_2,$t_1,$c_3,$c_1,$c_2,0, $a_5,$a_6); # mul_add_c2(a[5],b[6],c3,c1,c2); @@ -2091,24 +2109,22 @@ ___ &add_c2($t_2,$t_1,$c_1,$c_2,$c_3,0, $a_6,$a_6); # mul_add_c(a[6],b[6],c1,c2,c3); $code.=<<___; - mflo $t_1 - mfhi $t_2 $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 - $MULTU $a_6,$a_7 # mul_add_c2(a[6],b[7],c2,c3,c1); + $MULTU ($a_6,$a_7) # mul_add_c2(a[6],b[7],c2,c3,c1); $ADDU $t_2,$at $ADDU $c_2,$t_2 sltu $at,$c_2,$t_2 $ADDU $c_3,$at $ST $c_1,12*$BNSZ($a0) + mflo ($t_1,$a_6,$a_7) + mfhi ($t_2,$a_6,$a_7) ___ &add_c2($t_2,$t_1,$c_2,$c_3,$c_1,0, $a_7,$a_7); # mul_add_c(a[7],b[7],c3,c1,c2); $code.=<<___; $ST $c_2,13*$BNSZ($a0) - mflo $t_1 - mfhi $t_2 $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 $ADDU $t_2,$at @@ -2152,19 +2168,19 @@ $code.=<<___; .set reorder $LD $a_0,0($a1) $LD $a_1,$BNSZ($a1) - $MULTU $a_0,$a_0 # mul_add_c(a[0],b[0],c1,c2,c3); + $MULTU ($a_0,$a_0) # mul_add_c(a[0],b[0],c1,c2,c3); $LD $a_2,2*$BNSZ($a1) $LD $a_3,3*$BNSZ($a1) - mflo $c_1 - mfhi $c_2 + mflo ($c_1,$a_0,$a_0) + mfhi ($c_2,$a_0,$a_0) $ST $c_1,0($a0) - $MULTU $a_0,$a_1 # mul_add_c2(a[0],b[1],c2,c3,c1); - mflo $t_1 - mfhi $t_2 + $MULTU ($a_0,$a_1) # mul_add_c2(a[0],b[1],c2,c3,c1); + mflo ($t_1,$a_0,$a_1) + mfhi ($t_2,$a_0,$a_1) slt $c_1,$t_2,$zero $SLL $t_2,1 - $MULTU $a_2,$a_0 # mul_add_c2(a[2],b[0],c3,c1,c2); + $MULTU ($a_2,$a_0) # mul_add_c2(a[2],b[0],c3,c1,c2); slt $a2,$t_1,$zero $ADDU $t_2,$a2 $SLL $t_1,1 @@ -2172,20 +2188,22 @@ $code.=<<___; sltu $at,$c_2,$t_1 $ADDU $c_3,$t_2,$at $ST $c_2,$BNSZ($a0) + mflo ($t_1,$a_2,$a_0) + mfhi ($t_2,$a_2,$a_0) ___ &add_c2($t_2,$t_1,$c_3,$c_1,$c_2,0, $a_1,$a_1); # mul_add_c(a[1],b[1],c3,c1,c2); $code.=<<___; - mflo $t_1 - mfhi $t_2 $ADDU $c_3,$t_1 sltu $at,$c_3,$t_1 - $MULTU $a_0,$a_3 # mul_add_c2(a[0],b[3],c1,c2,c3); + $MULTU ($a_0,$a_3) # mul_add_c2(a[0],b[3],c1,c2,c3); $ADDU $t_2,$at $ADDU $c_1,$t_2 sltu $at,$c_1,$t_2 $ADDU $c_2,$at $ST $c_3,2*$BNSZ($a0) + mflo ($t_1,$a_0,$a_3) + mfhi ($t_2,$a_0,$a_3) ___ &add_c2($t_2,$t_1,$c_1,$c_2,$c_3,0, $a_1,$a_2); # mul_add_c2(a2[1],b[2],c1,c2,c3); @@ -2197,24 +2215,22 @@ ___ &add_c2($t_2,$t_1,$c_2,$c_3,$c_1,0, $a_2,$a_2); # mul_add_c(a[2],b[2],c2,c3,c1); $code.=<<___; - mflo $t_1 - mfhi $t_2 $ADDU $c_2,$t_1 sltu $at,$c_2,$t_1 - $MULTU $a_2,$a_3 # mul_add_c2(a[2],b[3],c3,c1,c2); + $MULTU ($a_2,$a_3) # mul_add_c2(a[2],b[3],c3,c1,c2); $ADDU $t_2,$at $ADDU $c_3,$t_2 sltu $at,$c_3,$t_2 $ADDU $c_1,$at $ST $c_2,4*$BNSZ($a0) + mflo ($t_1,$a_2,$a_3) + mfhi ($t_2,$a_2,$a_3) ___ &add_c2($t_2,$t_1,$c_3,$c_1,$c_2,0, $a_3,$a_3); # mul_add_c(a[3],b[3],c1,c2,c3); $code.=<<___; $ST $c_3,5*$BNSZ($a0) - mflo $t_1 - mfhi $t_2 $ADDU $c_1,$t_1 sltu $at,$c_1,$t_1 $ADDU $t_2,$at diff --git a/crypto/bn/asm/pa-risc2.s b/crypto/bn/asm/pa-risc2.s deleted file mode 100644 index 413eac71..00000000 --- a/crypto/bn/asm/pa-risc2.s +++ /dev/null @@ -1,1624 +0,0 @@ -; Copyright 1998-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 -; -; PA-RISC 2.0 implementation of bn_asm code, based on the -; 64-bit version of the code. This code is effectively the -; same as the 64-bit version except the register model is -; slightly different given all values must be 32-bit between -; function calls. Thus the 64-bit return values are returned -; in %ret0 and %ret1 vs just %ret0 as is done in 64-bit -; -; -; This code is approximately 2x faster than the C version -; for RSA/DSA. -; -; See http://devresource.hp.com/ for more details on the PA-RISC -; architecture. Also see the book "PA-RISC 2.0 Architecture" -; by Gerry Kane for information on the instruction set architecture. -; -; Code written by Chris Ruemmler (with some help from the HP C -; compiler). -; -; The code compiles with HP's assembler -; - - .level 2.0N - .space $TEXT$ - .subspa $CODE$,QUAD=0,ALIGN=8,ACCESS=0x2c,CODE_ONLY - -; -; Global Register definitions used for the routines. -; -; Some information about HP's runtime architecture for 32-bits. -; -; "Caller save" means the calling function must save the register -; if it wants the register to be preserved. -; "Callee save" means if a function uses the register, it must save -; the value before using it. -; -; For the floating point registers -; -; "caller save" registers: fr4-fr11, fr22-fr31 -; "callee save" registers: fr12-fr21 -; "special" registers: fr0-fr3 (status and exception registers) -; -; For the integer registers -; value zero : r0 -; "caller save" registers: r1,r19-r26 -; "callee save" registers: r3-r18 -; return register : r2 (rp) -; return values ; r28,r29 (ret0,ret1) -; Stack pointer ; r30 (sp) -; millicode return ptr ; r31 (also a caller save register) - - -; -; Arguments to the routines -; -r_ptr .reg %r26 -a_ptr .reg %r25 -b_ptr .reg %r24 -num .reg %r24 -n .reg %r23 - -; -; Note that the "w" argument for bn_mul_add_words and bn_mul_words -; is passed on the stack at a delta of -56 from the top of stack -; as the routine is entered. -; - -; -; Globals used in some routines -; - -top_overflow .reg %r23 -high_mask .reg %r22 ; value 0xffffffff80000000L - - -;------------------------------------------------------------------------------ -; -; bn_mul_add_words -; -;BN_ULONG bn_mul_add_words(BN_ULONG *r_ptr, BN_ULONG *a_ptr, -; int num, BN_ULONG w) -; -; arg0 = r_ptr -; arg1 = a_ptr -; arg3 = num -; -56(sp) = w -; -; Local register definitions -; - -fm1 .reg %fr22 -fm .reg %fr23 -ht_temp .reg %fr24 -ht_temp_1 .reg %fr25 -lt_temp .reg %fr26 -lt_temp_1 .reg %fr27 -fm1_1 .reg %fr28 -fm_1 .reg %fr29 - -fw_h .reg %fr7L -fw_l .reg %fr7R -fw .reg %fr7 - -fht_0 .reg %fr8L -flt_0 .reg %fr8R -t_float_0 .reg %fr8 - -fht_1 .reg %fr9L -flt_1 .reg %fr9R -t_float_1 .reg %fr9 - -tmp_0 .reg %r31 -tmp_1 .reg %r21 -m_0 .reg %r20 -m_1 .reg %r19 -ht_0 .reg %r1 -ht_1 .reg %r3 -lt_0 .reg %r4 -lt_1 .reg %r5 -m1_0 .reg %r6 -m1_1 .reg %r7 -rp_val .reg %r8 -rp_val_1 .reg %r9 - -bn_mul_add_words - .export bn_mul_add_words,entry,NO_RELOCATION,LONG_RETURN - .proc - .callinfo frame=128 - .entry - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - NOP ; Needed to make the loop 16-byte aligned - NOP ; needed to make the loop 16-byte aligned - - STD %r5,16(%sp) ; save r5 - NOP - STD %r6,24(%sp) ; save r6 - STD %r7,32(%sp) ; save r7 - - STD %r8,40(%sp) ; save r8 - STD %r9,48(%sp) ; save r9 - COPY %r0,%ret1 ; return 0 by default - DEPDI,Z 1,31,1,top_overflow ; top_overflow = 1 << 32 - - CMPIB,>= 0,num,bn_mul_add_words_exit ; if (num <= 0) then exit - LDO 128(%sp),%sp ; bump stack - - ; - ; The loop is unrolled twice, so if there is only 1 number - ; then go straight to the cleanup code. - ; - CMPIB,= 1,num,bn_mul_add_words_single_top - FLDD -184(%sp),fw ; (-56-128) load up w into fw (fw_h/fw_l) - - ; - ; This loop is unrolled 2 times (64-byte aligned as well) - ; - ; PA-RISC 2.0 chips have two fully pipelined multipliers, thus - ; two 32-bit mutiplies can be issued per cycle. - ; -bn_mul_add_words_unroll2 - - FLDD 0(a_ptr),t_float_0 ; load up 64-bit value (fr8L) ht(L)/lt(R) - FLDD 8(a_ptr),t_float_1 ; load up 64-bit value (fr8L) ht(L)/lt(R) - LDD 0(r_ptr),rp_val ; rp[0] - LDD 8(r_ptr),rp_val_1 ; rp[1] - - XMPYU fht_0,fw_l,fm1 ; m1[0] = fht_0*fw_l - XMPYU fht_1,fw_l,fm1_1 ; m1[1] = fht_1*fw_l - FSTD fm1,-16(%sp) ; -16(sp) = m1[0] - FSTD fm1_1,-48(%sp) ; -48(sp) = m1[1] - - XMPYU flt_0,fw_h,fm ; m[0] = flt_0*fw_h - XMPYU flt_1,fw_h,fm_1 ; m[1] = flt_1*fw_h - FSTD fm,-8(%sp) ; -8(sp) = m[0] - FSTD fm_1,-40(%sp) ; -40(sp) = m[1] - - XMPYU fht_0,fw_h,ht_temp ; ht_temp = fht_0*fw_h - XMPYU fht_1,fw_h,ht_temp_1 ; ht_temp_1 = fht_1*fw_h - FSTD ht_temp,-24(%sp) ; -24(sp) = ht_temp - FSTD ht_temp_1,-56(%sp) ; -56(sp) = ht_temp_1 - - XMPYU flt_0,fw_l,lt_temp ; lt_temp = lt*fw_l - XMPYU flt_1,fw_l,lt_temp_1 ; lt_temp = lt*fw_l - FSTD lt_temp,-32(%sp) ; -32(sp) = lt_temp - FSTD lt_temp_1,-64(%sp) ; -64(sp) = lt_temp_1 - - LDD -8(%sp),m_0 ; m[0] - LDD -40(%sp),m_1 ; m[1] - LDD -16(%sp),m1_0 ; m1[0] - LDD -48(%sp),m1_1 ; m1[1] - - LDD -24(%sp),ht_0 ; ht[0] - LDD -56(%sp),ht_1 ; ht[1] - ADD,L m1_0,m_0,tmp_0 ; tmp_0 = m[0] + m1[0]; - ADD,L m1_1,m_1,tmp_1 ; tmp_1 = m[1] + m1[1]; - - LDD -32(%sp),lt_0 - LDD -64(%sp),lt_1 - CMPCLR,*>>= tmp_0,m1_0, %r0 ; if (m[0] < m1[0]) - ADD,L ht_0,top_overflow,ht_0 ; ht[0] += (1<<32) - - CMPCLR,*>>= tmp_1,m1_1,%r0 ; if (m[1] < m1[1]) - ADD,L ht_1,top_overflow,ht_1 ; ht[1] += (1<<32) - EXTRD,U tmp_0,31,32,m_0 ; m[0]>>32 - DEPD,Z tmp_0,31,32,m1_0 ; m1[0] = m[0]<<32 - - EXTRD,U tmp_1,31,32,m_1 ; m[1]>>32 - DEPD,Z tmp_1,31,32,m1_1 ; m1[1] = m[1]<<32 - ADD,L ht_0,m_0,ht_0 ; ht[0]+= (m[0]>>32) - ADD,L ht_1,m_1,ht_1 ; ht[1]+= (m[1]>>32) - - ADD lt_0,m1_0,lt_0 ; lt[0] = lt[0]+m1[0]; - ADD,DC ht_0,%r0,ht_0 ; ht[0]++ - ADD lt_1,m1_1,lt_1 ; lt[1] = lt[1]+m1[1]; - ADD,DC ht_1,%r0,ht_1 ; ht[1]++ - - ADD %ret1,lt_0,lt_0 ; lt[0] = lt[0] + c; - ADD,DC ht_0,%r0,ht_0 ; ht[0]++ - ADD lt_0,rp_val,lt_0 ; lt[0] = lt[0]+rp[0] - ADD,DC ht_0,%r0,ht_0 ; ht[0]++ - - LDO -2(num),num ; num = num - 2; - ADD ht_0,lt_1,lt_1 ; lt[1] = lt[1] + ht_0 (c); - ADD,DC ht_1,%r0,ht_1 ; ht[1]++ - STD lt_0,0(r_ptr) ; rp[0] = lt[0] - - ADD lt_1,rp_val_1,lt_1 ; lt[1] = lt[1]+rp[1] - ADD,DC ht_1,%r0,%ret1 ; ht[1]++ - LDO 16(a_ptr),a_ptr ; a_ptr += 2 - - STD lt_1,8(r_ptr) ; rp[1] = lt[1] - CMPIB,<= 2,num,bn_mul_add_words_unroll2 ; go again if more to do - LDO 16(r_ptr),r_ptr ; r_ptr += 2 - - CMPIB,=,N 0,num,bn_mul_add_words_exit ; are we done, or cleanup last one - - ; - ; Top of loop aligned on 64-byte boundary - ; -bn_mul_add_words_single_top - FLDD 0(a_ptr),t_float_0 ; load up 64-bit value (fr8L) ht(L)/lt(R) - LDD 0(r_ptr),rp_val ; rp[0] - LDO 8(a_ptr),a_ptr ; a_ptr++ - XMPYU fht_0,fw_l,fm1 ; m1 = ht*fw_l - FSTD fm1,-16(%sp) ; -16(sp) = m1 - XMPYU flt_0,fw_h,fm ; m = lt*fw_h - FSTD fm,-8(%sp) ; -8(sp) = m - XMPYU fht_0,fw_h,ht_temp ; ht_temp = ht*fw_h - FSTD ht_temp,-24(%sp) ; -24(sp) = ht - XMPYU flt_0,fw_l,lt_temp ; lt_temp = lt*fw_l - FSTD lt_temp,-32(%sp) ; -32(sp) = lt - - LDD -8(%sp),m_0 - LDD -16(%sp),m1_0 ; m1 = temp1 - ADD,L m_0,m1_0,tmp_0 ; tmp_0 = m + m1; - LDD -24(%sp),ht_0 - LDD -32(%sp),lt_0 - - CMPCLR,*>>= tmp_0,m1_0,%r0 ; if (m < m1) - ADD,L ht_0,top_overflow,ht_0 ; ht += (1<<32) - - EXTRD,U tmp_0,31,32,m_0 ; m>>32 - DEPD,Z tmp_0,31,32,m1_0 ; m1 = m<<32 - - ADD,L ht_0,m_0,ht_0 ; ht+= (m>>32) - ADD lt_0,m1_0,tmp_0 ; tmp_0 = lt+m1; - ADD,DC ht_0,%r0,ht_0 ; ht++ - ADD %ret1,tmp_0,lt_0 ; lt = lt + c; - ADD,DC ht_0,%r0,ht_0 ; ht++ - ADD lt_0,rp_val,lt_0 ; lt = lt+rp[0] - ADD,DC ht_0,%r0,%ret1 ; ht++ - STD lt_0,0(r_ptr) ; rp[0] = lt - -bn_mul_add_words_exit - .EXIT - - EXTRD,U %ret1,31,32,%ret0 ; for 32-bit, return in ret0/ret1 - LDD -80(%sp),%r9 ; restore r9 - LDD -88(%sp),%r8 ; restore r8 - LDD -96(%sp),%r7 ; restore r7 - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 ; restore r3 - .PROCEND ;in=23,24,25,26,29;out=28; - -;---------------------------------------------------------------------------- -; -;BN_ULONG bn_mul_words(BN_ULONG *rp, BN_ULONG *ap, int num, BN_ULONG w) -; -; arg0 = rp -; arg1 = ap -; arg3 = num -; w on stack at -56(sp) - -bn_mul_words - .proc - .callinfo frame=128 - .entry - .EXPORT bn_mul_words,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - NOP - STD %r5,16(%sp) ; save r5 - - STD %r6,24(%sp) ; save r6 - STD %r7,32(%sp) ; save r7 - COPY %r0,%ret1 ; return 0 by default - DEPDI,Z 1,31,1,top_overflow ; top_overflow = 1 << 32 - - CMPIB,>= 0,num,bn_mul_words_exit - LDO 128(%sp),%sp ; bump stack - - ; - ; See if only 1 word to do, thus just do cleanup - ; - CMPIB,= 1,num,bn_mul_words_single_top - FLDD -184(%sp),fw ; (-56-128) load up w into fw (fw_h/fw_l) - - ; - ; This loop is unrolled 2 times (64-byte aligned as well) - ; - ; PA-RISC 2.0 chips have two fully pipelined multipliers, thus - ; two 32-bit mutiplies can be issued per cycle. - ; -bn_mul_words_unroll2 - - FLDD 0(a_ptr),t_float_0 ; load up 64-bit value (fr8L) ht(L)/lt(R) - FLDD 8(a_ptr),t_float_1 ; load up 64-bit value (fr8L) ht(L)/lt(R) - XMPYU fht_0,fw_l,fm1 ; m1[0] = fht_0*fw_l - XMPYU fht_1,fw_l,fm1_1 ; m1[1] = ht*fw_l - - FSTD fm1,-16(%sp) ; -16(sp) = m1 - FSTD fm1_1,-48(%sp) ; -48(sp) = m1 - XMPYU flt_0,fw_h,fm ; m = lt*fw_h - XMPYU flt_1,fw_h,fm_1 ; m = lt*fw_h - - FSTD fm,-8(%sp) ; -8(sp) = m - FSTD fm_1,-40(%sp) ; -40(sp) = m - XMPYU fht_0,fw_h,ht_temp ; ht_temp = fht_0*fw_h - XMPYU fht_1,fw_h,ht_temp_1 ; ht_temp = ht*fw_h - - FSTD ht_temp,-24(%sp) ; -24(sp) = ht - FSTD ht_temp_1,-56(%sp) ; -56(sp) = ht - XMPYU flt_0,fw_l,lt_temp ; lt_temp = lt*fw_l - XMPYU flt_1,fw_l,lt_temp_1 ; lt_temp = lt*fw_l - - FSTD lt_temp,-32(%sp) ; -32(sp) = lt - FSTD lt_temp_1,-64(%sp) ; -64(sp) = lt - LDD -8(%sp),m_0 - LDD -40(%sp),m_1 - - LDD -16(%sp),m1_0 - LDD -48(%sp),m1_1 - LDD -24(%sp),ht_0 - LDD -56(%sp),ht_1 - - ADD,L m1_0,m_0,tmp_0 ; tmp_0 = m + m1; - ADD,L m1_1,m_1,tmp_1 ; tmp_1 = m + m1; - LDD -32(%sp),lt_0 - LDD -64(%sp),lt_1 - - CMPCLR,*>>= tmp_0,m1_0, %r0 ; if (m < m1) - ADD,L ht_0,top_overflow,ht_0 ; ht += (1<<32) - CMPCLR,*>>= tmp_1,m1_1,%r0 ; if (m < m1) - ADD,L ht_1,top_overflow,ht_1 ; ht += (1<<32) - - EXTRD,U tmp_0,31,32,m_0 ; m>>32 - DEPD,Z tmp_0,31,32,m1_0 ; m1 = m<<32 - EXTRD,U tmp_1,31,32,m_1 ; m>>32 - DEPD,Z tmp_1,31,32,m1_1 ; m1 = m<<32 - - ADD,L ht_0,m_0,ht_0 ; ht+= (m>>32) - ADD,L ht_1,m_1,ht_1 ; ht+= (m>>32) - ADD lt_0,m1_0,lt_0 ; lt = lt+m1; - ADD,DC ht_0,%r0,ht_0 ; ht++ - - ADD lt_1,m1_1,lt_1 ; lt = lt+m1; - ADD,DC ht_1,%r0,ht_1 ; ht++ - ADD %ret1,lt_0,lt_0 ; lt = lt + c (ret1); - ADD,DC ht_0,%r0,ht_0 ; ht++ - - ADD ht_0,lt_1,lt_1 ; lt = lt + c (ht_0) - ADD,DC ht_1,%r0,ht_1 ; ht++ - STD lt_0,0(r_ptr) ; rp[0] = lt - STD lt_1,8(r_ptr) ; rp[1] = lt - - COPY ht_1,%ret1 ; carry = ht - LDO -2(num),num ; num = num - 2; - LDO 16(a_ptr),a_ptr ; ap += 2 - CMPIB,<= 2,num,bn_mul_words_unroll2 - LDO 16(r_ptr),r_ptr ; rp++ - - CMPIB,=,N 0,num,bn_mul_words_exit ; are we done? - - ; - ; Top of loop aligned on 64-byte boundary - ; -bn_mul_words_single_top - FLDD 0(a_ptr),t_float_0 ; load up 64-bit value (fr8L) ht(L)/lt(R) - - XMPYU fht_0,fw_l,fm1 ; m1 = ht*fw_l - FSTD fm1,-16(%sp) ; -16(sp) = m1 - XMPYU flt_0,fw_h,fm ; m = lt*fw_h - FSTD fm,-8(%sp) ; -8(sp) = m - XMPYU fht_0,fw_h,ht_temp ; ht_temp = ht*fw_h - FSTD ht_temp,-24(%sp) ; -24(sp) = ht - XMPYU flt_0,fw_l,lt_temp ; lt_temp = lt*fw_l - FSTD lt_temp,-32(%sp) ; -32(sp) = lt - - LDD -8(%sp),m_0 - LDD -16(%sp),m1_0 - ADD,L m_0,m1_0,tmp_0 ; tmp_0 = m + m1; - LDD -24(%sp),ht_0 - LDD -32(%sp),lt_0 - - CMPCLR,*>>= tmp_0,m1_0,%r0 ; if (m < m1) - ADD,L ht_0,top_overflow,ht_0 ; ht += (1<<32) - - EXTRD,U tmp_0,31,32,m_0 ; m>>32 - DEPD,Z tmp_0,31,32,m1_0 ; m1 = m<<32 - - ADD,L ht_0,m_0,ht_0 ; ht+= (m>>32) - ADD lt_0,m1_0,lt_0 ; lt= lt+m1; - ADD,DC ht_0,%r0,ht_0 ; ht++ - - ADD %ret1,lt_0,lt_0 ; lt = lt + c; - ADD,DC ht_0,%r0,ht_0 ; ht++ - - COPY ht_0,%ret1 ; copy carry - STD lt_0,0(r_ptr) ; rp[0] = lt - -bn_mul_words_exit - .EXIT - EXTRD,U %ret1,31,32,%ret0 ; for 32-bit, return in ret0/ret1 - LDD -96(%sp),%r7 ; restore r7 - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 ; restore r3 - .PROCEND - -;---------------------------------------------------------------------------- -; -;void bn_sqr_words(BN_ULONG *rp, BN_ULONG *ap, int num) -; -; arg0 = rp -; arg1 = ap -; arg2 = num -; - -bn_sqr_words - .proc - .callinfo FRAME=128,ENTRY_GR=%r3,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_sqr_words,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .entry - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - NOP - STD %r5,16(%sp) ; save r5 - - CMPIB,>= 0,num,bn_sqr_words_exit - LDO 128(%sp),%sp ; bump stack - - ; - ; If only 1, the goto straight to cleanup - ; - CMPIB,= 1,num,bn_sqr_words_single_top - DEPDI,Z -1,32,33,high_mask ; Create Mask 0xffffffff80000000L - - ; - ; This loop is unrolled 2 times (64-byte aligned as well) - ; - -bn_sqr_words_unroll2 - FLDD 0(a_ptr),t_float_0 ; a[0] - FLDD 8(a_ptr),t_float_1 ; a[1] - XMPYU fht_0,flt_0,fm ; m[0] - XMPYU fht_1,flt_1,fm_1 ; m[1] - - FSTD fm,-24(%sp) ; store m[0] - FSTD fm_1,-56(%sp) ; store m[1] - XMPYU flt_0,flt_0,lt_temp ; lt[0] - XMPYU flt_1,flt_1,lt_temp_1 ; lt[1] - - FSTD lt_temp,-16(%sp) ; store lt[0] - FSTD lt_temp_1,-48(%sp) ; store lt[1] - XMPYU fht_0,fht_0,ht_temp ; ht[0] - XMPYU fht_1,fht_1,ht_temp_1 ; ht[1] - - FSTD ht_temp,-8(%sp) ; store ht[0] - FSTD ht_temp_1,-40(%sp) ; store ht[1] - LDD -24(%sp),m_0 - LDD -56(%sp),m_1 - - AND m_0,high_mask,tmp_0 ; m[0] & Mask - AND m_1,high_mask,tmp_1 ; m[1] & Mask - DEPD,Z m_0,30,31,m_0 ; m[0] << 32+1 - DEPD,Z m_1,30,31,m_1 ; m[1] << 32+1 - - LDD -16(%sp),lt_0 - LDD -48(%sp),lt_1 - EXTRD,U tmp_0,32,33,tmp_0 ; tmp_0 = m[0]&Mask >> 32-1 - EXTRD,U tmp_1,32,33,tmp_1 ; tmp_1 = m[1]&Mask >> 32-1 - - LDD -8(%sp),ht_0 - LDD -40(%sp),ht_1 - ADD,L ht_0,tmp_0,ht_0 ; ht[0] += tmp_0 - ADD,L ht_1,tmp_1,ht_1 ; ht[1] += tmp_1 - - ADD lt_0,m_0,lt_0 ; lt = lt+m - ADD,DC ht_0,%r0,ht_0 ; ht[0]++ - STD lt_0,0(r_ptr) ; rp[0] = lt[0] - STD ht_0,8(r_ptr) ; rp[1] = ht[1] - - ADD lt_1,m_1,lt_1 ; lt = lt+m - ADD,DC ht_1,%r0,ht_1 ; ht[1]++ - STD lt_1,16(r_ptr) ; rp[2] = lt[1] - STD ht_1,24(r_ptr) ; rp[3] = ht[1] - - LDO -2(num),num ; num = num - 2; - LDO 16(a_ptr),a_ptr ; ap += 2 - CMPIB,<= 2,num,bn_sqr_words_unroll2 - LDO 32(r_ptr),r_ptr ; rp += 4 - - CMPIB,=,N 0,num,bn_sqr_words_exit ; are we done? - - ; - ; Top of loop aligned on 64-byte boundary - ; -bn_sqr_words_single_top - FLDD 0(a_ptr),t_float_0 ; load up 64-bit value (fr8L) ht(L)/lt(R) - - XMPYU fht_0,flt_0,fm ; m - FSTD fm,-24(%sp) ; store m - - XMPYU flt_0,flt_0,lt_temp ; lt - FSTD lt_temp,-16(%sp) ; store lt - - XMPYU fht_0,fht_0,ht_temp ; ht - FSTD ht_temp,-8(%sp) ; store ht - - LDD -24(%sp),m_0 ; load m - AND m_0,high_mask,tmp_0 ; m & Mask - DEPD,Z m_0,30,31,m_0 ; m << 32+1 - LDD -16(%sp),lt_0 ; lt - - LDD -8(%sp),ht_0 ; ht - EXTRD,U tmp_0,32,33,tmp_0 ; tmp_0 = m&Mask >> 32-1 - ADD m_0,lt_0,lt_0 ; lt = lt+m - ADD,L ht_0,tmp_0,ht_0 ; ht += tmp_0 - ADD,DC ht_0,%r0,ht_0 ; ht++ - - STD lt_0,0(r_ptr) ; rp[0] = lt - STD ht_0,8(r_ptr) ; rp[1] = ht - -bn_sqr_words_exit - .EXIT - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 - .PROCEND ;in=23,24,25,26,29;out=28; - - -;---------------------------------------------------------------------------- -; -;BN_ULONG bn_add_words(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) -; -; arg0 = rp -; arg1 = ap -; arg2 = bp -; arg3 = n - -t .reg %r22 -b .reg %r21 -l .reg %r20 - -bn_add_words - .proc - .entry - .callinfo - .EXPORT bn_add_words,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .align 64 - - CMPIB,>= 0,n,bn_add_words_exit - COPY %r0,%ret1 ; return 0 by default - - ; - ; If 2 or more numbers do the loop - ; - CMPIB,= 1,n,bn_add_words_single_top - NOP - - ; - ; This loop is unrolled 2 times (64-byte aligned as well) - ; -bn_add_words_unroll2 - LDD 0(a_ptr),t - LDD 0(b_ptr),b - ADD t,%ret1,t ; t = t+c; - ADD,DC %r0,%r0,%ret1 ; set c to carry - ADD t,b,l ; l = t + b[0] - ADD,DC %ret1,%r0,%ret1 ; c+= carry - STD l,0(r_ptr) - - LDD 8(a_ptr),t - LDD 8(b_ptr),b - ADD t,%ret1,t ; t = t+c; - ADD,DC %r0,%r0,%ret1 ; set c to carry - ADD t,b,l ; l = t + b[0] - ADD,DC %ret1,%r0,%ret1 ; c+= carry - STD l,8(r_ptr) - - LDO -2(n),n - LDO 16(a_ptr),a_ptr - LDO 16(b_ptr),b_ptr - - CMPIB,<= 2,n,bn_add_words_unroll2 - LDO 16(r_ptr),r_ptr - - CMPIB,=,N 0,n,bn_add_words_exit ; are we done? - -bn_add_words_single_top - LDD 0(a_ptr),t - LDD 0(b_ptr),b - - ADD t,%ret1,t ; t = t+c; - ADD,DC %r0,%r0,%ret1 ; set c to carry (could use CMPCLR??) - ADD t,b,l ; l = t + b[0] - ADD,DC %ret1,%r0,%ret1 ; c+= carry - STD l,0(r_ptr) - -bn_add_words_exit - .EXIT - BVE (%rp) - EXTRD,U %ret1,31,32,%ret0 ; for 32-bit, return in ret0/ret1 - .PROCEND ;in=23,24,25,26,29;out=28; - -;---------------------------------------------------------------------------- -; -;BN_ULONG bn_sub_words(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) -; -; arg0 = rp -; arg1 = ap -; arg2 = bp -; arg3 = n - -t1 .reg %r22 -t2 .reg %r21 -sub_tmp1 .reg %r20 -sub_tmp2 .reg %r19 - - -bn_sub_words - .proc - .callinfo - .EXPORT bn_sub_words,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .entry - .align 64 - - CMPIB,>= 0,n,bn_sub_words_exit - COPY %r0,%ret1 ; return 0 by default - - ; - ; If 2 or more numbers do the loop - ; - CMPIB,= 1,n,bn_sub_words_single_top - NOP - - ; - ; This loop is unrolled 2 times (64-byte aligned as well) - ; -bn_sub_words_unroll2 - LDD 0(a_ptr),t1 - LDD 0(b_ptr),t2 - SUB t1,t2,sub_tmp1 ; t3 = t1-t2; - SUB sub_tmp1,%ret1,sub_tmp1 ; t3 = t3- c; - - CMPCLR,*>> t1,t2,sub_tmp2 ; clear if t1 > t2 - LDO 1(%r0),sub_tmp2 - - CMPCLR,*= t1,t2,%r0 - COPY sub_tmp2,%ret1 - STD sub_tmp1,0(r_ptr) - - LDD 8(a_ptr),t1 - LDD 8(b_ptr),t2 - SUB t1,t2,sub_tmp1 ; t3 = t1-t2; - SUB sub_tmp1,%ret1,sub_tmp1 ; t3 = t3- c; - CMPCLR,*>> t1,t2,sub_tmp2 ; clear if t1 > t2 - LDO 1(%r0),sub_tmp2 - - CMPCLR,*= t1,t2,%r0 - COPY sub_tmp2,%ret1 - STD sub_tmp1,8(r_ptr) - - LDO -2(n),n - LDO 16(a_ptr),a_ptr - LDO 16(b_ptr),b_ptr - - CMPIB,<= 2,n,bn_sub_words_unroll2 - LDO 16(r_ptr),r_ptr - - CMPIB,=,N 0,n,bn_sub_words_exit ; are we done? - -bn_sub_words_single_top - LDD 0(a_ptr),t1 - LDD 0(b_ptr),t2 - SUB t1,t2,sub_tmp1 ; t3 = t1-t2; - SUB sub_tmp1,%ret1,sub_tmp1 ; t3 = t3- c; - CMPCLR,*>> t1,t2,sub_tmp2 ; clear if t1 > t2 - LDO 1(%r0),sub_tmp2 - - CMPCLR,*= t1,t2,%r0 - COPY sub_tmp2,%ret1 - - STD sub_tmp1,0(r_ptr) - -bn_sub_words_exit - .EXIT - BVE (%rp) - EXTRD,U %ret1,31,32,%ret0 ; for 32-bit, return in ret0/ret1 - .PROCEND ;in=23,24,25,26,29;out=28; - -;------------------------------------------------------------------------------ -; -; unsigned long bn_div_words(unsigned long h, unsigned long l, unsigned long d) -; -; arg0 = h -; arg1 = l -; arg2 = d -; -; This is mainly just output from the HP C compiler. -; -;------------------------------------------------------------------------------ -bn_div_words - .PROC - .EXPORT bn_div_words,ENTRY,PRIV_LEV=3,ARGW0=GR,ARGW1=GR,ARGW2=GR,ARGW3=GR,RTNVAL=GR,LONG_RETURN - .IMPORT BN_num_bits_word,CODE - ;--- not PIC .IMPORT __iob,DATA - ;--- not PIC .IMPORT fprintf,CODE - .IMPORT abort,CODE - .IMPORT $$div2U,MILLICODE - .CALLINFO CALLER,FRAME=144,ENTRY_GR=%r9,SAVE_RP,ARGS_SAVED,ORDERING_AWARE - .ENTRY - STW %r2,-20(%r30) ;offset 0x8ec - STW,MA %r3,192(%r30) ;offset 0x8f0 - STW %r4,-188(%r30) ;offset 0x8f4 - DEPD %r5,31,32,%r6 ;offset 0x8f8 - STD %r6,-184(%r30) ;offset 0x8fc - DEPD %r7,31,32,%r8 ;offset 0x900 - STD %r8,-176(%r30) ;offset 0x904 - STW %r9,-168(%r30) ;offset 0x908 - LDD -248(%r30),%r3 ;offset 0x90c - COPY %r26,%r4 ;offset 0x910 - COPY %r24,%r5 ;offset 0x914 - DEPD %r25,31,32,%r4 ;offset 0x918 - CMPB,*<> %r3,%r0,$0006000C ;offset 0x91c - DEPD %r23,31,32,%r5 ;offset 0x920 - MOVIB,TR -1,%r29,$00060002 ;offset 0x924 - EXTRD,U %r29,31,32,%r28 ;offset 0x928 -$0006002A - LDO -1(%r29),%r29 ;offset 0x92c - SUB %r23,%r7,%r23 ;offset 0x930 -$00060024 - SUB %r4,%r31,%r25 ;offset 0x934 - AND %r25,%r19,%r26 ;offset 0x938 - CMPB,*<>,N %r0,%r26,$00060046 ;offset 0x93c - DEPD,Z %r25,31,32,%r20 ;offset 0x940 - OR %r20,%r24,%r21 ;offset 0x944 - CMPB,*<<,N %r21,%r23,$0006002A ;offset 0x948 - SUB %r31,%r2,%r31 ;offset 0x94c -$00060046 -$0006002E - DEPD,Z %r23,31,32,%r25 ;offset 0x950 - EXTRD,U %r23,31,32,%r26 ;offset 0x954 - AND %r25,%r19,%r24 ;offset 0x958 - ADD,L %r31,%r26,%r31 ;offset 0x95c - CMPCLR,*>>= %r5,%r24,%r0 ;offset 0x960 - LDO 1(%r31),%r31 ;offset 0x964 -$00060032 - CMPB,*<<=,N %r31,%r4,$00060036 ;offset 0x968 - LDO -1(%r29),%r29 ;offset 0x96c - ADD,L %r4,%r3,%r4 ;offset 0x970 -$00060036 - ADDIB,=,N -1,%r8,$D0 ;offset 0x974 - SUB %r5,%r24,%r28 ;offset 0x978 -$0006003A - SUB %r4,%r31,%r24 ;offset 0x97c - SHRPD %r24,%r28,32,%r4 ;offset 0x980 - DEPD,Z %r29,31,32,%r9 ;offset 0x984 - DEPD,Z %r28,31,32,%r5 ;offset 0x988 -$0006001C - EXTRD,U %r4,31,32,%r31 ;offset 0x98c - CMPB,*<>,N %r31,%r2,$00060020 ;offset 0x990 - MOVB,TR %r6,%r29,$D1 ;offset 0x994 - STD %r29,-152(%r30) ;offset 0x998 -$0006000C - EXTRD,U %r3,31,32,%r25 ;offset 0x99c - COPY %r3,%r26 ;offset 0x9a0 - EXTRD,U %r3,31,32,%r9 ;offset 0x9a4 - EXTRD,U %r4,31,32,%r8 ;offset 0x9a8 - .CALL ARGW0=GR,ARGW1=GR,RTNVAL=GR ;in=25,26;out=28; - B,L BN_num_bits_word,%r2 ;offset 0x9ac - EXTRD,U %r5,31,32,%r7 ;offset 0x9b0 - LDI 64,%r20 ;offset 0x9b4 - DEPD %r7,31,32,%r5 ;offset 0x9b8 - DEPD %r8,31,32,%r4 ;offset 0x9bc - DEPD %r9,31,32,%r3 ;offset 0x9c0 - CMPB,= %r28,%r20,$00060012 ;offset 0x9c4 - COPY %r28,%r24 ;offset 0x9c8 - MTSARCM %r24 ;offset 0x9cc - DEPDI,Z -1,%sar,1,%r19 ;offset 0x9d0 - CMPB,*>>,N %r4,%r19,$D2 ;offset 0x9d4 -$00060012 - SUBI 64,%r24,%r31 ;offset 0x9d8 - CMPCLR,*<< %r4,%r3,%r0 ;offset 0x9dc - SUB %r4,%r3,%r4 ;offset 0x9e0 -$00060016 - CMPB,= %r31,%r0,$0006001A ;offset 0x9e4 - COPY %r0,%r9 ;offset 0x9e8 - MTSARCM %r31 ;offset 0x9ec - DEPD,Z %r3,%sar,64,%r3 ;offset 0x9f0 - SUBI 64,%r31,%r26 ;offset 0x9f4 - MTSAR %r26 ;offset 0x9f8 - SHRPD %r4,%r5,%sar,%r4 ;offset 0x9fc - MTSARCM %r31 ;offset 0xa00 - DEPD,Z %r5,%sar,64,%r5 ;offset 0xa04 -$0006001A - DEPDI,Z -1,31,32,%r19 ;offset 0xa08 - AND %r3,%r19,%r29 ;offset 0xa0c - EXTRD,U %r29,31,32,%r2 ;offset 0xa10 - DEPDI,Z -1,63,32,%r6 ;offset 0xa14 - MOVIB,TR 2,%r8,$0006001C ;offset 0xa18 - EXTRD,U %r3,63,32,%r7 ;offset 0xa1c -$D2 - ;--- not PIC ADDIL LR'__iob-$global$,%r27,%r1 ;offset 0xa20 - ;--- not PIC LDIL LR'C$7,%r21 ;offset 0xa24 - ;--- not PIC LDO RR'__iob-$global$+32(%r1),%r26 ;offset 0xa28 - ;--- not PIC .CALL ARGW0=GR,ARGW1=GR,ARGW2=GR,RTNVAL=GR ;in=24,25,26;out=28; - ;--- not PIC B,L fprintf,%r2 ;offset 0xa2c - ;--- not PIC LDO RR'C$7(%r21),%r25 ;offset 0xa30 - .CALL ; - B,L abort,%r2 ;offset 0xa34 - NOP ;offset 0xa38 - B $D3 ;offset 0xa3c - LDW -212(%r30),%r2 ;offset 0xa40 -$00060020 - COPY %r4,%r26 ;offset 0xa44 - EXTRD,U %r4,31,32,%r25 ;offset 0xa48 - COPY %r2,%r24 ;offset 0xa4c - .CALL ;in=23,24,25,26;out=20,21,22,28,29; (MILLICALL) - B,L $$div2U,%r31 ;offset 0xa50 - EXTRD,U %r2,31,32,%r23 ;offset 0xa54 - DEPD %r28,31,32,%r29 ;offset 0xa58 -$00060022 - STD %r29,-152(%r30) ;offset 0xa5c -$D1 - AND %r5,%r19,%r24 ;offset 0xa60 - EXTRD,U %r24,31,32,%r24 ;offset 0xa64 - STW %r2,-160(%r30) ;offset 0xa68 - STW %r7,-128(%r30) ;offset 0xa6c - FLDD -152(%r30),%fr4 ;offset 0xa70 - FLDD -152(%r30),%fr7 ;offset 0xa74 - FLDW -160(%r30),%fr8L ;offset 0xa78 - FLDW -128(%r30),%fr5L ;offset 0xa7c - XMPYU %fr8L,%fr7L,%fr10 ;offset 0xa80 - FSTD %fr10,-136(%r30) ;offset 0xa84 - XMPYU %fr8L,%fr7R,%fr22 ;offset 0xa88 - FSTD %fr22,-144(%r30) ;offset 0xa8c - XMPYU %fr5L,%fr4L,%fr11 ;offset 0xa90 - XMPYU %fr5L,%fr4R,%fr23 ;offset 0xa94 - FSTD %fr11,-112(%r30) ;offset 0xa98 - FSTD %fr23,-120(%r30) ;offset 0xa9c - LDD -136(%r30),%r28 ;offset 0xaa0 - DEPD,Z %r28,31,32,%r31 ;offset 0xaa4 - LDD -144(%r30),%r20 ;offset 0xaa8 - ADD,L %r20,%r31,%r31 ;offset 0xaac - LDD -112(%r30),%r22 ;offset 0xab0 - DEPD,Z %r22,31,32,%r22 ;offset 0xab4 - LDD -120(%r30),%r21 ;offset 0xab8 - B $00060024 ;offset 0xabc - ADD,L %r21,%r22,%r23 ;offset 0xac0 -$D0 - OR %r9,%r29,%r29 ;offset 0xac4 -$00060040 - EXTRD,U %r29,31,32,%r28 ;offset 0xac8 -$00060002 -$L2 - LDW -212(%r30),%r2 ;offset 0xacc -$D3 - LDW -168(%r30),%r9 ;offset 0xad0 - LDD -176(%r30),%r8 ;offset 0xad4 - EXTRD,U %r8,31,32,%r7 ;offset 0xad8 - LDD -184(%r30),%r6 ;offset 0xadc - EXTRD,U %r6,31,32,%r5 ;offset 0xae0 - LDW -188(%r30),%r4 ;offset 0xae4 - BVE (%r2) ;offset 0xae8 - .EXIT - LDW,MB -192(%r30),%r3 ;offset 0xaec - .PROCEND ;in=23,25;out=28,29;fpin=105,107; - - - - -;---------------------------------------------------------------------------- -; -; Registers to hold 64-bit values to manipulate. The "L" part -; of the register corresponds to the upper 32-bits, while the "R" -; part corresponds to the lower 32-bits -; -; Note, that when using b6 and b7, the code must save these before -; using them because they are callee save registers -; -; -; Floating point registers to use to save values that -; are manipulated. These don't collide with ftemp1-6 and -; are all caller save registers -; -a0 .reg %fr22 -a0L .reg %fr22L -a0R .reg %fr22R - -a1 .reg %fr23 -a1L .reg %fr23L -a1R .reg %fr23R - -a2 .reg %fr24 -a2L .reg %fr24L -a2R .reg %fr24R - -a3 .reg %fr25 -a3L .reg %fr25L -a3R .reg %fr25R - -a4 .reg %fr26 -a4L .reg %fr26L -a4R .reg %fr26R - -a5 .reg %fr27 -a5L .reg %fr27L -a5R .reg %fr27R - -a6 .reg %fr28 -a6L .reg %fr28L -a6R .reg %fr28R - -a7 .reg %fr29 -a7L .reg %fr29L -a7R .reg %fr29R - -b0 .reg %fr30 -b0L .reg %fr30L -b0R .reg %fr30R - -b1 .reg %fr31 -b1L .reg %fr31L -b1R .reg %fr31R - -; -; Temporary floating point variables, these are all caller save -; registers -; -ftemp1 .reg %fr4 -ftemp2 .reg %fr5 -ftemp3 .reg %fr6 -ftemp4 .reg %fr7 - -; -; The B set of registers when used. -; - -b2 .reg %fr8 -b2L .reg %fr8L -b2R .reg %fr8R - -b3 .reg %fr9 -b3L .reg %fr9L -b3R .reg %fr9R - -b4 .reg %fr10 -b4L .reg %fr10L -b4R .reg %fr10R - -b5 .reg %fr11 -b5L .reg %fr11L -b5R .reg %fr11R - -b6 .reg %fr12 -b6L .reg %fr12L -b6R .reg %fr12R - -b7 .reg %fr13 -b7L .reg %fr13L -b7R .reg %fr13R - -c1 .reg %r21 ; only reg -temp1 .reg %r20 ; only reg -temp2 .reg %r19 ; only reg -temp3 .reg %r31 ; only reg - -m1 .reg %r28 -c2 .reg %r23 -high_one .reg %r1 -ht .reg %r6 -lt .reg %r5 -m .reg %r4 -c3 .reg %r3 - -SQR_ADD_C .macro A0L,A0R,C1,C2,C3 - XMPYU A0L,A0R,ftemp1 ; m - FSTD ftemp1,-24(%sp) ; store m - - XMPYU A0R,A0R,ftemp2 ; lt - FSTD ftemp2,-16(%sp) ; store lt - - XMPYU A0L,A0L,ftemp3 ; ht - FSTD ftemp3,-8(%sp) ; store ht - - LDD -24(%sp),m ; load m - AND m,high_mask,temp2 ; m & Mask - DEPD,Z m,30,31,temp3 ; m << 32+1 - LDD -16(%sp),lt ; lt - - LDD -8(%sp),ht ; ht - EXTRD,U temp2,32,33,temp1 ; temp1 = m&Mask >> 32-1 - ADD temp3,lt,lt ; lt = lt+m - ADD,L ht,temp1,ht ; ht += temp1 - ADD,DC ht,%r0,ht ; ht++ - - ADD C1,lt,C1 ; c1=c1+lt - ADD,DC ht,%r0,ht ; ht++ - - ADD C2,ht,C2 ; c2=c2+ht - ADD,DC C3,%r0,C3 ; c3++ -.endm - -SQR_ADD_C2 .macro A0L,A0R,A1L,A1R,C1,C2,C3 - XMPYU A0L,A1R,ftemp1 ; m1 = bl*ht - FSTD ftemp1,-16(%sp) ; - XMPYU A0R,A1L,ftemp2 ; m = bh*lt - FSTD ftemp2,-8(%sp) ; - XMPYU A0R,A1R,ftemp3 ; lt = bl*lt - FSTD ftemp3,-32(%sp) - XMPYU A0L,A1L,ftemp4 ; ht = bh*ht - FSTD ftemp4,-24(%sp) ; - - LDD -8(%sp),m ; r21 = m - LDD -16(%sp),m1 ; r19 = m1 - ADD,L m,m1,m ; m+m1 - - DEPD,Z m,31,32,temp3 ; (m+m1<<32) - LDD -24(%sp),ht ; r24 = ht - - CMPCLR,*>>= m,m1,%r0 ; if (m < m1) - ADD,L ht,high_one,ht ; ht+=high_one - - EXTRD,U m,31,32,temp1 ; m >> 32 - LDD -32(%sp),lt ; lt - ADD,L ht,temp1,ht ; ht+= m>>32 - ADD lt,temp3,lt ; lt = lt+m1 - ADD,DC ht,%r0,ht ; ht++ - - ADD ht,ht,ht ; ht=ht+ht; - ADD,DC C3,%r0,C3 ; add in carry (c3++) - - ADD lt,lt,lt ; lt=lt+lt; - ADD,DC ht,%r0,ht ; add in carry (ht++) - - ADD C1,lt,C1 ; c1=c1+lt - ADD,DC,*NUV ht,%r0,ht ; add in carry (ht++) - LDO 1(C3),C3 ; bump c3 if overflow,nullify otherwise - - ADD C2,ht,C2 ; c2 = c2 + ht - ADD,DC C3,%r0,C3 ; add in carry (c3++) -.endm - -; -;void bn_sqr_comba8(BN_ULONG *r, BN_ULONG *a) -; arg0 = r_ptr -; arg1 = a_ptr -; - -bn_sqr_comba8 - .PROC - .CALLINFO FRAME=128,ENTRY_GR=%r3,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_sqr_comba8,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .ENTRY - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - STD %r5,16(%sp) ; save r5 - STD %r6,24(%sp) ; save r6 - - ; - ; Zero out carries - ; - COPY %r0,c1 - COPY %r0,c2 - COPY %r0,c3 - - LDO 128(%sp),%sp ; bump stack - DEPDI,Z -1,32,33,high_mask ; Create Mask 0xffffffff80000000L - DEPDI,Z 1,31,1,high_one ; Create Value 1 << 32 - - ; - ; Load up all of the values we are going to use - ; - FLDD 0(a_ptr),a0 - FLDD 8(a_ptr),a1 - FLDD 16(a_ptr),a2 - FLDD 24(a_ptr),a3 - FLDD 32(a_ptr),a4 - FLDD 40(a_ptr),a5 - FLDD 48(a_ptr),a6 - FLDD 56(a_ptr),a7 - - SQR_ADD_C a0L,a0R,c1,c2,c3 - STD c1,0(r_ptr) ; r[0] = c1; - COPY %r0,c1 - - SQR_ADD_C2 a1L,a1R,a0L,a0R,c2,c3,c1 - STD c2,8(r_ptr) ; r[1] = c2; - COPY %r0,c2 - - SQR_ADD_C a1L,a1R,c3,c1,c2 - SQR_ADD_C2 a2L,a2R,a0L,a0R,c3,c1,c2 - STD c3,16(r_ptr) ; r[2] = c3; - COPY %r0,c3 - - SQR_ADD_C2 a3L,a3R,a0L,a0R,c1,c2,c3 - SQR_ADD_C2 a2L,a2R,a1L,a1R,c1,c2,c3 - STD c1,24(r_ptr) ; r[3] = c1; - COPY %r0,c1 - - SQR_ADD_C a2L,a2R,c2,c3,c1 - SQR_ADD_C2 a3L,a3R,a1L,a1R,c2,c3,c1 - SQR_ADD_C2 a4L,a4R,a0L,a0R,c2,c3,c1 - STD c2,32(r_ptr) ; r[4] = c2; - COPY %r0,c2 - - SQR_ADD_C2 a5L,a5R,a0L,a0R,c3,c1,c2 - SQR_ADD_C2 a4L,a4R,a1L,a1R,c3,c1,c2 - SQR_ADD_C2 a3L,a3R,a2L,a2R,c3,c1,c2 - STD c3,40(r_ptr) ; r[5] = c3; - COPY %r0,c3 - - SQR_ADD_C a3L,a3R,c1,c2,c3 - SQR_ADD_C2 a4L,a4R,a2L,a2R,c1,c2,c3 - SQR_ADD_C2 a5L,a5R,a1L,a1R,c1,c2,c3 - SQR_ADD_C2 a6L,a6R,a0L,a0R,c1,c2,c3 - STD c1,48(r_ptr) ; r[6] = c1; - COPY %r0,c1 - - SQR_ADD_C2 a7L,a7R,a0L,a0R,c2,c3,c1 - SQR_ADD_C2 a6L,a6R,a1L,a1R,c2,c3,c1 - SQR_ADD_C2 a5L,a5R,a2L,a2R,c2,c3,c1 - SQR_ADD_C2 a4L,a4R,a3L,a3R,c2,c3,c1 - STD c2,56(r_ptr) ; r[7] = c2; - COPY %r0,c2 - - SQR_ADD_C a4L,a4R,c3,c1,c2 - SQR_ADD_C2 a5L,a5R,a3L,a3R,c3,c1,c2 - SQR_ADD_C2 a6L,a6R,a2L,a2R,c3,c1,c2 - SQR_ADD_C2 a7L,a7R,a1L,a1R,c3,c1,c2 - STD c3,64(r_ptr) ; r[8] = c3; - COPY %r0,c3 - - SQR_ADD_C2 a7L,a7R,a2L,a2R,c1,c2,c3 - SQR_ADD_C2 a6L,a6R,a3L,a3R,c1,c2,c3 - SQR_ADD_C2 a5L,a5R,a4L,a4R,c1,c2,c3 - STD c1,72(r_ptr) ; r[9] = c1; - COPY %r0,c1 - - SQR_ADD_C a5L,a5R,c2,c3,c1 - SQR_ADD_C2 a6L,a6R,a4L,a4R,c2,c3,c1 - SQR_ADD_C2 a7L,a7R,a3L,a3R,c2,c3,c1 - STD c2,80(r_ptr) ; r[10] = c2; - COPY %r0,c2 - - SQR_ADD_C2 a7L,a7R,a4L,a4R,c3,c1,c2 - SQR_ADD_C2 a6L,a6R,a5L,a5R,c3,c1,c2 - STD c3,88(r_ptr) ; r[11] = c3; - COPY %r0,c3 - - SQR_ADD_C a6L,a6R,c1,c2,c3 - SQR_ADD_C2 a7L,a7R,a5L,a5R,c1,c2,c3 - STD c1,96(r_ptr) ; r[12] = c1; - COPY %r0,c1 - - SQR_ADD_C2 a7L,a7R,a6L,a6R,c2,c3,c1 - STD c2,104(r_ptr) ; r[13] = c2; - COPY %r0,c2 - - SQR_ADD_C a7L,a7R,c3,c1,c2 - STD c3, 112(r_ptr) ; r[14] = c3 - STD c1, 120(r_ptr) ; r[15] = c1 - - .EXIT - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 - - .PROCEND - -;----------------------------------------------------------------------------- -; -;void bn_sqr_comba4(BN_ULONG *r, BN_ULONG *a) -; arg0 = r_ptr -; arg1 = a_ptr -; - -bn_sqr_comba4 - .proc - .callinfo FRAME=128,ENTRY_GR=%r3,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_sqr_comba4,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .entry - .align 64 - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - STD %r5,16(%sp) ; save r5 - STD %r6,24(%sp) ; save r6 - - ; - ; Zero out carries - ; - COPY %r0,c1 - COPY %r0,c2 - COPY %r0,c3 - - LDO 128(%sp),%sp ; bump stack - DEPDI,Z -1,32,33,high_mask ; Create Mask 0xffffffff80000000L - DEPDI,Z 1,31,1,high_one ; Create Value 1 << 32 - - ; - ; Load up all of the values we are going to use - ; - FLDD 0(a_ptr),a0 - FLDD 8(a_ptr),a1 - FLDD 16(a_ptr),a2 - FLDD 24(a_ptr),a3 - FLDD 32(a_ptr),a4 - FLDD 40(a_ptr),a5 - FLDD 48(a_ptr),a6 - FLDD 56(a_ptr),a7 - - SQR_ADD_C a0L,a0R,c1,c2,c3 - - STD c1,0(r_ptr) ; r[0] = c1; - COPY %r0,c1 - - SQR_ADD_C2 a1L,a1R,a0L,a0R,c2,c3,c1 - - STD c2,8(r_ptr) ; r[1] = c2; - COPY %r0,c2 - - SQR_ADD_C a1L,a1R,c3,c1,c2 - SQR_ADD_C2 a2L,a2R,a0L,a0R,c3,c1,c2 - - STD c3,16(r_ptr) ; r[2] = c3; - COPY %r0,c3 - - SQR_ADD_C2 a3L,a3R,a0L,a0R,c1,c2,c3 - SQR_ADD_C2 a2L,a2R,a1L,a1R,c1,c2,c3 - - STD c1,24(r_ptr) ; r[3] = c1; - COPY %r0,c1 - - SQR_ADD_C a2L,a2R,c2,c3,c1 - SQR_ADD_C2 a3L,a3R,a1L,a1R,c2,c3,c1 - - STD c2,32(r_ptr) ; r[4] = c2; - COPY %r0,c2 - - SQR_ADD_C2 a3L,a3R,a2L,a2R,c3,c1,c2 - STD c3,40(r_ptr) ; r[5] = c3; - COPY %r0,c3 - - SQR_ADD_C a3L,a3R,c1,c2,c3 - STD c1,48(r_ptr) ; r[6] = c1; - STD c2,56(r_ptr) ; r[7] = c2; - - .EXIT - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 - - .PROCEND - - -;--------------------------------------------------------------------------- - -MUL_ADD_C .macro A0L,A0R,B0L,B0R,C1,C2,C3 - XMPYU A0L,B0R,ftemp1 ; m1 = bl*ht - FSTD ftemp1,-16(%sp) ; - XMPYU A0R,B0L,ftemp2 ; m = bh*lt - FSTD ftemp2,-8(%sp) ; - XMPYU A0R,B0R,ftemp3 ; lt = bl*lt - FSTD ftemp3,-32(%sp) - XMPYU A0L,B0L,ftemp4 ; ht = bh*ht - FSTD ftemp4,-24(%sp) ; - - LDD -8(%sp),m ; r21 = m - LDD -16(%sp),m1 ; r19 = m1 - ADD,L m,m1,m ; m+m1 - - DEPD,Z m,31,32,temp3 ; (m+m1<<32) - LDD -24(%sp),ht ; r24 = ht - - CMPCLR,*>>= m,m1,%r0 ; if (m < m1) - ADD,L ht,high_one,ht ; ht+=high_one - - EXTRD,U m,31,32,temp1 ; m >> 32 - LDD -32(%sp),lt ; lt - ADD,L ht,temp1,ht ; ht+= m>>32 - ADD lt,temp3,lt ; lt = lt+m1 - ADD,DC ht,%r0,ht ; ht++ - - ADD C1,lt,C1 ; c1=c1+lt - ADD,DC ht,%r0,ht ; bump c3 if overflow,nullify otherwise - - ADD C2,ht,C2 ; c2 = c2 + ht - ADD,DC C3,%r0,C3 ; add in carry (c3++) -.endm - - -; -;void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) -; arg0 = r_ptr -; arg1 = a_ptr -; arg2 = b_ptr -; - -bn_mul_comba8 - .proc - .callinfo FRAME=128,ENTRY_GR=%r3,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_mul_comba8,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .entry - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - STD %r5,16(%sp) ; save r5 - STD %r6,24(%sp) ; save r6 - FSTD %fr12,32(%sp) ; save r6 - FSTD %fr13,40(%sp) ; save r7 - - ; - ; Zero out carries - ; - COPY %r0,c1 - COPY %r0,c2 - COPY %r0,c3 - - LDO 128(%sp),%sp ; bump stack - DEPDI,Z 1,31,1,high_one ; Create Value 1 << 32 - - ; - ; Load up all of the values we are going to use - ; - FLDD 0(a_ptr),a0 - FLDD 8(a_ptr),a1 - FLDD 16(a_ptr),a2 - FLDD 24(a_ptr),a3 - FLDD 32(a_ptr),a4 - FLDD 40(a_ptr),a5 - FLDD 48(a_ptr),a6 - FLDD 56(a_ptr),a7 - - FLDD 0(b_ptr),b0 - FLDD 8(b_ptr),b1 - FLDD 16(b_ptr),b2 - FLDD 24(b_ptr),b3 - FLDD 32(b_ptr),b4 - FLDD 40(b_ptr),b5 - FLDD 48(b_ptr),b6 - FLDD 56(b_ptr),b7 - - MUL_ADD_C a0L,a0R,b0L,b0R,c1,c2,c3 - STD c1,0(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a0L,a0R,b1L,b1R,c2,c3,c1 - MUL_ADD_C a1L,a1R,b0L,b0R,c2,c3,c1 - STD c2,8(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a2L,a2R,b0L,b0R,c3,c1,c2 - MUL_ADD_C a1L,a1R,b1L,b1R,c3,c1,c2 - MUL_ADD_C a0L,a0R,b2L,b2R,c3,c1,c2 - STD c3,16(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a0L,a0R,b3L,b3R,c1,c2,c3 - MUL_ADD_C a1L,a1R,b2L,b2R,c1,c2,c3 - MUL_ADD_C a2L,a2R,b1L,b1R,c1,c2,c3 - MUL_ADD_C a3L,a3R,b0L,b0R,c1,c2,c3 - STD c1,24(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a4L,a4R,b0L,b0R,c2,c3,c1 - MUL_ADD_C a3L,a3R,b1L,b1R,c2,c3,c1 - MUL_ADD_C a2L,a2R,b2L,b2R,c2,c3,c1 - MUL_ADD_C a1L,a1R,b3L,b3R,c2,c3,c1 - MUL_ADD_C a0L,a0R,b4L,b4R,c2,c3,c1 - STD c2,32(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a0L,a0R,b5L,b5R,c3,c1,c2 - MUL_ADD_C a1L,a1R,b4L,b4R,c3,c1,c2 - MUL_ADD_C a2L,a2R,b3L,b3R,c3,c1,c2 - MUL_ADD_C a3L,a3R,b2L,b2R,c3,c1,c2 - MUL_ADD_C a4L,a4R,b1L,b1R,c3,c1,c2 - MUL_ADD_C a5L,a5R,b0L,b0R,c3,c1,c2 - STD c3,40(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a6L,a6R,b0L,b0R,c1,c2,c3 - MUL_ADD_C a5L,a5R,b1L,b1R,c1,c2,c3 - MUL_ADD_C a4L,a4R,b2L,b2R,c1,c2,c3 - MUL_ADD_C a3L,a3R,b3L,b3R,c1,c2,c3 - MUL_ADD_C a2L,a2R,b4L,b4R,c1,c2,c3 - MUL_ADD_C a1L,a1R,b5L,b5R,c1,c2,c3 - MUL_ADD_C a0L,a0R,b6L,b6R,c1,c2,c3 - STD c1,48(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a0L,a0R,b7L,b7R,c2,c3,c1 - MUL_ADD_C a1L,a1R,b6L,b6R,c2,c3,c1 - MUL_ADD_C a2L,a2R,b5L,b5R,c2,c3,c1 - MUL_ADD_C a3L,a3R,b4L,b4R,c2,c3,c1 - MUL_ADD_C a4L,a4R,b3L,b3R,c2,c3,c1 - MUL_ADD_C a5L,a5R,b2L,b2R,c2,c3,c1 - MUL_ADD_C a6L,a6R,b1L,b1R,c2,c3,c1 - MUL_ADD_C a7L,a7R,b0L,b0R,c2,c3,c1 - STD c2,56(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a7L,a7R,b1L,b1R,c3,c1,c2 - MUL_ADD_C a6L,a6R,b2L,b2R,c3,c1,c2 - MUL_ADD_C a5L,a5R,b3L,b3R,c3,c1,c2 - MUL_ADD_C a4L,a4R,b4L,b4R,c3,c1,c2 - MUL_ADD_C a3L,a3R,b5L,b5R,c3,c1,c2 - MUL_ADD_C a2L,a2R,b6L,b6R,c3,c1,c2 - MUL_ADD_C a1L,a1R,b7L,b7R,c3,c1,c2 - STD c3,64(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a2L,a2R,b7L,b7R,c1,c2,c3 - MUL_ADD_C a3L,a3R,b6L,b6R,c1,c2,c3 - MUL_ADD_C a4L,a4R,b5L,b5R,c1,c2,c3 - MUL_ADD_C a5L,a5R,b4L,b4R,c1,c2,c3 - MUL_ADD_C a6L,a6R,b3L,b3R,c1,c2,c3 - MUL_ADD_C a7L,a7R,b2L,b2R,c1,c2,c3 - STD c1,72(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a7L,a7R,b3L,b3R,c2,c3,c1 - MUL_ADD_C a6L,a6R,b4L,b4R,c2,c3,c1 - MUL_ADD_C a5L,a5R,b5L,b5R,c2,c3,c1 - MUL_ADD_C a4L,a4R,b6L,b6R,c2,c3,c1 - MUL_ADD_C a3L,a3R,b7L,b7R,c2,c3,c1 - STD c2,80(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a4L,a4R,b7L,b7R,c3,c1,c2 - MUL_ADD_C a5L,a5R,b6L,b6R,c3,c1,c2 - MUL_ADD_C a6L,a6R,b5L,b5R,c3,c1,c2 - MUL_ADD_C a7L,a7R,b4L,b4R,c3,c1,c2 - STD c3,88(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a7L,a7R,b5L,b5R,c1,c2,c3 - MUL_ADD_C a6L,a6R,b6L,b6R,c1,c2,c3 - MUL_ADD_C a5L,a5R,b7L,b7R,c1,c2,c3 - STD c1,96(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a6L,a6R,b7L,b7R,c2,c3,c1 - MUL_ADD_C a7L,a7R,b6L,b6R,c2,c3,c1 - STD c2,104(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a7L,a7R,b7L,b7R,c3,c1,c2 - STD c3,112(r_ptr) - STD c1,120(r_ptr) - - .EXIT - FLDD -88(%sp),%fr13 - FLDD -96(%sp),%fr12 - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 - - .PROCEND - -;----------------------------------------------------------------------------- -; -;void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) -; arg0 = r_ptr -; arg1 = a_ptr -; arg2 = b_ptr -; - -bn_mul_comba4 - .proc - .callinfo FRAME=128,ENTRY_GR=%r3,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_mul_comba4,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .entry - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - STD %r5,16(%sp) ; save r5 - STD %r6,24(%sp) ; save r6 - FSTD %fr12,32(%sp) ; save r6 - FSTD %fr13,40(%sp) ; save r7 - - ; - ; Zero out carries - ; - COPY %r0,c1 - COPY %r0,c2 - COPY %r0,c3 - - LDO 128(%sp),%sp ; bump stack - DEPDI,Z 1,31,1,high_one ; Create Value 1 << 32 - - ; - ; Load up all of the values we are going to use - ; - FLDD 0(a_ptr),a0 - FLDD 8(a_ptr),a1 - FLDD 16(a_ptr),a2 - FLDD 24(a_ptr),a3 - - FLDD 0(b_ptr),b0 - FLDD 8(b_ptr),b1 - FLDD 16(b_ptr),b2 - FLDD 24(b_ptr),b3 - - MUL_ADD_C a0L,a0R,b0L,b0R,c1,c2,c3 - STD c1,0(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a0L,a0R,b1L,b1R,c2,c3,c1 - MUL_ADD_C a1L,a1R,b0L,b0R,c2,c3,c1 - STD c2,8(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a2L,a2R,b0L,b0R,c3,c1,c2 - MUL_ADD_C a1L,a1R,b1L,b1R,c3,c1,c2 - MUL_ADD_C a0L,a0R,b2L,b2R,c3,c1,c2 - STD c3,16(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a0L,a0R,b3L,b3R,c1,c2,c3 - MUL_ADD_C a1L,a1R,b2L,b2R,c1,c2,c3 - MUL_ADD_C a2L,a2R,b1L,b1R,c1,c2,c3 - MUL_ADD_C a3L,a3R,b0L,b0R,c1,c2,c3 - STD c1,24(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a3L,a3R,b1L,b1R,c2,c3,c1 - MUL_ADD_C a2L,a2R,b2L,b2R,c2,c3,c1 - MUL_ADD_C a1L,a1R,b3L,b3R,c2,c3,c1 - STD c2,32(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a2L,a2R,b3L,b3R,c3,c1,c2 - MUL_ADD_C a3L,a3R,b2L,b2R,c3,c1,c2 - STD c3,40(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a3L,a3R,b3L,b3R,c1,c2,c3 - STD c1,48(r_ptr) - STD c2,56(r_ptr) - - .EXIT - FLDD -88(%sp),%fr13 - FLDD -96(%sp),%fr12 - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 - - .PROCEND - - -;--- not PIC .SPACE $TEXT$ -;--- not PIC .SUBSPA $CODE$ -;--- not PIC .SPACE $PRIVATE$,SORT=16 -;--- not PIC .IMPORT $global$,DATA -;--- not PIC .SPACE $TEXT$ -;--- not PIC .SUBSPA $CODE$ -;--- not PIC .SUBSPA $LIT$,ACCESS=0x2c -;--- not PIC C$7 -;--- not PIC .ALIGN 8 -;--- not PIC .STRINGZ "Division would overflow (%d)\n" - .END diff --git a/crypto/bn/asm/pa-risc2W.s b/crypto/bn/asm/pa-risc2W.s deleted file mode 100644 index 97381172..00000000 --- a/crypto/bn/asm/pa-risc2W.s +++ /dev/null @@ -1,1612 +0,0 @@ -; Copyright 2000-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 - -; -; PA-RISC 64-bit implementation of bn_asm code -; -; This code is approximately 2x faster than the C version -; for RSA/DSA. -; -; See http://devresource.hp.com/ for more details on the PA-RISC -; architecture. Also see the book "PA-RISC 2.0 Architecture" -; by Gerry Kane for information on the instruction set architecture. -; -; Code written by Chris Ruemmler (with some help from the HP C -; compiler). -; -; The code compiles with HP's assembler -; - - .level 2.0W - .space $TEXT$ - .subspa $CODE$,QUAD=0,ALIGN=8,ACCESS=0x2c,CODE_ONLY - -; -; Global Register definitions used for the routines. -; -; Some information about HP's runtime architecture for 64-bits. -; -; "Caller save" means the calling function must save the register -; if it wants the register to be preserved. -; "Callee save" means if a function uses the register, it must save -; the value before using it. -; -; For the floating point registers -; -; "caller save" registers: fr4-fr11, fr22-fr31 -; "callee save" registers: fr12-fr21 -; "special" registers: fr0-fr3 (status and exception registers) -; -; For the integer registers -; value zero : r0 -; "caller save" registers: r1,r19-r26 -; "callee save" registers: r3-r18 -; return register : r2 (rp) -; return values ; r28 (ret0,ret1) -; Stack pointer ; r30 (sp) -; global data pointer ; r27 (dp) -; argument pointer ; r29 (ap) -; millicode return ptr ; r31 (also a caller save register) - - -; -; Arguments to the routines -; -r_ptr .reg %r26 -a_ptr .reg %r25 -b_ptr .reg %r24 -num .reg %r24 -w .reg %r23 -n .reg %r23 - - -; -; Globals used in some routines -; - -top_overflow .reg %r29 -high_mask .reg %r22 ; value 0xffffffff80000000L - - -;------------------------------------------------------------------------------ -; -; bn_mul_add_words -; -;BN_ULONG bn_mul_add_words(BN_ULONG *r_ptr, BN_ULONG *a_ptr, -; int num, BN_ULONG w) -; -; arg0 = r_ptr -; arg1 = a_ptr -; arg2 = num -; arg3 = w -; -; Local register definitions -; - -fm1 .reg %fr22 -fm .reg %fr23 -ht_temp .reg %fr24 -ht_temp_1 .reg %fr25 -lt_temp .reg %fr26 -lt_temp_1 .reg %fr27 -fm1_1 .reg %fr28 -fm_1 .reg %fr29 - -fw_h .reg %fr7L -fw_l .reg %fr7R -fw .reg %fr7 - -fht_0 .reg %fr8L -flt_0 .reg %fr8R -t_float_0 .reg %fr8 - -fht_1 .reg %fr9L -flt_1 .reg %fr9R -t_float_1 .reg %fr9 - -tmp_0 .reg %r31 -tmp_1 .reg %r21 -m_0 .reg %r20 -m_1 .reg %r19 -ht_0 .reg %r1 -ht_1 .reg %r3 -lt_0 .reg %r4 -lt_1 .reg %r5 -m1_0 .reg %r6 -m1_1 .reg %r7 -rp_val .reg %r8 -rp_val_1 .reg %r9 - -bn_mul_add_words - .export bn_mul_add_words,entry,NO_RELOCATION,LONG_RETURN - .proc - .callinfo frame=128 - .entry - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - NOP ; Needed to make the loop 16-byte aligned - NOP ; Needed to make the loop 16-byte aligned - - STD %r5,16(%sp) ; save r5 - STD %r6,24(%sp) ; save r6 - STD %r7,32(%sp) ; save r7 - STD %r8,40(%sp) ; save r8 - - STD %r9,48(%sp) ; save r9 - COPY %r0,%ret0 ; return 0 by default - DEPDI,Z 1,31,1,top_overflow ; top_overflow = 1 << 32 - STD w,56(%sp) ; store w on stack - - CMPIB,>= 0,num,bn_mul_add_words_exit ; if (num <= 0) then exit - LDO 128(%sp),%sp ; bump stack - - ; - ; The loop is unrolled twice, so if there is only 1 number - ; then go straight to the cleanup code. - ; - CMPIB,= 1,num,bn_mul_add_words_single_top - FLDD -72(%sp),fw ; load up w into fp register fw (fw_h/fw_l) - - ; - ; This loop is unrolled 2 times (64-byte aligned as well) - ; - ; PA-RISC 2.0 chips have two fully pipelined multipliers, thus - ; two 32-bit mutiplies can be issued per cycle. - ; -bn_mul_add_words_unroll2 - - FLDD 0(a_ptr),t_float_0 ; load up 64-bit value (fr8L) ht(L)/lt(R) - FLDD 8(a_ptr),t_float_1 ; load up 64-bit value (fr8L) ht(L)/lt(R) - LDD 0(r_ptr),rp_val ; rp[0] - LDD 8(r_ptr),rp_val_1 ; rp[1] - - XMPYU fht_0,fw_l,fm1 ; m1[0] = fht_0*fw_l - XMPYU fht_1,fw_l,fm1_1 ; m1[1] = fht_1*fw_l - FSTD fm1,-16(%sp) ; -16(sp) = m1[0] - FSTD fm1_1,-48(%sp) ; -48(sp) = m1[1] - - XMPYU flt_0,fw_h,fm ; m[0] = flt_0*fw_h - XMPYU flt_1,fw_h,fm_1 ; m[1] = flt_1*fw_h - FSTD fm,-8(%sp) ; -8(sp) = m[0] - FSTD fm_1,-40(%sp) ; -40(sp) = m[1] - - XMPYU fht_0,fw_h,ht_temp ; ht_temp = fht_0*fw_h - XMPYU fht_1,fw_h,ht_temp_1 ; ht_temp_1 = fht_1*fw_h - FSTD ht_temp,-24(%sp) ; -24(sp) = ht_temp - FSTD ht_temp_1,-56(%sp) ; -56(sp) = ht_temp_1 - - XMPYU flt_0,fw_l,lt_temp ; lt_temp = lt*fw_l - XMPYU flt_1,fw_l,lt_temp_1 ; lt_temp = lt*fw_l - FSTD lt_temp,-32(%sp) ; -32(sp) = lt_temp - FSTD lt_temp_1,-64(%sp) ; -64(sp) = lt_temp_1 - - LDD -8(%sp),m_0 ; m[0] - LDD -40(%sp),m_1 ; m[1] - LDD -16(%sp),m1_0 ; m1[0] - LDD -48(%sp),m1_1 ; m1[1] - - LDD -24(%sp),ht_0 ; ht[0] - LDD -56(%sp),ht_1 ; ht[1] - ADD,L m1_0,m_0,tmp_0 ; tmp_0 = m[0] + m1[0]; - ADD,L m1_1,m_1,tmp_1 ; tmp_1 = m[1] + m1[1]; - - LDD -32(%sp),lt_0 - LDD -64(%sp),lt_1 - CMPCLR,*>>= tmp_0,m1_0, %r0 ; if (m[0] < m1[0]) - ADD,L ht_0,top_overflow,ht_0 ; ht[0] += (1<<32) - - CMPCLR,*>>= tmp_1,m1_1,%r0 ; if (m[1] < m1[1]) - ADD,L ht_1,top_overflow,ht_1 ; ht[1] += (1<<32) - EXTRD,U tmp_0,31,32,m_0 ; m[0]>>32 - DEPD,Z tmp_0,31,32,m1_0 ; m1[0] = m[0]<<32 - - EXTRD,U tmp_1,31,32,m_1 ; m[1]>>32 - DEPD,Z tmp_1,31,32,m1_1 ; m1[1] = m[1]<<32 - ADD,L ht_0,m_0,ht_0 ; ht[0]+= (m[0]>>32) - ADD,L ht_1,m_1,ht_1 ; ht[1]+= (m[1]>>32) - - ADD lt_0,m1_0,lt_0 ; lt[0] = lt[0]+m1[0]; - ADD,DC ht_0,%r0,ht_0 ; ht[0]++ - ADD lt_1,m1_1,lt_1 ; lt[1] = lt[1]+m1[1]; - ADD,DC ht_1,%r0,ht_1 ; ht[1]++ - - ADD %ret0,lt_0,lt_0 ; lt[0] = lt[0] + c; - ADD,DC ht_0,%r0,ht_0 ; ht[0]++ - ADD lt_0,rp_val,lt_0 ; lt[0] = lt[0]+rp[0] - ADD,DC ht_0,%r0,ht_0 ; ht[0]++ - - LDO -2(num),num ; num = num - 2; - ADD ht_0,lt_1,lt_1 ; lt[1] = lt[1] + ht_0 (c); - ADD,DC ht_1,%r0,ht_1 ; ht[1]++ - STD lt_0,0(r_ptr) ; rp[0] = lt[0] - - ADD lt_1,rp_val_1,lt_1 ; lt[1] = lt[1]+rp[1] - ADD,DC ht_1,%r0,%ret0 ; ht[1]++ - LDO 16(a_ptr),a_ptr ; a_ptr += 2 - - STD lt_1,8(r_ptr) ; rp[1] = lt[1] - CMPIB,<= 2,num,bn_mul_add_words_unroll2 ; go again if more to do - LDO 16(r_ptr),r_ptr ; r_ptr += 2 - - CMPIB,=,N 0,num,bn_mul_add_words_exit ; are we done, or cleanup last one - - ; - ; Top of loop aligned on 64-byte boundary - ; -bn_mul_add_words_single_top - FLDD 0(a_ptr),t_float_0 ; load up 64-bit value (fr8L) ht(L)/lt(R) - LDD 0(r_ptr),rp_val ; rp[0] - LDO 8(a_ptr),a_ptr ; a_ptr++ - XMPYU fht_0,fw_l,fm1 ; m1 = ht*fw_l - FSTD fm1,-16(%sp) ; -16(sp) = m1 - XMPYU flt_0,fw_h,fm ; m = lt*fw_h - FSTD fm,-8(%sp) ; -8(sp) = m - XMPYU fht_0,fw_h,ht_temp ; ht_temp = ht*fw_h - FSTD ht_temp,-24(%sp) ; -24(sp) = ht - XMPYU flt_0,fw_l,lt_temp ; lt_temp = lt*fw_l - FSTD lt_temp,-32(%sp) ; -32(sp) = lt - - LDD -8(%sp),m_0 - LDD -16(%sp),m1_0 ; m1 = temp1 - ADD,L m_0,m1_0,tmp_0 ; tmp_0 = m + m1; - LDD -24(%sp),ht_0 - LDD -32(%sp),lt_0 - - CMPCLR,*>>= tmp_0,m1_0,%r0 ; if (m < m1) - ADD,L ht_0,top_overflow,ht_0 ; ht += (1<<32) - - EXTRD,U tmp_0,31,32,m_0 ; m>>32 - DEPD,Z tmp_0,31,32,m1_0 ; m1 = m<<32 - - ADD,L ht_0,m_0,ht_0 ; ht+= (m>>32) - ADD lt_0,m1_0,tmp_0 ; tmp_0 = lt+m1; - ADD,DC ht_0,%r0,ht_0 ; ht++ - ADD %ret0,tmp_0,lt_0 ; lt = lt + c; - ADD,DC ht_0,%r0,ht_0 ; ht++ - ADD lt_0,rp_val,lt_0 ; lt = lt+rp[0] - ADD,DC ht_0,%r0,%ret0 ; ht++ - STD lt_0,0(r_ptr) ; rp[0] = lt - -bn_mul_add_words_exit - .EXIT - LDD -80(%sp),%r9 ; restore r9 - LDD -88(%sp),%r8 ; restore r8 - LDD -96(%sp),%r7 ; restore r7 - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 ; restore r3 - .PROCEND ;in=23,24,25,26,29;out=28; - -;---------------------------------------------------------------------------- -; -;BN_ULONG bn_mul_words(BN_ULONG *rp, BN_ULONG *ap, int num, BN_ULONG w) -; -; arg0 = rp -; arg1 = ap -; arg2 = num -; arg3 = w - -bn_mul_words - .proc - .callinfo frame=128 - .entry - .EXPORT bn_mul_words,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - STD %r5,16(%sp) ; save r5 - STD %r6,24(%sp) ; save r6 - - STD %r7,32(%sp) ; save r7 - COPY %r0,%ret0 ; return 0 by default - DEPDI,Z 1,31,1,top_overflow ; top_overflow = 1 << 32 - STD w,56(%sp) ; w on stack - - CMPIB,>= 0,num,bn_mul_words_exit - LDO 128(%sp),%sp ; bump stack - - ; - ; See if only 1 word to do, thus just do cleanup - ; - CMPIB,= 1,num,bn_mul_words_single_top - FLDD -72(%sp),fw ; load up w into fp register fw (fw_h/fw_l) - - ; - ; This loop is unrolled 2 times (64-byte aligned as well) - ; - ; PA-RISC 2.0 chips have two fully pipelined multipliers, thus - ; two 32-bit mutiplies can be issued per cycle. - ; -bn_mul_words_unroll2 - - FLDD 0(a_ptr),t_float_0 ; load up 64-bit value (fr8L) ht(L)/lt(R) - FLDD 8(a_ptr),t_float_1 ; load up 64-bit value (fr8L) ht(L)/lt(R) - XMPYU fht_0,fw_l,fm1 ; m1[0] = fht_0*fw_l - XMPYU fht_1,fw_l,fm1_1 ; m1[1] = ht*fw_l - - FSTD fm1,-16(%sp) ; -16(sp) = m1 - FSTD fm1_1,-48(%sp) ; -48(sp) = m1 - XMPYU flt_0,fw_h,fm ; m = lt*fw_h - XMPYU flt_1,fw_h,fm_1 ; m = lt*fw_h - - FSTD fm,-8(%sp) ; -8(sp) = m - FSTD fm_1,-40(%sp) ; -40(sp) = m - XMPYU fht_0,fw_h,ht_temp ; ht_temp = fht_0*fw_h - XMPYU fht_1,fw_h,ht_temp_1 ; ht_temp = ht*fw_h - - FSTD ht_temp,-24(%sp) ; -24(sp) = ht - FSTD ht_temp_1,-56(%sp) ; -56(sp) = ht - XMPYU flt_0,fw_l,lt_temp ; lt_temp = lt*fw_l - XMPYU flt_1,fw_l,lt_temp_1 ; lt_temp = lt*fw_l - - FSTD lt_temp,-32(%sp) ; -32(sp) = lt - FSTD lt_temp_1,-64(%sp) ; -64(sp) = lt - LDD -8(%sp),m_0 - LDD -40(%sp),m_1 - - LDD -16(%sp),m1_0 - LDD -48(%sp),m1_1 - LDD -24(%sp),ht_0 - LDD -56(%sp),ht_1 - - ADD,L m1_0,m_0,tmp_0 ; tmp_0 = m + m1; - ADD,L m1_1,m_1,tmp_1 ; tmp_1 = m + m1; - LDD -32(%sp),lt_0 - LDD -64(%sp),lt_1 - - CMPCLR,*>>= tmp_0,m1_0, %r0 ; if (m < m1) - ADD,L ht_0,top_overflow,ht_0 ; ht += (1<<32) - CMPCLR,*>>= tmp_1,m1_1,%r0 ; if (m < m1) - ADD,L ht_1,top_overflow,ht_1 ; ht += (1<<32) - - EXTRD,U tmp_0,31,32,m_0 ; m>>32 - DEPD,Z tmp_0,31,32,m1_0 ; m1 = m<<32 - EXTRD,U tmp_1,31,32,m_1 ; m>>32 - DEPD,Z tmp_1,31,32,m1_1 ; m1 = m<<32 - - ADD,L ht_0,m_0,ht_0 ; ht+= (m>>32) - ADD,L ht_1,m_1,ht_1 ; ht+= (m>>32) - ADD lt_0,m1_0,lt_0 ; lt = lt+m1; - ADD,DC ht_0,%r0,ht_0 ; ht++ - - ADD lt_1,m1_1,lt_1 ; lt = lt+m1; - ADD,DC ht_1,%r0,ht_1 ; ht++ - ADD %ret0,lt_0,lt_0 ; lt = lt + c (ret0); - ADD,DC ht_0,%r0,ht_0 ; ht++ - - ADD ht_0,lt_1,lt_1 ; lt = lt + c (ht_0) - ADD,DC ht_1,%r0,ht_1 ; ht++ - STD lt_0,0(r_ptr) ; rp[0] = lt - STD lt_1,8(r_ptr) ; rp[1] = lt - - COPY ht_1,%ret0 ; carry = ht - LDO -2(num),num ; num = num - 2; - LDO 16(a_ptr),a_ptr ; ap += 2 - CMPIB,<= 2,num,bn_mul_words_unroll2 - LDO 16(r_ptr),r_ptr ; rp++ - - CMPIB,=,N 0,num,bn_mul_words_exit ; are we done? - - ; - ; Top of loop aligned on 64-byte boundary - ; -bn_mul_words_single_top - FLDD 0(a_ptr),t_float_0 ; load up 64-bit value (fr8L) ht(L)/lt(R) - - XMPYU fht_0,fw_l,fm1 ; m1 = ht*fw_l - FSTD fm1,-16(%sp) ; -16(sp) = m1 - XMPYU flt_0,fw_h,fm ; m = lt*fw_h - FSTD fm,-8(%sp) ; -8(sp) = m - XMPYU fht_0,fw_h,ht_temp ; ht_temp = ht*fw_h - FSTD ht_temp,-24(%sp) ; -24(sp) = ht - XMPYU flt_0,fw_l,lt_temp ; lt_temp = lt*fw_l - FSTD lt_temp,-32(%sp) ; -32(sp) = lt - - LDD -8(%sp),m_0 - LDD -16(%sp),m1_0 - ADD,L m_0,m1_0,tmp_0 ; tmp_0 = m + m1; - LDD -24(%sp),ht_0 - LDD -32(%sp),lt_0 - - CMPCLR,*>>= tmp_0,m1_0,%r0 ; if (m < m1) - ADD,L ht_0,top_overflow,ht_0 ; ht += (1<<32) - - EXTRD,U tmp_0,31,32,m_0 ; m>>32 - DEPD,Z tmp_0,31,32,m1_0 ; m1 = m<<32 - - ADD,L ht_0,m_0,ht_0 ; ht+= (m>>32) - ADD lt_0,m1_0,lt_0 ; lt= lt+m1; - ADD,DC ht_0,%r0,ht_0 ; ht++ - - ADD %ret0,lt_0,lt_0 ; lt = lt + c; - ADD,DC ht_0,%r0,ht_0 ; ht++ - - COPY ht_0,%ret0 ; copy carry - STD lt_0,0(r_ptr) ; rp[0] = lt - -bn_mul_words_exit - .EXIT - LDD -96(%sp),%r7 ; restore r7 - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 ; restore r3 - .PROCEND ;in=23,24,25,26,29;out=28; - -;---------------------------------------------------------------------------- -; -;void bn_sqr_words(BN_ULONG *rp, BN_ULONG *ap, int num) -; -; arg0 = rp -; arg1 = ap -; arg2 = num -; - -bn_sqr_words - .proc - .callinfo FRAME=128,ENTRY_GR=%r3,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_sqr_words,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .entry - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - NOP - STD %r5,16(%sp) ; save r5 - - CMPIB,>= 0,num,bn_sqr_words_exit - LDO 128(%sp),%sp ; bump stack - - ; - ; If only 1, the goto straight to cleanup - ; - CMPIB,= 1,num,bn_sqr_words_single_top - DEPDI,Z -1,32,33,high_mask ; Create Mask 0xffffffff80000000L - - ; - ; This loop is unrolled 2 times (64-byte aligned as well) - ; - -bn_sqr_words_unroll2 - FLDD 0(a_ptr),t_float_0 ; a[0] - FLDD 8(a_ptr),t_float_1 ; a[1] - XMPYU fht_0,flt_0,fm ; m[0] - XMPYU fht_1,flt_1,fm_1 ; m[1] - - FSTD fm,-24(%sp) ; store m[0] - FSTD fm_1,-56(%sp) ; store m[1] - XMPYU flt_0,flt_0,lt_temp ; lt[0] - XMPYU flt_1,flt_1,lt_temp_1 ; lt[1] - - FSTD lt_temp,-16(%sp) ; store lt[0] - FSTD lt_temp_1,-48(%sp) ; store lt[1] - XMPYU fht_0,fht_0,ht_temp ; ht[0] - XMPYU fht_1,fht_1,ht_temp_1 ; ht[1] - - FSTD ht_temp,-8(%sp) ; store ht[0] - FSTD ht_temp_1,-40(%sp) ; store ht[1] - LDD -24(%sp),m_0 - LDD -56(%sp),m_1 - - AND m_0,high_mask,tmp_0 ; m[0] & Mask - AND m_1,high_mask,tmp_1 ; m[1] & Mask - DEPD,Z m_0,30,31,m_0 ; m[0] << 32+1 - DEPD,Z m_1,30,31,m_1 ; m[1] << 32+1 - - LDD -16(%sp),lt_0 - LDD -48(%sp),lt_1 - EXTRD,U tmp_0,32,33,tmp_0 ; tmp_0 = m[0]&Mask >> 32-1 - EXTRD,U tmp_1,32,33,tmp_1 ; tmp_1 = m[1]&Mask >> 32-1 - - LDD -8(%sp),ht_0 - LDD -40(%sp),ht_1 - ADD,L ht_0,tmp_0,ht_0 ; ht[0] += tmp_0 - ADD,L ht_1,tmp_1,ht_1 ; ht[1] += tmp_1 - - ADD lt_0,m_0,lt_0 ; lt = lt+m - ADD,DC ht_0,%r0,ht_0 ; ht[0]++ - STD lt_0,0(r_ptr) ; rp[0] = lt[0] - STD ht_0,8(r_ptr) ; rp[1] = ht[1] - - ADD lt_1,m_1,lt_1 ; lt = lt+m - ADD,DC ht_1,%r0,ht_1 ; ht[1]++ - STD lt_1,16(r_ptr) ; rp[2] = lt[1] - STD ht_1,24(r_ptr) ; rp[3] = ht[1] - - LDO -2(num),num ; num = num - 2; - LDO 16(a_ptr),a_ptr ; ap += 2 - CMPIB,<= 2,num,bn_sqr_words_unroll2 - LDO 32(r_ptr),r_ptr ; rp += 4 - - CMPIB,=,N 0,num,bn_sqr_words_exit ; are we done? - - ; - ; Top of loop aligned on 64-byte boundary - ; -bn_sqr_words_single_top - FLDD 0(a_ptr),t_float_0 ; load up 64-bit value (fr8L) ht(L)/lt(R) - - XMPYU fht_0,flt_0,fm ; m - FSTD fm,-24(%sp) ; store m - - XMPYU flt_0,flt_0,lt_temp ; lt - FSTD lt_temp,-16(%sp) ; store lt - - XMPYU fht_0,fht_0,ht_temp ; ht - FSTD ht_temp,-8(%sp) ; store ht - - LDD -24(%sp),m_0 ; load m - AND m_0,high_mask,tmp_0 ; m & Mask - DEPD,Z m_0,30,31,m_0 ; m << 32+1 - LDD -16(%sp),lt_0 ; lt - - LDD -8(%sp),ht_0 ; ht - EXTRD,U tmp_0,32,33,tmp_0 ; tmp_0 = m&Mask >> 32-1 - ADD m_0,lt_0,lt_0 ; lt = lt+m - ADD,L ht_0,tmp_0,ht_0 ; ht += tmp_0 - ADD,DC ht_0,%r0,ht_0 ; ht++ - - STD lt_0,0(r_ptr) ; rp[0] = lt - STD ht_0,8(r_ptr) ; rp[1] = ht - -bn_sqr_words_exit - .EXIT - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 - .PROCEND ;in=23,24,25,26,29;out=28; - - -;---------------------------------------------------------------------------- -; -;BN_ULONG bn_add_words(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) -; -; arg0 = rp -; arg1 = ap -; arg2 = bp -; arg3 = n - -t .reg %r22 -b .reg %r21 -l .reg %r20 - -bn_add_words - .proc - .entry - .callinfo - .EXPORT bn_add_words,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .align 64 - - CMPIB,>= 0,n,bn_add_words_exit - COPY %r0,%ret0 ; return 0 by default - - ; - ; If 2 or more numbers do the loop - ; - CMPIB,= 1,n,bn_add_words_single_top - NOP - - ; - ; This loop is unrolled 2 times (64-byte aligned as well) - ; -bn_add_words_unroll2 - LDD 0(a_ptr),t - LDD 0(b_ptr),b - ADD t,%ret0,t ; t = t+c; - ADD,DC %r0,%r0,%ret0 ; set c to carry - ADD t,b,l ; l = t + b[0] - ADD,DC %ret0,%r0,%ret0 ; c+= carry - STD l,0(r_ptr) - - LDD 8(a_ptr),t - LDD 8(b_ptr),b - ADD t,%ret0,t ; t = t+c; - ADD,DC %r0,%r0,%ret0 ; set c to carry - ADD t,b,l ; l = t + b[0] - ADD,DC %ret0,%r0,%ret0 ; c+= carry - STD l,8(r_ptr) - - LDO -2(n),n - LDO 16(a_ptr),a_ptr - LDO 16(b_ptr),b_ptr - - CMPIB,<= 2,n,bn_add_words_unroll2 - LDO 16(r_ptr),r_ptr - - CMPIB,=,N 0,n,bn_add_words_exit ; are we done? - -bn_add_words_single_top - LDD 0(a_ptr),t - LDD 0(b_ptr),b - - ADD t,%ret0,t ; t = t+c; - ADD,DC %r0,%r0,%ret0 ; set c to carry (could use CMPCLR??) - ADD t,b,l ; l = t + b[0] - ADD,DC %ret0,%r0,%ret0 ; c+= carry - STD l,0(r_ptr) - -bn_add_words_exit - .EXIT - BVE (%rp) - NOP - .PROCEND ;in=23,24,25,26,29;out=28; - -;---------------------------------------------------------------------------- -; -;BN_ULONG bn_sub_words(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) -; -; arg0 = rp -; arg1 = ap -; arg2 = bp -; arg3 = n - -t1 .reg %r22 -t2 .reg %r21 -sub_tmp1 .reg %r20 -sub_tmp2 .reg %r19 - - -bn_sub_words - .proc - .callinfo - .EXPORT bn_sub_words,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .entry - .align 64 - - CMPIB,>= 0,n,bn_sub_words_exit - COPY %r0,%ret0 ; return 0 by default - - ; - ; If 2 or more numbers do the loop - ; - CMPIB,= 1,n,bn_sub_words_single_top - NOP - - ; - ; This loop is unrolled 2 times (64-byte aligned as well) - ; -bn_sub_words_unroll2 - LDD 0(a_ptr),t1 - LDD 0(b_ptr),t2 - SUB t1,t2,sub_tmp1 ; t3 = t1-t2; - SUB sub_tmp1,%ret0,sub_tmp1 ; t3 = t3- c; - - CMPCLR,*>> t1,t2,sub_tmp2 ; clear if t1 > t2 - LDO 1(%r0),sub_tmp2 - - CMPCLR,*= t1,t2,%r0 - COPY sub_tmp2,%ret0 - STD sub_tmp1,0(r_ptr) - - LDD 8(a_ptr),t1 - LDD 8(b_ptr),t2 - SUB t1,t2,sub_tmp1 ; t3 = t1-t2; - SUB sub_tmp1,%ret0,sub_tmp1 ; t3 = t3- c; - CMPCLR,*>> t1,t2,sub_tmp2 ; clear if t1 > t2 - LDO 1(%r0),sub_tmp2 - - CMPCLR,*= t1,t2,%r0 - COPY sub_tmp2,%ret0 - STD sub_tmp1,8(r_ptr) - - LDO -2(n),n - LDO 16(a_ptr),a_ptr - LDO 16(b_ptr),b_ptr - - CMPIB,<= 2,n,bn_sub_words_unroll2 - LDO 16(r_ptr),r_ptr - - CMPIB,=,N 0,n,bn_sub_words_exit ; are we done? - -bn_sub_words_single_top - LDD 0(a_ptr),t1 - LDD 0(b_ptr),t2 - SUB t1,t2,sub_tmp1 ; t3 = t1-t2; - SUB sub_tmp1,%ret0,sub_tmp1 ; t3 = t3- c; - CMPCLR,*>> t1,t2,sub_tmp2 ; clear if t1 > t2 - LDO 1(%r0),sub_tmp2 - - CMPCLR,*= t1,t2,%r0 - COPY sub_tmp2,%ret0 - - STD sub_tmp1,0(r_ptr) - -bn_sub_words_exit - .EXIT - BVE (%rp) - NOP - .PROCEND ;in=23,24,25,26,29;out=28; - -;------------------------------------------------------------------------------ -; -; unsigned long bn_div_words(unsigned long h, unsigned long l, unsigned long d) -; -; arg0 = h -; arg1 = l -; arg2 = d -; -; This is mainly just modified assembly from the compiler, thus the -; lack of variable names. -; -;------------------------------------------------------------------------------ -bn_div_words - .proc - .callinfo CALLER,FRAME=272,ENTRY_GR=%r10,SAVE_RP,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_div_words,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .IMPORT BN_num_bits_word,CODE,NO_RELOCATION - .IMPORT __iob,DATA - .IMPORT fprintf,CODE,NO_RELOCATION - .IMPORT abort,CODE,NO_RELOCATION - .IMPORT $$div2U,MILLICODE - .entry - STD %r2,-16(%r30) - STD,MA %r3,352(%r30) - STD %r4,-344(%r30) - STD %r5,-336(%r30) - STD %r6,-328(%r30) - STD %r7,-320(%r30) - STD %r8,-312(%r30) - STD %r9,-304(%r30) - STD %r10,-296(%r30) - - STD %r27,-288(%r30) ; save gp - - COPY %r24,%r3 ; save d - COPY %r26,%r4 ; save h (high 64-bits) - LDO -1(%r0),%ret0 ; return -1 by default - - CMPB,*= %r0,%arg2,$D3 ; if (d == 0) - COPY %r25,%r5 ; save l (low 64-bits) - - LDO -48(%r30),%r29 ; create ap - .CALL ;in=26,29;out=28; - B,L BN_num_bits_word,%r2 - COPY %r3,%r26 - LDD -288(%r30),%r27 ; restore gp - LDI 64,%r21 - - CMPB,= %r21,%ret0,$00000012 ;if (i == 64) (forward) - COPY %ret0,%r24 ; i - MTSARCM %r24 - DEPDI,Z -1,%sar,1,%r29 - CMPB,*<<,N %r29,%r4,bn_div_err_case ; if (h > 1<= d) - SUB %r4,%r3,%r4 ; h -= d - CMPB,= %r31,%r0,$0000001A ; if (i) - COPY %r0,%r10 ; ret = 0 - MTSARCM %r31 ; i to shift - DEPD,Z %r3,%sar,64,%r3 ; d <<= i; - SUBI 64,%r31,%r19 ; 64 - i; redundent - MTSAR %r19 ; (64 -i) to shift - SHRPD %r4,%r5,%sar,%r4 ; l>> (64-i) - MTSARCM %r31 ; i to shift - DEPD,Z %r5,%sar,64,%r5 ; l <<= i; - -$0000001A - DEPDI,Z -1,31,32,%r19 - EXTRD,U %r3,31,32,%r6 ; dh=(d&0xfff)>>32 - EXTRD,U %r3,63,32,%r8 ; dl = d&0xffffff - LDO 2(%r0),%r9 - STD %r3,-280(%r30) ; "d" to stack - -$0000001C - DEPDI,Z -1,63,32,%r29 ; - EXTRD,U %r4,31,32,%r31 ; h >> 32 - CMPB,*=,N %r31,%r6,$D2 ; if ((h>>32) != dh)(forward) div - COPY %r4,%r26 - EXTRD,U %r4,31,32,%r25 - COPY %r6,%r24 - .CALL ;in=23,24,25,26;out=20,21,22,28,29; (MILLICALL) - B,L $$div2U,%r2 - EXTRD,U %r6,31,32,%r23 - DEPD %r28,31,32,%r29 -$D2 - STD %r29,-272(%r30) ; q - AND %r5,%r19,%r24 ; t & 0xffffffff00000000; - EXTRD,U %r24,31,32,%r24 ; ??? - FLDD -272(%r30),%fr7 ; q - FLDD -280(%r30),%fr8 ; d - XMPYU %fr8L,%fr7L,%fr10 - FSTD %fr10,-256(%r30) - XMPYU %fr8L,%fr7R,%fr22 - FSTD %fr22,-264(%r30) - XMPYU %fr8R,%fr7L,%fr11 - XMPYU %fr8R,%fr7R,%fr23 - FSTD %fr11,-232(%r30) - FSTD %fr23,-240(%r30) - LDD -256(%r30),%r28 - DEPD,Z %r28,31,32,%r2 - LDD -264(%r30),%r20 - ADD,L %r20,%r2,%r31 - LDD -232(%r30),%r22 - DEPD,Z %r22,31,32,%r22 - LDD -240(%r30),%r21 - B $00000024 ; enter loop - ADD,L %r21,%r22,%r23 - -$0000002A - LDO -1(%r29),%r29 - SUB %r23,%r8,%r23 -$00000024 - SUB %r4,%r31,%r25 - AND %r25,%r19,%r26 - CMPB,*<>,N %r0,%r26,$00000046 ; (forward) - DEPD,Z %r25,31,32,%r20 - OR %r20,%r24,%r21 - CMPB,*<<,N %r21,%r23,$0000002A ;(backward) - SUB %r31,%r6,%r31 -;-------------Break path--------------------- - -$00000046 - DEPD,Z %r23,31,32,%r25 ;tl - EXTRD,U %r23,31,32,%r26 ;t - AND %r25,%r19,%r24 ;tl = (tl<<32)&0xfffffff0000000L - ADD,L %r31,%r26,%r31 ;th += t; - CMPCLR,*>>= %r5,%r24,%r0 ;if (l>32)); - DEPD,Z %r29,31,32,%r10 ; ret = q<<32 - b $0000001C - DEPD,Z %r28,31,32,%r5 ; l = l << 32 - -$D1 - OR %r10,%r29,%r28 ; ret |= q -$D3 - LDD -368(%r30),%r2 -$D0 - LDD -296(%r30),%r10 - LDD -304(%r30),%r9 - LDD -312(%r30),%r8 - LDD -320(%r30),%r7 - LDD -328(%r30),%r6 - LDD -336(%r30),%r5 - LDD -344(%r30),%r4 - BVE (%r2) - .EXIT - LDD,MB -352(%r30),%r3 - -bn_div_err_case - MFIA %r6 - ADDIL L'bn_div_words-bn_div_err_case,%r6,%r1 - LDO R'bn_div_words-bn_div_err_case(%r1),%r6 - ADDIL LT'__iob,%r27,%r1 - LDD RT'__iob(%r1),%r26 - ADDIL L'C$4-bn_div_words,%r6,%r1 - LDO R'C$4-bn_div_words(%r1),%r25 - LDO 64(%r26),%r26 - .CALL ;in=24,25,26,29;out=28; - B,L fprintf,%r2 - LDO -48(%r30),%r29 - LDD -288(%r30),%r27 - .CALL ;in=29; - B,L abort,%r2 - LDO -48(%r30),%r29 - LDD -288(%r30),%r27 - B $D0 - LDD -368(%r30),%r2 - .PROCEND ;in=24,25,26,29;out=28; - -;---------------------------------------------------------------------------- -; -; Registers to hold 64-bit values to manipulate. The "L" part -; of the register corresponds to the upper 32-bits, while the "R" -; part corresponds to the lower 32-bits -; -; Note, that when using b6 and b7, the code must save these before -; using them because they are callee save registers -; -; -; Floating point registers to use to save values that -; are manipulated. These don't collide with ftemp1-6 and -; are all caller save registers -; -a0 .reg %fr22 -a0L .reg %fr22L -a0R .reg %fr22R - -a1 .reg %fr23 -a1L .reg %fr23L -a1R .reg %fr23R - -a2 .reg %fr24 -a2L .reg %fr24L -a2R .reg %fr24R - -a3 .reg %fr25 -a3L .reg %fr25L -a3R .reg %fr25R - -a4 .reg %fr26 -a4L .reg %fr26L -a4R .reg %fr26R - -a5 .reg %fr27 -a5L .reg %fr27L -a5R .reg %fr27R - -a6 .reg %fr28 -a6L .reg %fr28L -a6R .reg %fr28R - -a7 .reg %fr29 -a7L .reg %fr29L -a7R .reg %fr29R - -b0 .reg %fr30 -b0L .reg %fr30L -b0R .reg %fr30R - -b1 .reg %fr31 -b1L .reg %fr31L -b1R .reg %fr31R - -; -; Temporary floating point variables, these are all caller save -; registers -; -ftemp1 .reg %fr4 -ftemp2 .reg %fr5 -ftemp3 .reg %fr6 -ftemp4 .reg %fr7 - -; -; The B set of registers when used. -; - -b2 .reg %fr8 -b2L .reg %fr8L -b2R .reg %fr8R - -b3 .reg %fr9 -b3L .reg %fr9L -b3R .reg %fr9R - -b4 .reg %fr10 -b4L .reg %fr10L -b4R .reg %fr10R - -b5 .reg %fr11 -b5L .reg %fr11L -b5R .reg %fr11R - -b6 .reg %fr12 -b6L .reg %fr12L -b6R .reg %fr12R - -b7 .reg %fr13 -b7L .reg %fr13L -b7R .reg %fr13R - -c1 .reg %r21 ; only reg -temp1 .reg %r20 ; only reg -temp2 .reg %r19 ; only reg -temp3 .reg %r31 ; only reg - -m1 .reg %r28 -c2 .reg %r23 -high_one .reg %r1 -ht .reg %r6 -lt .reg %r5 -m .reg %r4 -c3 .reg %r3 - -SQR_ADD_C .macro A0L,A0R,C1,C2,C3 - XMPYU A0L,A0R,ftemp1 ; m - FSTD ftemp1,-24(%sp) ; store m - - XMPYU A0R,A0R,ftemp2 ; lt - FSTD ftemp2,-16(%sp) ; store lt - - XMPYU A0L,A0L,ftemp3 ; ht - FSTD ftemp3,-8(%sp) ; store ht - - LDD -24(%sp),m ; load m - AND m,high_mask,temp2 ; m & Mask - DEPD,Z m,30,31,temp3 ; m << 32+1 - LDD -16(%sp),lt ; lt - - LDD -8(%sp),ht ; ht - EXTRD,U temp2,32,33,temp1 ; temp1 = m&Mask >> 32-1 - ADD temp3,lt,lt ; lt = lt+m - ADD,L ht,temp1,ht ; ht += temp1 - ADD,DC ht,%r0,ht ; ht++ - - ADD C1,lt,C1 ; c1=c1+lt - ADD,DC ht,%r0,ht ; ht++ - - ADD C2,ht,C2 ; c2=c2+ht - ADD,DC C3,%r0,C3 ; c3++ -.endm - -SQR_ADD_C2 .macro A0L,A0R,A1L,A1R,C1,C2,C3 - XMPYU A0L,A1R,ftemp1 ; m1 = bl*ht - FSTD ftemp1,-16(%sp) ; - XMPYU A0R,A1L,ftemp2 ; m = bh*lt - FSTD ftemp2,-8(%sp) ; - XMPYU A0R,A1R,ftemp3 ; lt = bl*lt - FSTD ftemp3,-32(%sp) - XMPYU A0L,A1L,ftemp4 ; ht = bh*ht - FSTD ftemp4,-24(%sp) ; - - LDD -8(%sp),m ; r21 = m - LDD -16(%sp),m1 ; r19 = m1 - ADD,L m,m1,m ; m+m1 - - DEPD,Z m,31,32,temp3 ; (m+m1<<32) - LDD -24(%sp),ht ; r24 = ht - - CMPCLR,*>>= m,m1,%r0 ; if (m < m1) - ADD,L ht,high_one,ht ; ht+=high_one - - EXTRD,U m,31,32,temp1 ; m >> 32 - LDD -32(%sp),lt ; lt - ADD,L ht,temp1,ht ; ht+= m>>32 - ADD lt,temp3,lt ; lt = lt+m1 - ADD,DC ht,%r0,ht ; ht++ - - ADD ht,ht,ht ; ht=ht+ht; - ADD,DC C3,%r0,C3 ; add in carry (c3++) - - ADD lt,lt,lt ; lt=lt+lt; - ADD,DC ht,%r0,ht ; add in carry (ht++) - - ADD C1,lt,C1 ; c1=c1+lt - ADD,DC,*NUV ht,%r0,ht ; add in carry (ht++) - LDO 1(C3),C3 ; bump c3 if overflow,nullify otherwise - - ADD C2,ht,C2 ; c2 = c2 + ht - ADD,DC C3,%r0,C3 ; add in carry (c3++) -.endm - -; -;void bn_sqr_comba8(BN_ULONG *r, BN_ULONG *a) -; arg0 = r_ptr -; arg1 = a_ptr -; - -bn_sqr_comba8 - .PROC - .CALLINFO FRAME=128,ENTRY_GR=%r3,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_sqr_comba8,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .ENTRY - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - STD %r5,16(%sp) ; save r5 - STD %r6,24(%sp) ; save r6 - - ; - ; Zero out carries - ; - COPY %r0,c1 - COPY %r0,c2 - COPY %r0,c3 - - LDO 128(%sp),%sp ; bump stack - DEPDI,Z -1,32,33,high_mask ; Create Mask 0xffffffff80000000L - DEPDI,Z 1,31,1,high_one ; Create Value 1 << 32 - - ; - ; Load up all of the values we are going to use - ; - FLDD 0(a_ptr),a0 - FLDD 8(a_ptr),a1 - FLDD 16(a_ptr),a2 - FLDD 24(a_ptr),a3 - FLDD 32(a_ptr),a4 - FLDD 40(a_ptr),a5 - FLDD 48(a_ptr),a6 - FLDD 56(a_ptr),a7 - - SQR_ADD_C a0L,a0R,c1,c2,c3 - STD c1,0(r_ptr) ; r[0] = c1; - COPY %r0,c1 - - SQR_ADD_C2 a1L,a1R,a0L,a0R,c2,c3,c1 - STD c2,8(r_ptr) ; r[1] = c2; - COPY %r0,c2 - - SQR_ADD_C a1L,a1R,c3,c1,c2 - SQR_ADD_C2 a2L,a2R,a0L,a0R,c3,c1,c2 - STD c3,16(r_ptr) ; r[2] = c3; - COPY %r0,c3 - - SQR_ADD_C2 a3L,a3R,a0L,a0R,c1,c2,c3 - SQR_ADD_C2 a2L,a2R,a1L,a1R,c1,c2,c3 - STD c1,24(r_ptr) ; r[3] = c1; - COPY %r0,c1 - - SQR_ADD_C a2L,a2R,c2,c3,c1 - SQR_ADD_C2 a3L,a3R,a1L,a1R,c2,c3,c1 - SQR_ADD_C2 a4L,a4R,a0L,a0R,c2,c3,c1 - STD c2,32(r_ptr) ; r[4] = c2; - COPY %r0,c2 - - SQR_ADD_C2 a5L,a5R,a0L,a0R,c3,c1,c2 - SQR_ADD_C2 a4L,a4R,a1L,a1R,c3,c1,c2 - SQR_ADD_C2 a3L,a3R,a2L,a2R,c3,c1,c2 - STD c3,40(r_ptr) ; r[5] = c3; - COPY %r0,c3 - - SQR_ADD_C a3L,a3R,c1,c2,c3 - SQR_ADD_C2 a4L,a4R,a2L,a2R,c1,c2,c3 - SQR_ADD_C2 a5L,a5R,a1L,a1R,c1,c2,c3 - SQR_ADD_C2 a6L,a6R,a0L,a0R,c1,c2,c3 - STD c1,48(r_ptr) ; r[6] = c1; - COPY %r0,c1 - - SQR_ADD_C2 a7L,a7R,a0L,a0R,c2,c3,c1 - SQR_ADD_C2 a6L,a6R,a1L,a1R,c2,c3,c1 - SQR_ADD_C2 a5L,a5R,a2L,a2R,c2,c3,c1 - SQR_ADD_C2 a4L,a4R,a3L,a3R,c2,c3,c1 - STD c2,56(r_ptr) ; r[7] = c2; - COPY %r0,c2 - - SQR_ADD_C a4L,a4R,c3,c1,c2 - SQR_ADD_C2 a5L,a5R,a3L,a3R,c3,c1,c2 - SQR_ADD_C2 a6L,a6R,a2L,a2R,c3,c1,c2 - SQR_ADD_C2 a7L,a7R,a1L,a1R,c3,c1,c2 - STD c3,64(r_ptr) ; r[8] = c3; - COPY %r0,c3 - - SQR_ADD_C2 a7L,a7R,a2L,a2R,c1,c2,c3 - SQR_ADD_C2 a6L,a6R,a3L,a3R,c1,c2,c3 - SQR_ADD_C2 a5L,a5R,a4L,a4R,c1,c2,c3 - STD c1,72(r_ptr) ; r[9] = c1; - COPY %r0,c1 - - SQR_ADD_C a5L,a5R,c2,c3,c1 - SQR_ADD_C2 a6L,a6R,a4L,a4R,c2,c3,c1 - SQR_ADD_C2 a7L,a7R,a3L,a3R,c2,c3,c1 - STD c2,80(r_ptr) ; r[10] = c2; - COPY %r0,c2 - - SQR_ADD_C2 a7L,a7R,a4L,a4R,c3,c1,c2 - SQR_ADD_C2 a6L,a6R,a5L,a5R,c3,c1,c2 - STD c3,88(r_ptr) ; r[11] = c3; - COPY %r0,c3 - - SQR_ADD_C a6L,a6R,c1,c2,c3 - SQR_ADD_C2 a7L,a7R,a5L,a5R,c1,c2,c3 - STD c1,96(r_ptr) ; r[12] = c1; - COPY %r0,c1 - - SQR_ADD_C2 a7L,a7R,a6L,a6R,c2,c3,c1 - STD c2,104(r_ptr) ; r[13] = c2; - COPY %r0,c2 - - SQR_ADD_C a7L,a7R,c3,c1,c2 - STD c3, 112(r_ptr) ; r[14] = c3 - STD c1, 120(r_ptr) ; r[15] = c1 - - .EXIT - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 - - .PROCEND - -;----------------------------------------------------------------------------- -; -;void bn_sqr_comba4(BN_ULONG *r, BN_ULONG *a) -; arg0 = r_ptr -; arg1 = a_ptr -; - -bn_sqr_comba4 - .proc - .callinfo FRAME=128,ENTRY_GR=%r3,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_sqr_comba4,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .entry - .align 64 - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - STD %r5,16(%sp) ; save r5 - STD %r6,24(%sp) ; save r6 - - ; - ; Zero out carries - ; - COPY %r0,c1 - COPY %r0,c2 - COPY %r0,c3 - - LDO 128(%sp),%sp ; bump stack - DEPDI,Z -1,32,33,high_mask ; Create Mask 0xffffffff80000000L - DEPDI,Z 1,31,1,high_one ; Create Value 1 << 32 - - ; - ; Load up all of the values we are going to use - ; - FLDD 0(a_ptr),a0 - FLDD 8(a_ptr),a1 - FLDD 16(a_ptr),a2 - FLDD 24(a_ptr),a3 - FLDD 32(a_ptr),a4 - FLDD 40(a_ptr),a5 - FLDD 48(a_ptr),a6 - FLDD 56(a_ptr),a7 - - SQR_ADD_C a0L,a0R,c1,c2,c3 - - STD c1,0(r_ptr) ; r[0] = c1; - COPY %r0,c1 - - SQR_ADD_C2 a1L,a1R,a0L,a0R,c2,c3,c1 - - STD c2,8(r_ptr) ; r[1] = c2; - COPY %r0,c2 - - SQR_ADD_C a1L,a1R,c3,c1,c2 - SQR_ADD_C2 a2L,a2R,a0L,a0R,c3,c1,c2 - - STD c3,16(r_ptr) ; r[2] = c3; - COPY %r0,c3 - - SQR_ADD_C2 a3L,a3R,a0L,a0R,c1,c2,c3 - SQR_ADD_C2 a2L,a2R,a1L,a1R,c1,c2,c3 - - STD c1,24(r_ptr) ; r[3] = c1; - COPY %r0,c1 - - SQR_ADD_C a2L,a2R,c2,c3,c1 - SQR_ADD_C2 a3L,a3R,a1L,a1R,c2,c3,c1 - - STD c2,32(r_ptr) ; r[4] = c2; - COPY %r0,c2 - - SQR_ADD_C2 a3L,a3R,a2L,a2R,c3,c1,c2 - STD c3,40(r_ptr) ; r[5] = c3; - COPY %r0,c3 - - SQR_ADD_C a3L,a3R,c1,c2,c3 - STD c1,48(r_ptr) ; r[6] = c1; - STD c2,56(r_ptr) ; r[7] = c2; - - .EXIT - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 - - .PROCEND - - -;--------------------------------------------------------------------------- - -MUL_ADD_C .macro A0L,A0R,B0L,B0R,C1,C2,C3 - XMPYU A0L,B0R,ftemp1 ; m1 = bl*ht - FSTD ftemp1,-16(%sp) ; - XMPYU A0R,B0L,ftemp2 ; m = bh*lt - FSTD ftemp2,-8(%sp) ; - XMPYU A0R,B0R,ftemp3 ; lt = bl*lt - FSTD ftemp3,-32(%sp) - XMPYU A0L,B0L,ftemp4 ; ht = bh*ht - FSTD ftemp4,-24(%sp) ; - - LDD -8(%sp),m ; r21 = m - LDD -16(%sp),m1 ; r19 = m1 - ADD,L m,m1,m ; m+m1 - - DEPD,Z m,31,32,temp3 ; (m+m1<<32) - LDD -24(%sp),ht ; r24 = ht - - CMPCLR,*>>= m,m1,%r0 ; if (m < m1) - ADD,L ht,high_one,ht ; ht+=high_one - - EXTRD,U m,31,32,temp1 ; m >> 32 - LDD -32(%sp),lt ; lt - ADD,L ht,temp1,ht ; ht+= m>>32 - ADD lt,temp3,lt ; lt = lt+m1 - ADD,DC ht,%r0,ht ; ht++ - - ADD C1,lt,C1 ; c1=c1+lt - ADD,DC ht,%r0,ht ; bump c3 if overflow,nullify otherwise - - ADD C2,ht,C2 ; c2 = c2 + ht - ADD,DC C3,%r0,C3 ; add in carry (c3++) -.endm - - -; -;void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) -; arg0 = r_ptr -; arg1 = a_ptr -; arg2 = b_ptr -; - -bn_mul_comba8 - .proc - .callinfo FRAME=128,ENTRY_GR=%r3,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_mul_comba8,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .entry - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - STD %r5,16(%sp) ; save r5 - STD %r6,24(%sp) ; save r6 - FSTD %fr12,32(%sp) ; save r6 - FSTD %fr13,40(%sp) ; save r7 - - ; - ; Zero out carries - ; - COPY %r0,c1 - COPY %r0,c2 - COPY %r0,c3 - - LDO 128(%sp),%sp ; bump stack - DEPDI,Z 1,31,1,high_one ; Create Value 1 << 32 - - ; - ; Load up all of the values we are going to use - ; - FLDD 0(a_ptr),a0 - FLDD 8(a_ptr),a1 - FLDD 16(a_ptr),a2 - FLDD 24(a_ptr),a3 - FLDD 32(a_ptr),a4 - FLDD 40(a_ptr),a5 - FLDD 48(a_ptr),a6 - FLDD 56(a_ptr),a7 - - FLDD 0(b_ptr),b0 - FLDD 8(b_ptr),b1 - FLDD 16(b_ptr),b2 - FLDD 24(b_ptr),b3 - FLDD 32(b_ptr),b4 - FLDD 40(b_ptr),b5 - FLDD 48(b_ptr),b6 - FLDD 56(b_ptr),b7 - - MUL_ADD_C a0L,a0R,b0L,b0R,c1,c2,c3 - STD c1,0(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a0L,a0R,b1L,b1R,c2,c3,c1 - MUL_ADD_C a1L,a1R,b0L,b0R,c2,c3,c1 - STD c2,8(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a2L,a2R,b0L,b0R,c3,c1,c2 - MUL_ADD_C a1L,a1R,b1L,b1R,c3,c1,c2 - MUL_ADD_C a0L,a0R,b2L,b2R,c3,c1,c2 - STD c3,16(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a0L,a0R,b3L,b3R,c1,c2,c3 - MUL_ADD_C a1L,a1R,b2L,b2R,c1,c2,c3 - MUL_ADD_C a2L,a2R,b1L,b1R,c1,c2,c3 - MUL_ADD_C a3L,a3R,b0L,b0R,c1,c2,c3 - STD c1,24(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a4L,a4R,b0L,b0R,c2,c3,c1 - MUL_ADD_C a3L,a3R,b1L,b1R,c2,c3,c1 - MUL_ADD_C a2L,a2R,b2L,b2R,c2,c3,c1 - MUL_ADD_C a1L,a1R,b3L,b3R,c2,c3,c1 - MUL_ADD_C a0L,a0R,b4L,b4R,c2,c3,c1 - STD c2,32(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a0L,a0R,b5L,b5R,c3,c1,c2 - MUL_ADD_C a1L,a1R,b4L,b4R,c3,c1,c2 - MUL_ADD_C a2L,a2R,b3L,b3R,c3,c1,c2 - MUL_ADD_C a3L,a3R,b2L,b2R,c3,c1,c2 - MUL_ADD_C a4L,a4R,b1L,b1R,c3,c1,c2 - MUL_ADD_C a5L,a5R,b0L,b0R,c3,c1,c2 - STD c3,40(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a6L,a6R,b0L,b0R,c1,c2,c3 - MUL_ADD_C a5L,a5R,b1L,b1R,c1,c2,c3 - MUL_ADD_C a4L,a4R,b2L,b2R,c1,c2,c3 - MUL_ADD_C a3L,a3R,b3L,b3R,c1,c2,c3 - MUL_ADD_C a2L,a2R,b4L,b4R,c1,c2,c3 - MUL_ADD_C a1L,a1R,b5L,b5R,c1,c2,c3 - MUL_ADD_C a0L,a0R,b6L,b6R,c1,c2,c3 - STD c1,48(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a0L,a0R,b7L,b7R,c2,c3,c1 - MUL_ADD_C a1L,a1R,b6L,b6R,c2,c3,c1 - MUL_ADD_C a2L,a2R,b5L,b5R,c2,c3,c1 - MUL_ADD_C a3L,a3R,b4L,b4R,c2,c3,c1 - MUL_ADD_C a4L,a4R,b3L,b3R,c2,c3,c1 - MUL_ADD_C a5L,a5R,b2L,b2R,c2,c3,c1 - MUL_ADD_C a6L,a6R,b1L,b1R,c2,c3,c1 - MUL_ADD_C a7L,a7R,b0L,b0R,c2,c3,c1 - STD c2,56(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a7L,a7R,b1L,b1R,c3,c1,c2 - MUL_ADD_C a6L,a6R,b2L,b2R,c3,c1,c2 - MUL_ADD_C a5L,a5R,b3L,b3R,c3,c1,c2 - MUL_ADD_C a4L,a4R,b4L,b4R,c3,c1,c2 - MUL_ADD_C a3L,a3R,b5L,b5R,c3,c1,c2 - MUL_ADD_C a2L,a2R,b6L,b6R,c3,c1,c2 - MUL_ADD_C a1L,a1R,b7L,b7R,c3,c1,c2 - STD c3,64(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a2L,a2R,b7L,b7R,c1,c2,c3 - MUL_ADD_C a3L,a3R,b6L,b6R,c1,c2,c3 - MUL_ADD_C a4L,a4R,b5L,b5R,c1,c2,c3 - MUL_ADD_C a5L,a5R,b4L,b4R,c1,c2,c3 - MUL_ADD_C a6L,a6R,b3L,b3R,c1,c2,c3 - MUL_ADD_C a7L,a7R,b2L,b2R,c1,c2,c3 - STD c1,72(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a7L,a7R,b3L,b3R,c2,c3,c1 - MUL_ADD_C a6L,a6R,b4L,b4R,c2,c3,c1 - MUL_ADD_C a5L,a5R,b5L,b5R,c2,c3,c1 - MUL_ADD_C a4L,a4R,b6L,b6R,c2,c3,c1 - MUL_ADD_C a3L,a3R,b7L,b7R,c2,c3,c1 - STD c2,80(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a4L,a4R,b7L,b7R,c3,c1,c2 - MUL_ADD_C a5L,a5R,b6L,b6R,c3,c1,c2 - MUL_ADD_C a6L,a6R,b5L,b5R,c3,c1,c2 - MUL_ADD_C a7L,a7R,b4L,b4R,c3,c1,c2 - STD c3,88(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a7L,a7R,b5L,b5R,c1,c2,c3 - MUL_ADD_C a6L,a6R,b6L,b6R,c1,c2,c3 - MUL_ADD_C a5L,a5R,b7L,b7R,c1,c2,c3 - STD c1,96(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a6L,a6R,b7L,b7R,c2,c3,c1 - MUL_ADD_C a7L,a7R,b6L,b6R,c2,c3,c1 - STD c2,104(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a7L,a7R,b7L,b7R,c3,c1,c2 - STD c3,112(r_ptr) - STD c1,120(r_ptr) - - .EXIT - FLDD -88(%sp),%fr13 - FLDD -96(%sp),%fr12 - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 - - .PROCEND - -;----------------------------------------------------------------------------- -; -;void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) -; arg0 = r_ptr -; arg1 = a_ptr -; arg2 = b_ptr -; - -bn_mul_comba4 - .proc - .callinfo FRAME=128,ENTRY_GR=%r3,ARGS_SAVED,ORDERING_AWARE - .EXPORT bn_mul_comba4,ENTRY,PRIV_LEV=3,NO_RELOCATION,LONG_RETURN - .entry - .align 64 - - STD %r3,0(%sp) ; save r3 - STD %r4,8(%sp) ; save r4 - STD %r5,16(%sp) ; save r5 - STD %r6,24(%sp) ; save r6 - FSTD %fr12,32(%sp) ; save r6 - FSTD %fr13,40(%sp) ; save r7 - - ; - ; Zero out carries - ; - COPY %r0,c1 - COPY %r0,c2 - COPY %r0,c3 - - LDO 128(%sp),%sp ; bump stack - DEPDI,Z 1,31,1,high_one ; Create Value 1 << 32 - - ; - ; Load up all of the values we are going to use - ; - FLDD 0(a_ptr),a0 - FLDD 8(a_ptr),a1 - FLDD 16(a_ptr),a2 - FLDD 24(a_ptr),a3 - - FLDD 0(b_ptr),b0 - FLDD 8(b_ptr),b1 - FLDD 16(b_ptr),b2 - FLDD 24(b_ptr),b3 - - MUL_ADD_C a0L,a0R,b0L,b0R,c1,c2,c3 - STD c1,0(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a0L,a0R,b1L,b1R,c2,c3,c1 - MUL_ADD_C a1L,a1R,b0L,b0R,c2,c3,c1 - STD c2,8(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a2L,a2R,b0L,b0R,c3,c1,c2 - MUL_ADD_C a1L,a1R,b1L,b1R,c3,c1,c2 - MUL_ADD_C a0L,a0R,b2L,b2R,c3,c1,c2 - STD c3,16(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a0L,a0R,b3L,b3R,c1,c2,c3 - MUL_ADD_C a1L,a1R,b2L,b2R,c1,c2,c3 - MUL_ADD_C a2L,a2R,b1L,b1R,c1,c2,c3 - MUL_ADD_C a3L,a3R,b0L,b0R,c1,c2,c3 - STD c1,24(r_ptr) - COPY %r0,c1 - - MUL_ADD_C a3L,a3R,b1L,b1R,c2,c3,c1 - MUL_ADD_C a2L,a2R,b2L,b2R,c2,c3,c1 - MUL_ADD_C a1L,a1R,b3L,b3R,c2,c3,c1 - STD c2,32(r_ptr) - COPY %r0,c2 - - MUL_ADD_C a2L,a2R,b3L,b3R,c3,c1,c2 - MUL_ADD_C a3L,a3R,b2L,b2R,c3,c1,c2 - STD c3,40(r_ptr) - COPY %r0,c3 - - MUL_ADD_C a3L,a3R,b3L,b3R,c1,c2,c3 - STD c1,48(r_ptr) - STD c2,56(r_ptr) - - .EXIT - FLDD -88(%sp),%fr13 - FLDD -96(%sp),%fr12 - LDD -104(%sp),%r6 ; restore r6 - LDD -112(%sp),%r5 ; restore r5 - LDD -120(%sp),%r4 ; restore r4 - BVE (%rp) - LDD,MB -128(%sp),%r3 - - .PROCEND - - - .SPACE $TEXT$ - .SUBSPA $CODE$ - .SPACE $PRIVATE$,SORT=16 - .IMPORT $global$,DATA - .SPACE $TEXT$ - .SUBSPA $CODE$ - .SUBSPA $LIT$,ACCESS=0x2c -C$4 - .ALIGN 8 - .STRINGZ "Division would overflow (%d)\n" - .END diff --git a/crypto/bn/asm/parisc-mont.pl b/crypto/bn/asm/parisc-mont.pl index 8aa94e85..a705e163 100644 --- a/crypto/bn/asm/parisc-mont.pl +++ b/crypto/bn/asm/parisc-mont.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -21,7 +21,7 @@ # optimal in respect to instruction set capabilities. Fair comparison # with vendor compiler is problematic, because OpenSSL doesn't define # BN_LLONG [presumably] for historical reasons, which drives compiler -# toward 4 times 16x16=32-bit multiplicatons [plus complementary +# toward 4 times 16x16=32-bit multiplications [plus complementary # shifts and additions] instead. This means that you should observe # several times improvement over code generated by vendor compiler # for PA-RISC 1.1, but the "baseline" is far from optimal. The actual @@ -546,7 +546,7 @@ L\$copy ldd $idx($np),$hi0 std,ma %r0,8($tp) addib,<> 8,$idx,.-8 ; L\$copy - std,ma $hi0,8($rp) + std,ma $hi0,8($rp) ___ if ($BN_SZ==4) { # PA-RISC 1.1 code-path @@ -868,7 +868,7 @@ L\$copy_pa11 ldwx $idx($np),$hi0 stws,ma %r0,4($tp) addib,<> 4,$idx,L\$copy_pa11 - stws,ma $hi0,4($rp) + stws,ma $hi0,4($rp) nop ; alignment L\$done diff --git a/crypto/bn/asm/ppc-mont.pl b/crypto/bn/asm/ppc-mont.pl index 5802260c..9aa96c8e 100644 --- a/crypto/bn/asm/ppc-mont.pl +++ b/crypto/bn/asm/ppc-mont.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -26,11 +26,21 @@ # So far RSA *sign* performance improvement over pre-bn_mul_mont asm # for 64-bit application running on PPC970/G5 is: # -# 512-bit +65% +# 512-bit +65% # 1024-bit +35% # 2048-bit +18% # 4096-bit +4% +# September 2016 +# +# Add multiplication procedure operating on lengths divisible by 4 +# and squaring procedure operating on lengths divisible by 8. Length +# is expressed in number of limbs. RSA private key operations are +# ~35-50% faster (more for longer keys) on contemporary high-end POWER +# processors in 64-bit builds, [mysteriously enough] more in 32-bit +# builds. On low-end 32-bit processors performance improvement turned +# to be marginal... + $flavour = shift; if ($flavour =~ /32/) { @@ -49,7 +59,8 @@ if ($flavour =~ /32/) { $UMULL= "mullw"; # unsigned multiply low $UMULH= "mulhwu"; # unsigned multiply high $UCMP= "cmplw"; # unsigned compare - $SHRI= "srwi"; # unsigned shift right by immediate + $SHRI= "srwi"; # unsigned shift right by immediate + $SHLI= "slwi"; # unsigned shift left by immediate $PUSH= $ST; $POP= $LD; } elsif ($flavour =~ /64/) { @@ -69,7 +80,8 @@ if ($flavour =~ /32/) { $UMULL= "mulld"; # unsigned multiply low $UMULH= "mulhdu"; # unsigned multiply high $UCMP= "cmpld"; # unsigned compare - $SHRI= "srdi"; # unsigned shift right by immediate + $SHRI= "srdi"; # unsigned shift right by immediate + $SHLI= "sldi"; # unsigned shift left by immediate $PUSH= $ST; $POP= $LD; } else { die "nonsense $flavour"; } @@ -86,43 +98,44 @@ open STDOUT,"| $^X $xlate $flavour ".shift || die "can't call $xlate: $!"; $sp="r1"; $toc="r2"; -$rp="r3"; $ovf="r3"; +$rp="r3"; $ap="r4"; $bp="r5"; $np="r6"; $n0="r7"; $num="r8"; -$rp="r9"; # $rp is reassigned -$aj="r10"; -$nj="r11"; -$tj="r12"; + +{ +my $ovf=$rp; +my $rp="r9"; # $rp is reassigned +my $aj="r10"; +my $nj="r11"; +my $tj="r12"; # non-volatile registers -$i="r20"; -$j="r21"; -$tp="r22"; -$m0="r23"; -$m1="r24"; -$lo0="r25"; -$hi0="r26"; -$lo1="r27"; -$hi1="r28"; -$alo="r29"; -$ahi="r30"; -$nlo="r31"; +my $i="r20"; +my $j="r21"; +my $tp="r22"; +my $m0="r23"; +my $m1="r24"; +my $lo0="r25"; +my $hi0="r26"; +my $lo1="r27"; +my $hi1="r28"; +my $alo="r29"; +my $ahi="r30"; +my $nlo="r31"; # -$nhi="r0"; +my $nhi="r0"; $code=<<___; .machine "any" .text .globl .bn_mul_mont_int -.align 4 +.align 5 .bn_mul_mont_int: - cmpwi $num,4 mr $rp,r3 ; $rp is reassigned li r3,0 - bltlr ___ $code.=<<___ if ($BNSZ==4); cmpwi $num,32 ; longer key performance is not better @@ -333,7 +346,1641 @@ Lcopy: ; copy or in-place refresh .byte 0,12,4,0,0x80,12,6,0 .long 0 .size .bn_mul_mont_int,.-.bn_mul_mont_int +___ +} +if (1) { +my ($a0,$a1,$a2,$a3, + $t0,$t1,$t2,$t3, + $m0,$m1,$m2,$m3, + $acc0,$acc1,$acc2,$acc3,$acc4, + $bi,$mi,$tp,$ap_end,$cnt) = map("r$_",(9..12,14..31)); +my ($carry,$zero) = ($rp,"r0"); +# sp----------->+-------------------------------+ +# | saved sp | +# +-------------------------------+ +# . . +# +8*size_t +-------------------------------+ +# | 4 "n0*t0" | +# . . +# . . +# +12*size_t +-------------------------------+ +# | size_t tmp[num] | +# . . +# . . +# . . +# +-------------------------------+ +# | topmost carry | +# . . +# -18*size_t +-------------------------------+ +# | 18 saved gpr, r14-r31 | +# . . +# . . +# +-------------------------------+ +$code.=<<___; +.globl .bn_mul4x_mont_int +.align 5 +.bn_mul4x_mont_int: + andi. r0,$num,7 + bne .Lmul4x_do + $UCMP $ap,$bp + bne .Lmul4x_do + b .Lsqr8x_do +.Lmul4x_do: + slwi $num,$num,`log($SIZE_T)/log(2)` + mr $a0,$sp + li $a1,-32*$SIZE_T + sub $a1,$a1,$num + $STUX $sp,$sp,$a1 # alloca + + $PUSH r14,-$SIZE_T*18($a0) + $PUSH r15,-$SIZE_T*17($a0) + $PUSH r16,-$SIZE_T*16($a0) + $PUSH r17,-$SIZE_T*15($a0) + $PUSH r18,-$SIZE_T*14($a0) + $PUSH r19,-$SIZE_T*13($a0) + $PUSH r20,-$SIZE_T*12($a0) + $PUSH r21,-$SIZE_T*11($a0) + $PUSH r22,-$SIZE_T*10($a0) + $PUSH r23,-$SIZE_T*9($a0) + $PUSH r24,-$SIZE_T*8($a0) + $PUSH r25,-$SIZE_T*7($a0) + $PUSH r26,-$SIZE_T*6($a0) + $PUSH r27,-$SIZE_T*5($a0) + $PUSH r28,-$SIZE_T*4($a0) + $PUSH r29,-$SIZE_T*3($a0) + $PUSH r30,-$SIZE_T*2($a0) + $PUSH r31,-$SIZE_T*1($a0) + + subi $ap,$ap,$SIZE_T # bias by -1 + subi $np,$np,$SIZE_T # bias by -1 + subi $rp,$rp,$SIZE_T # bias by -1 + $LD $n0,0($n0) # *n0 + + add $t0,$bp,$num + add $ap_end,$ap,$num + subi $t0,$t0,$SIZE_T*4 # &b[num-4] + + $LD $bi,$SIZE_T*0($bp) # b[0] + li $acc0,0 + $LD $a0,$SIZE_T*1($ap) # a[0..3] + li $acc1,0 + $LD $a1,$SIZE_T*2($ap) + li $acc2,0 + $LD $a2,$SIZE_T*3($ap) + li $acc3,0 + $LDU $a3,$SIZE_T*4($ap) + $LD $m0,$SIZE_T*1($np) # n[0..3] + $LD $m1,$SIZE_T*2($np) + $LD $m2,$SIZE_T*3($np) + $LDU $m3,$SIZE_T*4($np) + + $PUSH $rp,$SIZE_T*6($sp) # offload rp and &b[num-4] + $PUSH $t0,$SIZE_T*7($sp) + li $carry,0 + addic $tp,$sp,$SIZE_T*7 # &t[-1], clear carry bit + li $cnt,0 + li $zero,0 + b .Loop_mul4x_1st_reduction + +.align 5 +.Loop_mul4x_1st_reduction: + $UMULL $t0,$a0,$bi # lo(a[0..3]*b[0]) + addze $carry,$carry # modulo-scheduled + $UMULL $t1,$a1,$bi + addi $cnt,$cnt,$SIZE_T + $UMULL $t2,$a2,$bi + andi. $cnt,$cnt,$SIZE_T*4-1 + $UMULL $t3,$a3,$bi + addc $acc0,$acc0,$t0 + $UMULH $t0,$a0,$bi # hi(a[0..3]*b[0]) + adde $acc1,$acc1,$t1 + $UMULH $t1,$a1,$bi + adde $acc2,$acc2,$t2 + $UMULL $mi,$acc0,$n0 # t[0]*n0 + adde $acc3,$acc3,$t3 + $UMULH $t2,$a2,$bi + addze $acc4,$zero + $UMULH $t3,$a3,$bi + $LDX $bi,$bp,$cnt # next b[i] (or b[0]) + addc $acc1,$acc1,$t0 + # (*) mul $t0,$m0,$mi # lo(n[0..3]*t[0]*n0) + $STU $mi,$SIZE_T($tp) # put aside t[0]*n0 for tail processing + adde $acc2,$acc2,$t1 + $UMULL $t1,$m1,$mi + adde $acc3,$acc3,$t2 + $UMULL $t2,$m2,$mi + adde $acc4,$acc4,$t3 # can't overflow + $UMULL $t3,$m3,$mi + # (*) addc $acc0,$acc0,$t0 + # (*) As for removal of first multiplication and addition + # instructions. The outcome of first addition is + # guaranteed to be zero, which leaves two computationally + # significant outcomes: it either carries or not. Then + # question is when does it carry? Is there alternative + # way to deduce it? If you follow operations, you can + # observe that condition for carry is quite simple: + # $acc0 being non-zero. So that carry can be calculated + # by adding -1 to $acc0. That's what next instruction does. + addic $acc0,$acc0,-1 # (*), discarded + $UMULH $t0,$m0,$mi # hi(n[0..3]*t[0]*n0) + adde $acc0,$acc1,$t1 + $UMULH $t1,$m1,$mi + adde $acc1,$acc2,$t2 + $UMULH $t2,$m2,$mi + adde $acc2,$acc3,$t3 + $UMULH $t3,$m3,$mi + adde $acc3,$acc4,$carry + addze $carry,$zero + addc $acc0,$acc0,$t0 + adde $acc1,$acc1,$t1 + adde $acc2,$acc2,$t2 + adde $acc3,$acc3,$t3 + #addze $carry,$carry + bne .Loop_mul4x_1st_reduction + + $UCMP $ap_end,$ap + beq .Lmul4x4_post_condition + + $LD $a0,$SIZE_T*1($ap) # a[4..7] + $LD $a1,$SIZE_T*2($ap) + $LD $a2,$SIZE_T*3($ap) + $LDU $a3,$SIZE_T*4($ap) + $LD $mi,$SIZE_T*8($sp) # a[0]*n0 + $LD $m0,$SIZE_T*1($np) # n[4..7] + $LD $m1,$SIZE_T*2($np) + $LD $m2,$SIZE_T*3($np) + $LDU $m3,$SIZE_T*4($np) + b .Loop_mul4x_1st_tail + +.align 5 +.Loop_mul4x_1st_tail: + $UMULL $t0,$a0,$bi # lo(a[4..7]*b[i]) + addze $carry,$carry # modulo-scheduled + $UMULL $t1,$a1,$bi + addi $cnt,$cnt,$SIZE_T + $UMULL $t2,$a2,$bi + andi. $cnt,$cnt,$SIZE_T*4-1 + $UMULL $t3,$a3,$bi + addc $acc0,$acc0,$t0 + $UMULH $t0,$a0,$bi # hi(a[4..7]*b[i]) + adde $acc1,$acc1,$t1 + $UMULH $t1,$a1,$bi + adde $acc2,$acc2,$t2 + $UMULH $t2,$a2,$bi + adde $acc3,$acc3,$t3 + $UMULH $t3,$a3,$bi + addze $acc4,$zero + $LDX $bi,$bp,$cnt # next b[i] (or b[0]) + addc $acc1,$acc1,$t0 + $UMULL $t0,$m0,$mi # lo(n[4..7]*a[0]*n0) + adde $acc2,$acc2,$t1 + $UMULL $t1,$m1,$mi + adde $acc3,$acc3,$t2 + $UMULL $t2,$m2,$mi + adde $acc4,$acc4,$t3 # can't overflow + $UMULL $t3,$m3,$mi + addc $acc0,$acc0,$t0 + $UMULH $t0,$m0,$mi # hi(n[4..7]*a[0]*n0) + adde $acc1,$acc1,$t1 + $UMULH $t1,$m1,$mi + adde $acc2,$acc2,$t2 + $UMULH $t2,$m2,$mi + adde $acc3,$acc3,$t3 + adde $acc4,$acc4,$carry + $UMULH $t3,$m3,$mi + addze $carry,$zero + addi $mi,$sp,$SIZE_T*8 + $LDX $mi,$mi,$cnt # next t[0]*n0 + $STU $acc0,$SIZE_T($tp) # word of result + addc $acc0,$acc1,$t0 + adde $acc1,$acc2,$t1 + adde $acc2,$acc3,$t2 + adde $acc3,$acc4,$t3 + #addze $carry,$carry + bne .Loop_mul4x_1st_tail + + sub $t1,$ap_end,$num # rewinded $ap + $UCMP $ap_end,$ap # done yet? + beq .Lmul4x_proceed + + $LD $a0,$SIZE_T*1($ap) + $LD $a1,$SIZE_T*2($ap) + $LD $a2,$SIZE_T*3($ap) + $LDU $a3,$SIZE_T*4($ap) + $LD $m0,$SIZE_T*1($np) + $LD $m1,$SIZE_T*2($np) + $LD $m2,$SIZE_T*3($np) + $LDU $m3,$SIZE_T*4($np) + b .Loop_mul4x_1st_tail + +.align 5 +.Lmul4x_proceed: + $LDU $bi,$SIZE_T*4($bp) # *++b + addze $carry,$carry # topmost carry + $LD $a0,$SIZE_T*1($t1) + $LD $a1,$SIZE_T*2($t1) + $LD $a2,$SIZE_T*3($t1) + $LD $a3,$SIZE_T*4($t1) + addi $ap,$t1,$SIZE_T*4 + sub $np,$np,$num # rewind np + + $ST $acc0,$SIZE_T*1($tp) # result + $ST $acc1,$SIZE_T*2($tp) + $ST $acc2,$SIZE_T*3($tp) + $ST $acc3,$SIZE_T*4($tp) + $ST $carry,$SIZE_T*5($tp) # save topmost carry + $LD $acc0,$SIZE_T*12($sp) # t[0..3] + $LD $acc1,$SIZE_T*13($sp) + $LD $acc2,$SIZE_T*14($sp) + $LD $acc3,$SIZE_T*15($sp) + + $LD $m0,$SIZE_T*1($np) # n[0..3] + $LD $m1,$SIZE_T*2($np) + $LD $m2,$SIZE_T*3($np) + $LDU $m3,$SIZE_T*4($np) + addic $tp,$sp,$SIZE_T*7 # &t[-1], clear carry bit + li $carry,0 + b .Loop_mul4x_reduction + +.align 5 +.Loop_mul4x_reduction: + $UMULL $t0,$a0,$bi # lo(a[0..3]*b[4]) + addze $carry,$carry # modulo-scheduled + $UMULL $t1,$a1,$bi + addi $cnt,$cnt,$SIZE_T + $UMULL $t2,$a2,$bi + andi. $cnt,$cnt,$SIZE_T*4-1 + $UMULL $t3,$a3,$bi + addc $acc0,$acc0,$t0 + $UMULH $t0,$a0,$bi # hi(a[0..3]*b[4]) + adde $acc1,$acc1,$t1 + $UMULH $t1,$a1,$bi + adde $acc2,$acc2,$t2 + $UMULL $mi,$acc0,$n0 # t[0]*n0 + adde $acc3,$acc3,$t3 + $UMULH $t2,$a2,$bi + addze $acc4,$zero + $UMULH $t3,$a3,$bi + $LDX $bi,$bp,$cnt # next b[i] + addc $acc1,$acc1,$t0 + # (*) mul $t0,$m0,$mi + $STU $mi,$SIZE_T($tp) # put aside t[0]*n0 for tail processing + adde $acc2,$acc2,$t1 + $UMULL $t1,$m1,$mi # lo(n[0..3]*t[0]*n0 + adde $acc3,$acc3,$t2 + $UMULL $t2,$m2,$mi + adde $acc4,$acc4,$t3 # can't overflow + $UMULL $t3,$m3,$mi + # (*) addc $acc0,$acc0,$t0 + addic $acc0,$acc0,-1 # (*), discarded + $UMULH $t0,$m0,$mi # hi(n[0..3]*t[0]*n0 + adde $acc0,$acc1,$t1 + $UMULH $t1,$m1,$mi + adde $acc1,$acc2,$t2 + $UMULH $t2,$m2,$mi + adde $acc2,$acc3,$t3 + $UMULH $t3,$m3,$mi + adde $acc3,$acc4,$carry + addze $carry,$zero + addc $acc0,$acc0,$t0 + adde $acc1,$acc1,$t1 + adde $acc2,$acc2,$t2 + adde $acc3,$acc3,$t3 + #addze $carry,$carry + bne .Loop_mul4x_reduction + + $LD $t0,$SIZE_T*5($tp) # t[4..7] + addze $carry,$carry + $LD $t1,$SIZE_T*6($tp) + $LD $t2,$SIZE_T*7($tp) + $LD $t3,$SIZE_T*8($tp) + $LD $a0,$SIZE_T*1($ap) # a[4..7] + $LD $a1,$SIZE_T*2($ap) + $LD $a2,$SIZE_T*3($ap) + $LDU $a3,$SIZE_T*4($ap) + addc $acc0,$acc0,$t0 + adde $acc1,$acc1,$t1 + adde $acc2,$acc2,$t2 + adde $acc3,$acc3,$t3 + #addze $carry,$carry + + $LD $mi,$SIZE_T*8($sp) # t[0]*n0 + $LD $m0,$SIZE_T*1($np) # n[4..7] + $LD $m1,$SIZE_T*2($np) + $LD $m2,$SIZE_T*3($np) + $LDU $m3,$SIZE_T*4($np) + b .Loop_mul4x_tail + +.align 5 +.Loop_mul4x_tail: + $UMULL $t0,$a0,$bi # lo(a[4..7]*b[4]) + addze $carry,$carry # modulo-scheduled + $UMULL $t1,$a1,$bi + addi $cnt,$cnt,$SIZE_T + $UMULL $t2,$a2,$bi + andi. $cnt,$cnt,$SIZE_T*4-1 + $UMULL $t3,$a3,$bi + addc $acc0,$acc0,$t0 + $UMULH $t0,$a0,$bi # hi(a[4..7]*b[4]) + adde $acc1,$acc1,$t1 + $UMULH $t1,$a1,$bi + adde $acc2,$acc2,$t2 + $UMULH $t2,$a2,$bi + adde $acc3,$acc3,$t3 + $UMULH $t3,$a3,$bi + addze $acc4,$zero + $LDX $bi,$bp,$cnt # next b[i] + addc $acc1,$acc1,$t0 + $UMULL $t0,$m0,$mi # lo(n[4..7]*t[0]*n0) + adde $acc2,$acc2,$t1 + $UMULL $t1,$m1,$mi + adde $acc3,$acc3,$t2 + $UMULL $t2,$m2,$mi + adde $acc4,$acc4,$t3 # can't overflow + $UMULL $t3,$m3,$mi + addc $acc0,$acc0,$t0 + $UMULH $t0,$m0,$mi # hi(n[4..7]*t[0]*n0) + adde $acc1,$acc1,$t1 + $UMULH $t1,$m1,$mi + adde $acc2,$acc2,$t2 + $UMULH $t2,$m2,$mi + adde $acc3,$acc3,$t3 + $UMULH $t3,$m3,$mi + adde $acc4,$acc4,$carry + addi $mi,$sp,$SIZE_T*8 + $LDX $mi,$mi,$cnt # next a[0]*n0 + addze $carry,$zero + $STU $acc0,$SIZE_T($tp) # word of result + addc $acc0,$acc1,$t0 + adde $acc1,$acc2,$t1 + adde $acc2,$acc3,$t2 + adde $acc3,$acc4,$t3 + #addze $carry,$carry + bne .Loop_mul4x_tail + + $LD $t0,$SIZE_T*5($tp) # next t[i] or topmost carry + sub $t1,$np,$num # rewinded np? + addze $carry,$carry + $UCMP $ap_end,$ap # done yet? + beq .Loop_mul4x_break + + $LD $t1,$SIZE_T*6($tp) + $LD $t2,$SIZE_T*7($tp) + $LD $t3,$SIZE_T*8($tp) + $LD $a0,$SIZE_T*1($ap) + $LD $a1,$SIZE_T*2($ap) + $LD $a2,$SIZE_T*3($ap) + $LDU $a3,$SIZE_T*4($ap) + addc $acc0,$acc0,$t0 + adde $acc1,$acc1,$t1 + adde $acc2,$acc2,$t2 + adde $acc3,$acc3,$t3 + #addze $carry,$carry + + $LD $m0,$SIZE_T*1($np) # n[4..7] + $LD $m1,$SIZE_T*2($np) + $LD $m2,$SIZE_T*3($np) + $LDU $m3,$SIZE_T*4($np) + b .Loop_mul4x_tail + +.align 5 +.Loop_mul4x_break: + $POP $t2,$SIZE_T*6($sp) # pull rp and &b[num-4] + $POP $t3,$SIZE_T*7($sp) + addc $a0,$acc0,$t0 # accumulate topmost carry + $LD $acc0,$SIZE_T*12($sp) # t[0..3] + addze $a1,$acc1 + $LD $acc1,$SIZE_T*13($sp) + addze $a2,$acc2 + $LD $acc2,$SIZE_T*14($sp) + addze $a3,$acc3 + $LD $acc3,$SIZE_T*15($sp) + addze $carry,$carry # topmost carry + $ST $a0,$SIZE_T*1($tp) # result + sub $ap,$ap_end,$num # rewind ap + $ST $a1,$SIZE_T*2($tp) + $ST $a2,$SIZE_T*3($tp) + $ST $a3,$SIZE_T*4($tp) + $ST $carry,$SIZE_T*5($tp) # store topmost carry + + $LD $m0,$SIZE_T*1($t1) # n[0..3] + $LD $m1,$SIZE_T*2($t1) + $LD $m2,$SIZE_T*3($t1) + $LD $m3,$SIZE_T*4($t1) + addi $np,$t1,$SIZE_T*4 + $UCMP $bp,$t3 # done yet? + beq .Lmul4x_post + + $LDU $bi,$SIZE_T*4($bp) + $LD $a0,$SIZE_T*1($ap) # a[0..3] + $LD $a1,$SIZE_T*2($ap) + $LD $a2,$SIZE_T*3($ap) + $LDU $a3,$SIZE_T*4($ap) + li $carry,0 + addic $tp,$sp,$SIZE_T*7 # &t[-1], clear carry bit + b .Loop_mul4x_reduction + +.align 5 +.Lmul4x_post: + # Final step. We see if result is larger than modulus, and + # if it is, subtract the modulus. But comparison implies + # subtraction. So we subtract modulus, see if it borrowed, + # and conditionally copy original value. + srwi $cnt,$num,`log($SIZE_T)/log(2)+2` + mr $bp,$t2 # &rp[-1] + subi $cnt,$cnt,1 + mr $ap_end,$t2 # &rp[-1] copy + subfc $t0,$m0,$acc0 + addi $tp,$sp,$SIZE_T*15 + subfe $t1,$m1,$acc1 + + mtctr $cnt +.Lmul4x_sub: + $LD $m0,$SIZE_T*1($np) + $LD $acc0,$SIZE_T*1($tp) + subfe $t2,$m2,$acc2 + $LD $m1,$SIZE_T*2($np) + $LD $acc1,$SIZE_T*2($tp) + subfe $t3,$m3,$acc3 + $LD $m2,$SIZE_T*3($np) + $LD $acc2,$SIZE_T*3($tp) + $LDU $m3,$SIZE_T*4($np) + $LDU $acc3,$SIZE_T*4($tp) + $ST $t0,$SIZE_T*1($bp) + $ST $t1,$SIZE_T*2($bp) + subfe $t0,$m0,$acc0 + $ST $t2,$SIZE_T*3($bp) + $STU $t3,$SIZE_T*4($bp) + subfe $t1,$m1,$acc1 + bdnz .Lmul4x_sub + + $LD $a0,$SIZE_T*1($ap_end) + $ST $t0,$SIZE_T*1($bp) + $LD $t0,$SIZE_T*12($sp) + subfe $t2,$m2,$acc2 + $LD $a1,$SIZE_T*2($ap_end) + $ST $t1,$SIZE_T*2($bp) + $LD $t1,$SIZE_T*13($sp) + subfe $t3,$m3,$acc3 + subfe $carry,$zero,$carry # did it borrow? + addi $tp,$sp,$SIZE_T*12 + $LD $a2,$SIZE_T*3($ap_end) + $ST $t2,$SIZE_T*3($bp) + $LD $t2,$SIZE_T*14($sp) + $LD $a3,$SIZE_T*4($ap_end) + $ST $t3,$SIZE_T*4($bp) + $LD $t3,$SIZE_T*15($sp) + + mtctr $cnt +.Lmul4x_cond_copy: + and $t0,$t0,$carry + andc $a0,$a0,$carry + $ST $zero,$SIZE_T*0($tp) # wipe stack clean + and $t1,$t1,$carry + andc $a1,$a1,$carry + $ST $zero,$SIZE_T*1($tp) + and $t2,$t2,$carry + andc $a2,$a2,$carry + $ST $zero,$SIZE_T*2($tp) + and $t3,$t3,$carry + andc $a3,$a3,$carry + $ST $zero,$SIZE_T*3($tp) + or $acc0,$t0,$a0 + $LD $a0,$SIZE_T*5($ap_end) + $LD $t0,$SIZE_T*4($tp) + or $acc1,$t1,$a1 + $LD $a1,$SIZE_T*6($ap_end) + $LD $t1,$SIZE_T*5($tp) + or $acc2,$t2,$a2 + $LD $a2,$SIZE_T*7($ap_end) + $LD $t2,$SIZE_T*6($tp) + or $acc3,$t3,$a3 + $LD $a3,$SIZE_T*8($ap_end) + $LD $t3,$SIZE_T*7($tp) + addi $tp,$tp,$SIZE_T*4 + $ST $acc0,$SIZE_T*1($ap_end) + $ST $acc1,$SIZE_T*2($ap_end) + $ST $acc2,$SIZE_T*3($ap_end) + $STU $acc3,$SIZE_T*4($ap_end) + bdnz .Lmul4x_cond_copy + + $POP $bp,0($sp) # pull saved sp + and $t0,$t0,$carry + andc $a0,$a0,$carry + $ST $zero,$SIZE_T*0($tp) + and $t1,$t1,$carry + andc $a1,$a1,$carry + $ST $zero,$SIZE_T*1($tp) + and $t2,$t2,$carry + andc $a2,$a2,$carry + $ST $zero,$SIZE_T*2($tp) + and $t3,$t3,$carry + andc $a3,$a3,$carry + $ST $zero,$SIZE_T*3($tp) + or $acc0,$t0,$a0 + or $acc1,$t1,$a1 + $ST $zero,$SIZE_T*4($tp) + or $acc2,$t2,$a2 + or $acc3,$t3,$a3 + $ST $acc0,$SIZE_T*1($ap_end) + $ST $acc1,$SIZE_T*2($ap_end) + $ST $acc2,$SIZE_T*3($ap_end) + $ST $acc3,$SIZE_T*4($ap_end) + + b .Lmul4x_done + +.align 4 +.Lmul4x4_post_condition: + $POP $ap,$SIZE_T*6($sp) # pull &rp[-1] + $POP $bp,0($sp) # pull saved sp + addze $carry,$carry # modulo-scheduled + # $acc0-3,$carry hold result, $m0-3 hold modulus + subfc $a0,$m0,$acc0 + subfe $a1,$m1,$acc1 + subfe $a2,$m2,$acc2 + subfe $a3,$m3,$acc3 + subfe $carry,$zero,$carry # did it borrow? + + and $m0,$m0,$carry + and $m1,$m1,$carry + addc $a0,$a0,$m0 + and $m2,$m2,$carry + adde $a1,$a1,$m1 + and $m3,$m3,$carry + adde $a2,$a2,$m2 + adde $a3,$a3,$m3 + + $ST $a0,$SIZE_T*1($ap) # write result + $ST $a1,$SIZE_T*2($ap) + $ST $a2,$SIZE_T*3($ap) + $ST $a3,$SIZE_T*4($ap) + +.Lmul4x_done: + $ST $zero,$SIZE_T*8($sp) # wipe stack clean + $ST $zero,$SIZE_T*9($sp) + $ST $zero,$SIZE_T*10($sp) + $ST $zero,$SIZE_T*11($sp) + li r3,1 # signal "done" + $POP r14,-$SIZE_T*18($bp) + $POP r15,-$SIZE_T*17($bp) + $POP r16,-$SIZE_T*16($bp) + $POP r17,-$SIZE_T*15($bp) + $POP r18,-$SIZE_T*14($bp) + $POP r19,-$SIZE_T*13($bp) + $POP r20,-$SIZE_T*12($bp) + $POP r21,-$SIZE_T*11($bp) + $POP r22,-$SIZE_T*10($bp) + $POP r23,-$SIZE_T*9($bp) + $POP r24,-$SIZE_T*8($bp) + $POP r25,-$SIZE_T*7($bp) + $POP r26,-$SIZE_T*6($bp) + $POP r27,-$SIZE_T*5($bp) + $POP r28,-$SIZE_T*4($bp) + $POP r29,-$SIZE_T*3($bp) + $POP r30,-$SIZE_T*2($bp) + $POP r31,-$SIZE_T*1($bp) + mr $sp,$bp + blr + .long 0 + .byte 0,12,4,0x20,0x80,18,6,0 + .long 0 +.size .bn_mul4x_mont_int,.-.bn_mul4x_mont_int +___ +} + +if (1) { +######################################################################## +# Following is PPC adaptation of sqrx8x_mont from x86_64-mont5 module. + +my ($a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7)=map("r$_",(9..12,14..17)); +my ($t0,$t1,$t2,$t3)=map("r$_",(18..21)); +my ($acc0,$acc1,$acc2,$acc3,$acc4,$acc5,$acc6,$acc7)=map("r$_",(22..29)); +my ($cnt,$carry,$zero)=("r30","r31","r0"); +my ($tp,$ap_end,$na0)=($bp,$np,$carry); + +# sp----------->+-------------------------------+ +# | saved sp | +# +-------------------------------+ +# . . +# +12*size_t +-------------------------------+ +# | size_t tmp[2*num] | +# . . +# . . +# . . +# +-------------------------------+ +# . . +# -18*size_t +-------------------------------+ +# | 18 saved gpr, r14-r31 | +# . . +# . . +# +-------------------------------+ +$code.=<<___; +.align 5 +__bn_sqr8x_mont: +.Lsqr8x_do: + mr $a0,$sp + slwi $a1,$num,`log($SIZE_T)/log(2)+1` + li $a2,-32*$SIZE_T + sub $a1,$a2,$a1 + slwi $num,$num,`log($SIZE_T)/log(2)` + $STUX $sp,$sp,$a1 # alloca + + $PUSH r14,-$SIZE_T*18($a0) + $PUSH r15,-$SIZE_T*17($a0) + $PUSH r16,-$SIZE_T*16($a0) + $PUSH r17,-$SIZE_T*15($a0) + $PUSH r18,-$SIZE_T*14($a0) + $PUSH r19,-$SIZE_T*13($a0) + $PUSH r20,-$SIZE_T*12($a0) + $PUSH r21,-$SIZE_T*11($a0) + $PUSH r22,-$SIZE_T*10($a0) + $PUSH r23,-$SIZE_T*9($a0) + $PUSH r24,-$SIZE_T*8($a0) + $PUSH r25,-$SIZE_T*7($a0) + $PUSH r26,-$SIZE_T*6($a0) + $PUSH r27,-$SIZE_T*5($a0) + $PUSH r28,-$SIZE_T*4($a0) + $PUSH r29,-$SIZE_T*3($a0) + $PUSH r30,-$SIZE_T*2($a0) + $PUSH r31,-$SIZE_T*1($a0) + + subi $ap,$ap,$SIZE_T # bias by -1 + subi $t0,$np,$SIZE_T # bias by -1 + subi $rp,$rp,$SIZE_T # bias by -1 + $LD $n0,0($n0) # *n0 + li $zero,0 + + add $ap_end,$ap,$num + $LD $a0,$SIZE_T*1($ap) + #li $acc0,0 + $LD $a1,$SIZE_T*2($ap) + li $acc1,0 + $LD $a2,$SIZE_T*3($ap) + li $acc2,0 + $LD $a3,$SIZE_T*4($ap) + li $acc3,0 + $LD $a4,$SIZE_T*5($ap) + li $acc4,0 + $LD $a5,$SIZE_T*6($ap) + li $acc5,0 + $LD $a6,$SIZE_T*7($ap) + li $acc6,0 + $LDU $a7,$SIZE_T*8($ap) + li $acc7,0 + + addi $tp,$sp,$SIZE_T*11 # &tp[-1] + subic. $cnt,$num,$SIZE_T*8 + b .Lsqr8x_zero_start + +.align 5 +.Lsqr8x_zero: + subic. $cnt,$cnt,$SIZE_T*8 + $ST $zero,$SIZE_T*1($tp) + $ST $zero,$SIZE_T*2($tp) + $ST $zero,$SIZE_T*3($tp) + $ST $zero,$SIZE_T*4($tp) + $ST $zero,$SIZE_T*5($tp) + $ST $zero,$SIZE_T*6($tp) + $ST $zero,$SIZE_T*7($tp) + $ST $zero,$SIZE_T*8($tp) +.Lsqr8x_zero_start: + $ST $zero,$SIZE_T*9($tp) + $ST $zero,$SIZE_T*10($tp) + $ST $zero,$SIZE_T*11($tp) + $ST $zero,$SIZE_T*12($tp) + $ST $zero,$SIZE_T*13($tp) + $ST $zero,$SIZE_T*14($tp) + $ST $zero,$SIZE_T*15($tp) + $STU $zero,$SIZE_T*16($tp) + bne .Lsqr8x_zero + + $PUSH $rp,$SIZE_T*6($sp) # offload &rp[-1] + $PUSH $t0,$SIZE_T*7($sp) # offload &np[-1] + $PUSH $n0,$SIZE_T*8($sp) # offload n0 + $PUSH $tp,$SIZE_T*9($sp) # &tp[2*num-1] + $PUSH $zero,$SIZE_T*10($sp) # initial top-most carry + addi $tp,$sp,$SIZE_T*11 # &tp[-1] + + # Multiply everything but a[i]*a[i] +.align 5 +.Lsqr8x_outer_loop: + # a[1]a[0] (i) + # a[2]a[0] + # a[3]a[0] + # a[4]a[0] + # a[5]a[0] + # a[6]a[0] + # a[7]a[0] + # a[2]a[1] (ii) + # a[3]a[1] + # a[4]a[1] + # a[5]a[1] + # a[6]a[1] + # a[7]a[1] + # a[3]a[2] (iii) + # a[4]a[2] + # a[5]a[2] + # a[6]a[2] + # a[7]a[2] + # a[4]a[3] (iv) + # a[5]a[3] + # a[6]a[3] + # a[7]a[3] + # a[5]a[4] (v) + # a[6]a[4] + # a[7]a[4] + # a[6]a[5] (vi) + # a[7]a[5] + # a[7]a[6] (vii) + + $UMULL $t0,$a1,$a0 # lo(a[1..7]*a[0]) (i) + $UMULL $t1,$a2,$a0 + $UMULL $t2,$a3,$a0 + $UMULL $t3,$a4,$a0 + addc $acc1,$acc1,$t0 # t[1]+lo(a[1]*a[0]) + $UMULL $t0,$a5,$a0 + adde $acc2,$acc2,$t1 + $UMULL $t1,$a6,$a0 + adde $acc3,$acc3,$t2 + $UMULL $t2,$a7,$a0 + adde $acc4,$acc4,$t3 + $UMULH $t3,$a1,$a0 # hi(a[1..7]*a[0]) + adde $acc5,$acc5,$t0 + $UMULH $t0,$a2,$a0 + adde $acc6,$acc6,$t1 + $UMULH $t1,$a3,$a0 + adde $acc7,$acc7,$t2 + $UMULH $t2,$a4,$a0 + $ST $acc0,$SIZE_T*1($tp) # t[0] + addze $acc0,$zero # t[8] + $ST $acc1,$SIZE_T*2($tp) # t[1] + addc $acc2,$acc2,$t3 # t[2]+lo(a[1]*a[0]) + $UMULH $t3,$a5,$a0 + adde $acc3,$acc3,$t0 + $UMULH $t0,$a6,$a0 + adde $acc4,$acc4,$t1 + $UMULH $t1,$a7,$a0 + adde $acc5,$acc5,$t2 + $UMULL $t2,$a2,$a1 # lo(a[2..7]*a[1]) (ii) + adde $acc6,$acc6,$t3 + $UMULL $t3,$a3,$a1 + adde $acc7,$acc7,$t0 + $UMULL $t0,$a4,$a1 + adde $acc0,$acc0,$t1 + + $UMULL $t1,$a5,$a1 + addc $acc3,$acc3,$t2 + $UMULL $t2,$a6,$a1 + adde $acc4,$acc4,$t3 + $UMULL $t3,$a7,$a1 + adde $acc5,$acc5,$t0 + $UMULH $t0,$a2,$a1 # hi(a[2..7]*a[1]) + adde $acc6,$acc6,$t1 + $UMULH $t1,$a3,$a1 + adde $acc7,$acc7,$t2 + $UMULH $t2,$a4,$a1 + adde $acc0,$acc0,$t3 + $UMULH $t3,$a5,$a1 + $ST $acc2,$SIZE_T*3($tp) # t[2] + addze $acc1,$zero # t[9] + $ST $acc3,$SIZE_T*4($tp) # t[3] + addc $acc4,$acc4,$t0 + $UMULH $t0,$a6,$a1 + adde $acc5,$acc5,$t1 + $UMULH $t1,$a7,$a1 + adde $acc6,$acc6,$t2 + $UMULL $t2,$a3,$a2 # lo(a[3..7]*a[2]) (iii) + adde $acc7,$acc7,$t3 + $UMULL $t3,$a4,$a2 + adde $acc0,$acc0,$t0 + $UMULL $t0,$a5,$a2 + adde $acc1,$acc1,$t1 + + $UMULL $t1,$a6,$a2 + addc $acc5,$acc5,$t2 + $UMULL $t2,$a7,$a2 + adde $acc6,$acc6,$t3 + $UMULH $t3,$a3,$a2 # hi(a[3..7]*a[2]) + adde $acc7,$acc7,$t0 + $UMULH $t0,$a4,$a2 + adde $acc0,$acc0,$t1 + $UMULH $t1,$a5,$a2 + adde $acc1,$acc1,$t2 + $UMULH $t2,$a6,$a2 + $ST $acc4,$SIZE_T*5($tp) # t[4] + addze $acc2,$zero # t[10] + $ST $acc5,$SIZE_T*6($tp) # t[5] + addc $acc6,$acc6,$t3 + $UMULH $t3,$a7,$a2 + adde $acc7,$acc7,$t0 + $UMULL $t0,$a4,$a3 # lo(a[4..7]*a[3]) (iv) + adde $acc0,$acc0,$t1 + $UMULL $t1,$a5,$a3 + adde $acc1,$acc1,$t2 + $UMULL $t2,$a6,$a3 + adde $acc2,$acc2,$t3 + + $UMULL $t3,$a7,$a3 + addc $acc7,$acc7,$t0 + $UMULH $t0,$a4,$a3 # hi(a[4..7]*a[3]) + adde $acc0,$acc0,$t1 + $UMULH $t1,$a5,$a3 + adde $acc1,$acc1,$t2 + $UMULH $t2,$a6,$a3 + adde $acc2,$acc2,$t3 + $UMULH $t3,$a7,$a3 + $ST $acc6,$SIZE_T*7($tp) # t[6] + addze $acc3,$zero # t[11] + $STU $acc7,$SIZE_T*8($tp) # t[7] + addc $acc0,$acc0,$t0 + $UMULL $t0,$a5,$a4 # lo(a[5..7]*a[4]) (v) + adde $acc1,$acc1,$t1 + $UMULL $t1,$a6,$a4 + adde $acc2,$acc2,$t2 + $UMULL $t2,$a7,$a4 + adde $acc3,$acc3,$t3 + + $UMULH $t3,$a5,$a4 # hi(a[5..7]*a[4]) + addc $acc1,$acc1,$t0 + $UMULH $t0,$a6,$a4 + adde $acc2,$acc2,$t1 + $UMULH $t1,$a7,$a4 + adde $acc3,$acc3,$t2 + $UMULL $t2,$a6,$a5 # lo(a[6..7]*a[5]) (vi) + addze $acc4,$zero # t[12] + addc $acc2,$acc2,$t3 + $UMULL $t3,$a7,$a5 + adde $acc3,$acc3,$t0 + $UMULH $t0,$a6,$a5 # hi(a[6..7]*a[5]) + adde $acc4,$acc4,$t1 + + $UMULH $t1,$a7,$a5 + addc $acc3,$acc3,$t2 + $UMULL $t2,$a7,$a6 # lo(a[7]*a[6]) (vii) + adde $acc4,$acc4,$t3 + $UMULH $t3,$a7,$a6 # hi(a[7]*a[6]) + addze $acc5,$zero # t[13] + addc $acc4,$acc4,$t0 + $UCMP $ap_end,$ap # done yet? + adde $acc5,$acc5,$t1 + + addc $acc5,$acc5,$t2 + sub $t0,$ap_end,$num # rewinded ap + addze $acc6,$zero # t[14] + add $acc6,$acc6,$t3 + + beq .Lsqr8x_outer_break + + mr $n0,$a0 + $LD $a0,$SIZE_T*1($tp) + $LD $a1,$SIZE_T*2($tp) + $LD $a2,$SIZE_T*3($tp) + $LD $a3,$SIZE_T*4($tp) + $LD $a4,$SIZE_T*5($tp) + $LD $a5,$SIZE_T*6($tp) + $LD $a6,$SIZE_T*7($tp) + $LD $a7,$SIZE_T*8($tp) + addc $acc0,$acc0,$a0 + $LD $a0,$SIZE_T*1($ap) + adde $acc1,$acc1,$a1 + $LD $a1,$SIZE_T*2($ap) + adde $acc2,$acc2,$a2 + $LD $a2,$SIZE_T*3($ap) + adde $acc3,$acc3,$a3 + $LD $a3,$SIZE_T*4($ap) + adde $acc4,$acc4,$a4 + $LD $a4,$SIZE_T*5($ap) + adde $acc5,$acc5,$a5 + $LD $a5,$SIZE_T*6($ap) + adde $acc6,$acc6,$a6 + $LD $a6,$SIZE_T*7($ap) + subi $rp,$ap,$SIZE_T*7 + addze $acc7,$a7 + $LDU $a7,$SIZE_T*8($ap) + #addze $carry,$zero # moved below + li $cnt,0 + b .Lsqr8x_mul + + # a[8]a[0] + # a[9]a[0] + # a[a]a[0] + # a[b]a[0] + # a[c]a[0] + # a[d]a[0] + # a[e]a[0] + # a[f]a[0] + # a[8]a[1] + # a[f]a[1]........................ + # a[8]a[2] + # a[f]a[2]........................ + # a[8]a[3] + # a[f]a[3]........................ + # a[8]a[4] + # a[f]a[4]........................ + # a[8]a[5] + # a[f]a[5]........................ + # a[8]a[6] + # a[f]a[6]........................ + # a[8]a[7] + # a[f]a[7]........................ +.align 5 +.Lsqr8x_mul: + $UMULL $t0,$a0,$n0 + addze $carry,$zero # carry bit, modulo-scheduled + $UMULL $t1,$a1,$n0 + addi $cnt,$cnt,$SIZE_T + $UMULL $t2,$a2,$n0 + andi. $cnt,$cnt,$SIZE_T*8-1 + $UMULL $t3,$a3,$n0 + addc $acc0,$acc0,$t0 + $UMULL $t0,$a4,$n0 + adde $acc1,$acc1,$t1 + $UMULL $t1,$a5,$n0 + adde $acc2,$acc2,$t2 + $UMULL $t2,$a6,$n0 + adde $acc3,$acc3,$t3 + $UMULL $t3,$a7,$n0 + adde $acc4,$acc4,$t0 + $UMULH $t0,$a0,$n0 + adde $acc5,$acc5,$t1 + $UMULH $t1,$a1,$n0 + adde $acc6,$acc6,$t2 + $UMULH $t2,$a2,$n0 + adde $acc7,$acc7,$t3 + $UMULH $t3,$a3,$n0 + addze $carry,$carry + $STU $acc0,$SIZE_T($tp) + addc $acc0,$acc1,$t0 + $UMULH $t0,$a4,$n0 + adde $acc1,$acc2,$t1 + $UMULH $t1,$a5,$n0 + adde $acc2,$acc3,$t2 + $UMULH $t2,$a6,$n0 + adde $acc3,$acc4,$t3 + $UMULH $t3,$a7,$n0 + $LDX $n0,$rp,$cnt + adde $acc4,$acc5,$t0 + adde $acc5,$acc6,$t1 + adde $acc6,$acc7,$t2 + adde $acc7,$carry,$t3 + #addze $carry,$zero # moved above + bne .Lsqr8x_mul + # note that carry flag is guaranteed + # to be zero at this point + $UCMP $ap,$ap_end # done yet? + beq .Lsqr8x_break + + $LD $a0,$SIZE_T*1($tp) + $LD $a1,$SIZE_T*2($tp) + $LD $a2,$SIZE_T*3($tp) + $LD $a3,$SIZE_T*4($tp) + $LD $a4,$SIZE_T*5($tp) + $LD $a5,$SIZE_T*6($tp) + $LD $a6,$SIZE_T*7($tp) + $LD $a7,$SIZE_T*8($tp) + addc $acc0,$acc0,$a0 + $LD $a0,$SIZE_T*1($ap) + adde $acc1,$acc1,$a1 + $LD $a1,$SIZE_T*2($ap) + adde $acc2,$acc2,$a2 + $LD $a2,$SIZE_T*3($ap) + adde $acc3,$acc3,$a3 + $LD $a3,$SIZE_T*4($ap) + adde $acc4,$acc4,$a4 + $LD $a4,$SIZE_T*5($ap) + adde $acc5,$acc5,$a5 + $LD $a5,$SIZE_T*6($ap) + adde $acc6,$acc6,$a6 + $LD $a6,$SIZE_T*7($ap) + adde $acc7,$acc7,$a7 + $LDU $a7,$SIZE_T*8($ap) + #addze $carry,$zero # moved above + b .Lsqr8x_mul + +.align 5 +.Lsqr8x_break: + $LD $a0,$SIZE_T*8($rp) + addi $ap,$rp,$SIZE_T*15 + $LD $a1,$SIZE_T*9($rp) + sub. $t0,$ap_end,$ap # is it last iteration? + $LD $a2,$SIZE_T*10($rp) + sub $t1,$tp,$t0 + $LD $a3,$SIZE_T*11($rp) + $LD $a4,$SIZE_T*12($rp) + $LD $a5,$SIZE_T*13($rp) + $LD $a6,$SIZE_T*14($rp) + $LD $a7,$SIZE_T*15($rp) + beq .Lsqr8x_outer_loop + + $ST $acc0,$SIZE_T*1($tp) + $LD $acc0,$SIZE_T*1($t1) + $ST $acc1,$SIZE_T*2($tp) + $LD $acc1,$SIZE_T*2($t1) + $ST $acc2,$SIZE_T*3($tp) + $LD $acc2,$SIZE_T*3($t1) + $ST $acc3,$SIZE_T*4($tp) + $LD $acc3,$SIZE_T*4($t1) + $ST $acc4,$SIZE_T*5($tp) + $LD $acc4,$SIZE_T*5($t1) + $ST $acc5,$SIZE_T*6($tp) + $LD $acc5,$SIZE_T*6($t1) + $ST $acc6,$SIZE_T*7($tp) + $LD $acc6,$SIZE_T*7($t1) + $ST $acc7,$SIZE_T*8($tp) + $LD $acc7,$SIZE_T*8($t1) + mr $tp,$t1 + b .Lsqr8x_outer_loop + +.align 5 +.Lsqr8x_outer_break: + #################################################################### + # Now multiply above result by 2 and add a[n-1]*a[n-1]|...|a[0]*a[0] + $LD $a1,$SIZE_T*1($t0) # recall that $t0 is &a[-1] + $LD $a3,$SIZE_T*2($t0) + $LD $a5,$SIZE_T*3($t0) + $LD $a7,$SIZE_T*4($t0) + addi $ap,$t0,$SIZE_T*4 + # "tp[x]" comments are for num==8 case + $LD $t1,$SIZE_T*13($sp) # =tp[1], t[0] is not interesting + $LD $t2,$SIZE_T*14($sp) + $LD $t3,$SIZE_T*15($sp) + $LD $t0,$SIZE_T*16($sp) + + $ST $acc0,$SIZE_T*1($tp) # tp[8]= + srwi $cnt,$num,`log($SIZE_T)/log(2)+2` + $ST $acc1,$SIZE_T*2($tp) + subi $cnt,$cnt,1 + $ST $acc2,$SIZE_T*3($tp) + $ST $acc3,$SIZE_T*4($tp) + $ST $acc4,$SIZE_T*5($tp) + $ST $acc5,$SIZE_T*6($tp) + $ST $acc6,$SIZE_T*7($tp) + #$ST $acc7,$SIZE_T*8($tp) # tp[15] is not interesting + addi $tp,$sp,$SIZE_T*11 # &tp[-1] + $UMULL $acc0,$a1,$a1 + $UMULH $a1,$a1,$a1 + add $acc1,$t1,$t1 # <<1 + $SHRI $t1,$t1,$BITS-1 + $UMULL $a2,$a3,$a3 + $UMULH $a3,$a3,$a3 + addc $acc1,$acc1,$a1 + add $acc2,$t2,$t2 + $SHRI $t2,$t2,$BITS-1 + add $acc3,$t3,$t3 + $SHRI $t3,$t3,$BITS-1 + or $acc2,$acc2,$t1 + + mtctr $cnt +.Lsqr4x_shift_n_add: + $UMULL $a4,$a5,$a5 + $UMULH $a5,$a5,$a5 + $LD $t1,$SIZE_T*6($tp) # =tp[5] + $LD $a1,$SIZE_T*1($ap) + adde $acc2,$acc2,$a2 + add $acc4,$t0,$t0 + $SHRI $t0,$t0,$BITS-1 + or $acc3,$acc3,$t2 + $LD $t2,$SIZE_T*7($tp) # =tp[6] + adde $acc3,$acc3,$a3 + $LD $a3,$SIZE_T*2($ap) + add $acc5,$t1,$t1 + $SHRI $t1,$t1,$BITS-1 + or $acc4,$acc4,$t3 + $LD $t3,$SIZE_T*8($tp) # =tp[7] + $UMULL $a6,$a7,$a7 + $UMULH $a7,$a7,$a7 + adde $acc4,$acc4,$a4 + add $acc6,$t2,$t2 + $SHRI $t2,$t2,$BITS-1 + or $acc5,$acc5,$t0 + $LD $t0,$SIZE_T*9($tp) # =tp[8] + adde $acc5,$acc5,$a5 + $LD $a5,$SIZE_T*3($ap) + add $acc7,$t3,$t3 + $SHRI $t3,$t3,$BITS-1 + or $acc6,$acc6,$t1 + $LD $t1,$SIZE_T*10($tp) # =tp[9] + $UMULL $a0,$a1,$a1 + $UMULH $a1,$a1,$a1 + adde $acc6,$acc6,$a6 + $ST $acc0,$SIZE_T*1($tp) # tp[0]= + add $acc0,$t0,$t0 + $SHRI $t0,$t0,$BITS-1 + or $acc7,$acc7,$t2 + $LD $t2,$SIZE_T*11($tp) # =tp[10] + adde $acc7,$acc7,$a7 + $LDU $a7,$SIZE_T*4($ap) + $ST $acc1,$SIZE_T*2($tp) # tp[1]= + add $acc1,$t1,$t1 + $SHRI $t1,$t1,$BITS-1 + or $acc0,$acc0,$t3 + $LD $t3,$SIZE_T*12($tp) # =tp[11] + $UMULL $a2,$a3,$a3 + $UMULH $a3,$a3,$a3 + adde $acc0,$acc0,$a0 + $ST $acc2,$SIZE_T*3($tp) # tp[2]= + add $acc2,$t2,$t2 + $SHRI $t2,$t2,$BITS-1 + or $acc1,$acc1,$t0 + $LD $t0,$SIZE_T*13($tp) # =tp[12] + adde $acc1,$acc1,$a1 + $ST $acc3,$SIZE_T*4($tp) # tp[3]= + $ST $acc4,$SIZE_T*5($tp) # tp[4]= + $ST $acc5,$SIZE_T*6($tp) # tp[5]= + $ST $acc6,$SIZE_T*7($tp) # tp[6]= + $STU $acc7,$SIZE_T*8($tp) # tp[7]= + add $acc3,$t3,$t3 + $SHRI $t3,$t3,$BITS-1 + or $acc2,$acc2,$t1 + bdnz .Lsqr4x_shift_n_add +___ +my ($np,$np_end)=($ap,$ap_end); +$code.=<<___; + $POP $np,$SIZE_T*7($sp) # pull &np[-1] and n0 + $POP $n0,$SIZE_T*8($sp) + + $UMULL $a4,$a5,$a5 + $UMULH $a5,$a5,$a5 + $ST $acc0,$SIZE_T*1($tp) # tp[8]= + $LD $acc0,$SIZE_T*12($sp) # =tp[0] + $LD $t1,$SIZE_T*6($tp) # =tp[13] + adde $acc2,$acc2,$a2 + add $acc4,$t0,$t0 + $SHRI $t0,$t0,$BITS-1 + or $acc3,$acc3,$t2 + $LD $t2,$SIZE_T*7($tp) # =tp[14] + adde $acc3,$acc3,$a3 + add $acc5,$t1,$t1 + $SHRI $t1,$t1,$BITS-1 + or $acc4,$acc4,$t3 + $UMULL $a6,$a7,$a7 + $UMULH $a7,$a7,$a7 + adde $acc4,$acc4,$a4 + add $acc6,$t2,$t2 + $SHRI $t2,$t2,$BITS-1 + or $acc5,$acc5,$t0 + $ST $acc1,$SIZE_T*2($tp) # tp[9]= + $LD $acc1,$SIZE_T*13($sp) # =tp[1] + adde $acc5,$acc5,$a5 + or $acc6,$acc6,$t1 + $LD $a0,$SIZE_T*1($np) + $LD $a1,$SIZE_T*2($np) + adde $acc6,$acc6,$a6 + $LD $a2,$SIZE_T*3($np) + $LD $a3,$SIZE_T*4($np) + adde $acc7,$a7,$t2 + $LD $a4,$SIZE_T*5($np) + $LD $a5,$SIZE_T*6($np) + + ################################################################ + # Reduce by 8 limbs per iteration + $UMULL $na0,$n0,$acc0 # t[0]*n0 + li $cnt,8 + $LD $a6,$SIZE_T*7($np) + add $np_end,$np,$num + $LDU $a7,$SIZE_T*8($np) + $ST $acc2,$SIZE_T*3($tp) # tp[10]= + $LD $acc2,$SIZE_T*14($sp) + $ST $acc3,$SIZE_T*4($tp) # tp[11]= + $LD $acc3,$SIZE_T*15($sp) + $ST $acc4,$SIZE_T*5($tp) # tp[12]= + $LD $acc4,$SIZE_T*16($sp) + $ST $acc5,$SIZE_T*6($tp) # tp[13]= + $LD $acc5,$SIZE_T*17($sp) + $ST $acc6,$SIZE_T*7($tp) # tp[14]= + $LD $acc6,$SIZE_T*18($sp) + $ST $acc7,$SIZE_T*8($tp) # tp[15]= + $LD $acc7,$SIZE_T*19($sp) + addi $tp,$sp,$SIZE_T*11 # &tp[-1] + mtctr $cnt + b .Lsqr8x_reduction + +.align 5 +.Lsqr8x_reduction: + # (*) $UMULL $t0,$a0,$na0 # lo(n[0-7])*lo(t[0]*n0) + $UMULL $t1,$a1,$na0 + $UMULL $t2,$a2,$na0 + $STU $na0,$SIZE_T($tp) # put aside t[0]*n0 for tail processing + $UMULL $t3,$a3,$na0 + # (*) addc $acc0,$acc0,$t0 + addic $acc0,$acc0,-1 # (*) + $UMULL $t0,$a4,$na0 + adde $acc0,$acc1,$t1 + $UMULL $t1,$a5,$na0 + adde $acc1,$acc2,$t2 + $UMULL $t2,$a6,$na0 + adde $acc2,$acc3,$t3 + $UMULL $t3,$a7,$na0 + adde $acc3,$acc4,$t0 + $UMULH $t0,$a0,$na0 # hi(n[0-7])*lo(t[0]*n0) + adde $acc4,$acc5,$t1 + $UMULH $t1,$a1,$na0 + adde $acc5,$acc6,$t2 + $UMULH $t2,$a2,$na0 + adde $acc6,$acc7,$t3 + $UMULH $t3,$a3,$na0 + addze $acc7,$zero + addc $acc0,$acc0,$t0 + $UMULH $t0,$a4,$na0 + adde $acc1,$acc1,$t1 + $UMULH $t1,$a5,$na0 + adde $acc2,$acc2,$t2 + $UMULH $t2,$a6,$na0 + adde $acc3,$acc3,$t3 + $UMULH $t3,$a7,$na0 + $UMULL $na0,$n0,$acc0 # next t[0]*n0 + adde $acc4,$acc4,$t0 + adde $acc5,$acc5,$t1 + adde $acc6,$acc6,$t2 + adde $acc7,$acc7,$t3 + bdnz .Lsqr8x_reduction + + $LD $t0,$SIZE_T*1($tp) + $LD $t1,$SIZE_T*2($tp) + $LD $t2,$SIZE_T*3($tp) + $LD $t3,$SIZE_T*4($tp) + subi $rp,$tp,$SIZE_T*7 + $UCMP $np_end,$np # done yet? + addc $acc0,$acc0,$t0 + $LD $t0,$SIZE_T*5($tp) + adde $acc1,$acc1,$t1 + $LD $t1,$SIZE_T*6($tp) + adde $acc2,$acc2,$t2 + $LD $t2,$SIZE_T*7($tp) + adde $acc3,$acc3,$t3 + $LD $t3,$SIZE_T*8($tp) + adde $acc4,$acc4,$t0 + adde $acc5,$acc5,$t1 + adde $acc6,$acc6,$t2 + adde $acc7,$acc7,$t3 + #addze $carry,$zero # moved below + beq .Lsqr8x8_post_condition + + $LD $n0,$SIZE_T*0($rp) + $LD $a0,$SIZE_T*1($np) + $LD $a1,$SIZE_T*2($np) + $LD $a2,$SIZE_T*3($np) + $LD $a3,$SIZE_T*4($np) + $LD $a4,$SIZE_T*5($np) + $LD $a5,$SIZE_T*6($np) + $LD $a6,$SIZE_T*7($np) + $LDU $a7,$SIZE_T*8($np) + li $cnt,0 + +.align 5 +.Lsqr8x_tail: + $UMULL $t0,$a0,$n0 + addze $carry,$zero # carry bit, modulo-scheduled + $UMULL $t1,$a1,$n0 + addi $cnt,$cnt,$SIZE_T + $UMULL $t2,$a2,$n0 + andi. $cnt,$cnt,$SIZE_T*8-1 + $UMULL $t3,$a3,$n0 + addc $acc0,$acc0,$t0 + $UMULL $t0,$a4,$n0 + adde $acc1,$acc1,$t1 + $UMULL $t1,$a5,$n0 + adde $acc2,$acc2,$t2 + $UMULL $t2,$a6,$n0 + adde $acc3,$acc3,$t3 + $UMULL $t3,$a7,$n0 + adde $acc4,$acc4,$t0 + $UMULH $t0,$a0,$n0 + adde $acc5,$acc5,$t1 + $UMULH $t1,$a1,$n0 + adde $acc6,$acc6,$t2 + $UMULH $t2,$a2,$n0 + adde $acc7,$acc7,$t3 + $UMULH $t3,$a3,$n0 + addze $carry,$carry + $STU $acc0,$SIZE_T($tp) + addc $acc0,$acc1,$t0 + $UMULH $t0,$a4,$n0 + adde $acc1,$acc2,$t1 + $UMULH $t1,$a5,$n0 + adde $acc2,$acc3,$t2 + $UMULH $t2,$a6,$n0 + adde $acc3,$acc4,$t3 + $UMULH $t3,$a7,$n0 + $LDX $n0,$rp,$cnt + adde $acc4,$acc5,$t0 + adde $acc5,$acc6,$t1 + adde $acc6,$acc7,$t2 + adde $acc7,$carry,$t3 + #addze $carry,$zero # moved above + bne .Lsqr8x_tail + # note that carry flag is guaranteed + # to be zero at this point + $LD $a0,$SIZE_T*1($tp) + $POP $carry,$SIZE_T*10($sp) # pull top-most carry in case we break + $UCMP $np_end,$np # done yet? + $LD $a1,$SIZE_T*2($tp) + sub $t2,$np_end,$num # rewinded np + $LD $a2,$SIZE_T*3($tp) + $LD $a3,$SIZE_T*4($tp) + $LD $a4,$SIZE_T*5($tp) + $LD $a5,$SIZE_T*6($tp) + $LD $a6,$SIZE_T*7($tp) + $LD $a7,$SIZE_T*8($tp) + beq .Lsqr8x_tail_break + + addc $acc0,$acc0,$a0 + $LD $a0,$SIZE_T*1($np) + adde $acc1,$acc1,$a1 + $LD $a1,$SIZE_T*2($np) + adde $acc2,$acc2,$a2 + $LD $a2,$SIZE_T*3($np) + adde $acc3,$acc3,$a3 + $LD $a3,$SIZE_T*4($np) + adde $acc4,$acc4,$a4 + $LD $a4,$SIZE_T*5($np) + adde $acc5,$acc5,$a5 + $LD $a5,$SIZE_T*6($np) + adde $acc6,$acc6,$a6 + $LD $a6,$SIZE_T*7($np) + adde $acc7,$acc7,$a7 + $LDU $a7,$SIZE_T*8($np) + #addze $carry,$zero # moved above + b .Lsqr8x_tail + +.align 5 +.Lsqr8x_tail_break: + $POP $n0,$SIZE_T*8($sp) # pull n0 + $POP $t3,$SIZE_T*9($sp) # &tp[2*num-1] + addi $cnt,$tp,$SIZE_T*8 # end of current t[num] window + + addic $carry,$carry,-1 # "move" top-most carry to carry bit + adde $t0,$acc0,$a0 + $LD $acc0,$SIZE_T*8($rp) + $LD $a0,$SIZE_T*1($t2) # recall that $t2 is &n[-1] + adde $t1,$acc1,$a1 + $LD $acc1,$SIZE_T*9($rp) + $LD $a1,$SIZE_T*2($t2) + adde $acc2,$acc2,$a2 + $LD $a2,$SIZE_T*3($t2) + adde $acc3,$acc3,$a3 + $LD $a3,$SIZE_T*4($t2) + adde $acc4,$acc4,$a4 + $LD $a4,$SIZE_T*5($t2) + adde $acc5,$acc5,$a5 + $LD $a5,$SIZE_T*6($t2) + adde $acc6,$acc6,$a6 + $LD $a6,$SIZE_T*7($t2) + adde $acc7,$acc7,$a7 + $LD $a7,$SIZE_T*8($t2) + addi $np,$t2,$SIZE_T*8 + addze $t2,$zero # top-most carry + $UMULL $na0,$n0,$acc0 + $ST $t0,$SIZE_T*1($tp) + $UCMP $cnt,$t3 # did we hit the bottom? + $ST $t1,$SIZE_T*2($tp) + li $cnt,8 + $ST $acc2,$SIZE_T*3($tp) + $LD $acc2,$SIZE_T*10($rp) + $ST $acc3,$SIZE_T*4($tp) + $LD $acc3,$SIZE_T*11($rp) + $ST $acc4,$SIZE_T*5($tp) + $LD $acc4,$SIZE_T*12($rp) + $ST $acc5,$SIZE_T*6($tp) + $LD $acc5,$SIZE_T*13($rp) + $ST $acc6,$SIZE_T*7($tp) + $LD $acc6,$SIZE_T*14($rp) + $ST $acc7,$SIZE_T*8($tp) + $LD $acc7,$SIZE_T*15($rp) + $PUSH $t2,$SIZE_T*10($sp) # off-load top-most carry + addi $tp,$rp,$SIZE_T*7 # slide the window + mtctr $cnt + bne .Lsqr8x_reduction + + ################################################################ + # Final step. We see if result is larger than modulus, and + # if it is, subtract the modulus. But comparison implies + # subtraction. So we subtract modulus, see if it borrowed, + # and conditionally copy original value. + $POP $rp,$SIZE_T*6($sp) # pull &rp[-1] + srwi $cnt,$num,`log($SIZE_T)/log(2)+3` + mr $n0,$tp # put tp aside + addi $tp,$tp,$SIZE_T*8 + subi $cnt,$cnt,1 + subfc $t0,$a0,$acc0 + subfe $t1,$a1,$acc1 + mr $carry,$t2 + mr $ap_end,$rp # $rp copy + + mtctr $cnt + b .Lsqr8x_sub + +.align 5 +.Lsqr8x_sub: + $LD $a0,$SIZE_T*1($np) + $LD $acc0,$SIZE_T*1($tp) + $LD $a1,$SIZE_T*2($np) + $LD $acc1,$SIZE_T*2($tp) + subfe $t2,$a2,$acc2 + $LD $a2,$SIZE_T*3($np) + $LD $acc2,$SIZE_T*3($tp) + subfe $t3,$a3,$acc3 + $LD $a3,$SIZE_T*4($np) + $LD $acc3,$SIZE_T*4($tp) + $ST $t0,$SIZE_T*1($rp) + subfe $t0,$a4,$acc4 + $LD $a4,$SIZE_T*5($np) + $LD $acc4,$SIZE_T*5($tp) + $ST $t1,$SIZE_T*2($rp) + subfe $t1,$a5,$acc5 + $LD $a5,$SIZE_T*6($np) + $LD $acc5,$SIZE_T*6($tp) + $ST $t2,$SIZE_T*3($rp) + subfe $t2,$a6,$acc6 + $LD $a6,$SIZE_T*7($np) + $LD $acc6,$SIZE_T*7($tp) + $ST $t3,$SIZE_T*4($rp) + subfe $t3,$a7,$acc7 + $LDU $a7,$SIZE_T*8($np) + $LDU $acc7,$SIZE_T*8($tp) + $ST $t0,$SIZE_T*5($rp) + subfe $t0,$a0,$acc0 + $ST $t1,$SIZE_T*6($rp) + subfe $t1,$a1,$acc1 + $ST $t2,$SIZE_T*7($rp) + $STU $t3,$SIZE_T*8($rp) + bdnz .Lsqr8x_sub + + srwi $cnt,$num,`log($SIZE_T)/log(2)+2` + $LD $a0,$SIZE_T*1($ap_end) # original $rp + $LD $acc0,$SIZE_T*1($n0) # original $tp + subi $cnt,$cnt,1 + $LD $a1,$SIZE_T*2($ap_end) + $LD $acc1,$SIZE_T*2($n0) + subfe $t2,$a2,$acc2 + $LD $a2,$SIZE_T*3($ap_end) + $LD $acc2,$SIZE_T*3($n0) + subfe $t3,$a3,$acc3 + $LD $a3,$SIZE_T*4($ap_end) + $LDU $acc3,$SIZE_T*4($n0) + $ST $t0,$SIZE_T*1($rp) + subfe $t0,$a4,$acc4 + $ST $t1,$SIZE_T*2($rp) + subfe $t1,$a5,$acc5 + $ST $t2,$SIZE_T*3($rp) + subfe $t2,$a6,$acc6 + $ST $t3,$SIZE_T*4($rp) + subfe $t3,$a7,$acc7 + $ST $t0,$SIZE_T*5($rp) + subfe $carry,$zero,$carry # did it borrow? + $ST $t1,$SIZE_T*6($rp) + $ST $t2,$SIZE_T*7($rp) + $ST $t3,$SIZE_T*8($rp) + + addi $tp,$sp,$SIZE_T*11 + mtctr $cnt + +.Lsqr4x_cond_copy: + andc $a0,$a0,$carry + $ST $zero,-$SIZE_T*3($n0) # wipe stack clean + and $acc0,$acc0,$carry + $ST $zero,-$SIZE_T*2($n0) + andc $a1,$a1,$carry + $ST $zero,-$SIZE_T*1($n0) + and $acc1,$acc1,$carry + $ST $zero,-$SIZE_T*0($n0) + andc $a2,$a2,$carry + $ST $zero,$SIZE_T*1($tp) + and $acc2,$acc2,$carry + $ST $zero,$SIZE_T*2($tp) + andc $a3,$a3,$carry + $ST $zero,$SIZE_T*3($tp) + and $acc3,$acc3,$carry + $STU $zero,$SIZE_T*4($tp) + or $t0,$a0,$acc0 + $LD $a0,$SIZE_T*5($ap_end) + $LD $acc0,$SIZE_T*1($n0) + or $t1,$a1,$acc1 + $LD $a1,$SIZE_T*6($ap_end) + $LD $acc1,$SIZE_T*2($n0) + or $t2,$a2,$acc2 + $LD $a2,$SIZE_T*7($ap_end) + $LD $acc2,$SIZE_T*3($n0) + or $t3,$a3,$acc3 + $LD $a3,$SIZE_T*8($ap_end) + $LDU $acc3,$SIZE_T*4($n0) + $ST $t0,$SIZE_T*1($ap_end) + $ST $t1,$SIZE_T*2($ap_end) + $ST $t2,$SIZE_T*3($ap_end) + $STU $t3,$SIZE_T*4($ap_end) + bdnz .Lsqr4x_cond_copy + + $POP $ap,0($sp) # pull saved sp + andc $a0,$a0,$carry + and $acc0,$acc0,$carry + andc $a1,$a1,$carry + and $acc1,$acc1,$carry + andc $a2,$a2,$carry + and $acc2,$acc2,$carry + andc $a3,$a3,$carry + and $acc3,$acc3,$carry + or $t0,$a0,$acc0 + or $t1,$a1,$acc1 + or $t2,$a2,$acc2 + or $t3,$a3,$acc3 + $ST $t0,$SIZE_T*1($ap_end) + $ST $t1,$SIZE_T*2($ap_end) + $ST $t2,$SIZE_T*3($ap_end) + $ST $t3,$SIZE_T*4($ap_end) + + b .Lsqr8x_done + +.align 5 +.Lsqr8x8_post_condition: + $POP $rp,$SIZE_T*6($sp) # pull rp + $POP $ap,0($sp) # pull saved sp + addze $carry,$zero + + # $acc0-7,$carry hold result, $a0-7 hold modulus + subfc $acc0,$a0,$acc0 + subfe $acc1,$a1,$acc1 + $ST $zero,$SIZE_T*12($sp) # wipe stack clean + $ST $zero,$SIZE_T*13($sp) + subfe $acc2,$a2,$acc2 + $ST $zero,$SIZE_T*14($sp) + $ST $zero,$SIZE_T*15($sp) + subfe $acc3,$a3,$acc3 + $ST $zero,$SIZE_T*16($sp) + $ST $zero,$SIZE_T*17($sp) + subfe $acc4,$a4,$acc4 + $ST $zero,$SIZE_T*18($sp) + $ST $zero,$SIZE_T*19($sp) + subfe $acc5,$a5,$acc5 + $ST $zero,$SIZE_T*20($sp) + $ST $zero,$SIZE_T*21($sp) + subfe $acc6,$a6,$acc6 + $ST $zero,$SIZE_T*22($sp) + $ST $zero,$SIZE_T*23($sp) + subfe $acc7,$a7,$acc7 + $ST $zero,$SIZE_T*24($sp) + $ST $zero,$SIZE_T*25($sp) + subfe $carry,$zero,$carry # did it borrow? + $ST $zero,$SIZE_T*26($sp) + $ST $zero,$SIZE_T*27($sp) + + and $a0,$a0,$carry + and $a1,$a1,$carry + addc $acc0,$acc0,$a0 # add modulus back if borrowed + and $a2,$a2,$carry + adde $acc1,$acc1,$a1 + and $a3,$a3,$carry + adde $acc2,$acc2,$a2 + and $a4,$a4,$carry + adde $acc3,$acc3,$a3 + and $a5,$a5,$carry + adde $acc4,$acc4,$a4 + and $a6,$a6,$carry + adde $acc5,$acc5,$a5 + and $a7,$a7,$carry + adde $acc6,$acc6,$a6 + adde $acc7,$acc7,$a7 + $ST $acc0,$SIZE_T*1($rp) + $ST $acc1,$SIZE_T*2($rp) + $ST $acc2,$SIZE_T*3($rp) + $ST $acc3,$SIZE_T*4($rp) + $ST $acc4,$SIZE_T*5($rp) + $ST $acc5,$SIZE_T*6($rp) + $ST $acc6,$SIZE_T*7($rp) + $ST $acc7,$SIZE_T*8($rp) + +.Lsqr8x_done: + $PUSH $zero,$SIZE_T*8($sp) + $PUSH $zero,$SIZE_T*10($sp) + + $POP r14,-$SIZE_T*18($ap) + li r3,1 # signal "done" + $POP r15,-$SIZE_T*17($ap) + $POP r16,-$SIZE_T*16($ap) + $POP r17,-$SIZE_T*15($ap) + $POP r18,-$SIZE_T*14($ap) + $POP r19,-$SIZE_T*13($ap) + $POP r20,-$SIZE_T*12($ap) + $POP r21,-$SIZE_T*11($ap) + $POP r22,-$SIZE_T*10($ap) + $POP r23,-$SIZE_T*9($ap) + $POP r24,-$SIZE_T*8($ap) + $POP r25,-$SIZE_T*7($ap) + $POP r26,-$SIZE_T*6($ap) + $POP r27,-$SIZE_T*5($ap) + $POP r28,-$SIZE_T*4($ap) + $POP r29,-$SIZE_T*3($ap) + $POP r30,-$SIZE_T*2($ap) + $POP r31,-$SIZE_T*1($ap) + mr $sp,$ap + blr + .long 0 + .byte 0,12,4,0x20,0x80,18,6,0 + .long 0 +.size __bn_sqr8x_mont,.-__bn_sqr8x_mont +___ +} +$code.=<<___; .asciz "Montgomery Multiplication for PPC, CRYPTOGAMS by " ___ diff --git a/crypto/bn/asm/ppc.pl b/crypto/bn/asm/ppc.pl index 4ea534a1..39349ae8 100644 --- a/crypto/bn/asm/ppc.pl +++ b/crypto/bn/asm/ppc.pl @@ -38,7 +38,7 @@ #rsa 2048 bits 0.3036s 0.0085s 3.3 117.1 #rsa 4096 bits 2.0040s 0.0299s 0.5 33.4 #dsa 512 bits 0.0087s 0.0106s 114.3 94.5 -#dsa 1024 bits 0.0256s 0.0313s 39.0 32.0 +#dsa 1024 bits 0.0256s 0.0313s 39.0 32.0 # # Same bechmark with this assembler code: # @@ -74,7 +74,7 @@ #rsa 4096 bits 0.3700s 0.0058s 2.7 171.0 #dsa 512 bits 0.0016s 0.0020s 610.7 507.1 #dsa 1024 bits 0.0047s 0.0058s 212.5 173.2 -# +# # Again, performance increases by at about 75% # # Mac OS X, Apple G5 1.8GHz (Note this is 32 bit code) @@ -101,10 +101,7 @@ #dsa 2048 bits 0.0061s 0.0075s 163.5 132.8 # # Performance increase of ~60% -# -# If you have comments or suggestions to improve code send -# me a note at schari@us.ibm.com -# +# Based on submission from Suresh N. Chari of IBM $flavour = shift; @@ -125,7 +122,7 @@ if ($flavour =~ /32/) { $CNTLZ= "cntlzw"; # count leading zeros $SHL= "slw"; # shift left $SHR= "srw"; # unsigned shift right - $SHRI= "srwi"; # unsigned shift right by immediate + $SHRI= "srwi"; # unsigned shift right by immediate $SHLI= "slwi"; # shift left by immediate $CLRU= "clrlwi"; # clear upper bits $INSR= "insrwi"; # insert right @@ -149,10 +146,10 @@ if ($flavour =~ /32/) { $CNTLZ= "cntlzd"; # count leading zeros $SHL= "sld"; # shift left $SHR= "srd"; # unsigned shift right - $SHRI= "srdi"; # unsigned shift right by immediate + $SHRI= "srdi"; # unsigned shift right by immediate $SHLI= "sldi"; # shift left by immediate $CLRU= "clrldi"; # clear upper bits - $INSR= "insrdi"; # insert right + $INSR= "insrdi"; # insert right $ROTL= "rotldi"; # rotate left by immediate $TR= "td"; # conditional trap } else { die "nonsense $flavour"; } @@ -189,7 +186,7 @@ $data=<=d? blt Lppcasm_div3 #goto Lppcasm_div3 if not - subf r3,r5,r3 #h-=d ; + subf r3,r5,r3 #h-=d ; Lppcasm_div3: #r7 = BN_BITS2-i. so r7=i cmpi 0,0,r7,0 # is (i == 0)? beq Lppcasm_div4 @@ -1668,7 +1665,7 @@ Lppcasm_div4: # as it saves registers. li r6,2 #r6=2 mtctr r6 #counter will be in count. -Lppcasm_divouterloop: +Lppcasm_divouterloop: $SHRI r8,r3,`$BITS/2` #r8 = (h>>BN_BITS4) $SHRI r11,r4,`$BITS/2` #r11= (l&BN_MASK2h)>>BN_BITS4 # compute here for innerloop. @@ -1676,7 +1673,7 @@ Lppcasm_divouterloop: bne Lppcasm_div5 # goto Lppcasm_div5 if not li r8,-1 - $CLRU r8,r8,`$BITS/2` #q = BN_MASK2l + $CLRU r8,r8,`$BITS/2` #q = BN_MASK2l b Lppcasm_div6 Lppcasm_div5: $UDIV r8,r3,r9 #q = h/dh @@ -1684,7 +1681,7 @@ Lppcasm_div6: $UMULL r12,r9,r8 #th = q*dh $CLRU r10,r5,`$BITS/2` #r10=dl $UMULL r6,r8,r10 #tl = q*dl - + Lppcasm_divinnerloop: subf r10,r12,r3 #t = h -th $SHRI r7,r10,`$BITS/2` #r7= (t &BN_MASK2H), sort of... @@ -1761,7 +1758,7 @@ Lppcasm_div9: addi r4,r4,-$BNSZ addi r3,r3,-$BNSZ mtctr r5 -Lppcasm_sqr_mainloop: +Lppcasm_sqr_mainloop: #sqr(r[0],r[1],a[0]); $LDU r6,$BNSZ(r4) $UMULL r7,r6,r6 @@ -1769,7 +1766,7 @@ Lppcasm_sqr_mainloop: $STU r7,$BNSZ(r3) $STU r8,$BNSZ(r3) bdnz Lppcasm_sqr_mainloop -Lppcasm_sqr_adios: +Lppcasm_sqr_adios: blr .long 0 .byte 0,12,0x14,0,0,0,3,0 @@ -1783,7 +1780,7 @@ Lppcasm_sqr_adios: # done in the build # -.align 4 +.align 4 .bn_mul_words: # # BN_ULONG bn_mul_words(BN_ULONG *rp, BN_ULONG *ap, int num, BN_ULONG w) @@ -1797,7 +1794,7 @@ Lppcasm_sqr_adios: rlwinm. r7,r5,30,2,31 # num >> 2 beq Lppcasm_mw_REM mtctr r7 -Lppcasm_mw_LOOP: +Lppcasm_mw_LOOP: #mul(rp[0],ap[0],w,c1); $LD r8,`0*$BNSZ`(r4) $UMULL r9,r6,r8 @@ -1809,7 +1806,7 @@ Lppcasm_mw_LOOP: #using adde. $ST r9,`0*$BNSZ`(r3) #mul(rp[1],ap[1],w,c1); - $LD r8,`1*$BNSZ`(r4) + $LD r8,`1*$BNSZ`(r4) $UMULL r11,r6,r8 $UMULH r12,r6,r8 adde r11,r11,r10 @@ -1830,7 +1827,7 @@ Lppcasm_mw_LOOP: addze r12,r12 #this spin we collect carry into #r12 $ST r11,`3*$BNSZ`(r3) - + addi r3,r3,`4*$BNSZ` addi r4,r4,`4*$BNSZ` bdnz Lppcasm_mw_LOOP @@ -1846,25 +1843,25 @@ Lppcasm_mw_REM: addze r10,r10 $ST r9,`0*$BNSZ`(r3) addi r12,r10,0 - + addi r5,r5,-1 cmpli 0,0,r5,0 beq Lppcasm_mw_OVER - + #mul(rp[1],ap[1],w,c1); - $LD r8,`1*$BNSZ`(r4) + $LD r8,`1*$BNSZ`(r4) $UMULL r9,r6,r8 $UMULH r10,r6,r8 addc r9,r9,r12 addze r10,r10 $ST r9,`1*$BNSZ`(r3) addi r12,r10,0 - + addi r5,r5,-1 cmpli 0,0,r5,0 beq Lppcasm_mw_OVER - + #mul_add(rp[2],ap[2],w,c1); $LD r8,`2*$BNSZ`(r4) $UMULL r9,r6,r8 @@ -1873,14 +1870,14 @@ Lppcasm_mw_REM: addze r10,r10 $ST r9,`2*$BNSZ`(r3) addi r12,r10,0 - -Lppcasm_mw_OVER: + +Lppcasm_mw_OVER: addi r3,r12,0 blr .long 0 .byte 0,12,0x14,0,0,0,4,0 .long 0 -.size bn_mul_words,.-bn_mul_words +.size .bn_mul_words,.-.bn_mul_words # # NOTE: The following label name should be changed to @@ -1902,11 +1899,11 @@ Lppcasm_mw_OVER: # empirical evidence suggests that unrolled version performs best!! # xor r0,r0,r0 #r0 = 0 - xor r12,r12,r12 #r12 = 0 . used for carry + xor r12,r12,r12 #r12 = 0 . used for carry rlwinm. r7,r5,30,2,31 # num >> 2 beq Lppcasm_maw_leftover # if (num < 4) go LPPCASM_maw_leftover mtctr r7 -Lppcasm_maw_mainloop: +Lppcasm_maw_mainloop: #mul_add(rp[0],ap[0],w,c1); $LD r8,`0*$BNSZ`(r4) $LD r11,`0*$BNSZ`(r3) @@ -1922,9 +1919,9 @@ Lppcasm_maw_mainloop: #by multiply and will be collected #in the next spin $ST r9,`0*$BNSZ`(r3) - + #mul_add(rp[1],ap[1],w,c1); - $LD r8,`1*$BNSZ`(r4) + $LD r8,`1*$BNSZ`(r4) $LD r9,`1*$BNSZ`(r3) $UMULL r11,r6,r8 $UMULH r12,r6,r8 @@ -1933,7 +1930,7 @@ Lppcasm_maw_mainloop: addc r11,r11,r9 #addze r12,r12 $ST r11,`1*$BNSZ`(r3) - + #mul_add(rp[2],ap[2],w,c1); $LD r8,`2*$BNSZ`(r4) $UMULL r9,r6,r8 @@ -1944,7 +1941,7 @@ Lppcasm_maw_mainloop: addc r9,r9,r11 #addze r10,r10 $ST r9,`2*$BNSZ`(r3) - + #mul_add(rp[3],ap[3],w,c1); $LD r8,`3*$BNSZ`(r4) $UMULL r11,r6,r8 @@ -1958,7 +1955,7 @@ Lppcasm_maw_mainloop: addi r3,r3,`4*$BNSZ` addi r4,r4,`4*$BNSZ` bdnz Lppcasm_maw_mainloop - + Lppcasm_maw_leftover: andi. r5,r5,0x3 beq Lppcasm_maw_adios @@ -1975,10 +1972,10 @@ Lppcasm_maw_leftover: addc r9,r9,r12 addze r12,r10 $ST r9,0(r3) - + bdz Lppcasm_maw_adios #mul_add(rp[1],ap[1],w,c1); - $LDU r8,$BNSZ(r4) + $LDU r8,$BNSZ(r4) $UMULL r9,r6,r8 $UMULH r10,r6,r8 $LDU r11,$BNSZ(r3) @@ -1987,7 +1984,7 @@ Lppcasm_maw_leftover: addc r9,r9,r12 addze r12,r10 $ST r9,0(r3) - + bdz Lppcasm_maw_adios #mul_add(rp[2],ap[2],w,c1); $LDU r8,$BNSZ(r4) @@ -1999,8 +1996,8 @@ Lppcasm_maw_leftover: addc r9,r9,r12 addze r12,r10 $ST r9,0(r3) - -Lppcasm_maw_adios: + +Lppcasm_maw_adios: addi r3,r12,0 blr .long 0 diff --git a/crypto/bn/asm/ppc64-mont.pl b/crypto/bn/asm/ppc64-mont.pl index 1e19c958..0b2bb39f 100644 --- a/crypto/bn/asm/ppc64-mont.pl +++ b/crypto/bn/asm/ppc64-mont.pl @@ -35,7 +35,7 @@ # key lengths. As it's obviously inappropriate as "best all-round" # alternative, it has to be complemented with run-time CPU family # detection. Oh! It should also be noted that unlike other PowerPC -# implementation IALU ppc-mont.pl module performs *suboptimaly* on +# implementation IALU ppc-mont.pl module performs *suboptimally* on # >=1024-bit key lengths on Power 6. It should also be noted that # *everything* said so far applies to 64-bit builds! As far as 32-bit # application executed on 64-bit CPU goes, this module is likely to @@ -1353,7 +1353,7 @@ $code.=<<___; std $t3,-16($tp) ; tp[j-1] std $t5,-8($tp) ; tp[j] - add $carry,$carry,$ovf ; comsume upmost overflow + add $carry,$carry,$ovf ; consume upmost overflow add $t6,$t6,$carry ; can not overflow srdi $carry,$t6,16 add $t7,$t7,$carry diff --git a/crypto/bn/asm/rsaz-avx2.pl b/crypto/bn/asm/rsaz-avx2.pl index 46d746b7..8c56a914 100755 --- a/crypto/bn/asm/rsaz-avx2.pl +++ b/crypto/bn/asm/rsaz-avx2.pl @@ -1,68 +1,30 @@ #! /usr/bin/env perl # Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright (c) 2012, Intel Corporation. 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 - - -############################################################################## -# # -# Copyright (c) 2012, Intel Corporation # -# # -# All rights reserved. # -# # -# Redistribution and use in source and binary forms, with or without # -# modification, are permitted provided that the following conditions are # -# met: # -# # -# * Redistributions of source code must retain the above copyright # -# notice, this list of conditions and the following disclaimer. # -# # -# * 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. # -# # -# * Neither the name of the Intel Corporation nor the names of its # -# contributors may be used to endorse or promote products derived from # -# this software without specific prior written permission. # -# # -# # -# THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION ""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 INTEL CORPORATION 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. # -# # -############################################################################## -# Developers and authors: # -# Shay Gueron (1, 2), and Vlad Krasnov (1) # -# (1) Intel Corporation, Israel Development Center, Haifa, Israel # -# (2) University of Haifa, Israel # -############################################################################## -# Reference: # -# [1] S. Gueron, V. Krasnov: "Software Implementation of Modular # -# Exponentiation, Using Advanced Vector Instructions Architectures", # -# F. Ozbudak and F. Rodriguez-Henriquez (Eds.): WAIFI 2012, LNCS 7369, # -# pp. 119?135, 2012. Springer-Verlag Berlin Heidelberg 2012 # -# [2] S. Gueron: "Efficient Software Implementations of Modular # -# Exponentiation", Journal of Cryptographic Engineering 2:31-43 (2012). # -# [3] S. Gueron, V. Krasnov: "Speeding up Big-numbers Squaring",IEEE # -# Proceedings of 9th International Conference on Information Technology: # -# New Generations (ITNG 2012), pp.821-823 (2012) # -# [4] S. Gueron, V. Krasnov: "[PATCH] Efficient and side channel analysis # -# resistant 1024-bit modular exponentiation, for optimizing RSA2048 # -# on AVX2 capable x86_64 platforms", # -# http://rt.openssl.org/Ticket/Display.html?id=2850&user=guest&pass=guest# -############################################################################## +# +# Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) +# (1) Intel Corporation, Israel Development Center, Haifa, Israel +# (2) University of Haifa, Israel +# +# References: +# [1] S. Gueron, V. Krasnov: "Software Implementation of Modular +# Exponentiation, Using Advanced Vector Instructions Architectures", +# F. Ozbudak and F. Rodriguez-Henriquez (Eds.): WAIFI 2012, LNCS 7369, +# pp. 119?135, 2012. Springer-Verlag Berlin Heidelberg 2012 +# [2] S. Gueron: "Efficient Software Implementations of Modular +# Exponentiation", Journal of Cryptographic Engineering 2:31-43 (2012). +# [3] S. Gueron, V. Krasnov: "Speeding up Big-numbers Squaring",IEEE +# Proceedings of 9th International Conference on Information Technology: +# New Generations (ITNG 2012), pp.821-823 (2012) +# [4] S. Gueron, V. Krasnov: "[PATCH] Efficient and side channel analysis +# resistant 1024-bit modular exponentiation, for optimizing RSA2048 +# on AVX2 capable x86_64 platforms", +# http://rt.openssl.org/Ticket/Display.html?id=2850&user=guest&pass=guest # # +13% improvement over original submission by # @@ -168,13 +130,21 @@ $code.=<<___; .type rsaz_1024_sqr_avx2,\@function,5 .align 64 rsaz_1024_sqr_avx2: # 702 cycles, 14% faster than rsaz_1024_mul_avx2 +.cfi_startproc lea (%rsp), %rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 vzeroupper ___ $code.=<<___ if ($win64); @@ -193,6 +163,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov %rax,%rbp +.cfi_def_cfa_register %rbp mov %rdx, $np # reassigned argument sub \$$FrameSize, %rsp mov $np, $tmp @@ -382,7 +353,7 @@ $code.=<<___; vpaddq $TEMP1, $ACC1, $ACC1 vpmuludq 32*7-128($aap), $B2, $ACC2 vpbroadcastq 32*5-128($tpa), $B2 - vpaddq 32*11-448($tp1), $ACC2, $ACC2 + vpaddq 32*11-448($tp1), $ACC2, $ACC2 vmovdqu $ACC6, 32*6-192($tp0) vmovdqu $ACC7, 32*7-192($tp0) @@ -441,7 +412,7 @@ $code.=<<___; vmovdqu $ACC7, 32*16-448($tp1) lea 8($tp1), $tp1 - dec $i + dec $i jnz .LOOP_SQR_1024 ___ $ZERO = $ACC9; @@ -786,7 +757,7 @@ $code.=<<___; vpblendd \$3, $TEMP4, $TEMP5, $TEMP4 vpaddq $TEMP3, $ACC7, $ACC7 vpaddq $TEMP4, $ACC8, $ACC8 - + vpsrlq \$29, $ACC4, $TEMP1 vpand $AND_MASK, $ACC4, $ACC4 vpsrlq \$29, $ACC5, $TEMP2 @@ -825,8 +796,10 @@ $code.=<<___; vzeroall mov %rbp, %rax +.cfi_def_cfa_register %rax ___ $code.=<<___ if ($win64); +.Lsqr_1024_in_tail: movaps -0xd8(%rax),%xmm6 movaps -0xc8(%rax),%xmm7 movaps -0xb8(%rax),%xmm8 @@ -840,14 +813,22 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -48(%rax),%r15 +.cfi_restore %r15 mov -40(%rax),%r14 +.cfi_restore %r14 mov -32(%rax),%r13 +.cfi_restore %r13 mov -24(%rax),%r12 +.cfi_restore %r12 mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp # restore %rsp +.cfi_def_cfa_register %rsp .Lsqr_1024_epilogue: ret +.cfi_endproc .size rsaz_1024_sqr_avx2,.-rsaz_1024_sqr_avx2 ___ } @@ -900,13 +881,21 @@ $code.=<<___; .type rsaz_1024_mul_avx2,\@function,5 .align 64 rsaz_1024_mul_avx2: +.cfi_startproc lea (%rsp), %rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 ___ $code.=<<___ if ($win64); vzeroupper @@ -925,6 +914,7 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov %rax,%rbp +.cfi_def_cfa_register %rbp vzeroall mov %rdx, $bp # reassigned argument sub \$64,%rsp @@ -1450,15 +1440,17 @@ $code.=<<___; vpaddq $TEMP4, $ACC8, $ACC8 vmovdqu $ACC4, 128-128($rp) - vmovdqu $ACC5, 160-128($rp) + vmovdqu $ACC5, 160-128($rp) vmovdqu $ACC6, 192-128($rp) vmovdqu $ACC7, 224-128($rp) vmovdqu $ACC8, 256-128($rp) vzeroupper mov %rbp, %rax +.cfi_def_cfa_register %rax ___ $code.=<<___ if ($win64); +.Lmul_1024_in_tail: movaps -0xd8(%rax),%xmm6 movaps -0xc8(%rax),%xmm7 movaps -0xb8(%rax),%xmm8 @@ -1472,14 +1464,22 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -48(%rax),%r15 +.cfi_restore %r15 mov -40(%rax),%r14 +.cfi_restore %r14 mov -32(%rax),%r13 +.cfi_restore %r13 mov -24(%rax),%r12 +.cfi_restore %r12 mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp # restore %rsp +.cfi_def_cfa_register %rsp .Lmul_1024_epilogue: ret +.cfi_endproc .size rsaz_1024_mul_avx2,.-rsaz_1024_mul_avx2 ___ } @@ -1598,8 +1598,10 @@ rsaz_1024_scatter5_avx2: .type rsaz_1024_gather5_avx2,\@abi-omnipotent .align 32 rsaz_1024_gather5_avx2: +.cfi_startproc vzeroupper mov %rsp,%r11 +.cfi_def_cfa_register %r11 ___ $code.=<<___ if ($win64); lea -0x88(%rsp),%rax @@ -1737,11 +1739,13 @@ $code.=<<___ if ($win64); movaps -0x38(%r11),%xmm13 movaps -0x28(%r11),%xmm14 movaps -0x18(%r11),%xmm15 -.LSEH_end_rsaz_1024_gather5: ___ $code.=<<___; lea (%r11),%rsp +.cfi_def_cfa_register %rsp ret +.cfi_endproc +.LSEH_end_rsaz_1024_gather5: .size rsaz_1024_gather5_avx2,.-rsaz_1024_gather5_avx2 ___ } @@ -1814,14 +1818,17 @@ rsaz_se_handler: cmp %r10,%rbx # context->RipRsp - mov 4(%r11),%r10d # HandlerData[1] lea (%rsi,%r10),%r10 # epilogue label cmp %r10,%rbx # context->Rip>=epilogue label jae .Lcommon_seh_tail - mov 160($context),%rax # pull context->Rbp + mov 160($context),%rbp # pull context->Rbp + + mov 8(%r11),%r10d # HandlerData[2] + lea (%rsi,%r10),%r10 # "in tail" label + cmp %r10,%rbx # context->Rip>="in tail" label + cmovc %rbp,%rax mov -48(%rax),%r15 mov -40(%rax),%r14 @@ -1899,11 +1906,13 @@ rsaz_se_handler: .LSEH_info_rsaz_1024_sqr_avx2: .byte 9,0,0,0 .rva rsaz_se_handler - .rva .Lsqr_1024_body,.Lsqr_1024_epilogue + .rva .Lsqr_1024_body,.Lsqr_1024_epilogue,.Lsqr_1024_in_tail + .long 0 .LSEH_info_rsaz_1024_mul_avx2: .byte 9,0,0,0 .rva rsaz_se_handler - .rva .Lmul_1024_body,.Lmul_1024_epilogue + .rva .Lmul_1024_body,.Lmul_1024_epilogue,.Lmul_1024_in_tail + .long 0 .LSEH_info_rsaz_1024_gather5: .byte 0x01,0x36,0x17,0x0b .byte 0x36,0xf8,0x09,0x00 # vmovaps 0x90(rsp),xmm15 diff --git a/crypto/bn/asm/rsaz-x86_64.pl b/crypto/bn/asm/rsaz-x86_64.pl index 6f3b664f..b1797b64 100755 --- a/crypto/bn/asm/rsaz-x86_64.pl +++ b/crypto/bn/asm/rsaz-x86_64.pl @@ -1,68 +1,29 @@ #! /usr/bin/env perl # Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright (c) 2012, Intel Corporation. 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 - - -############################################################################## -# # -# Copyright (c) 2012, Intel Corporation # -# # -# All rights reserved. # -# # -# Redistribution and use in source and binary forms, with or without # -# modification, are permitted provided that the following conditions are # -# met: # -# # -# * Redistributions of source code must retain the above copyright # -# notice, this list of conditions and the following disclaimer. # -# # -# * 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. # -# # -# * Neither the name of the Intel Corporation nor the names of its # -# contributors may be used to endorse or promote products derived from # -# this software without specific prior written permission. # -# # -# # -# THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION ""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 INTEL CORPORATION 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. # -# # -############################################################################## -# Developers and authors: # -# Shay Gueron (1, 2), and Vlad Krasnov (1) # -# (1) Intel Architecture Group, Microprocessor and Chipset Development, # -# Israel Development Center, Haifa, Israel # -# (2) University of Haifa # -############################################################################## -# Reference: # -# [1] S. Gueron, "Efficient Software Implementations of Modular # -# Exponentiation", http://eprint.iacr.org/2011/239 # -# [2] S. Gueron, V. Krasnov. "Speeding up Big-Numbers Squaring". # -# IEEE Proceedings of 9th International Conference on Information # -# Technology: New Generations (ITNG 2012), 821-823 (2012). # -# [3] S. Gueron, Efficient Software Implementations of Modular Exponentiation# -# Journal of Cryptographic Engineering 2:31-43 (2012). # -# [4] S. Gueron, V. Krasnov: "[PATCH] Efficient and side channel analysis # -# resistant 512-bit and 1024-bit modular exponentiation for optimizing # -# RSA1024 and RSA2048 on x86_64 platforms", # -# http://rt.openssl.org/Ticket/Display.html?id=2582&user=guest&pass=guest# -############################################################################## - +# +# Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) +# (1) Intel Corporation, Israel Development Center, Haifa, Israel +# (2) University of Haifa, Israel +# +# References: +# [1] S. Gueron, "Efficient Software Implementations of Modular +# Exponentiation", http://eprint.iacr.org/2011/239 +# [2] S. Gueron, V. Krasnov. "Speeding up Big-Numbers Squaring". +# IEEE Proceedings of 9th International Conference on Information +# Technology: New Generations (ITNG 2012), 821-823 (2012). +# [3] S. Gueron, Efficient Software Implementations of Modular Exponentiation +# Journal of Cryptographic Engineering 2:31-43 (2012). +# [4] S. Gueron, V. Krasnov: "[PATCH] Efficient and side channel analysis +# resistant 512-bit and 1024-bit modular exponentiation for optimizing +# RSA1024 and RSA2048 on x86_64 platforms", +# http://rt.openssl.org/Ticket/Display.html?id=2582&user=guest&pass=guest +# # While original submission covers 512- and 1024-bit exponentiation, # this module is limited to 512-bit version only (and as such # accelerates RSA1024 sign). This is because improvement for longer @@ -138,14 +99,22 @@ $code.=<<___; .type rsaz_512_sqr,\@function,5 .align 32 rsaz_512_sqr: # 25-29% faster than rsaz_512_mul +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 subq \$128+24, %rsp +.cfi_adjust_cfa_offset 128+24 .Lsqr_body: movq $mod, %rbp # common argument movq ($inp), %rdx @@ -282,9 +251,9 @@ $code.=<<___; movq %r9, 16(%rsp) movq %r10, 24(%rsp) shrq \$63, %rbx - + #third iteration - movq 16($inp), %r9 + movq 16($inp), %r9 movq 24($inp), %rax mulq %r9 addq %rax, %r12 @@ -532,7 +501,7 @@ $code.=<<___; movl $times,128+8(%rsp) movq $out, %xmm0 # off-load movq %rbp, %xmm1 # off-load -#first iteration +#first iteration mulx %rax, %r8, %r9 mulx 16($inp), %rcx, %r10 @@ -568,7 +537,7 @@ $code.=<<___; mov %rax, (%rsp) mov %r8, 8(%rsp) -#second iteration +#second iteration mulx 16($inp), %rax, %rbx adox %rax, %r10 adcx %rbx, %r11 @@ -607,8 +576,8 @@ $code.=<<___; mov %r9, 16(%rsp) .byte 0x4c,0x89,0x94,0x24,0x18,0x00,0x00,0x00 # mov %r10, 24(%rsp) - -#third iteration + +#third iteration .byte 0xc4,0x62,0xc3,0xf6,0x8e,0x18,0x00,0x00,0x00 # mulx 24($inp), $out, %r9 adox $out, %r12 adcx %r9, %r13 @@ -643,8 +612,8 @@ $code.=<<___; mov %r11, 32(%rsp) .byte 0x4c,0x89,0xa4,0x24,0x28,0x00,0x00,0x00 # mov %r12, 40(%rsp) - -#fourth iteration + +#fourth iteration .byte 0xc4,0xe2,0xfb,0xf6,0x9e,0x20,0x00,0x00,0x00 # mulx 32($inp), %rax, %rbx adox %rax, %r14 adcx %rbx, %r15 @@ -676,8 +645,8 @@ $code.=<<___; mov %r13, 48(%rsp) mov %r14, 56(%rsp) - -#fifth iteration + +#fifth iteration .byte 0xc4,0x62,0xc3,0xf6,0x9e,0x28,0x00,0x00,0x00 # mulx 40($inp), $out, %r11 adox $out, %r8 adcx %r11, %r9 @@ -704,8 +673,8 @@ $code.=<<___; mov %r15, 64(%rsp) mov %r8, 72(%rsp) - -#sixth iteration + +#sixth iteration .byte 0xc4,0xe2,0xfb,0xf6,0x9e,0x30,0x00,0x00,0x00 # mulx 48($inp), %rax, %rbx adox %rax, %r10 adcx %rbx, %r11 @@ -800,15 +769,24 @@ ___ $code.=<<___; leaq 128+24+48(%rsp), %rax +.cfi_def_cfa %rax,8 movq -48(%rax), %r15 +.cfi_restore %r15 movq -40(%rax), %r14 +.cfi_restore %r14 movq -32(%rax), %r13 +.cfi_restore %r13 movq -24(%rax), %r12 +.cfi_restore %r12 movq -16(%rax), %rbp +.cfi_restore %rbp movq -8(%rax), %rbx +.cfi_restore %rbx leaq (%rax), %rsp +.cfi_def_cfa_register %rsp .Lsqr_epilogue: ret +.cfi_endproc .size rsaz_512_sqr,.-rsaz_512_sqr ___ } @@ -819,14 +797,22 @@ $code.=<<___; .type rsaz_512_mul,\@function,5 .align 32 rsaz_512_mul: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 subq \$128+24, %rsp +.cfi_adjust_cfa_offset 128+24 .Lmul_body: movq $out, %xmm0 # off-load arguments movq $mod, %xmm1 @@ -896,15 +882,24 @@ $code.=<<___; call __rsaz_512_subtract leaq 128+24+48(%rsp), %rax +.cfi_def_cfa %rax,8 movq -48(%rax), %r15 +.cfi_restore %r15 movq -40(%rax), %r14 +.cfi_restore %r14 movq -32(%rax), %r13 +.cfi_restore %r13 movq -24(%rax), %r12 +.cfi_restore %r12 movq -16(%rax), %rbp +.cfi_restore %rbp movq -8(%rax), %rbx +.cfi_restore %rbx leaq (%rax), %rsp +.cfi_def_cfa_register %rsp .Lmul_epilogue: ret +.cfi_endproc .size rsaz_512_mul,.-rsaz_512_mul ___ } @@ -915,14 +910,22 @@ $code.=<<___; .type rsaz_512_mul_gather4,\@function,6 .align 32 rsaz_512_mul_gather4: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 subq \$`128+24+($win64?0xb0:0)`, %rsp +.cfi_adjust_cfa_offset `128+24+($win64?0xb0:0)` ___ $code.=<<___ if ($win64); movaps %xmm6,0xa0(%rsp) @@ -1048,7 +1051,7 @@ $code.=<<___; movq 56($ap), %rax movq %rdx, %r14 adcq \$0, %r14 - + mulq %rbx addq %rax, %r14 movq ($ap), %rax @@ -1150,7 +1153,7 @@ $code.=<<___; movq ($ap), %rax adcq \$0, %rdx addq %r15, %r14 - movq %rdx, %r15 + movq %rdx, %r15 adcq \$0, %r15 leaq 8(%rdi), %rdi @@ -1212,7 +1215,7 @@ $code.=<<___ if ($addx); mulx 48($ap), %rbx, %r14 adcx %rax, %r12 - + mulx 56($ap), %rax, %r15 adcx %rbx, %r13 adcx %rax, %r14 @@ -1348,15 +1351,24 @@ $code.=<<___ if ($win64); lea 0xb0(%rax),%rax ___ $code.=<<___; +.cfi_def_cfa %rax,8 movq -48(%rax), %r15 +.cfi_restore %r15 movq -40(%rax), %r14 +.cfi_restore %r14 movq -32(%rax), %r13 +.cfi_restore %r13 movq -24(%rax), %r12 +.cfi_restore %r12 movq -16(%rax), %rbp +.cfi_restore %rbp movq -8(%rax), %rbx +.cfi_restore %rbx leaq (%rax), %rsp +.cfi_def_cfa_register %rsp .Lmul_gather4_epilogue: ret +.cfi_endproc .size rsaz_512_mul_gather4,.-rsaz_512_mul_gather4 ___ } @@ -1367,15 +1379,23 @@ $code.=<<___; .type rsaz_512_mul_scatter4,\@function,6 .align 32 rsaz_512_mul_scatter4: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 mov $pwr, $pwr subq \$128+24, %rsp +.cfi_adjust_cfa_offset 128+24 .Lmul_scatter4_body: leaq ($tbl,$pwr,8), $tbl movq $out, %xmm0 # off-load arguments @@ -1411,7 +1431,7 @@ $code.=<<___; ___ $code.=<<___ if ($addx); jmp .Lmul_scatter_tail - + .align 32 .Lmulx_scatter: movq ($out), %rdx # pass b[0] @@ -1458,15 +1478,24 @@ $code.=<<___; movq %r15, 128*7($inp) leaq 128+24+48(%rsp), %rax +.cfi_def_cfa %rax,8 movq -48(%rax), %r15 +.cfi_restore %r15 movq -40(%rax), %r14 +.cfi_restore %r14 movq -32(%rax), %r13 +.cfi_restore %r13 movq -24(%rax), %r12 +.cfi_restore %r12 movq -16(%rax), %rbp +.cfi_restore %rbp movq -8(%rax), %rbx +.cfi_restore %rbx leaq (%rax), %rsp +.cfi_def_cfa_register %rsp .Lmul_scatter4_epilogue: ret +.cfi_endproc .size rsaz_512_mul_scatter4,.-rsaz_512_mul_scatter4 ___ } @@ -1477,14 +1506,22 @@ $code.=<<___; .type rsaz_512_mul_by_one,\@function,4 .align 32 rsaz_512_mul_by_one: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 subq \$128+24, %rsp +.cfi_adjust_cfa_offset 128+24 .Lmul_by_one_body: ___ $code.=<<___ if ($addx); @@ -1539,15 +1576,24 @@ $code.=<<___; movq %r15, 56($out) leaq 128+24+48(%rsp), %rax +.cfi_def_cfa %rax,8 movq -48(%rax), %r15 +.cfi_restore %r15 movq -40(%rax), %r14 +.cfi_restore %r14 movq -32(%rax), %r13 +.cfi_restore %r13 movq -24(%rax), %r12 +.cfi_restore %r12 movq -16(%rax), %rbp +.cfi_restore %rbp movq -8(%rax), %rbx +.cfi_restore %rbx leaq (%rax), %rsp +.cfi_def_cfa_register %rsp .Lmul_by_one_epilogue: ret +.cfi_endproc .size rsaz_512_mul_by_one,.-rsaz_512_mul_by_one ___ } @@ -1824,7 +1870,7 @@ __rsaz_512_mul: movq 56($ap), %rax movq %rdx, %r14 adcq \$0, %r14 - + mulq %rbx addq %rax, %r14 movq ($ap), %rax @@ -1901,7 +1947,7 @@ __rsaz_512_mul: movq ($ap), %rax adcq \$0, %rdx addq %r15, %r14 - movq %rdx, %r15 + movq %rdx, %r15 adcq \$0, %r15 leaq 8(%rdi), %rdi diff --git a/crypto/bn/asm/s390x-gf2m.pl b/crypto/bn/asm/s390x-gf2m.pl index cbd16f42..06181bf9 100644 --- a/crypto/bn/asm/s390x-gf2m.pl +++ b/crypto/bn/asm/s390x-gf2m.pl @@ -20,7 +20,7 @@ # in bn_gf2m.c. It's kind of low-hanging mechanical port from C for # the time being... gcc 4.3 appeared to generate poor code, therefore # the effort. And indeed, the module delivers 55%-90%(*) improvement -# on haviest ECDSA verify and ECDH benchmarks for 163- and 571-bit +# on heaviest ECDSA verify and ECDH benchmarks for 163- and 571-bit # key lengths on z990, 30%-55%(*) - on z10, and 70%-110%(*) - on z196. # This is for 64-bit build. In 32-bit "highgprs" case improvement is # even higher, for example on z990 it was measured 80%-150%. ECDSA @@ -198,7 +198,7 @@ $code.=<<___; xgr $hi,@r[1] xgr $lo,@r[0] xgr $hi,@r[2] - xgr $lo,@r[3] + xgr $lo,@r[3] xgr $hi,@r[3] xgr $lo,$hi stg $hi,16($rp) diff --git a/crypto/bn/asm/s390x-mont.pl b/crypto/bn/asm/s390x-mont.pl index 2205bc2c..0eaade3e 100644 --- a/crypto/bn/asm/s390x-mont.pl +++ b/crypto/bn/asm/s390x-mont.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. diff --git a/crypto/bn/asm/sparct4-mont.pl b/crypto/bn/asm/sparct4-mont.pl index 4faf66f1..6eb634d2 100755 --- a/crypto/bn/asm/sparct4-mont.pl +++ b/crypto/bn/asm/sparct4-mont.pl @@ -8,9 +8,9 @@ # ==================================================================== -# Written by David S. Miller and Andy Polyakov -# . The module is licensed under 2-clause BSD -# license. November 2012. All rights reserved. +# Written by David S. Miller and Andy Polyakov +# The module is licensed under 2-clause BSD license. +# November 2012. All rights reserved. # ==================================================================== ###################################################################### diff --git a/crypto/bn/asm/sparcv8.S b/crypto/bn/asm/sparcv8.S index 9c31073b..75d72eb9 100644 --- a/crypto/bn/asm/sparcv8.S +++ b/crypto/bn/asm/sparcv8.S @@ -1,5 +1,5 @@ .ident "sparcv8.s, Version 1.4" -.ident "SPARC v8 ISA artwork by Andy Polyakov " +.ident "SPARC v8 ISA artwork by Andy Polyakov " /* * ==================================================================== @@ -13,7 +13,7 @@ */ /* - * This is my modest contributon to OpenSSL project (see + * This is my modest contribution to OpenSSL project (see * http://www.openssl.org/ for more information about it) and is * a drop-in SuperSPARC ISA replacement for crypto/bn/bn_asm.c * module. For updates see http://fy.chalmers.se/~appro/hpe/. @@ -159,12 +159,12 @@ bn_mul_add_words: */ bn_mul_words: cmp %o2,0 - bg,a .L_bn_mul_words_proceeed + bg,a .L_bn_mul_words_proceed ld [%o1],%g2 retl clr %o0 -.L_bn_mul_words_proceeed: +.L_bn_mul_words_proceed: andcc %o2,-4,%g0 bz .L_bn_mul_words_tail clr %o5 @@ -251,12 +251,12 @@ bn_mul_words: */ bn_sqr_words: cmp %o2,0 - bg,a .L_bn_sqr_words_proceeed + bg,a .L_bn_sqr_words_proceed ld [%o1],%g2 retl clr %o0 -.L_bn_sqr_words_proceeed: +.L_bn_sqr_words_proceed: andcc %o2,-4,%g0 bz .L_bn_sqr_words_tail clr %o5 diff --git a/crypto/bn/asm/sparcv8plus.S b/crypto/bn/asm/sparcv8plus.S index 714a1366..fe4699b2 100644 --- a/crypto/bn/asm/sparcv8plus.S +++ b/crypto/bn/asm/sparcv8plus.S @@ -1,5 +1,5 @@ .ident "sparcv8plus.s, Version 1.4" -.ident "SPARC v9 ISA artwork by Andy Polyakov " +.ident "SPARC v9 ISA artwork by Andy Polyakov " /* * ==================================================================== @@ -13,7 +13,7 @@ */ /* - * This is my modest contributon to OpenSSL project (see + * This is my modest contribution to OpenSSL project (see * http://www.openssl.org/ for more information about it) and is * a drop-in UltraSPARC ISA replacement for crypto/bn/bn_asm.c * module. For updates see http://fy.chalmers.se/~appro/hpe/. @@ -144,10 +144,6 @@ * } */ -#ifdef OPENSSL_FIPSCANISTER -#include -#endif - #if defined(__SUNPRO_C) && defined(__sparcv9) /* They've said -xarch=v9 at command line */ .register %g2,#scratch @@ -282,7 +278,7 @@ bn_mul_add_words: */ bn_mul_words: sra %o2,%g0,%o2 ! signx %o2 - brgz,a %o2,.L_bn_mul_words_proceeed + brgz,a %o2,.L_bn_mul_words_proceed lduw [%o1],%g2 retl clr %o0 @@ -290,7 +286,7 @@ bn_mul_words: nop nop -.L_bn_mul_words_proceeed: +.L_bn_mul_words_proceed: srl %o3,%g0,%o3 ! clruw %o3 andcc %o2,-4,%g0 bz,pn %icc,.L_bn_mul_words_tail @@ -370,7 +366,7 @@ bn_mul_words: */ bn_sqr_words: sra %o2,%g0,%o2 ! signx %o2 - brgz,a %o2,.L_bn_sqr_words_proceeed + brgz,a %o2,.L_bn_sqr_words_proceed lduw [%o1],%g2 retl clr %o0 @@ -378,7 +374,7 @@ bn_sqr_words: nop nop -.L_bn_sqr_words_proceeed: +.L_bn_sqr_words_proceed: andcc %o2,-4,%g0 nop bz,pn %icc,.L_bn_sqr_words_tail diff --git a/crypto/bn/asm/sparcv9-mont.pl b/crypto/bn/asm/sparcv9-mont.pl index 6807c8b6..44d28ac4 100644 --- a/crypto/bn/asm/sparcv9-mont.pl +++ b/crypto/bn/asm/sparcv9-mont.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -611,7 +611,7 @@ $code.=<<___; add $tp,8,$tp .type $fname,#function .size $fname,(.-$fname) -.asciz "Montgomery Multipltication for SPARCv9, CRYPTOGAMS by " +.asciz "Montgomery Multiplication for SPARCv9, CRYPTOGAMS by " .align 32 ___ $code =~ s/\`([^\`]*)\`/eval($1)/gem; diff --git a/crypto/bn/asm/sparcv9a-mont.pl b/crypto/bn/asm/sparcv9a-mont.pl index 50b69065..c8f759df 100755 --- a/crypto/bn/asm/sparcv9a-mont.pl +++ b/crypto/bn/asm/sparcv9a-mont.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -865,7 +865,7 @@ $fname: restore .type $fname,#function .size $fname,(.-$fname) -.asciz "Montgomery Multipltication for UltraSPARC, CRYPTOGAMS by " +.asciz "Montgomery Multiplication for UltraSPARC, CRYPTOGAMS by " .align 32 ___ diff --git a/crypto/bn/asm/via-mont.pl b/crypto/bn/asm/via-mont.pl index 9f81bc82..eaac4dd6 100644 --- a/crypto/bn/asm/via-mont.pl +++ b/crypto/bn/asm/via-mont.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -76,7 +76,7 @@ # dsa 1024 bits 0.001346s 0.001595s 742.7 627.0 # dsa 2048 bits 0.004745s 0.005582s 210.7 179.1 # -# Conclusions: +# Conclusions: # - VIA SDK leaves a *lot* of room for improvement (which this # implementation successfully fills:-); # - 'rep montmul' gives up to >3x performance improvement depending on @@ -91,7 +91,7 @@ require "x86asm.pl"; $output = pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"via-mont.pl"); +&asm_init($ARGV[0]); # int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np,const BN_ULONG *n0, int num); $func="bn_mul_mont_padlock"; diff --git a/crypto/bn/asm/vis3-mont.pl b/crypto/bn/asm/vis3-mont.pl index 64dba448..04694a4c 100644 --- a/crypto/bn/asm/vis3-mont.pl +++ b/crypto/bn/asm/vis3-mont.pl @@ -16,7 +16,7 @@ # October 2012. # -# SPARCv9 VIS3 Montgomery multiplicaion procedure suitable for T3 and +# SPARCv9 VIS3 Montgomery multiplication procedure suitable for T3 and # onward. There are three new instructions used here: umulxhi, # addxc[cc] and initializing store. On T3 RSA private key operations # are 1.54/1.87/2.11/2.26 times faster for 512/1024/2048/4096-bit key diff --git a/crypto/bn/asm/x86-gf2m.pl b/crypto/bn/asm/x86-gf2m.pl index f4643687..d03efcc7 100644 --- a/crypto/bn/asm/x86-gf2m.pl +++ b/crypto/bn/asm/x86-gf2m.pl @@ -46,7 +46,7 @@ require "x86asm.pl"; $output = pop; open STDOUT,">$output"; -&asm_init($ARGV[0],$0,$x86only = $ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$x86only = $ARGV[$#ARGV] eq "386"); $sse2=0; for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } @@ -152,7 +152,7 @@ $R="mm0"; &xor ($a4,$a2); # a2=a4^a2^a4 &mov (&DWP(5*4,"esp"),$a1); # a1^a4 &xor ($a4,$a1); # a1^a2^a4 - &sar (@i[1],31); # broardcast 30th bit + &sar (@i[1],31); # broadcast 30th bit &and ($lo,$b); &mov (&DWP(6*4,"esp"),$a2); # a2^a4 &and (@i[1],$b); diff --git a/crypto/bn/asm/x86-mont.pl b/crypto/bn/asm/x86-mont.pl index 67875036..66997e27 100755 --- a/crypto/bn/asm/x86-mont.pl +++ b/crypto/bn/asm/x86-mont.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -39,8 +39,8 @@ require "x86asm.pl"; $output = pop; open STDOUT,">$output"; - -&asm_init($ARGV[0],$0); + +&asm_init($ARGV[0]); $sse2=0; for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } @@ -78,7 +78,7 @@ $frame=32; # size of above frame rounded up to 16n &lea ("ebp",&DWP(-$frame,"esp","edi",4)); # future alloca($frame+4*(num+2)) &neg ("edi"); - # minimize cache contention by arraning 2K window between stack + # minimize cache contention by arranging 2K window between stack # pointer and ap argument [np is also position sensitive vector, # but it's assumed to be near ap, as it's allocated at ~same # time]. diff --git a/crypto/bn/asm/x86_64-gcc.c b/crypto/bn/asm/x86_64-gcc.c index 0ff3805a..d38f3371 100644 --- a/crypto/bn/asm/x86_64-gcc.c +++ b/crypto/bn/asm/x86_64-gcc.c @@ -14,7 +14,7 @@ /*- * x86_64 BIGNUM accelerator version 0.1, December 2002. * - * Implemented by Andy Polyakov for the OpenSSL + * Implemented by Andy Polyakov for the OpenSSL * project. * * Rights for redistribution and usage in source and binary forms are @@ -120,7 +120,7 @@ BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG c1 = 0; if (num <= 0) - return (c1); + return c1; while (num & ~3) { mul_add(rp[0], ap[0], w, c1); @@ -142,7 +142,7 @@ BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, return c1; } - return (c1); + return c1; } BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) @@ -150,7 +150,7 @@ BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) BN_ULONG c1 = 0; if (num <= 0) - return (c1); + return c1; while (num & ~3) { mul(rp[0], ap[0], w, c1); @@ -170,7 +170,7 @@ BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) return c1; mul(rp[2], ap[2], w, c1); } - return (c1); + return c1; } void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, int n) @@ -270,7 +270,7 @@ BN_ULONG bn_sub_words(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) int c = 0; if (n <= 0) - return ((BN_ULONG)0); + return (BN_ULONG)0; for (;;) { t1 = a[0]; @@ -309,7 +309,7 @@ BN_ULONG bn_sub_words(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) b += 4; r += 4; } - return (c); + return c; } # endif diff --git a/crypto/bn/asm/x86_64-gf2m.pl b/crypto/bn/asm/x86_64-gf2m.pl index d962f620..0fd6e985 100644 --- a/crypto/bn/asm/x86_64-gf2m.pl +++ b/crypto/bn/asm/x86_64-gf2m.pl @@ -54,7 +54,9 @@ $code.=<<___; .type _mul_1x1,\@abi-omnipotent .align 16 _mul_1x1: +.cfi_startproc sub \$128+8,%rsp +.cfi_adjust_cfa_offset 128+8 mov \$-1,$a1 lea ($a,$a),$i0 shr \$3,$a1 @@ -66,7 +68,7 @@ _mul_1x1: sar \$63,$i0 # broadcast 62nd bit lea (,$a1,4),$a4 and $b,$a - sar \$63,$i1 # boardcast 61st bit + sar \$63,$i1 # broadcast 61st bit mov $a,$hi # $a is $lo shl \$63,$lo and $b,$i0 @@ -160,8 +162,10 @@ $code.=<<___; xor $i1,$hi add \$128+8,%rsp +.cfi_adjust_cfa_offset -128-8 ret .Lend_mul_1x1: +.cfi_endproc .size _mul_1x1,.-_mul_1x1 ___ @@ -174,8 +178,10 @@ $code.=<<___; .type bn_GF2m_mul_2x2,\@abi-omnipotent .align 16 bn_GF2m_mul_2x2: - mov OPENSSL_ia32cap_P(%rip),%rax - bt \$33,%rax +.cfi_startproc + mov %rsp,%rax + mov OPENSSL_ia32cap_P(%rip),%r10 + bt \$33,%r10 jnc .Lvanilla_mul_2x2 movq $a1,%xmm0 @@ -210,6 +216,7 @@ $code.=<<___; .align 16 .Lvanilla_mul_2x2: lea -8*17(%rsp),%rsp +.cfi_adjust_cfa_offset 8*17 ___ $code.=<<___ if ($win64); mov `8*17+40`(%rsp),$b0 @@ -218,10 +225,15 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov %r14,8*10(%rsp) +.cfi_rel_offset %r14,8*10 mov %r13,8*11(%rsp) +.cfi_rel_offset %r13,8*11 mov %r12,8*12(%rsp) +.cfi_rel_offset %r12,8*12 mov %rbp,8*13(%rsp) +.cfi_rel_offset %rbp,8*13 mov %rbx,8*14(%rsp) +.cfi_rel_offset %rbx,8*14 .Lbody_mul_2x2: mov $rp,32(%rsp) # save the arguments mov $a1,40(%rsp) @@ -269,10 +281,15 @@ $code.=<<___; mov $lo,8(%rbp) mov 8*10(%rsp),%r14 +.cfi_restore %r14 mov 8*11(%rsp),%r13 +.cfi_restore %r13 mov 8*12(%rsp),%r12 +.cfi_restore %r12 mov 8*13(%rsp),%rbp +.cfi_restore %rbp mov 8*14(%rsp),%rbx +.cfi_restore %rbx ___ $code.=<<___ if ($win64); mov 8*15(%rsp),%rdi @@ -280,8 +297,11 @@ $code.=<<___ if ($win64); ___ $code.=<<___; lea 8*17(%rsp),%rsp +.cfi_adjust_cfa_offset -8*17 +.Lepilogue_mul_2x2: ret .Lend_mul_2x2: +.cfi_endproc .size bn_GF2m_mul_2x2,.-bn_GF2m_mul_2x2 .asciz "GF(2^m) Multiplication for x86_64, CRYPTOGAMS by " .align 16 @@ -312,13 +332,19 @@ se_handler: pushfq sub \$64,%rsp - mov 152($context),%rax # pull context->Rsp + mov 120($context),%rax # pull context->Rax mov 248($context),%rbx # pull context->Rip lea .Lbody_mul_2x2(%rip),%r10 cmp %r10,%rbx # context->Rip<"prologue" label jb .Lin_prologue + mov 152($context),%rax # pull context->Rsp + + lea .Lepilogue_mul_2x2(%rip),%r10 + cmp %r10,%rbx # context->Rip>="epilogue" label + jae .Lin_prologue + mov 8*10(%rax),%r14 # mimic epilogue mov 8*11(%rax),%r13 mov 8*12(%rax),%r12 @@ -335,8 +361,9 @@ se_handler: mov %r13,224($context) # restore context->R13 mov %r14,232($context) # restore context->R14 -.Lin_prologue: lea 8*17(%rax),%rax + +.Lin_prologue: mov %rax,152($context) # restore context->Rsp mov 40($disp),%rdi # disp->ContextRecord diff --git a/crypto/bn/asm/x86_64-mont.pl b/crypto/bn/asm/x86_64-mont.pl index df4cca5b..7e6e9027 100755 --- a/crypto/bn/asm/x86_64-mont.pl +++ b/crypto/bn/asm/x86_64-mont.pl @@ -104,8 +104,10 @@ $code=<<___; .type bn_mul_mont,\@function,6 .align 16 bn_mul_mont: +.cfi_startproc mov ${num}d,${num}d mov %rsp,%rax +.cfi_def_cfa_register %rax test \$3,${num}d jnz .Lmul_enter cmp \$8,${num}d @@ -124,11 +126,17 @@ $code.=<<___; .align 16 .Lmul_enter: push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 neg $num mov %rsp,%r11 @@ -161,6 +169,7 @@ $code.=<<___; .Lmul_page_walk_done: mov %rax,8(%rsp,$num,8) # tp[num+1]=%rsp +.cfi_cfa_expression %rsp+8,$num,8,mul,plus,deref,+8 .Lmul_body: mov $bp,%r12 # reassign $bp ___ @@ -310,7 +319,7 @@ $code.=<<___; mov %rax,($rp,$i,8) # rp[i]=tp[i]-np[i] mov 8($ap,$i,8),%rax # tp[i+1] lea 1($i),$i # i++ - dec $j # doesnn't affect CF! + dec $j # doesn't affect CF! jnz .Lsub sbb \$0,%rax # handle upmost overflow bit @@ -331,16 +340,25 @@ $code.=<<___; jnz .Lcopy mov 8(%rsp,$num,8),%rsi # restore %rsp +.cfi_def_cfa %rsi,8 mov \$1,%rax mov -48(%rsi),%r15 +.cfi_restore %r15 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lmul_epilogue: ret +.cfi_endproc .size bn_mul_mont,.-bn_mul_mont ___ {{{ @@ -350,8 +368,10 @@ $code.=<<___; .type bn_mul4x_mont,\@function,6 .align 16 bn_mul4x_mont: +.cfi_startproc mov ${num}d,${num}d mov %rsp,%rax +.cfi_def_cfa_register %rax .Lmul4x_enter: ___ $code.=<<___ if ($addx); @@ -361,11 +381,17 @@ $code.=<<___ if ($addx); ___ $code.=<<___; push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 neg $num mov %rsp,%r11 @@ -389,6 +415,7 @@ $code.=<<___; .Lmul4x_page_walk_done: mov %rax,8(%rsp,$num,8) # tp[num+1]=%rsp +.cfi_cfa_expression %rsp+8,$num,8,mul,plus,deref,+8 .Lmul4x_body: mov $rp,16(%rsp,$num,8) # tp[num+2]=$rp mov %rdx,%r12 # reassign $bp @@ -695,10 +722,11 @@ ___ my @ri=("%rax","%rdx",$m0,$m1); $code.=<<___; mov 16(%rsp,$num,8),$rp # restore $rp + lea -4($num),$j mov 0(%rsp),@ri[0] # tp[0] pxor %xmm0,%xmm0 mov 8(%rsp),@ri[1] # tp[1] - shr \$2,$num # num/=4 + shr \$2,$j # j=num/4-1 lea (%rsp),$ap # borrow ap for tp xor $i,$i # i=0 and clear CF! @@ -706,7 +734,6 @@ $code.=<<___; mov 16($ap),@ri[2] # tp[2] mov 24($ap),@ri[3] # tp[3] sbb 8($np),@ri[1] - lea -1($num),$j # j=num/4-1 jmp .Lsub4x .align 16 .Lsub4x: @@ -723,7 +750,7 @@ $code.=<<___; mov 56($ap,$i,8),@ri[3] sbb 40($np,$i,8),@ri[1] lea 4($i),$i # i++ - dec $j # doesnn't affect CF! + dec $j # doesn't affect CF! jnz .Lsub4x mov @ri[0],0($rp,$i,8) # rp[i]=tp[i]-np[i] @@ -740,8 +767,9 @@ $code.=<<___; not @ri[0] mov $rp,$np and @ri[0],$np - lea -1($num),$j + lea -4($num),$j or $np,$ap # ap=borrow?tp:rp + shr \$2,$j # j=num/4-1 movdqu ($ap),%xmm1 movdqa %xmm0,(%rsp) @@ -759,7 +787,6 @@ $code.=<<___; dec $j jnz .Lcopy4x - shl \$2,$num movdqu 16($ap,$i),%xmm2 movdqa %xmm0,16(%rsp,$i) movdqu %xmm2,16($rp,$i) @@ -767,16 +794,25 @@ ___ } $code.=<<___; mov 8(%rsp,$num,8),%rsi # restore %rsp +.cfi_def_cfa %rsi, 8 mov \$1,%rax mov -48(%rsi),%r15 +.cfi_restore %r15 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lmul4x_epilogue: ret +.cfi_endproc .size bn_mul4x_mont,.-bn_mul4x_mont ___ }}} @@ -804,14 +840,22 @@ $code.=<<___; .type bn_sqr8x_mont,\@function,6 .align 32 bn_sqr8x_mont: +.cfi_startproc mov %rsp,%rax +.cfi_def_cfa_register %rax .Lsqr8x_enter: push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lsqr8x_prologue: mov ${num}d,%r10d @@ -867,6 +911,7 @@ bn_sqr8x_mont: mov $n0, 32(%rsp) mov %rax, 40(%rsp) # save original %rsp +.cfi_cfa_expression %rsp+40,deref,+8 .Lsqr8x_body: movq $nptr, %xmm2 # save pointer to modulus @@ -936,6 +981,7 @@ $code.=<<___; pxor %xmm0,%xmm0 pshufd \$0,%xmm1,%xmm1 mov 40(%rsp),%rsi # restore %rsp +.cfi_def_cfa %rsi,8 jmp .Lsqr8x_cond_copy .align 32 @@ -965,14 +1011,22 @@ $code.=<<___; mov \$1,%rax mov -48(%rsi),%r15 +.cfi_restore %r15 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lsqr8x_epilogue: ret +.cfi_endproc .size bn_sqr8x_mont,.-bn_sqr8x_mont ___ }}} @@ -984,14 +1038,22 @@ $code.=<<___; .type bn_mulx4x_mont,\@function,6 .align 32 bn_mulx4x_mont: +.cfi_startproc mov %rsp,%rax +.cfi_def_cfa_register %rax .Lmulx4x_enter: push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lmulx4x_prologue: shl \$3,${num}d # convert $num to bytes @@ -1037,6 +1099,7 @@ bn_mulx4x_mont: mov $n0, 24(%rsp) # save *n0 mov $rp, 32(%rsp) # save $rp mov %rax,40(%rsp) # save original %rsp +.cfi_cfa_expression %rsp+40,deref,+8 mov $num,48(%rsp) # inner counter jmp .Lmulx4x_body @@ -1286,6 +1349,7 @@ $code.=<<___; pxor %xmm0,%xmm0 pshufd \$0,%xmm1,%xmm1 mov 40(%rsp),%rsi # restore %rsp +.cfi_def_cfa %rsi,8 jmp .Lmulx4x_cond_copy .align 32 @@ -1315,14 +1379,22 @@ $code.=<<___; mov \$1,%rax mov -48(%rsi),%r15 +.cfi_restore %r15 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lmulx4x_epilogue: ret +.cfi_endproc .size bn_mulx4x_mont,.-bn_mulx4x_mont ___ }}} @@ -1401,12 +1473,12 @@ sqr_handler: mov 0(%r11),%r10d # HandlerData[0] lea (%rsi,%r10),%r10 # end of prologue label - cmp %r10,%rbx # context->Rip<.Lsqr_body + cmp %r10,%rbx # context->Rip<.Lsqr_prologue jb .Lcommon_seh_tail mov 4(%r11),%r10d # HandlerData[1] lea (%rsi,%r10),%r10 # body label - cmp %r10,%rbx # context->Rip>=.Lsqr_epilogue + cmp %r10,%rbx # context->Rip<.Lsqr_body jb .Lcommon_pop_regs mov 152($context),%rax # pull context->Rsp diff --git a/crypto/bn/asm/x86_64-mont5.pl b/crypto/bn/asm/x86_64-mont5.pl index 5779059e..26354357 100755 --- a/crypto/bn/asm/x86_64-mont5.pl +++ b/crypto/bn/asm/x86_64-mont5.pl @@ -93,8 +93,10 @@ $code=<<___; .type bn_mul_mont_gather5,\@function,6 .align 64 bn_mul_mont_gather5: +.cfi_startproc mov ${num}d,${num}d mov %rsp,%rax +.cfi_def_cfa_register %rax test \$7,${num}d jnz .Lmul_enter ___ @@ -108,11 +110,17 @@ $code.=<<___; .Lmul_enter: movd `($win64?56:8)`(%rsp),%xmm5 # load 7th argument push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 neg $num mov %rsp,%r11 @@ -145,6 +153,7 @@ $code.=<<___; lea .Linc(%rip),%r10 mov %rax,8(%rsp,$num,8) # tp[num+1]=%rsp +.cfi_cfa_expression %rsp+8,$num,8,mul,plus,deref,+8 .Lmul_body: lea 128($bp),%r12 # reassign $bp (+size optimization) @@ -410,7 +419,7 @@ $code.=<<___; mov %rax,($rp,$i,8) # rp[i]=tp[i]-np[i] mov 8($ap,$i,8),%rax # tp[i+1] lea 1($i),$i # i++ - dec $j # doesnn't affect CF! + dec $j # doesn't affect CF! jnz .Lsub sbb \$0,%rax # handle upmost overflow bit @@ -431,17 +440,26 @@ $code.=<<___; jnz .Lcopy mov 8(%rsp,$num,8),%rsi # restore %rsp +.cfi_def_cfa %rsi,8 mov \$1,%rax mov -48(%rsi),%r15 +.cfi_restore %r15 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lmul_epilogue: ret +.cfi_endproc .size bn_mul_mont_gather5,.-bn_mul_mont_gather5 ___ {{{ @@ -451,8 +469,10 @@ $code.=<<___; .type bn_mul4x_mont_gather5,\@function,6 .align 32 bn_mul4x_mont_gather5: +.cfi_startproc .byte 0x67 mov %rsp,%rax +.cfi_def_cfa_register %rax .Lmul4x_enter: ___ $code.=<<___ if ($addx); @@ -462,11 +482,17 @@ $code.=<<___ if ($addx); ___ $code.=<<___; push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lmul4x_prologue: .byte 0x67 @@ -522,22 +548,32 @@ $code.=<<___; neg $num mov %rax,40(%rsp) +.cfi_cfa_expression %rsp+40,deref,+8 .Lmul4x_body: call mul4x_internal mov 40(%rsp),%rsi # restore %rsp +.cfi_def_cfa %rsi,8 mov \$1,%rax mov -48(%rsi),%r15 +.cfi_restore %r15 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lmul4x_epilogue: ret +.cfi_endproc .size bn_mul4x_mont_gather5,.-bn_mul4x_mont_gather5 .type mul4x_internal,\@abi-omnipotent @@ -1049,7 +1085,7 @@ my $bptr="%rdx"; # const void *table, my $nptr="%rcx"; # const BN_ULONG *nptr, my $n0 ="%r8"; # const BN_ULONG *n0); my $num ="%r9"; # int num, has to be divisible by 8 - # int pwr + # int pwr my ($i,$j,$tptr)=("%rbp","%rcx",$rptr); my @A0=("%r10","%r11"); @@ -1061,7 +1097,9 @@ $code.=<<___; .type bn_power5,\@function,6 .align 32 bn_power5: +.cfi_startproc mov %rsp,%rax +.cfi_def_cfa_register %rax ___ $code.=<<___ if ($addx); mov OPENSSL_ia32cap_P+8(%rip),%r11d @@ -1071,11 +1109,17 @@ $code.=<<___ if ($addx); ___ $code.=<<___; push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lpower5_prologue: shl \$3,${num}d # convert $num to bytes @@ -1126,7 +1170,7 @@ $code.=<<___; ja .Lpwr_page_walk .Lpwr_page_walk_done: - mov $num,%r10 + mov $num,%r10 neg $num ############################################################## @@ -1140,6 +1184,7 @@ $code.=<<___; # mov $n0, 32(%rsp) mov %rax, 40(%rsp) # save original %rsp +.cfi_cfa_expression %rsp+40,deref,+8 .Lpower5_body: movq $rptr,%xmm1 # save $rptr, used in sqr8x movq $nptr,%xmm2 # save $nptr @@ -1166,16 +1211,25 @@ $code.=<<___; call mul4x_internal mov 40(%rsp),%rsi # restore %rsp +.cfi_def_cfa %rsi,8 mov \$1,%rax mov -48(%rsi),%r15 +.cfi_restore %r15 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lpower5_epilogue: ret +.cfi_endproc .size bn_power5,.-bn_power5 .globl bn_sqr8x_internal @@ -2035,7 +2089,7 @@ __bn_post4x_internal: jnz .Lsqr4x_sub mov $num,%r10 # prepare for back-to-back call - neg $num # restore $num + neg $num # restore $num ret .size __bn_post4x_internal,.-__bn_post4x_internal ___ @@ -2055,14 +2109,22 @@ bn_from_montgomery: .type bn_from_mont8x,\@function,6 .align 32 bn_from_mont8x: +.cfi_startproc .byte 0x67 mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lfrom_prologue: shl \$3,${num}d # convert $num to bytes @@ -2127,6 +2189,7 @@ bn_from_mont8x: # mov $n0, 32(%rsp) mov %rax, 40(%rsp) # save original %rsp +.cfi_cfa_expression %rsp+40,deref,+8 .Lfrom_body: mov $num,%r11 lea 48(%rsp),%rax @@ -2170,7 +2233,6 @@ $code.=<<___ if ($addx); pxor %xmm0,%xmm0 lea 48(%rsp),%rax - mov 40(%rsp),%rsi # restore %rsp jmp .Lfrom_mont_zero .align 32 @@ -2182,11 +2244,12 @@ $code.=<<___; pxor %xmm0,%xmm0 lea 48(%rsp),%rax - mov 40(%rsp),%rsi # restore %rsp jmp .Lfrom_mont_zero .align 32 .Lfrom_mont_zero: + mov 40(%rsp),%rsi # restore %rsp +.cfi_def_cfa %rsi,8 movdqa %xmm0,16*0(%rax) movdqa %xmm0,16*1(%rax) movdqa %xmm0,16*2(%rax) @@ -2197,14 +2260,22 @@ $code.=<<___; mov \$1,%rax mov -48(%rsi),%r15 +.cfi_restore %r15 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lfrom_epilogue: ret +.cfi_endproc .size bn_from_mont8x,.-bn_from_mont8x ___ } @@ -2217,14 +2288,22 @@ $code.=<<___; .type bn_mulx4x_mont_gather5,\@function,6 .align 32 bn_mulx4x_mont_gather5: +.cfi_startproc mov %rsp,%rax +.cfi_def_cfa_register %rax .Lmulx4x_enter: push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lmulx4x_prologue: shl \$3,${num}d # convert $num to bytes @@ -2258,7 +2337,7 @@ bn_mulx4x_mont_gather5: mov \$0,%r10 cmovc %r10,%r11 sub %r11,%rbp -.Lmulx4xsp_done: +.Lmulx4xsp_done: and \$-64,%rbp # ensure alignment mov %rsp,%r11 sub %rbp,%r11 @@ -2290,21 +2369,31 @@ bn_mulx4x_mont_gather5: # mov $n0, 32(%rsp) # save *n0 mov %rax,40(%rsp) # save original %rsp +.cfi_cfa_expression %rsp+40,deref,+8 .Lmulx4x_body: call mulx4x_internal mov 40(%rsp),%rsi # restore %rsp +.cfi_def_cfa %rsi,8 mov \$1,%rax mov -48(%rsi),%r15 +.cfi_restore %r15 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lmulx4x_epilogue: ret +.cfi_endproc .size bn_mulx4x_mont_gather5,.-bn_mulx4x_mont_gather5 .type mulx4x_internal,\@abi-omnipotent @@ -2332,7 +2421,7 @@ my $N=$STRIDE/4; # should match cache line size $code.=<<___; movdqa 0(%rax),%xmm0 # 00000001000000010000000000000000 movdqa 16(%rax),%xmm1 # 00000002000000020000000200000002 - lea 88-112(%rsp,%r10),%r10 # place the mask after tp[num+1] (+ICache optimizaton) + lea 88-112(%rsp,%r10),%r10 # place the mask after tp[num+1] (+ICache optimization) lea 128($bp),$bptr # size optimization pshufd \$0,%xmm5,%xmm5 # broadcast index @@ -2682,14 +2771,22 @@ $code.=<<___; .type bn_powerx5,\@function,6 .align 32 bn_powerx5: +.cfi_startproc mov %rsp,%rax +.cfi_def_cfa_register %rax .Lpowerx5_enter: push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lpowerx5_prologue: shl \$3,${num}d # convert $num to bytes @@ -2740,7 +2837,7 @@ bn_powerx5: ja .Lpwrx_page_walk .Lpwrx_page_walk_done: - mov $num,%r10 + mov $num,%r10 neg $num ############################################################## @@ -2761,6 +2858,7 @@ bn_powerx5: movq $bptr,%xmm4 mov $n0, 32(%rsp) mov %rax, 40(%rsp) # save original %rsp +.cfi_cfa_expression %rsp+40,deref,+8 .Lpowerx5_body: call __bn_sqrx8x_internal @@ -2783,17 +2881,26 @@ bn_powerx5: call mulx4x_internal mov 40(%rsp),%rsi # restore %rsp +.cfi_def_cfa %rsi,8 mov \$1,%rax mov -48(%rsi),%r15 +.cfi_restore %r15 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lpowerx5_epilogue: ret +.cfi_endproc .size bn_powerx5,.-bn_powerx5 .globl bn_sqrx8x_internal @@ -3677,8 +3784,8 @@ mul_handler: jb .Lcommon_seh_tail mov 4(%r11),%r10d # HandlerData[1] - lea (%rsi,%r10),%r10 # epilogue label - cmp %r10,%rbx # context->Rip>=epilogue label + lea (%rsi,%r10),%r10 # beginning of body label + cmp %r10,%rbx # context->RipRsp diff --git a/crypto/bn/bn_asm.c b/crypto/bn/bn_asm.c index 39c6c213..729b2480 100644 --- a/crypto/bn/bn_asm.c +++ b/crypto/bn/bn_asm.c @@ -21,7 +21,7 @@ BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, assert(num >= 0); if (num <= 0) - return (c1); + return c1; # ifndef OPENSSL_SMALL_FOOTPRINT while (num & ~3) { @@ -41,7 +41,7 @@ BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, num--; } - return (c1); + return c1; } BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) @@ -50,7 +50,7 @@ BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) assert(num >= 0); if (num <= 0) - return (c1); + return c1; # ifndef OPENSSL_SMALL_FOOTPRINT while (num & ~3) { @@ -69,7 +69,7 @@ BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) rp++; num--; } - return (c1); + return c1; } void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, int n) @@ -108,7 +108,7 @@ BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, assert(num >= 0); if (num <= 0) - return ((BN_ULONG)0); + return (BN_ULONG)0; bl = LBITS(w); bh = HBITS(w); @@ -130,7 +130,7 @@ BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, rp++; num--; } - return (c); + return c; } BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) @@ -140,7 +140,7 @@ BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) assert(num >= 0); if (num <= 0) - return ((BN_ULONG)0); + return (BN_ULONG)0; bl = LBITS(w); bh = HBITS(w); @@ -162,7 +162,7 @@ BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) rp++; num--; } - return (carry); + return carry; } void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, int n) @@ -210,7 +210,7 @@ BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) int i, count = 2; if (d == 0) - return (BN_MASK2); + return BN_MASK2; i = BN_num_bits_word(d); assert((i == BN_BITS2) || (h <= (BN_ULONG)1 << i)); @@ -264,7 +264,7 @@ BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) l = (l & BN_MASK2l) << BN_BITS4; } ret |= q; - return (ret); + return ret; } #endif /* !defined(BN_LLONG) && defined(BN_DIV2W) */ @@ -276,7 +276,7 @@ BN_ULONG bn_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, assert(n >= 0); if (n <= 0) - return ((BN_ULONG)0); + return (BN_ULONG)0; # ifndef OPENSSL_SMALL_FOOTPRINT while (n & ~3) { @@ -307,7 +307,7 @@ BN_ULONG bn_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, r++; n--; } - return ((BN_ULONG)ll); + return (BN_ULONG)ll; } #else /* !BN_LLONG */ BN_ULONG bn_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, @@ -317,7 +317,7 @@ BN_ULONG bn_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, assert(n >= 0); if (n <= 0) - return ((BN_ULONG)0); + return (BN_ULONG)0; c = 0; # ifndef OPENSSL_SMALL_FOOTPRINT @@ -364,7 +364,7 @@ BN_ULONG bn_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, r++; n--; } - return ((BN_ULONG)c); + return (BN_ULONG)c; } #endif /* !BN_LLONG */ @@ -376,7 +376,7 @@ BN_ULONG bn_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, assert(n >= 0); if (n <= 0) - return ((BN_ULONG)0); + return (BN_ULONG)0; #ifndef OPENSSL_SMALL_FOOTPRINT while (n & ~3) { @@ -417,7 +417,7 @@ BN_ULONG bn_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, r++; n--; } - return (c); + return c; } #if defined(BN_MUL_COMBA) && !defined(OPENSSL_SMALL_FOOTPRINT) diff --git a/crypto/bn/bn_blind.c b/crypto/bn/bn_blind.c index 24d13830..006ad6e5 100644 --- a/crypto/bn/bn_blind.c +++ b/crypto/bn/bn_blind.c @@ -119,7 +119,7 @@ int BN_BLINDING_update(BN_BLINDING *b, BN_CTX *ctx) err: if (b->counter == BN_BLINDING_COUNTER) b->counter = 0; - return (ret); + return ret; } int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx) @@ -135,14 +135,14 @@ int BN_BLINDING_convert_ex(BIGNUM *n, BIGNUM *r, BN_BLINDING *b, BN_CTX *ctx) if ((b->A == NULL) || (b->Ai == NULL)) { BNerr(BN_F_BN_BLINDING_CONVERT_EX, BN_R_NOT_INITIALIZED); - return (0); + return 0; } if (b->counter == -1) /* Fresh blinding, doesn't need updating. */ b->counter = 0; else if (!BN_BLINDING_update(b, ctx)) - return (0); + return 0; if (r != NULL) { if (!BN_copy(r, b->Ai)) @@ -172,13 +172,13 @@ int BN_BLINDING_invert_ex(BIGNUM *n, const BIGNUM *r, BN_BLINDING *b, else { if (b->Ai == NULL) { BNerr(BN_F_BN_BLINDING_INVERT_EX, BN_R_NOT_INITIALIZED); - return (0); + return 0; } ret = BN_mod_mul(n, n, b->Ai, b->mod, ctx); } bn_check_top(n); - return (ret); + return ret; } int BN_BLINDING_is_current_thread(BN_BLINDING *b) diff --git a/crypto/bn/bn_dh.c b/crypto/bn/bn_dh.c index 17d05597..38acdee2 100644 --- a/crypto/bn/bn_dh.c +++ b/crypto/bn/bn_dh.c @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2014-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 @@ -8,7 +8,7 @@ */ #include "bn_lcl.h" -#include "e_os.h" +#include "internal/nelem.h" #ifndef OPENSSL_NO_DH #include @@ -104,6 +104,146 @@ static const BN_ULONG dh2048_256_q[] = { 0x8CF83642A709A097ULL }; +/* Primes from RFC 7919 */ +static const BN_ULONG ffdhe2048_p[] = { + 0xFFFFFFFFFFFFFFFFULL, 0x886B423861285C97ULL, 0xC6F34A26C1B2EFFAULL, + 0xC58EF1837D1683B2ULL, 0x3BB5FCBC2EC22005ULL, 0xC3FE3B1B4C6FAD73ULL, + 0x8E4F1232EEF28183ULL, 0x9172FE9CE98583FFULL, 0xC03404CD28342F61ULL, + 0x9E02FCE1CDF7E2ECULL, 0x0B07A7C8EE0A6D70ULL, 0xAE56EDE76372BB19ULL, + 0x1D4F42A3DE394DF4ULL, 0xB96ADAB760D7F468ULL, 0xD108A94BB2C8E3FBULL, + 0xBC0AB182B324FB61ULL, 0x30ACCA4F483A797AULL, 0x1DF158A136ADE735ULL, + 0xE2A689DAF3EFE872ULL, 0x984F0C70E0E68B77ULL, 0xB557135E7F57C935ULL, + 0x856365553DED1AF3ULL, 0x2433F51F5F066ED0ULL, 0xD3DF1ED5D5FD6561ULL, + 0xF681B202AEC4617AULL, 0x7D2FE363630C75D8ULL, 0xCC939DCE249B3EF9ULL, + 0xA9E13641146433FBULL, 0xD8B9C583CE2D3695ULL, 0xAFDC5620273D3CF1ULL, + 0xADF85458A2BB4A9AULL, 0xFFFFFFFFFFFFFFFFULL +}; + +static const BN_ULONG ffdhe3072_p[] = { + 0xFFFFFFFFFFFFFFFFULL, 0x25E41D2B66C62E37ULL, 0x3C1B20EE3FD59D7CULL, + 0x0ABCD06BFA53DDEFULL, 0x1DBF9A42D5C4484EULL, 0xABC521979B0DEADAULL, + 0xE86D2BC522363A0DULL, 0x5CAE82AB9C9DF69EULL, 0x64F2E21E71F54BFFULL, + 0xF4FD4452E2D74DD3ULL, 0xB4130C93BC437944ULL, 0xAEFE130985139270ULL, + 0x598CB0FAC186D91CULL, 0x7AD91D2691F7F7EEULL, 0x61B46FC9D6E6C907ULL, + 0xBC34F4DEF99C0238ULL, 0xDE355B3B6519035BULL, 0x886B4238611FCFDCULL, + 0xC6F34A26C1B2EFFAULL, 0xC58EF1837D1683B2ULL, 0x3BB5FCBC2EC22005ULL, + 0xC3FE3B1B4C6FAD73ULL, 0x8E4F1232EEF28183ULL, 0x9172FE9CE98583FFULL, + 0xC03404CD28342F61ULL, 0x9E02FCE1CDF7E2ECULL, 0x0B07A7C8EE0A6D70ULL, + 0xAE56EDE76372BB19ULL, 0x1D4F42A3DE394DF4ULL, 0xB96ADAB760D7F468ULL, + 0xD108A94BB2C8E3FBULL, 0xBC0AB182B324FB61ULL, 0x30ACCA4F483A797AULL, + 0x1DF158A136ADE735ULL, 0xE2A689DAF3EFE872ULL, 0x984F0C70E0E68B77ULL, + 0xB557135E7F57C935ULL, 0x856365553DED1AF3ULL, 0x2433F51F5F066ED0ULL, + 0xD3DF1ED5D5FD6561ULL, 0xF681B202AEC4617AULL, 0x7D2FE363630C75D8ULL, + 0xCC939DCE249B3EF9ULL, 0xA9E13641146433FBULL, 0xD8B9C583CE2D3695ULL, + 0xAFDC5620273D3CF1ULL, 0xADF85458A2BB4A9AULL, 0xFFFFFFFFFFFFFFFFULL +}; + +static const BN_ULONG ffdhe4096_p[] = { + 0xFFFFFFFFFFFFFFFFULL, 0xC68A007E5E655F6AULL, 0x4DB5A851F44182E1ULL, + 0x8EC9B55A7F88A46BULL, 0x0A8291CDCEC97DCFULL, 0x2A4ECEA9F98D0ACCULL, + 0x1A1DB93D7140003CULL, 0x092999A333CB8B7AULL, 0x6DC778F971AD0038ULL, + 0xA907600A918130C4ULL, 0xED6A1E012D9E6832ULL, 0x7135C886EFB4318AULL, + 0x87F55BA57E31CC7AULL, 0x7763CF1D55034004ULL, 0xAC7D5F42D69F6D18ULL, + 0x7930E9E4E58857B6ULL, 0x6E6F52C3164DF4FBULL, 0x25E41D2B669E1EF1ULL, + 0x3C1B20EE3FD59D7CULL, 0x0ABCD06BFA53DDEFULL, 0x1DBF9A42D5C4484EULL, + 0xABC521979B0DEADAULL, 0xE86D2BC522363A0DULL, 0x5CAE82AB9C9DF69EULL, + 0x64F2E21E71F54BFFULL, 0xF4FD4452E2D74DD3ULL, 0xB4130C93BC437944ULL, + 0xAEFE130985139270ULL, 0x598CB0FAC186D91CULL, 0x7AD91D2691F7F7EEULL, + 0x61B46FC9D6E6C907ULL, 0xBC34F4DEF99C0238ULL, 0xDE355B3B6519035BULL, + 0x886B4238611FCFDCULL, 0xC6F34A26C1B2EFFAULL, 0xC58EF1837D1683B2ULL, + 0x3BB5FCBC2EC22005ULL, 0xC3FE3B1B4C6FAD73ULL, 0x8E4F1232EEF28183ULL, + 0x9172FE9CE98583FFULL, 0xC03404CD28342F61ULL, 0x9E02FCE1CDF7E2ECULL, + 0x0B07A7C8EE0A6D70ULL, 0xAE56EDE76372BB19ULL, 0x1D4F42A3DE394DF4ULL, + 0xB96ADAB760D7F468ULL, 0xD108A94BB2C8E3FBULL, 0xBC0AB182B324FB61ULL, + 0x30ACCA4F483A797AULL, 0x1DF158A136ADE735ULL, 0xE2A689DAF3EFE872ULL, + 0x984F0C70E0E68B77ULL, 0xB557135E7F57C935ULL, 0x856365553DED1AF3ULL, + 0x2433F51F5F066ED0ULL, 0xD3DF1ED5D5FD6561ULL, 0xF681B202AEC4617AULL, + 0x7D2FE363630C75D8ULL, 0xCC939DCE249B3EF9ULL, 0xA9E13641146433FBULL, + 0xD8B9C583CE2D3695ULL, 0xAFDC5620273D3CF1ULL, 0xADF85458A2BB4A9AULL, + 0xFFFFFFFFFFFFFFFFULL +}; + +static const BN_ULONG ffdhe6144_p[] = { + 0xFFFFFFFFFFFFFFFFULL, 0xA40E329CD0E40E65ULL, 0xA41D570D7938DAD4ULL, + 0x62A69526D43161C1ULL, 0x3FDD4A8E9ADB1E69ULL, 0x5B3B71F9DC6B80D6ULL, + 0xEC9D1810C6272B04ULL, 0x8CCF2DD5CACEF403ULL, 0xE49F5235C95B9117ULL, + 0x505DC82DB854338AULL, 0x62292C311562A846ULL, 0xD72B03746AE77F5EULL, + 0xF9C9091B462D538CULL, 0x0AE8DB5847A67CBEULL, 0xB3A739C122611682ULL, + 0xEEAAC0232A281BF6ULL, 0x94C6651E77CAF992ULL, 0x763E4E4B94B2BBC1ULL, + 0x587E38DA0077D9B4ULL, 0x7FB29F8C183023C3ULL, 0x0ABEC1FFF9E3A26EULL, + 0xA00EF092350511E3ULL, 0xB855322EDB6340D8ULL, 0xA52471F7A9A96910ULL, + 0x388147FB4CFDB477ULL, 0x9B1F5C3E4E46041FULL, 0xCDAD0657FCCFEC71ULL, + 0xB38E8C334C701C3AULL, 0x917BDD64B1C0FD4CULL, 0x3BB454329B7624C8ULL, + 0x23BA4442CAF53EA6ULL, 0x4E677D2C38532A3AULL, 0x0BFD64B645036C7AULL, + 0xC68A007E5E0DD902ULL, 0x4DB5A851F44182E1ULL, 0x8EC9B55A7F88A46BULL, + 0x0A8291CDCEC97DCFULL, 0x2A4ECEA9F98D0ACCULL, 0x1A1DB93D7140003CULL, + 0x092999A333CB8B7AULL, 0x6DC778F971AD0038ULL, 0xA907600A918130C4ULL, + 0xED6A1E012D9E6832ULL, 0x7135C886EFB4318AULL, 0x87F55BA57E31CC7AULL, + 0x7763CF1D55034004ULL, 0xAC7D5F42D69F6D18ULL, 0x7930E9E4E58857B6ULL, + 0x6E6F52C3164DF4FBULL, 0x25E41D2B669E1EF1ULL, 0x3C1B20EE3FD59D7CULL, + 0x0ABCD06BFA53DDEFULL, 0x1DBF9A42D5C4484EULL, 0xABC521979B0DEADAULL, + 0xE86D2BC522363A0DULL, 0x5CAE82AB9C9DF69EULL, 0x64F2E21E71F54BFFULL, + 0xF4FD4452E2D74DD3ULL, 0xB4130C93BC437944ULL, 0xAEFE130985139270ULL, + 0x598CB0FAC186D91CULL, 0x7AD91D2691F7F7EEULL, 0x61B46FC9D6E6C907ULL, + 0xBC34F4DEF99C0238ULL, 0xDE355B3B6519035BULL, 0x886B4238611FCFDCULL, + 0xC6F34A26C1B2EFFAULL, 0xC58EF1837D1683B2ULL, 0x3BB5FCBC2EC22005ULL, + 0xC3FE3B1B4C6FAD73ULL, 0x8E4F1232EEF28183ULL, 0x9172FE9CE98583FFULL, + 0xC03404CD28342F61ULL, 0x9E02FCE1CDF7E2ECULL, 0x0B07A7C8EE0A6D70ULL, + 0xAE56EDE76372BB19ULL, 0x1D4F42A3DE394DF4ULL, 0xB96ADAB760D7F468ULL, + 0xD108A94BB2C8E3FBULL, 0xBC0AB182B324FB61ULL, 0x30ACCA4F483A797AULL, + 0x1DF158A136ADE735ULL, 0xE2A689DAF3EFE872ULL, 0x984F0C70E0E68B77ULL, + 0xB557135E7F57C935ULL, 0x856365553DED1AF3ULL, 0x2433F51F5F066ED0ULL, + 0xD3DF1ED5D5FD6561ULL, 0xF681B202AEC4617AULL, 0x7D2FE363630C75D8ULL, + 0xCC939DCE249B3EF9ULL, 0xA9E13641146433FBULL, 0xD8B9C583CE2D3695ULL, + 0xAFDC5620273D3CF1ULL, 0xADF85458A2BB4A9AULL, 0xFFFFFFFFFFFFFFFFULL +}; + +static const BN_ULONG ffdhe8192_p[] = { + 0xFFFFFFFFFFFFFFFFULL, 0xD68C8BB7C5C6424CULL, 0x011E2A94838FF88CULL, + 0x0822E506A9F4614EULL, 0x97D11D49F7A8443DULL, 0xA6BBFDE530677F0DULL, + 0x2F741EF8C1FE86FEULL, 0xFAFABE1C5D71A87EULL, 0xDED2FBABFBE58A30ULL, + 0xB6855DFE72B0A66EULL, 0x1EFC8CE0BA8A4FE8ULL, 0x83F81D4A3F2FA457ULL, + 0xA1FE3075A577E231ULL, 0xD5B8019488D9C0A0ULL, 0x624816CDAD9A95F9ULL, + 0x99E9E31650C1217BULL, 0x51AA691E0E423CFCULL, 0x1C217E6C3826E52CULL, + 0x51A8A93109703FEEULL, 0xBB7099876A460E74ULL, 0x541FC68C9C86B022ULL, + 0x59160CC046FD8251ULL, 0x2846C0BA35C35F5CULL, 0x54504AC78B758282ULL, + 0x29388839D2AF05E4ULL, 0xCB2C0F1CC01BD702ULL, 0x555B2F747C932665ULL, + 0x86B63142A3AB8829ULL, 0x0B8CC3BDF64B10EFULL, 0x687FEB69EDD1CC5EULL, + 0xFDB23FCEC9509D43ULL, 0x1E425A31D951AE64ULL, 0x36AD004CF600C838ULL, + 0xA40E329CCFF46AAAULL, 0xA41D570D7938DAD4ULL, 0x62A69526D43161C1ULL, + 0x3FDD4A8E9ADB1E69ULL, 0x5B3B71F9DC6B80D6ULL, 0xEC9D1810C6272B04ULL, + 0x8CCF2DD5CACEF403ULL, 0xE49F5235C95B9117ULL, 0x505DC82DB854338AULL, + 0x62292C311562A846ULL, 0xD72B03746AE77F5EULL, 0xF9C9091B462D538CULL, + 0x0AE8DB5847A67CBEULL, 0xB3A739C122611682ULL, 0xEEAAC0232A281BF6ULL, + 0x94C6651E77CAF992ULL, 0x763E4E4B94B2BBC1ULL, 0x587E38DA0077D9B4ULL, + 0x7FB29F8C183023C3ULL, 0x0ABEC1FFF9E3A26EULL, 0xA00EF092350511E3ULL, + 0xB855322EDB6340D8ULL, 0xA52471F7A9A96910ULL, 0x388147FB4CFDB477ULL, + 0x9B1F5C3E4E46041FULL, 0xCDAD0657FCCFEC71ULL, 0xB38E8C334C701C3AULL, + 0x917BDD64B1C0FD4CULL, 0x3BB454329B7624C8ULL, 0x23BA4442CAF53EA6ULL, + 0x4E677D2C38532A3AULL, 0x0BFD64B645036C7AULL, 0xC68A007E5E0DD902ULL, + 0x4DB5A851F44182E1ULL, 0x8EC9B55A7F88A46BULL, 0x0A8291CDCEC97DCFULL, + 0x2A4ECEA9F98D0ACCULL, 0x1A1DB93D7140003CULL, 0x092999A333CB8B7AULL, + 0x6DC778F971AD0038ULL, 0xA907600A918130C4ULL, 0xED6A1E012D9E6832ULL, + 0x7135C886EFB4318AULL, 0x87F55BA57E31CC7AULL, 0x7763CF1D55034004ULL, + 0xAC7D5F42D69F6D18ULL, 0x7930E9E4E58857B6ULL, 0x6E6F52C3164DF4FBULL, + 0x25E41D2B669E1EF1ULL, 0x3C1B20EE3FD59D7CULL, 0x0ABCD06BFA53DDEFULL, + 0x1DBF9A42D5C4484EULL, 0xABC521979B0DEADAULL, 0xE86D2BC522363A0DULL, + 0x5CAE82AB9C9DF69EULL, 0x64F2E21E71F54BFFULL, 0xF4FD4452E2D74DD3ULL, + 0xB4130C93BC437944ULL, 0xAEFE130985139270ULL, 0x598CB0FAC186D91CULL, + 0x7AD91D2691F7F7EEULL, 0x61B46FC9D6E6C907ULL, 0xBC34F4DEF99C0238ULL, + 0xDE355B3B6519035BULL, 0x886B4238611FCFDCULL, 0xC6F34A26C1B2EFFAULL, + 0xC58EF1837D1683B2ULL, 0x3BB5FCBC2EC22005ULL, 0xC3FE3B1B4C6FAD73ULL, + 0x8E4F1232EEF28183ULL, 0x9172FE9CE98583FFULL, 0xC03404CD28342F61ULL, + 0x9E02FCE1CDF7E2ECULL, 0x0B07A7C8EE0A6D70ULL, 0xAE56EDE76372BB19ULL, + 0x1D4F42A3DE394DF4ULL, 0xB96ADAB760D7F468ULL, 0xD108A94BB2C8E3FBULL, + 0xBC0AB182B324FB61ULL, 0x30ACCA4F483A797AULL, 0x1DF158A136ADE735ULL, + 0xE2A689DAF3EFE872ULL, 0x984F0C70E0E68B77ULL, 0xB557135E7F57C935ULL, + 0x856365553DED1AF3ULL, 0x2433F51F5F066ED0ULL, 0xD3DF1ED5D5FD6561ULL, + 0xF681B202AEC4617AULL, 0x7D2FE363630C75D8ULL, 0xCC939DCE249B3EF9ULL, + 0xA9E13641146433FBULL, 0xD8B9C583CE2D3695ULL, 0xAFDC5620273D3CF1ULL, + 0xADF85458A2BB4A9AULL, 0xFFFFFFFFFFFFFFFFULL +}; + # elif BN_BITS2 == 32 static const BN_ULONG dh1024_160_p[] = { @@ -194,6 +334,147 @@ static const BN_ULONG dh2048_256_q[] = { 0xA709A097, 0x8CF83642 }; +/* Primes from RFC 7919 */ + +static const BN_ULONG ffdhe2048_p[] = { + 0xFFFFFFFF, 0xFFFFFFFF, 0x61285C97, 0x886B4238, 0xC1B2EFFA, 0xC6F34A26, + 0x7D1683B2, 0xC58EF183, 0x2EC22005, 0x3BB5FCBC, 0x4C6FAD73, 0xC3FE3B1B, + 0xEEF28183, 0x8E4F1232, 0xE98583FF, 0x9172FE9C, 0x28342F61, 0xC03404CD, + 0xCDF7E2EC, 0x9E02FCE1, 0xEE0A6D70, 0x0B07A7C8, 0x6372BB19, 0xAE56EDE7, + 0xDE394DF4, 0x1D4F42A3, 0x60D7F468, 0xB96ADAB7, 0xB2C8E3FB, 0xD108A94B, + 0xB324FB61, 0xBC0AB182, 0x483A797A, 0x30ACCA4F, 0x36ADE735, 0x1DF158A1, + 0xF3EFE872, 0xE2A689DA, 0xE0E68B77, 0x984F0C70, 0x7F57C935, 0xB557135E, + 0x3DED1AF3, 0x85636555, 0x5F066ED0, 0x2433F51F, 0xD5FD6561, 0xD3DF1ED5, + 0xAEC4617A, 0xF681B202, 0x630C75D8, 0x7D2FE363, 0x249B3EF9, 0xCC939DCE, + 0x146433FB, 0xA9E13641, 0xCE2D3695, 0xD8B9C583, 0x273D3CF1, 0xAFDC5620, + 0xA2BB4A9A, 0xADF85458, 0xFFFFFFFF, 0xFFFFFFFF +}; + +static const BN_ULONG ffdhe3072_p[] = { + 0xFFFFFFFF, 0xFFFFFFFF, 0x66C62E37, 0x25E41D2B, 0x3FD59D7C, 0x3C1B20EE, + 0xFA53DDEF, 0x0ABCD06B, 0xD5C4484E, 0x1DBF9A42, 0x9B0DEADA, 0xABC52197, + 0x22363A0D, 0xE86D2BC5, 0x9C9DF69E, 0x5CAE82AB, 0x71F54BFF, 0x64F2E21E, + 0xE2D74DD3, 0xF4FD4452, 0xBC437944, 0xB4130C93, 0x85139270, 0xAEFE1309, + 0xC186D91C, 0x598CB0FA, 0x91F7F7EE, 0x7AD91D26, 0xD6E6C907, 0x61B46FC9, + 0xF99C0238, 0xBC34F4DE, 0x6519035B, 0xDE355B3B, 0x611FCFDC, 0x886B4238, + 0xC1B2EFFA, 0xC6F34A26, 0x7D1683B2, 0xC58EF183, 0x2EC22005, 0x3BB5FCBC, + 0x4C6FAD73, 0xC3FE3B1B, 0xEEF28183, 0x8E4F1232, 0xE98583FF, 0x9172FE9C, + 0x28342F61, 0xC03404CD, 0xCDF7E2EC, 0x9E02FCE1, 0xEE0A6D70, 0x0B07A7C8, + 0x6372BB19, 0xAE56EDE7, 0xDE394DF4, 0x1D4F42A3, 0x60D7F468, 0xB96ADAB7, + 0xB2C8E3FB, 0xD108A94B, 0xB324FB61, 0xBC0AB182, 0x483A797A, 0x30ACCA4F, + 0x36ADE735, 0x1DF158A1, 0xF3EFE872, 0xE2A689DA, 0xE0E68B77, 0x984F0C70, + 0x7F57C935, 0xB557135E, 0x3DED1AF3, 0x85636555, 0x5F066ED0, 0x2433F51F, + 0xD5FD6561, 0xD3DF1ED5, 0xAEC4617A, 0xF681B202, 0x630C75D8, 0x7D2FE363, + 0x249B3EF9, 0xCC939DCE, 0x146433FB, 0xA9E13641, 0xCE2D3695, 0xD8B9C583, + 0x273D3CF1, 0xAFDC5620, 0xA2BB4A9A, 0xADF85458, 0xFFFFFFFF, 0xFFFFFFFF +}; + +static const BN_ULONG ffdhe4096_p[] = { + 0xFFFFFFFF, 0xFFFFFFFF, 0x5E655F6A, 0xC68A007E, 0xF44182E1, 0x4DB5A851, + 0x7F88A46B, 0x8EC9B55A, 0xCEC97DCF, 0x0A8291CD, 0xF98D0ACC, 0x2A4ECEA9, + 0x7140003C, 0x1A1DB93D, 0x33CB8B7A, 0x092999A3, 0x71AD0038, 0x6DC778F9, + 0x918130C4, 0xA907600A, 0x2D9E6832, 0xED6A1E01, 0xEFB4318A, 0x7135C886, + 0x7E31CC7A, 0x87F55BA5, 0x55034004, 0x7763CF1D, 0xD69F6D18, 0xAC7D5F42, + 0xE58857B6, 0x7930E9E4, 0x164DF4FB, 0x6E6F52C3, 0x669E1EF1, 0x25E41D2B, + 0x3FD59D7C, 0x3C1B20EE, 0xFA53DDEF, 0x0ABCD06B, 0xD5C4484E, 0x1DBF9A42, + 0x9B0DEADA, 0xABC52197, 0x22363A0D, 0xE86D2BC5, 0x9C9DF69E, 0x5CAE82AB, + 0x71F54BFF, 0x64F2E21E, 0xE2D74DD3, 0xF4FD4452, 0xBC437944, 0xB4130C93, + 0x85139270, 0xAEFE1309, 0xC186D91C, 0x598CB0FA, 0x91F7F7EE, 0x7AD91D26, + 0xD6E6C907, 0x61B46FC9, 0xF99C0238, 0xBC34F4DE, 0x6519035B, 0xDE355B3B, + 0x611FCFDC, 0x886B4238, 0xC1B2EFFA, 0xC6F34A26, 0x7D1683B2, 0xC58EF183, + 0x2EC22005, 0x3BB5FCBC, 0x4C6FAD73, 0xC3FE3B1B, 0xEEF28183, 0x8E4F1232, + 0xE98583FF, 0x9172FE9C, 0x28342F61, 0xC03404CD, 0xCDF7E2EC, 0x9E02FCE1, + 0xEE0A6D70, 0x0B07A7C8, 0x6372BB19, 0xAE56EDE7, 0xDE394DF4, 0x1D4F42A3, + 0x60D7F468, 0xB96ADAB7, 0xB2C8E3FB, 0xD108A94B, 0xB324FB61, 0xBC0AB182, + 0x483A797A, 0x30ACCA4F, 0x36ADE735, 0x1DF158A1, 0xF3EFE872, 0xE2A689DA, + 0xE0E68B77, 0x984F0C70, 0x7F57C935, 0xB557135E, 0x3DED1AF3, 0x85636555, + 0x5F066ED0, 0x2433F51F, 0xD5FD6561, 0xD3DF1ED5, 0xAEC4617A, 0xF681B202, + 0x630C75D8, 0x7D2FE363, 0x249B3EF9, 0xCC939DCE, 0x146433FB, 0xA9E13641, + 0xCE2D3695, 0xD8B9C583, 0x273D3CF1, 0xAFDC5620, 0xA2BB4A9A, 0xADF85458, + 0xFFFFFFFF, 0xFFFFFFFF +}; + +static const BN_ULONG ffdhe6144_p[] = { + 0xFFFFFFFF, 0xFFFFFFFF, 0xD0E40E65, 0xA40E329C, 0x7938DAD4, 0xA41D570D, + 0xD43161C1, 0x62A69526, 0x9ADB1E69, 0x3FDD4A8E, 0xDC6B80D6, 0x5B3B71F9, + 0xC6272B04, 0xEC9D1810, 0xCACEF403, 0x8CCF2DD5, 0xC95B9117, 0xE49F5235, + 0xB854338A, 0x505DC82D, 0x1562A846, 0x62292C31, 0x6AE77F5E, 0xD72B0374, + 0x462D538C, 0xF9C9091B, 0x47A67CBE, 0x0AE8DB58, 0x22611682, 0xB3A739C1, + 0x2A281BF6, 0xEEAAC023, 0x77CAF992, 0x94C6651E, 0x94B2BBC1, 0x763E4E4B, + 0x0077D9B4, 0x587E38DA, 0x183023C3, 0x7FB29F8C, 0xF9E3A26E, 0x0ABEC1FF, + 0x350511E3, 0xA00EF092, 0xDB6340D8, 0xB855322E, 0xA9A96910, 0xA52471F7, + 0x4CFDB477, 0x388147FB, 0x4E46041F, 0x9B1F5C3E, 0xFCCFEC71, 0xCDAD0657, + 0x4C701C3A, 0xB38E8C33, 0xB1C0FD4C, 0x917BDD64, 0x9B7624C8, 0x3BB45432, + 0xCAF53EA6, 0x23BA4442, 0x38532A3A, 0x4E677D2C, 0x45036C7A, 0x0BFD64B6, + 0x5E0DD902, 0xC68A007E, 0xF44182E1, 0x4DB5A851, 0x7F88A46B, 0x8EC9B55A, + 0xCEC97DCF, 0x0A8291CD, 0xF98D0ACC, 0x2A4ECEA9, 0x7140003C, 0x1A1DB93D, + 0x33CB8B7A, 0x092999A3, 0x71AD0038, 0x6DC778F9, 0x918130C4, 0xA907600A, + 0x2D9E6832, 0xED6A1E01, 0xEFB4318A, 0x7135C886, 0x7E31CC7A, 0x87F55BA5, + 0x55034004, 0x7763CF1D, 0xD69F6D18, 0xAC7D5F42, 0xE58857B6, 0x7930E9E4, + 0x164DF4FB, 0x6E6F52C3, 0x669E1EF1, 0x25E41D2B, 0x3FD59D7C, 0x3C1B20EE, + 0xFA53DDEF, 0x0ABCD06B, 0xD5C4484E, 0x1DBF9A42, 0x9B0DEADA, 0xABC52197, + 0x22363A0D, 0xE86D2BC5, 0x9C9DF69E, 0x5CAE82AB, 0x71F54BFF, 0x64F2E21E, + 0xE2D74DD3, 0xF4FD4452, 0xBC437944, 0xB4130C93, 0x85139270, 0xAEFE1309, + 0xC186D91C, 0x598CB0FA, 0x91F7F7EE, 0x7AD91D26, 0xD6E6C907, 0x61B46FC9, + 0xF99C0238, 0xBC34F4DE, 0x6519035B, 0xDE355B3B, 0x611FCFDC, 0x886B4238, + 0xC1B2EFFA, 0xC6F34A26, 0x7D1683B2, 0xC58EF183, 0x2EC22005, 0x3BB5FCBC, + 0x4C6FAD73, 0xC3FE3B1B, 0xEEF28183, 0x8E4F1232, 0xE98583FF, 0x9172FE9C, + 0x28342F61, 0xC03404CD, 0xCDF7E2EC, 0x9E02FCE1, 0xEE0A6D70, 0x0B07A7C8, + 0x6372BB19, 0xAE56EDE7, 0xDE394DF4, 0x1D4F42A3, 0x60D7F468, 0xB96ADAB7, + 0xB2C8E3FB, 0xD108A94B, 0xB324FB61, 0xBC0AB182, 0x483A797A, 0x30ACCA4F, + 0x36ADE735, 0x1DF158A1, 0xF3EFE872, 0xE2A689DA, 0xE0E68B77, 0x984F0C70, + 0x7F57C935, 0xB557135E, 0x3DED1AF3, 0x85636555, 0x5F066ED0, 0x2433F51F, + 0xD5FD6561, 0xD3DF1ED5, 0xAEC4617A, 0xF681B202, 0x630C75D8, 0x7D2FE363, + 0x249B3EF9, 0xCC939DCE, 0x146433FB, 0xA9E13641, 0xCE2D3695, 0xD8B9C583, + 0x273D3CF1, 0xAFDC5620, 0xA2BB4A9A, 0xADF85458, 0xFFFFFFFF, 0xFFFFFFFF +}; + +static const BN_ULONG ffdhe8192_p[] = { + 0xFFFFFFFF, 0xFFFFFFFF, 0xC5C6424C, 0xD68C8BB7, 0x838FF88C, 0x011E2A94, + 0xA9F4614E, 0x0822E506, 0xF7A8443D, 0x97D11D49, 0x30677F0D, 0xA6BBFDE5, + 0xC1FE86FE, 0x2F741EF8, 0x5D71A87E, 0xFAFABE1C, 0xFBE58A30, 0xDED2FBAB, + 0x72B0A66E, 0xB6855DFE, 0xBA8A4FE8, 0x1EFC8CE0, 0x3F2FA457, 0x83F81D4A, + 0xA577E231, 0xA1FE3075, 0x88D9C0A0, 0xD5B80194, 0xAD9A95F9, 0x624816CD, + 0x50C1217B, 0x99E9E316, 0x0E423CFC, 0x51AA691E, 0x3826E52C, 0x1C217E6C, + 0x09703FEE, 0x51A8A931, 0x6A460E74, 0xBB709987, 0x9C86B022, 0x541FC68C, + 0x46FD8251, 0x59160CC0, 0x35C35F5C, 0x2846C0BA, 0x8B758282, 0x54504AC7, + 0xD2AF05E4, 0x29388839, 0xC01BD702, 0xCB2C0F1C, 0x7C932665, 0x555B2F74, + 0xA3AB8829, 0x86B63142, 0xF64B10EF, 0x0B8CC3BD, 0xEDD1CC5E, 0x687FEB69, + 0xC9509D43, 0xFDB23FCE, 0xD951AE64, 0x1E425A31, 0xF600C838, 0x36AD004C, + 0xCFF46AAA, 0xA40E329C, 0x7938DAD4, 0xA41D570D, 0xD43161C1, 0x62A69526, + 0x9ADB1E69, 0x3FDD4A8E, 0xDC6B80D6, 0x5B3B71F9, 0xC6272B04, 0xEC9D1810, + 0xCACEF403, 0x8CCF2DD5, 0xC95B9117, 0xE49F5235, 0xB854338A, 0x505DC82D, + 0x1562A846, 0x62292C31, 0x6AE77F5E, 0xD72B0374, 0x462D538C, 0xF9C9091B, + 0x47A67CBE, 0x0AE8DB58, 0x22611682, 0xB3A739C1, 0x2A281BF6, 0xEEAAC023, + 0x77CAF992, 0x94C6651E, 0x94B2BBC1, 0x763E4E4B, 0x0077D9B4, 0x587E38DA, + 0x183023C3, 0x7FB29F8C, 0xF9E3A26E, 0x0ABEC1FF, 0x350511E3, 0xA00EF092, + 0xDB6340D8, 0xB855322E, 0xA9A96910, 0xA52471F7, 0x4CFDB477, 0x388147FB, + 0x4E46041F, 0x9B1F5C3E, 0xFCCFEC71, 0xCDAD0657, 0x4C701C3A, 0xB38E8C33, + 0xB1C0FD4C, 0x917BDD64, 0x9B7624C8, 0x3BB45432, 0xCAF53EA6, 0x23BA4442, + 0x38532A3A, 0x4E677D2C, 0x45036C7A, 0x0BFD64B6, 0x5E0DD902, 0xC68A007E, + 0xF44182E1, 0x4DB5A851, 0x7F88A46B, 0x8EC9B55A, 0xCEC97DCF, 0x0A8291CD, + 0xF98D0ACC, 0x2A4ECEA9, 0x7140003C, 0x1A1DB93D, 0x33CB8B7A, 0x092999A3, + 0x71AD0038, 0x6DC778F9, 0x918130C4, 0xA907600A, 0x2D9E6832, 0xED6A1E01, + 0xEFB4318A, 0x7135C886, 0x7E31CC7A, 0x87F55BA5, 0x55034004, 0x7763CF1D, + 0xD69F6D18, 0xAC7D5F42, 0xE58857B6, 0x7930E9E4, 0x164DF4FB, 0x6E6F52C3, + 0x669E1EF1, 0x25E41D2B, 0x3FD59D7C, 0x3C1B20EE, 0xFA53DDEF, 0x0ABCD06B, + 0xD5C4484E, 0x1DBF9A42, 0x9B0DEADA, 0xABC52197, 0x22363A0D, 0xE86D2BC5, + 0x9C9DF69E, 0x5CAE82AB, 0x71F54BFF, 0x64F2E21E, 0xE2D74DD3, 0xF4FD4452, + 0xBC437944, 0xB4130C93, 0x85139270, 0xAEFE1309, 0xC186D91C, 0x598CB0FA, + 0x91F7F7EE, 0x7AD91D26, 0xD6E6C907, 0x61B46FC9, 0xF99C0238, 0xBC34F4DE, + 0x6519035B, 0xDE355B3B, 0x611FCFDC, 0x886B4238, 0xC1B2EFFA, 0xC6F34A26, + 0x7D1683B2, 0xC58EF183, 0x2EC22005, 0x3BB5FCBC, 0x4C6FAD73, 0xC3FE3B1B, + 0xEEF28183, 0x8E4F1232, 0xE98583FF, 0x9172FE9C, 0x28342F61, 0xC03404CD, + 0xCDF7E2EC, 0x9E02FCE1, 0xEE0A6D70, 0x0B07A7C8, 0x6372BB19, 0xAE56EDE7, + 0xDE394DF4, 0x1D4F42A3, 0x60D7F468, 0xB96ADAB7, 0xB2C8E3FB, 0xD108A94B, + 0xB324FB61, 0xBC0AB182, 0x483A797A, 0x30ACCA4F, 0x36ADE735, 0x1DF158A1, + 0xF3EFE872, 0xE2A689DA, 0xE0E68B77, 0x984F0C70, 0x7F57C935, 0xB557135E, + 0x3DED1AF3, 0x85636555, 0x5F066ED0, 0x2433F51F, 0xD5FD6561, 0xD3DF1ED5, + 0xAEC4617A, 0xF681B202, 0x630C75D8, 0x7D2FE363, 0x249B3EF9, 0xCC939DCE, + 0x146433FB, 0xA9E13641, 0xCE2D3695, 0xD8B9C583, 0x273D3CF1, 0xAFDC5620, + 0xA2BB4A9A, 0xADF85458, 0xFFFFFFFF, 0xFFFFFFFF +}; + # else # error "unsupported BN_BITS2" # endif @@ -206,6 +487,10 @@ static const BN_ULONG dh2048_256_q[] = { OSSL_NELEM(x),\ 0, BN_FLG_STATIC_DATA }; +static const BN_ULONG value_2 = 2; + +const BIGNUM _bignum_const_2 = + { (BN_ULONG *)&value_2, 1, 1, 0, BN_FLG_STATIC_DATA }; make_dh_bn(dh1024_160_p) make_dh_bn(dh1024_160_g) @@ -217,4 +502,11 @@ make_dh_bn(dh2048_256_p) make_dh_bn(dh2048_256_g) make_dh_bn(dh2048_256_q) +make_dh_bn(ffdhe2048_p) +make_dh_bn(ffdhe3072_p) +make_dh_bn(ffdhe4096_p) +make_dh_bn(ffdhe6144_p) +make_dh_bn(ffdhe8192_p) + + #endif diff --git a/crypto/bn/bn_div.c b/crypto/bn/bn_div.c index 5e620b20..b9b85fda 100644 --- a/crypto/bn/bn_div.c +++ b/crypto/bn/bn_div.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -24,17 +24,17 @@ int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d, bn_check_top(d); if (BN_is_zero(d)) { BNerr(BN_F_BN_DIV, BN_R_DIV_BY_ZERO); - return (0); + return 0; } if (BN_ucmp(m, d) < 0) { if (rem != NULL) { if (BN_copy(rem, m) == NULL) - return (0); + return 0; } if (dv != NULL) BN_zero(dv); - return (1); + return 1; } BN_CTX_start(ctx); @@ -81,7 +81,7 @@ int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d, ret = 1; end: BN_CTX_end(ctx); - return (ret); + return ret; } #else @@ -97,8 +97,6 @@ int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d, * understand why...); * - divl doesn't only calculate quotient, but also leaves * remainder in %edx which we can definitely use here:-) - * - * */ # undef bn_div_words # define bn_div_words(n0,n1,d0) \ @@ -113,7 +111,6 @@ int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d, # elif defined(__x86_64) && defined(SIXTY_FOUR_BIT_LONG) /* * Same story here, but it's 128-bit by 64-bit division. Wow! - * */ # undef bn_div_words # define bn_div_words(n0,n1,d0) \ @@ -177,28 +174,25 @@ int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor, if (BN_is_zero(divisor)) { BNerr(BN_F_BN_DIV, BN_R_DIV_BY_ZERO); - return (0); + return 0; } if (!no_branch && BN_ucmp(num, divisor) < 0) { if (rm != NULL) { if (BN_copy(rm, num) == NULL) - return (0); + return 0; } if (dv != NULL) BN_zero(dv); - return (1); + return 1; } BN_CTX_start(ctx); + res = (dv == NULL) ? BN_CTX_get(ctx) : dv; tmp = BN_CTX_get(ctx); snum = BN_CTX_get(ctx); sdiv = BN_CTX_get(ctx); - if (dv == NULL) - res = BN_CTX_get(ctx); - else - res = dv; - if (sdiv == NULL || res == NULL || tmp == NULL || snum == NULL) + if (sdiv == NULL) goto err; /* First we normalise the numbers */ @@ -414,10 +408,10 @@ int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor, if (no_branch) bn_correct_top(res); BN_CTX_end(ctx); - return (1); + return 1; err: bn_check_top(rm); BN_CTX_end(ctx); - return (0); + return 0; } #endif diff --git a/crypto/bn/bn_err.c b/crypto/bn/bn_err.c index 5fe9db9e..e2817470 100644 --- a/crypto/bn/bn_err.c +++ b/crypto/bn/bn_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,87 +8,95 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_BN,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_BN,0,reason) - -static ERR_STRING_DATA BN_str_functs[] = { - {ERR_FUNC(BN_F_BNRAND), "bnrand"}, - {ERR_FUNC(BN_F_BN_BLINDING_CONVERT_EX), "BN_BLINDING_convert_ex"}, - {ERR_FUNC(BN_F_BN_BLINDING_CREATE_PARAM), "BN_BLINDING_create_param"}, - {ERR_FUNC(BN_F_BN_BLINDING_INVERT_EX), "BN_BLINDING_invert_ex"}, - {ERR_FUNC(BN_F_BN_BLINDING_NEW), "BN_BLINDING_new"}, - {ERR_FUNC(BN_F_BN_BLINDING_UPDATE), "BN_BLINDING_update"}, - {ERR_FUNC(BN_F_BN_BN2DEC), "BN_bn2dec"}, - {ERR_FUNC(BN_F_BN_BN2HEX), "BN_bn2hex"}, - {ERR_FUNC(BN_F_BN_COMPUTE_WNAF), "bn_compute_wNAF"}, - {ERR_FUNC(BN_F_BN_CTX_GET), "BN_CTX_get"}, - {ERR_FUNC(BN_F_BN_CTX_NEW), "BN_CTX_new"}, - {ERR_FUNC(BN_F_BN_CTX_START), "BN_CTX_start"}, - {ERR_FUNC(BN_F_BN_DIV), "BN_div"}, - {ERR_FUNC(BN_F_BN_DIV_RECP), "BN_div_recp"}, - {ERR_FUNC(BN_F_BN_EXP), "BN_exp"}, - {ERR_FUNC(BN_F_BN_EXPAND_INTERNAL), "bn_expand_internal"}, - {ERR_FUNC(BN_F_BN_GENCB_NEW), "BN_GENCB_new"}, - {ERR_FUNC(BN_F_BN_GENERATE_DSA_NONCE), "BN_generate_dsa_nonce"}, - {ERR_FUNC(BN_F_BN_GENERATE_PRIME_EX), "BN_generate_prime_ex"}, - {ERR_FUNC(BN_F_BN_GF2M_MOD), "BN_GF2m_mod"}, - {ERR_FUNC(BN_F_BN_GF2M_MOD_EXP), "BN_GF2m_mod_exp"}, - {ERR_FUNC(BN_F_BN_GF2M_MOD_MUL), "BN_GF2m_mod_mul"}, - {ERR_FUNC(BN_F_BN_GF2M_MOD_SOLVE_QUAD), "BN_GF2m_mod_solve_quad"}, - {ERR_FUNC(BN_F_BN_GF2M_MOD_SOLVE_QUAD_ARR), "BN_GF2m_mod_solve_quad_arr"}, - {ERR_FUNC(BN_F_BN_GF2M_MOD_SQR), "BN_GF2m_mod_sqr"}, - {ERR_FUNC(BN_F_BN_GF2M_MOD_SQRT), "BN_GF2m_mod_sqrt"}, - {ERR_FUNC(BN_F_BN_LSHIFT), "BN_lshift"}, - {ERR_FUNC(BN_F_BN_MOD_EXP2_MONT), "BN_mod_exp2_mont"}, - {ERR_FUNC(BN_F_BN_MOD_EXP_MONT), "BN_mod_exp_mont"}, - {ERR_FUNC(BN_F_BN_MOD_EXP_MONT_CONSTTIME), "BN_mod_exp_mont_consttime"}, - {ERR_FUNC(BN_F_BN_MOD_EXP_MONT_WORD), "BN_mod_exp_mont_word"}, - {ERR_FUNC(BN_F_BN_MOD_EXP_RECP), "BN_mod_exp_recp"}, - {ERR_FUNC(BN_F_BN_MOD_EXP_SIMPLE), "BN_mod_exp_simple"}, - {ERR_FUNC(BN_F_BN_MOD_INVERSE), "BN_mod_inverse"}, - {ERR_FUNC(BN_F_BN_MOD_INVERSE_NO_BRANCH), "BN_mod_inverse_no_branch"}, - {ERR_FUNC(BN_F_BN_MOD_LSHIFT_QUICK), "BN_mod_lshift_quick"}, - {ERR_FUNC(BN_F_BN_MOD_SQRT), "BN_mod_sqrt"}, - {ERR_FUNC(BN_F_BN_MPI2BN), "BN_mpi2bn"}, - {ERR_FUNC(BN_F_BN_NEW), "BN_new"}, - {ERR_FUNC(BN_F_BN_RAND), "BN_rand"}, - {ERR_FUNC(BN_F_BN_RAND_RANGE), "BN_rand_range"}, - {ERR_FUNC(BN_F_BN_RSHIFT), "BN_rshift"}, - {ERR_FUNC(BN_F_BN_SET_WORDS), "bn_set_words"}, - {ERR_FUNC(BN_F_BN_USUB), "BN_usub"}, +static const ERR_STRING_DATA BN_str_functs[] = { + {ERR_PACK(ERR_LIB_BN, BN_F_BNRAND, 0), "bnrand"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BNRAND_RANGE, 0), "bnrand_range"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_BLINDING_CONVERT_EX, 0), + "BN_BLINDING_convert_ex"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_BLINDING_CREATE_PARAM, 0), + "BN_BLINDING_create_param"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_BLINDING_INVERT_EX, 0), + "BN_BLINDING_invert_ex"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_BLINDING_NEW, 0), "BN_BLINDING_new"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_BLINDING_UPDATE, 0), "BN_BLINDING_update"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_BN2DEC, 0), "BN_bn2dec"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_BN2HEX, 0), "BN_bn2hex"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_COMPUTE_WNAF, 0), "bn_compute_wNAF"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_CTX_GET, 0), "BN_CTX_get"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_CTX_NEW, 0), "BN_CTX_new"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_CTX_START, 0), "BN_CTX_start"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_DIV, 0), "BN_div"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_DIV_RECP, 0), "BN_div_recp"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_EXP, 0), "BN_exp"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_EXPAND_INTERNAL, 0), "bn_expand_internal"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_GENCB_NEW, 0), "BN_GENCB_new"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_GENERATE_DSA_NONCE, 0), + "BN_generate_dsa_nonce"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_GENERATE_PRIME_EX, 0), + "BN_generate_prime_ex"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_GF2M_MOD, 0), "BN_GF2m_mod"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_GF2M_MOD_EXP, 0), "BN_GF2m_mod_exp"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_GF2M_MOD_MUL, 0), "BN_GF2m_mod_mul"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_GF2M_MOD_SOLVE_QUAD, 0), + "BN_GF2m_mod_solve_quad"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_GF2M_MOD_SOLVE_QUAD_ARR, 0), + "BN_GF2m_mod_solve_quad_arr"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_GF2M_MOD_SQR, 0), "BN_GF2m_mod_sqr"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_GF2M_MOD_SQRT, 0), "BN_GF2m_mod_sqrt"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_LSHIFT, 0), "BN_lshift"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MOD_EXP2_MONT, 0), "BN_mod_exp2_mont"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MOD_EXP_MONT, 0), "BN_mod_exp_mont"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MOD_EXP_MONT_CONSTTIME, 0), + "BN_mod_exp_mont_consttime"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MOD_EXP_MONT_WORD, 0), + "BN_mod_exp_mont_word"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MOD_EXP_RECP, 0), "BN_mod_exp_recp"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MOD_EXP_SIMPLE, 0), "BN_mod_exp_simple"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MOD_INVERSE, 0), "BN_mod_inverse"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MOD_INVERSE_NO_BRANCH, 0), + "BN_mod_inverse_no_branch"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MOD_LSHIFT_QUICK, 0), "BN_mod_lshift_quick"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MOD_SQRT, 0), "BN_mod_sqrt"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_MPI2BN, 0), "BN_mpi2bn"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_NEW, 0), "BN_new"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_RAND, 0), "BN_rand"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_RAND_RANGE, 0), "BN_rand_range"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_RSHIFT, 0), "BN_rshift"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_SET_WORDS, 0), "bn_set_words"}, + {ERR_PACK(ERR_LIB_BN, BN_F_BN_USUB, 0), "BN_usub"}, {0, NULL} }; -static ERR_STRING_DATA BN_str_reasons[] = { - {ERR_REASON(BN_R_ARG2_LT_ARG3), "arg2 lt arg3"}, - {ERR_REASON(BN_R_BAD_RECIPROCAL), "bad reciprocal"}, - {ERR_REASON(BN_R_BIGNUM_TOO_LONG), "bignum too long"}, - {ERR_REASON(BN_R_BITS_TOO_SMALL), "bits too small"}, - {ERR_REASON(BN_R_CALLED_WITH_EVEN_MODULUS), "called with even modulus"}, - {ERR_REASON(BN_R_DIV_BY_ZERO), "div by zero"}, - {ERR_REASON(BN_R_ENCODING_ERROR), "encoding error"}, - {ERR_REASON(BN_R_EXPAND_ON_STATIC_BIGNUM_DATA), - "expand on static bignum data"}, - {ERR_REASON(BN_R_INPUT_NOT_REDUCED), "input not reduced"}, - {ERR_REASON(BN_R_INVALID_LENGTH), "invalid length"}, - {ERR_REASON(BN_R_INVALID_RANGE), "invalid range"}, - {ERR_REASON(BN_R_INVALID_SHIFT), "invalid shift"}, - {ERR_REASON(BN_R_NOT_A_SQUARE), "not a square"}, - {ERR_REASON(BN_R_NOT_INITIALIZED), "not initialized"}, - {ERR_REASON(BN_R_NO_INVERSE), "no inverse"}, - {ERR_REASON(BN_R_NO_SOLUTION), "no solution"}, - {ERR_REASON(BN_R_PRIVATE_KEY_TOO_LARGE), "private key too large"}, - {ERR_REASON(BN_R_P_IS_NOT_PRIME), "p is not prime"}, - {ERR_REASON(BN_R_TOO_MANY_ITERATIONS), "too many iterations"}, - {ERR_REASON(BN_R_TOO_MANY_TEMPORARY_VARIABLES), - "too many temporary variables"}, +static const ERR_STRING_DATA BN_str_reasons[] = { + {ERR_PACK(ERR_LIB_BN, 0, BN_R_ARG2_LT_ARG3), "arg2 lt arg3"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_BAD_RECIPROCAL), "bad reciprocal"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_BIGNUM_TOO_LONG), "bignum too long"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_BITS_TOO_SMALL), "bits too small"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_CALLED_WITH_EVEN_MODULUS), + "called with even modulus"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_DIV_BY_ZERO), "div by zero"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_ENCODING_ERROR), "encoding error"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_EXPAND_ON_STATIC_BIGNUM_DATA), + "expand on static bignum data"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_INPUT_NOT_REDUCED), "input not reduced"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_INVALID_LENGTH), "invalid length"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_INVALID_RANGE), "invalid range"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_INVALID_SHIFT), "invalid shift"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_NOT_A_SQUARE), "not a square"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_NOT_INITIALIZED), "not initialized"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_NO_INVERSE), "no inverse"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_NO_SOLUTION), "no solution"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_PRIVATE_KEY_TOO_LARGE), + "private key too large"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_P_IS_NOT_PRIME), "p is not prime"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_TOO_MANY_ITERATIONS), "too many iterations"}, + {ERR_PACK(ERR_LIB_BN, 0, BN_R_TOO_MANY_TEMPORARY_VARIABLES), + "too many temporary variables"}, {0, NULL} }; @@ -97,10 +105,9 @@ static ERR_STRING_DATA BN_str_reasons[] = { int ERR_load_BN_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(BN_str_functs[0].error) == NULL) { - ERR_load_strings(0, BN_str_functs); - ERR_load_strings(0, BN_str_reasons); + ERR_load_strings_const(BN_str_functs); + ERR_load_strings_const(BN_str_reasons); } #endif return 1; diff --git a/crypto/bn/bn_exp.c b/crypto/bn/bn_exp.c index 0d2d1eca..9b2042db 100644 --- a/crypto/bn/bn_exp.c +++ b/crypto/bn/bn_exp.c @@ -51,10 +51,7 @@ int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) } BN_CTX_start(ctx); - if ((r == a) || (r == p)) - rr = BN_CTX_get(ctx); - else - rr = r; + rr = ((r == a) || (r == p)) ? BN_CTX_get(ctx) : r; v = BN_CTX_get(ctx); if (rr == NULL || v == NULL) goto err; @@ -86,7 +83,7 @@ int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) err: BN_CTX_end(ctx); bn_check_top(r); - return (ret); + return ret; } int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, @@ -134,13 +131,6 @@ int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, #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 @@ -165,7 +155,7 @@ int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, #endif bn_check_top(r); - return (ret); + return ret; } int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, @@ -201,7 +191,7 @@ int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX_start(ctx); aa = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); - if (!aa || !val[0]) + if (val[0] == NULL) goto err; BN_RECP_CTX_init(&recp); @@ -300,7 +290,7 @@ int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX_end(ctx); BN_RECP_CTX_free(&recp); bn_check_top(r); - return (ret); + return ret; } int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, @@ -326,7 +316,7 @@ int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, if (!BN_is_odd(m)) { BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS); - return (0); + return 0; } bits = BN_num_bits(p); if (bits == 0) { @@ -344,7 +334,7 @@ int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, d = BN_CTX_get(ctx); r = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); - if (!d || !r || !val[0]) + if (val[0] == NULL) goto err; /* @@ -480,7 +470,7 @@ int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); - return (ret); + return ret; } #if defined(SPARC_T4_MONT) @@ -628,7 +618,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, if (!BN_is_odd(m)) { BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS); - return (0); + return 0; } top = m->top; @@ -665,31 +655,33 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, } #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)) + if (!a->neg) { + /* + * 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; - 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)) + } 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; - 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 @@ -762,7 +754,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, /* prepare a^1 in Montgomery domain */ if (a->neg || BN_ucmp(a, m) >= 0) { - if (!BN_mod(&am, a, m, ctx)) + if (!BN_nnmod(&am, a, m, ctx)) goto err; if (!BN_to_montgomery(&am, &am, mont, ctx)) goto err; @@ -1103,7 +1095,7 @@ int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, OPENSSL_free(powerbufFree); } BN_CTX_end(ctx); - return (ret); + return ret; } int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, @@ -1113,7 +1105,7 @@ int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, int b, bits, ret = 0; int r_is_one; BN_ULONG w, next_w; - BIGNUM *d, *r, *t; + BIGNUM *r, *t; BIGNUM *swap_tmp; #define BN_MOD_MUL_WORD(r, w, m) \ (BN_mul_word(r, (w)) && \ @@ -1144,7 +1136,7 @@ int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, if (!BN_is_odd(m)) { BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS); - return (0); + return 0; } if (m->top == 1) a %= m->d[0]; /* make sure that 'a' is reduced */ @@ -1167,10 +1159,9 @@ int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, } 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) + if (t == NULL) goto err; if (in_mont != NULL) @@ -1251,7 +1242,7 @@ int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); - return (ret); + return ret; } /* The old fallback, simple version :-) */ @@ -1273,7 +1264,7 @@ int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, } bits = BN_num_bits(p); - if (bits == 0) { + if (bits == 0) { /* x**0 mod 1 is still zero. */ if (BN_is_one(m)) { ret = 1; @@ -1287,7 +1278,7 @@ int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX_start(ctx); d = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); - if (!d || !val[0]) + if (val[0] == NULL) goto err; if (!BN_nnmod(val[0], a, m, ctx)) @@ -1372,5 +1363,5 @@ int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, err: BN_CTX_end(ctx); bn_check_top(r); - return (ret); + return ret; } diff --git a/crypto/bn/bn_exp2.c b/crypto/bn/bn_exp2.c index 5141c21f..082c9286 100644 --- a/crypto/bn/bn_exp2.c +++ b/crypto/bn/bn_exp2.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -34,7 +34,7 @@ int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1, if (!(m->d[0] & 1)) { BNerr(BN_F_BN_MOD_EXP2_MONT, BN_R_CALLED_WITH_EVEN_MODULUS); - return (0); + return 0; } bits1 = BN_num_bits(p1); bits2 = BN_num_bits(p2); @@ -50,7 +50,7 @@ int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1, r = BN_CTX_get(ctx); val1[0] = BN_CTX_get(ctx); val2[0] = BN_CTX_get(ctx); - if (!d || !r || !val1[0] || !val2[0]) + if (val2[0] == NULL) goto err; if (in_mont != NULL) @@ -197,5 +197,5 @@ int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1, BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); - return (ret); + return ret; } diff --git a/crypto/bn/bn_gcd.c b/crypto/bn/bn_gcd.c index 06764264..22f80939 100644 --- a/crypto/bn/bn_gcd.c +++ b/crypto/bn/bn_gcd.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -23,7 +23,7 @@ int BN_gcd(BIGNUM *r, const BIGNUM *in_a, const BIGNUM *in_b, BN_CTX *ctx) BN_CTX_start(ctx); a = BN_CTX_get(ctx); b = BN_CTX_get(ctx); - if (a == NULL || b == NULL) + if (b == NULL) goto err; if (BN_copy(a, in_a) == NULL) @@ -48,7 +48,7 @@ int BN_gcd(BIGNUM *r, const BIGNUM *in_a, const BIGNUM *in_b, BN_CTX *ctx) err: BN_CTX_end(ctx); bn_check_top(r); - return (ret); + return ret; } static BIGNUM *euclid(BIGNUM *a, BIGNUM *b) @@ -111,9 +111,9 @@ static BIGNUM *euclid(BIGNUM *a, BIGNUM *b) goto err; } bn_check_top(a); - return (a); + return a; err: - return (NULL); + return NULL; } /* solves ax == 1 (mod n) */ @@ -441,7 +441,7 @@ BIGNUM *int_bn_mod_inverse(BIGNUM *in, BN_free(R); BN_CTX_end(ctx); bn_check_top(ret); - return (ret); + return ret; } /* @@ -612,5 +612,5 @@ static BIGNUM *BN_mod_inverse_no_branch(BIGNUM *in, BN_free(R); BN_CTX_end(ctx); bn_check_top(ret); - return (ret); + return ret; } diff --git a/crypto/bn/bn_gf2m.c b/crypto/bn/bn_gf2m.c index b1987f55..16868f79 100644 --- a/crypto/bn/bn_gf2m.c +++ b/crypto/bn/bn_gf2m.c @@ -1,5 +1,6 @@ /* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2002-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,17 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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. - */ - #include #include #include @@ -567,13 +557,11 @@ int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) BN_CTX_start(ctx); - if ((b = BN_CTX_get(ctx)) == NULL) - goto err; - if ((c = BN_CTX_get(ctx)) == NULL) - goto err; - if ((u = BN_CTX_get(ctx)) == NULL) - goto err; - if ((v = BN_CTX_get(ctx)) == NULL) + b = BN_CTX_get(ctx); + c = BN_CTX_get(ctx); + u = BN_CTX_get(ctx); + v = BN_CTX_get(ctx); + if (v == NULL) goto err; if (!BN_GF2m_mod(u, a, p)) @@ -916,7 +904,7 @@ int BN_GF2m_mod_exp_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, bn_check_top(b); if (BN_is_zero(b)) - return (BN_one(r)); + return BN_one(r); if (BN_abs_is_word(b, 1)) return (BN_copy(r, a) != NULL); @@ -1089,7 +1077,7 @@ int BN_GF2m_mod_solve_quad_arr(BIGNUM *r, const BIGNUM *a_, const int p[], if (tmp == NULL) goto err; do { - if (!BN_rand(rho, p[0], BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) + if (!BN_priv_rand(rho, p[0], BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) goto err; if (!BN_GF2m_mod_arr(rho, rho, p)) goto err; diff --git a/crypto/bn/bn_intern.c b/crypto/bn/bn_intern.c index 2c970647..2524eb2a 100644 --- a/crypto/bn/bn_intern.c +++ b/crypto/bn/bn_intern.c @@ -143,11 +143,6 @@ int bn_get_top(const BIGNUM *a) return a->top; } -void bn_set_top(BIGNUM *a, int top) -{ - a->top = top; -} - int bn_get_dmax(const BIGNUM *a) { return a->dmax; @@ -198,13 +193,3 @@ int bn_set_words(BIGNUM *a, BN_ULONG *words, int num_words) bn_correct_top(a); return 1; } - -size_t bn_sizeof_BIGNUM(void) -{ - return sizeof(BIGNUM); -} - -BIGNUM *bn_array_el(BIGNUM *base, int el) -{ - return &base[el]; -} diff --git a/crypto/bn/bn_lcl.h b/crypto/bn/bn_lcl.h index 5fb38145..bab2c9d7 100644 --- a/crypto/bn/bn_lcl.h +++ b/crypto/bn/bn_lcl.h @@ -145,13 +145,8 @@ extern "C" { */ # ifdef BN_DEBUG - +# include # ifdef BN_DEBUG_RAND -/* To avoid "make update" cvs wars due to BN_DEBUG, use some tricks */ -# ifndef RAND_bytes -int RAND_bytes(unsigned char *buf, int num); -# define BN_DEBUG_TRIX -# endif # define bn_pollute(a) \ do { \ const BIGNUM *_bnum1 = (a); \ @@ -167,9 +162,6 @@ int RAND_bytes(unsigned char *buf, int num); sizeof(*_not_const) * (_bnum1->dmax - _bnum1->top)); \ } \ } while(0) -# ifdef BN_DEBUG_TRIX -# undef RAND_bytes -# endif # else # define bn_pollute(a) # endif @@ -177,8 +169,8 @@ int RAND_bytes(unsigned char *buf, int num); do { \ const BIGNUM *_bnum2 = (a); \ if (_bnum2 != NULL) { \ - OPENSSL_assert(((_bnum2->top == 0) && !_bnum2->neg) || \ - (_bnum2->top && (_bnum2->d[_bnum2->top - 1] != 0))); \ + assert(((_bnum2->top == 0) && !_bnum2->neg) || \ + (_bnum2->top && (_bnum2->d[_bnum2->top - 1] != 0))); \ bn_pollute(_bnum2); \ } \ } while(0) @@ -189,8 +181,8 @@ int RAND_bytes(unsigned char *buf, int num); # define bn_wcheck_size(bn, words) \ do { \ const BIGNUM *_bnum2 = (bn); \ - OPENSSL_assert((words) <= (_bnum2)->dmax && \ - (words) >= (_bnum2)->top); \ + assert((words) <= (_bnum2)->dmax && \ + (words) >= (_bnum2)->top); \ /* avoid unused variable warning with NDEBUG */ \ (void)(_bnum2); \ } while(0) @@ -357,59 +349,58 @@ struct bn_gencb_st { # if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) && !defined(PEDANTIC) /* * BN_UMULT_HIGH section. - * - * No, I'm not trying to overwhelm you when stating that the - * product of N-bit numbers is 2*N bits wide:-) No, I don't expect - * you to be impressed when I say that if the compiler doesn't - * support 2*N integer type, then you have to replace every N*N - * multiplication with 4 (N/2)*(N/2) accompanied by some shifts - * and additions which unavoidably results in severe performance - * penalties. Of course provided that the hardware is capable of - * producing 2*N result... That's when you normally start - * considering assembler implementation. However! It should be - * pointed out that some CPUs (most notably Alpha, PowerPC and - * upcoming IA-64 family:-) provide *separate* instruction - * calculating the upper half of the product placing the result - * into a general purpose register. Now *if* the compiler supports - * inline assembler, then it's not impossible to implement the - * "bignum" routines (and have the compiler optimize 'em) - * exhibiting "native" performance in C. That's what BN_UMULT_HIGH - * macro is about:-) - * - * + * If the compiler doesn't support 2*N integer type, then you have to + * replace every N*N multiplication with 4 (N/2)*(N/2) accompanied by some + * shifts and additions which unavoidably results in severe performance + * penalties. Of course provided that the hardware is capable of producing + * 2*N result... That's when you normally start considering assembler + * implementation. However! It should be pointed out that some CPUs (e.g., + * PowerPC, Alpha, and IA-64) provide *separate* instruction calculating + * the upper half of the product placing the result into a general + * purpose register. Now *if* the compiler supports inline assembler, + * then it's not impossible to implement the "bignum" routines (and have + * the compiler optimize 'em) exhibiting "native" performance in C. That's + * what BN_UMULT_HIGH macro is about:-) Note that more recent compilers do + * support 2*64 integer type, which is also used here. */ -# if defined(__alpha) && (defined(SIXTY_FOUR_BIT_LONG) || defined(SIXTY_FOUR_BIT)) +# if defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16 && \ + (defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG)) +# define BN_UMULT_HIGH(a,b) (((__uint128_t)(a)*(b))>>64) +# define BN_UMULT_LOHI(low,high,a,b) ({ \ + __uint128_t ret=(__uint128_t)(a)*(b); \ + (high)=ret>>64; (low)=ret; }) +# elif defined(__alpha) && (defined(SIXTY_FOUR_BIT_LONG) || defined(SIXTY_FOUR_BIT)) # if defined(__DECC) # include # define BN_UMULT_HIGH(a,b) (BN_ULONG)asm("umulh %a0,%a1,%v0",(a),(b)) # elif defined(__GNUC__) && __GNUC__>=2 -# define BN_UMULT_HIGH(a,b) ({ \ +# define BN_UMULT_HIGH(a,b) ({ \ register BN_ULONG ret; \ asm ("umulh %1,%2,%0" \ : "=r"(ret) \ : "r"(a), "r"(b)); \ - ret; }) + ret; }) # endif /* compiler */ -# elif defined(_ARCH_PPC) && defined(__64BIT__) && defined(SIXTY_FOUR_BIT_LONG) +# elif defined(_ARCH_PPC64) && defined(SIXTY_FOUR_BIT_LONG) # if defined(__GNUC__) && __GNUC__>=2 -# define BN_UMULT_HIGH(a,b) ({ \ +# define BN_UMULT_HIGH(a,b) ({ \ register BN_ULONG ret; \ asm ("mulhdu %0,%1,%2" \ : "=r"(ret) \ : "r"(a), "r"(b)); \ - ret; }) + ret; }) # endif /* compiler */ # elif (defined(__x86_64) || defined(__x86_64__)) && \ (defined(SIXTY_FOUR_BIT_LONG) || defined(SIXTY_FOUR_BIT)) # if defined(__GNUC__) && __GNUC__>=2 -# define BN_UMULT_HIGH(a,b) ({ \ +# define BN_UMULT_HIGH(a,b) ({ \ register BN_ULONG ret,discard; \ asm ("mulq %3" \ : "=a"(discard),"=d"(ret) \ : "a"(a), "g"(b) \ : "cc"); \ - ret; }) -# define BN_UMULT_LOHI(low,high,a,b) \ + ret; }) +# define BN_UMULT_LOHI(low,high,a,b) \ asm ("mulq %3" \ : "=a"(low),"=d"(high) \ : "a"(a),"g"(b) \ @@ -426,43 +417,29 @@ unsigned __int64 _umul128(unsigned __int64 a, unsigned __int64 b, # endif # elif defined(__mips) && (defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG)) # if defined(__GNUC__) && __GNUC__>=2 -# if defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16 - /* "h" constraint is not an option on R6 and was removed in 4.4 */ -# define BN_UMULT_HIGH(a,b) (((__uint128_t)(a)*(b))>>64) -# define BN_UMULT_LOHI(low,high,a,b) ({ \ - __uint128_t ret=(__uint128_t)(a)*(b); \ - (high)=ret>>64; (low)=ret; }) -# else -# define BN_UMULT_HIGH(a,b) ({ \ +# define BN_UMULT_HIGH(a,b) ({ \ register BN_ULONG ret; \ asm ("dmultu %1,%2" \ : "=h"(ret) \ : "r"(a), "r"(b) : "l"); \ ret; }) -# define BN_UMULT_LOHI(low,high,a,b)\ +# define BN_UMULT_LOHI(low,high,a,b) \ asm ("dmultu %2,%3" \ : "=l"(low),"=h"(high) \ : "r"(a), "r"(b)); -# endif # endif # elif defined(__aarch64__) && defined(SIXTY_FOUR_BIT_LONG) # if defined(__GNUC__) && __GNUC__>=2 -# define BN_UMULT_HIGH(a,b) ({ \ +# define BN_UMULT_HIGH(a,b) ({ \ register BN_ULONG ret; \ asm ("umulh %0,%1,%2" \ : "=r"(ret) \ : "r"(a), "r"(b)); \ - ret; }) + ret; }) # endif # endif /* cpu */ # endif /* OPENSSL_NO_ASM */ -/************************************************************* - * Using the long long type - */ -# define Lw(t) (((BN_ULONG)(t))&BN_MASK2) -# define Hw(t) (((BN_ULONG)((t)>>BN_BITS2))&BN_MASK2) - # ifdef BN_DEBUG_RAND # define bn_clear_top2max(a) \ { \ @@ -476,6 +453,12 @@ unsigned __int64 _umul128(unsigned __int64 a, unsigned __int64 b, # endif # ifdef BN_LLONG +/******************************************************************* + * Using the long long type, has to be twice as wide as BN_ULONG... + */ +# define Lw(t) (((BN_ULONG)(t))&BN_MASK2) +# define Hw(t) (((BN_ULONG)((t)>>BN_BITS2))&BN_MASK2) + # define mul_add(r,a,w,c) { \ BN_ULLONG t; \ t=(BN_ULLONG)w * (a) + (r) + (c); \ @@ -653,10 +636,6 @@ void bn_sqr_recursive(BN_ULONG *r, const BN_ULONG *a, int n2, BN_ULONG *t); void bn_mul_low_normal(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n); void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, BN_ULONG *t); -void bn_mul_high(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, BN_ULONG *l, int n2, - BN_ULONG *t); -BN_ULONG bn_add_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, - int cl, int dl); BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int cl, int dl); int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, @@ -668,8 +647,6 @@ BIGNUM *int_bn_mod_inverse(BIGNUM *in, int bn_probable_prime_dh(BIGNUM *rnd, int bits, const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx); -int bn_probable_prime_dh_retry(BIGNUM *rnd, int bits, BN_CTX *ctx); -int bn_probable_prime_dh_coprime(BIGNUM *rnd, int bits, BN_CTX *ctx); static ossl_inline BIGNUM *bn_expand(BIGNUM *a, int bits) { diff --git a/crypto/bn/bn_lib.c b/crypto/bn/bn_lib.c index 70584940..57fe4528 100644 --- a/crypto/bn/bn_lib.c +++ b/crypto/bn/bn_lib.c @@ -65,15 +65,15 @@ void BN_set_params(int mult, int high, int low, int mont) int BN_get_params(int which) { if (which == 0) - return (bn_limit_bits); + return bn_limit_bits; else if (which == 1) - return (bn_limit_bits_high); + return bn_limit_bits_high; else if (which == 2) - return (bn_limit_bits_low); + return bn_limit_bits_low; else if (which == 3) - return (bn_limit_bits_mont); + return bn_limit_bits_mont; else - return (0); + return 0; } #endif @@ -83,7 +83,7 @@ const BIGNUM *BN_value_one(void) static const BIGNUM const_one = { (BN_ULONG *)&data_one, 1, 1, 0, BN_FLG_STATIC_DATA }; - return (&const_one); + return &const_one; } int BN_num_bits_word(BN_ULONG l) @@ -152,37 +152,26 @@ static void bn_free_d(BIGNUM *a) void BN_clear_free(BIGNUM *a) { - int i; - if (a == NULL) return; - bn_check_top(a); - if (a->d != NULL) { + if (a->d != NULL && !BN_get_flags(a, BN_FLG_STATIC_DATA)) { OPENSSL_cleanse(a->d, a->dmax * sizeof(a->d[0])); - if (!BN_get_flags(a, BN_FLG_STATIC_DATA)) - bn_free_d(a); + bn_free_d(a); } - i = BN_get_flags(a, BN_FLG_MALLOCED); - OPENSSL_cleanse(a, sizeof(*a)); - if (i) + if (BN_get_flags(a, BN_FLG_MALLOCED)) { + OPENSSL_cleanse(a, sizeof(*a)); OPENSSL_free(a); + } } void BN_free(BIGNUM *a) { if (a == NULL) return; - bn_check_top(a); if (!BN_get_flags(a, BN_FLG_STATIC_DATA)) bn_free_d(a); if (a->flags & BN_FLG_MALLOCED) OPENSSL_free(a); - else { -#if OPENSSL_API_COMPAT < 0x00908000L - a->flags |= BN_FLG_FREE; -#endif - a->d = NULL; - } } void bn_init(BIGNUM *a) @@ -199,11 +188,11 @@ BIGNUM *BN_new(void) if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) { BNerr(BN_F_BN_NEW, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } ret->flags = BN_FLG_MALLOCED; bn_check_top(ret); - return (ret); + return ret; } BIGNUM *BN_secure_new(void) @@ -211,16 +200,14 @@ BIGNUM *BN_new(void) BIGNUM *ret = BN_new(); if (ret != NULL) ret->flags |= BN_FLG_SECURE; - return (ret); + return ret; } /* This is used by bn_expand2() */ /* The caller MUST check that words > b->dmax before calling this */ static BN_ULONG *bn_expand_internal(const BIGNUM *b, int words) { - BN_ULONG *A, *a = NULL; - const BN_ULONG *B; - int i; + BN_ULONG *a = NULL; bn_check_top(b); @@ -230,62 +217,22 @@ static BN_ULONG *bn_expand_internal(const BIGNUM *b, int words) } if (BN_get_flags(b, BN_FLG_STATIC_DATA)) { BNerr(BN_F_BN_EXPAND_INTERNAL, BN_R_EXPAND_ON_STATIC_BIGNUM_DATA); - return (NULL); + return NULL; } if (BN_get_flags(b, BN_FLG_SECURE)) - a = A = OPENSSL_secure_zalloc(words * sizeof(*a)); + a = OPENSSL_secure_zalloc(words * sizeof(*a)); else - a = A = OPENSSL_zalloc(words * sizeof(*a)); - if (A == NULL) { + a = OPENSSL_zalloc(words * sizeof(*a)); + if (a == NULL) { BNerr(BN_F_BN_EXPAND_INTERNAL, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } -#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 accommodate more data. - * I'd unroll it 8-wise otherwise:-) - * - * - */ - 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; - } - switch (b->top & 3) { - case 3: - A[2] = B[2]; - /* fall thru */ - case 2: - A[1] = B[1]; - /* fall thru */ - case 1: - A[0] = B[0]; - /* fall thru */ - case 0: - /* Without the "case 0" some old optimizers got this wrong. */ - ; - } - } -#else - memset(A, 0, sizeof(*A) * words); - memcpy(A, b->d, sizeof(b->d[0]) * b->top); -#endif + assert(b->top <= words); + if (b->top > 0) + memcpy(a, b->d, sizeof(*a) * b->top); - return (a); + return a; } /* @@ -337,52 +284,20 @@ BIGNUM *BN_dup(const BIGNUM *a) 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); + return a; if (bn_wexpand(a, b->top) == NULL) - return (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]; - /* fall thru */ - case 2: - A[1] = B[1]; - /* fall thru */ - case 1: - A[0] = B[0]; - /* fall thru */ - case 0:; - } -#else - memcpy(a->d, b->d, sizeof(b->d[0]) * b->top); -#endif + if (b->top > 0) + memcpy(a->d, b->d, sizeof(b->d[0]) * b->top); a->top = b->top; a->neg = b->neg; bn_check_top(a); - return (a); + return a; } void BN_swap(BIGNUM *a, BIGNUM *b) @@ -443,12 +358,12 @@ 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); + return 0; a->neg = 0; a->d[0] = w; a->top = (w ? 1 : 0); bn_check_top(a); - return (1); + return 1; } BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret) @@ -461,7 +376,7 @@ BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret) if (ret == NULL) ret = bn = BN_new(); if (ret == NULL) - return (NULL); + return NULL; bn_check_top(ret); /* Skip leading zero's. */ for ( ; len > 0 && *s == 0; s++, len--) @@ -469,7 +384,7 @@ BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret) n = len; if (n == 0) { ret->top = 0; - return (ret); + return ret; } i = ((n - 1) / BN_BYTES) + 1; m = ((n - 1) % (BN_BYTES)); @@ -493,7 +408,7 @@ BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret) * bit set (-ve number) */ bn_correct_top(ret); - return (ret); + return ret; } /* ignore negative */ @@ -542,7 +457,7 @@ BIGNUM *BN_lebin2bn(const unsigned char *s, int len, BIGNUM *ret) if (ret == NULL) ret = bn = BN_new(); if (ret == NULL) - return (NULL); + return NULL; bn_check_top(ret); s += len; /* Skip trailing zeroes. */ @@ -609,7 +524,7 @@ int BN_ucmp(const BIGNUM *a, const BIGNUM *b) i = a->top - b->top; if (i != 0) - return (i); + return i; ap = a->d; bp = b->d; for (i = a->top - 1; i >= 0; i--) { @@ -618,7 +533,7 @@ int BN_ucmp(const BIGNUM *a, const BIGNUM *b) if (t1 != t2) return ((t1 > t2) ? 1 : -1); } - return (0); + return 0; } int BN_cmp(const BIGNUM *a, const BIGNUM *b) @@ -629,11 +544,11 @@ int BN_cmp(const BIGNUM *a, const BIGNUM *b) if ((a == NULL) || (b == NULL)) { if (a != NULL) - return (-1); + return -1; else if (b != NULL) - return (1); + return 1; else - return (0); + return 0; } bn_check_top(a); @@ -641,9 +556,9 @@ int BN_cmp(const BIGNUM *a, const BIGNUM *b) if (a->neg != b->neg) { if (a->neg) - return (-1); + return -1; else - return (1); + return 1; } if (a->neg == 0) { gt = 1; @@ -654,18 +569,18 @@ int BN_cmp(const BIGNUM *a, const BIGNUM *b) } if (a->top > b->top) - return (gt); + return gt; if (a->top < b->top) - return (lt); + return lt; for (i = a->top - 1; i >= 0; i--) { t1 = a->d[i]; t2 = b->d[i]; if (t1 > t2) - return (gt); + return gt; if (t1 < t2) - return (lt); + return lt; } - return (0); + return 0; } int BN_set_bit(BIGNUM *a, int n) @@ -679,7 +594,7 @@ int BN_set_bit(BIGNUM *a, int n) j = n % BN_BITS2; if (a->top <= i) { if (bn_wexpand(a, i + 1) == NULL) - return (0); + return 0; for (k = a->top; k < i + 1; k++) a->d[k] = 0; a->top = i + 1; @@ -687,7 +602,7 @@ int BN_set_bit(BIGNUM *a, int n) a->d[i] |= (((BN_ULONG)1) << j); bn_check_top(a); - return (1); + return 1; } int BN_clear_bit(BIGNUM *a, int n) @@ -701,11 +616,11 @@ int BN_clear_bit(BIGNUM *a, int n) i = n / BN_BITS2; j = n % BN_BITS2; if (a->top <= i) - return (0); + return 0; a->d[i] &= (~(((BN_ULONG)1) << j)); bn_correct_top(a); - return (1); + return 1; } int BN_is_bit_set(const BIGNUM *a, int n) @@ -741,7 +656,7 @@ int BN_mask_bits(BIGNUM *a, int n) a->d[w] &= ~(BN_MASK2 << b); } bn_correct_top(a); - return (1); + return 1; } void BN_set_negative(BIGNUM *a, int b) @@ -767,7 +682,7 @@ int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n) if (aa != bb) return ((aa > bb) ? 1 : -1); } - return (0); + return 0; } /* @@ -944,7 +859,7 @@ BN_GENCB *BN_GENCB_new(void) if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) { BNerr(BN_F_BN_GENCB_NEW, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } return ret; diff --git a/crypto/bn/bn_mod.c b/crypto/bn/bn_mod.c index 13b583f7..76adfb74 100644 --- a/crypto/bn/bn_mod.c +++ b/crypto/bn/bn_mod.c @@ -96,7 +96,7 @@ int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, ret = 1; err: BN_CTX_end(ctx); - return (ret); + return ret; } int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) diff --git a/crypto/bn/bn_mont.c b/crypto/bn/bn_mont.c index faef5815..6357c60c 100644 --- a/crypto/bn/bn_mont.c +++ b/crypto/bn/bn_mont.c @@ -33,12 +33,12 @@ int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, if (num > 1 && a->top == num && b->top == num) { if (bn_wexpand(r, num) == NULL) - return (0); + 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); + return 1; } } #endif @@ -68,7 +68,7 @@ int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, ret = 1; err: BN_CTX_end(ctx); - return (ret); + return ret; } #ifdef MONT_WORD @@ -82,12 +82,12 @@ static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont) nl = n->top; if (nl == 0) { ret->top = 0; - return (1); + return 1; } max = (2 * nl); /* carry is stored separately */ if (bn_wexpand(r, max) == NULL) - return (0); + return 0; r->neg ^= n->neg; np = n->d; @@ -115,7 +115,7 @@ static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont) } if (bn_wexpand(ret, nl) == NULL) - return (0); + return 0; ret->top = nl; ret->neg = r->neg; @@ -142,7 +142,7 @@ static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont) bn_correct_top(ret); bn_check_top(ret); - return (1); + return 1; } #endif /* MONT_WORD */ @@ -163,7 +163,7 @@ int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont, BN_CTX_start(ctx); t1 = BN_CTX_get(ctx); t2 = BN_CTX_get(ctx); - if (t1 == NULL || t2 == NULL) + if (t2 == NULL) goto err; if (!BN_copy(t1, a)) @@ -190,7 +190,7 @@ int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont, err: BN_CTX_end(ctx); #endif /* MONT_WORD */ - return (retn); + return retn; } BN_MONT_CTX *BN_MONT_CTX_new(void) @@ -198,11 +198,11 @@ BN_MONT_CTX *BN_MONT_CTX_new(void) BN_MONT_CTX *ret; if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) - return (NULL); + return NULL; BN_MONT_CTX_init(ret); ret->flags = BN_FLG_MALLOCED; - return (ret); + return ret; } void BN_MONT_CTX_init(BN_MONT_CTX *ctx) @@ -369,7 +369,7 @@ int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx) BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from) { if (to == from) - return (to); + return to; if (!BN_copy(&(to->RR), &(from->RR))) return NULL; @@ -380,7 +380,7 @@ BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from) to->ri = from->ri; to->n0[0] = from->n0[0]; to->n0[1] = from->n0[1]; - return (to); + return to; } BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_RWLOCK *lock, diff --git a/crypto/bn/bn_mul.c b/crypto/bn/bn_mul.c index a1abc5b0..07aaf589 100644 --- a/crypto/bn/bn_mul.c +++ b/crypto/bn/bn_mul.c @@ -154,170 +154,6 @@ BN_ULONG bn_sub_part_words(BN_ULONG *r, } #endif -BN_ULONG bn_add_part_words(BN_ULONG *r, - const BN_ULONG *a, const BN_ULONG *b, - int cl, int dl) -{ - BN_ULONG c, l, t; - - assert(cl >= 0); - c = bn_add_words(r, a, b, cl); - - if (dl == 0) - return c; - - r += cl; - a += cl; - b += cl; - - if (dl < 0) { - int save_dl = dl; - while (c) { - l = (c + b[0]) & BN_MASK2; - c = (l < c); - r[0] = l; - if (++dl >= 0) - break; - - l = (c + b[1]) & BN_MASK2; - c = (l < c); - r[1] = l; - if (++dl >= 0) - break; - - l = (c + b[2]) & BN_MASK2; - c = (l < c); - r[2] = l; - if (++dl >= 0) - break; - - l = (c + b[3]) & BN_MASK2; - c = (l < c); - r[3] = l; - if (++dl >= 0) - break; - - save_dl = dl; - b += 4; - r += 4; - } - if (dl < 0) { - if (save_dl < dl) { - switch (dl - save_dl) { - case 1: - r[1] = b[1]; - if (++dl >= 0) - break; - /* fall thru */ - case 2: - r[2] = b[2]; - if (++dl >= 0) - break; - /* fall thru */ - case 3: - r[3] = b[3]; - if (++dl >= 0) - break; - } - b += 4; - r += 4; - } - } - if (dl < 0) { - for (;;) { - r[0] = b[0]; - if (++dl >= 0) - break; - r[1] = b[1]; - if (++dl >= 0) - break; - r[2] = b[2]; - if (++dl >= 0) - break; - r[3] = b[3]; - if (++dl >= 0) - break; - - b += 4; - r += 4; - } - } - } else { - int save_dl = dl; - while (c) { - t = (a[0] + c) & BN_MASK2; - c = (t < c); - r[0] = t; - if (--dl <= 0) - break; - - t = (a[1] + c) & BN_MASK2; - c = (t < c); - r[1] = t; - if (--dl <= 0) - break; - - t = (a[2] + c) & BN_MASK2; - c = (t < c); - r[2] = t; - if (--dl <= 0) - break; - - t = (a[3] + c) & BN_MASK2; - c = (t < c); - r[3] = t; - if (--dl <= 0) - break; - - save_dl = dl; - a += 4; - r += 4; - } - if (dl > 0) { - if (save_dl > dl) { - switch (save_dl - dl) { - case 1: - r[1] = a[1]; - if (--dl <= 0) - break; - /* fall thru */ - case 2: - r[2] = a[2]; - if (--dl <= 0) - break; - /* fall thru */ - case 3: - r[3] = a[3]; - if (--dl <= 0) - break; - } - a += 4; - r += 4; - } - } - if (dl > 0) { - for (;;) { - r[0] = a[0]; - if (--dl <= 0) - break; - r[1] = a[1]; - if (--dl <= 0) - break; - r[2] = a[2]; - if (--dl <= 0) - break; - r[3] = a[3]; - if (--dl <= 0) - break; - - a += 4; - r += 4; - } - } - } - return c; -} - #ifdef BN_RECURSION /* * Karatsuba recursive multiplication algorithm (cf. Knuth, The Art of @@ -505,7 +341,6 @@ void bn_mul_part_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n, bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ break; case -3: - /* break; */ case -2: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); /* + */ @@ -514,14 +349,12 @@ void bn_mul_part_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n, case -1: case 0: case 1: - /* break; */ case 2: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); /* + */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ neg = 1; break; case 3: - /* break; */ case 4: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); @@ -659,176 +492,6 @@ void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, bn_add_words(&(r[n]), &(r[n]), &(t[n]), n); } } - -/*- - * a and b must be the same size, which is n2. - * r needs to be n2 words and t needs to be n2*2 - * l is the low words of the output. - * t needs to be n2*3 - */ -void bn_mul_high(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, BN_ULONG *l, int n2, - BN_ULONG *t) -{ - int i, n; - int c1, c2; - int neg, oneg, zero; - BN_ULONG ll, lc, *lp, *mp; - - n = n2 / 2; - - /* Calculate (al-ah)*(bh-bl) */ - neg = zero = 0; - c1 = bn_cmp_words(&(a[0]), &(a[n]), n); - c2 = bn_cmp_words(&(b[n]), &(b[0]), n); - switch (c1 * 3 + c2) { - case -4: - bn_sub_words(&(r[0]), &(a[n]), &(a[0]), n); - bn_sub_words(&(r[n]), &(b[0]), &(b[n]), n); - break; - case -3: - zero = 1; - break; - case -2: - bn_sub_words(&(r[0]), &(a[n]), &(a[0]), n); - bn_sub_words(&(r[n]), &(b[n]), &(b[0]), n); - neg = 1; - break; - case -1: - case 0: - case 1: - zero = 1; - break; - case 2: - bn_sub_words(&(r[0]), &(a[0]), &(a[n]), n); - bn_sub_words(&(r[n]), &(b[0]), &(b[n]), n); - neg = 1; - break; - case 3: - zero = 1; - break; - case 4: - bn_sub_words(&(r[0]), &(a[0]), &(a[n]), n); - bn_sub_words(&(r[n]), &(b[n]), &(b[0]), n); - break; - } - - oneg = neg; - /* t[10] = (a[0]-a[1])*(b[1]-b[0]) */ - /* r[10] = (a[1]*b[1]) */ -# ifdef BN_MUL_COMBA - if (n == 8) { - bn_mul_comba8(&(t[0]), &(r[0]), &(r[n])); - bn_mul_comba8(r, &(a[n]), &(b[n])); - } else -# endif - { - bn_mul_recursive(&(t[0]), &(r[0]), &(r[n]), n, 0, 0, &(t[n2])); - bn_mul_recursive(r, &(a[n]), &(b[n]), n, 0, 0, &(t[n2])); - } - - /*- - * s0 == low(al*bl) - * s1 == low(ah*bh)+low((al-ah)*(bh-bl))+low(al*bl)+high(al*bl) - * We know s0 and s1 so the only unknown is high(al*bl) - * high(al*bl) == s1 - low(ah*bh+s0+(al-ah)*(bh-bl)) - * high(al*bl) == s1 - (r[0]+l[0]+t[0]) - */ - if (l != NULL) { - lp = &(t[n2 + n]); - bn_add_words(lp, &(r[0]), &(l[0]), n); - } else { - lp = &(r[0]); - } - - if (neg) - neg = (int)(bn_sub_words(&(t[n2]), lp, &(t[0]), n)); - else { - bn_add_words(&(t[n2]), lp, &(t[0]), n); - neg = 0; - } - - if (l != NULL) { - bn_sub_words(&(t[n2 + n]), &(l[n]), &(t[n2]), n); - } else { - lp = &(t[n2 + n]); - mp = &(t[n2]); - for (i = 0; i < n; i++) - lp[i] = ((~mp[i]) + 1) & BN_MASK2; - } - - /*- - * s[0] = low(al*bl) - * t[3] = high(al*bl) - * t[10] = (a[0]-a[1])*(b[1]-b[0]) neg is the sign - * r[10] = (a[1]*b[1]) - */ - /*- - * R[10] = al*bl - * R[21] = al*bl + ah*bh + (a[0]-a[1])*(b[1]-b[0]) - * R[32] = ah*bh - */ - /*- - * R[1]=t[3]+l[0]+r[0](+-)t[0] (have carry/borrow) - * R[2]=r[0]+t[3]+r[1](+-)t[1] (have carry/borrow) - * R[3]=r[1]+(carry/borrow) - */ - if (l != NULL) { - lp = &(t[n2]); - c1 = (int)(bn_add_words(lp, &(t[n2 + n]), &(l[0]), n)); - } else { - lp = &(t[n2 + n]); - c1 = 0; - } - c1 += (int)(bn_add_words(&(t[n2]), lp, &(r[0]), n)); - if (oneg) - c1 -= (int)(bn_sub_words(&(t[n2]), &(t[n2]), &(t[0]), n)); - else - c1 += (int)(bn_add_words(&(t[n2]), &(t[n2]), &(t[0]), n)); - - c2 = (int)(bn_add_words(&(r[0]), &(r[0]), &(t[n2 + n]), n)); - c2 += (int)(bn_add_words(&(r[0]), &(r[0]), &(r[n]), n)); - if (oneg) - c2 -= (int)(bn_sub_words(&(r[0]), &(r[0]), &(t[n]), n)); - else - c2 += (int)(bn_add_words(&(r[0]), &(r[0]), &(t[n]), n)); - - if (c1 != 0) { /* Add starting at r[0], could be +ve or -ve */ - i = 0; - if (c1 > 0) { - lc = c1; - do { - ll = (r[i] + lc) & BN_MASK2; - r[i++] = ll; - lc = (lc > ll); - } while (lc); - } else { - lc = -c1; - do { - ll = r[i]; - r[i++] = (ll - lc) & BN_MASK2; - lc = (lc > ll); - } while (lc); - } - } - if (c2 != 0) { /* Add starting at r[1] */ - i = n; - if (c2 > 0) { - lc = c2; - do { - ll = (r[i] + lc) & BN_MASK2; - r[i++] = ll; - lc = (lc > ll); - } while (lc); - } else { - lc = -c2; - do { - ll = r[i]; - r[i++] = (ll - lc) & BN_MASK2; - lc = (lc > ll); - } while (lc); - } - } -} #endif /* BN_RECURSION */ int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) @@ -853,7 +516,7 @@ int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) if ((al == 0) || (bl == 0)) { BN_zero(r); - return (1); + return 1; } top = al + bl; @@ -943,7 +606,7 @@ int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) err: bn_check_top(r); BN_CTX_end(ctx); - return (ret); + return ret; } void bn_mul_normal(BN_ULONG *r, BN_ULONG *a, int na, BN_ULONG *b, int nb) diff --git a/crypto/bn/bn_nist.c b/crypto/bn/bn_nist.c index 53598f97..fcc2b77f 100644 --- a/crypto/bn/bn_nist.c +++ b/crypto/bn/bn_nist.c @@ -254,7 +254,7 @@ static void nist_cp_bn_0(BN_ULONG *dst, const BN_ULONG *src, int top, int max) int i; #ifdef BN_DEBUG - OPENSSL_assert(top <= max); + assert(top <= max); #endif for (i = 0; i < top; i++) dst[i] = src[i]; diff --git a/crypto/bn/bn_prime.c b/crypto/bn/bn_prime.c index 616389cf..36d6e884 100644 --- a/crypto/bn/bn_prime.c +++ b/crypto/bn/bn_prime.c @@ -1,7 +1,5 @@ /* - * WARNING: do not edit! - * Generated by crypto/bn/bn_prime.pl - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -29,53 +27,6 @@ static int probable_prime_dh_safe(BIGNUM *rnd, int bits, const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx); -static const int prime_offsets[480] = { - 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, - 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, - 167, 169, 173, 179, 181, 191, 193, 197, 199, 211, 221, 223, 227, 229, - 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281, 283, 289, 293, - 299, 307, 311, 313, 317, 323, 331, 337, 347, 349, 353, 359, 361, 367, - 373, 377, 379, 383, 389, 391, 397, 401, 403, 409, 419, 421, 431, 433, - 437, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491, 493, 499, - 503, 509, 521, 523, 527, 529, 533, 541, 547, 551, 557, 559, 563, 569, - 571, 577, 587, 589, 593, 599, 601, 607, 611, 613, 617, 619, 629, 631, - 641, 643, 647, 653, 659, 661, 667, 673, 677, 683, 689, 691, 697, 701, - 703, 709, 713, 719, 727, 731, 733, 739, 743, 751, 757, 761, 767, 769, - 773, 779, 787, 793, 797, 799, 809, 811, 817, 821, 823, 827, 829, 839, - 841, 851, 853, 857, 859, 863, 871, 877, 881, 883, 887, 893, 899, 901, - 907, 911, 919, 923, 929, 937, 941, 943, 947, 949, 953, 961, 967, 971, - 977, 983, 989, 991, 997, 1003, 1007, 1009, 1013, 1019, 1021, 1027, 1031, - 1033, 1037, 1039, 1049, 1051, 1061, 1063, 1069, 1073, 1079, 1081, 1087, - 1091, 1093, 1097, 1103, 1109, 1117, 1121, 1123, 1129, 1139, 1147, 1151, - 1153, 1157, 1159, 1163, 1171, 1181, 1187, 1189, 1193, 1201, 1207, 1213, - 1217, 1219, 1223, 1229, 1231, 1237, 1241, 1247, 1249, 1259, 1261, 1271, - 1273, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1313, 1319, - 1321, 1327, 1333, 1339, 1343, 1349, 1357, 1361, 1363, 1367, 1369, 1373, - 1381, 1387, 1391, 1399, 1403, 1409, 1411, 1417, 1423, 1427, 1429, 1433, - 1439, 1447, 1451, 1453, 1457, 1459, 1469, 1471, 1481, 1483, 1487, 1489, - 1493, 1499, 1501, 1511, 1513, 1517, 1523, 1531, 1537, 1541, 1543, 1549, - 1553, 1559, 1567, 1571, 1577, 1579, 1583, 1591, 1597, 1601, 1607, 1609, - 1613, 1619, 1621, 1627, 1633, 1637, 1643, 1649, 1651, 1657, 1663, 1667, - 1669, 1679, 1681, 1691, 1693, 1697, 1699, 1703, 1709, 1711, 1717, 1721, - 1723, 1733, 1739, 1741, 1747, 1751, 1753, 1759, 1763, 1769, 1777, 1781, - 1783, 1787, 1789, 1801, 1807, 1811, 1817, 1819, 1823, 1829, 1831, 1843, - 1847, 1849, 1853, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1891, 1901, - 1907, 1909, 1913, 1919, 1921, 1927, 1931, 1933, 1937, 1943, 1949, 1951, - 1957, 1961, 1963, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, - 2021, 2027, 2029, 2033, 2039, 2041, 2047, 2053, 2059, 2063, 2069, 2071, - 2077, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2117, 2119, 2129, 2131, - 2137, 2141, 2143, 2147, 2153, 2159, 2161, 2171, 2173, 2179, 2183, 2197, - 2201, 2203, 2207, 2209, 2213, 2221, 2227, 2231, 2237, 2239, 2243, 2249, - 2251, 2257, 2263, 2267, 2269, 2273, 2279, 2281, 2287, 2291, 2293, 2297, - 2309, 2311 -}; - -static const int prime_offset_count = 480; -static const int prime_multiplier = 2310; -static const int prime_multiplier_bits = 11; /* 2^|prime_multiplier_bits| <= - * |prime_multiplier| */ -static const int first_prime_index = 5; - int BN_GENCB_call(BN_GENCB *cb, int a, int b) { /* No callback means continue */ @@ -127,7 +78,7 @@ int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, goto err; BN_CTX_start(ctx); t = BN_CTX_get(ctx); - if (!t) + if (t == NULL) goto err; loop: /* make a random number and set the top and bottom bits */ @@ -222,7 +173,7 @@ int BN_is_prime_fasttest_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed, if (mod == (BN_ULONG)-1) goto err; if (mod == 0) - return 0; + return BN_is_word(a, primes[i]); } if (!BN_GENCB_call(cb, 1, -1)) goto err; @@ -265,7 +216,7 @@ int BN_is_prime_fasttest_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed, goto err; for (i = 0; i < checks; i++) { - if (!BN_pseudo_rand_range(check, A1)) + if (!BN_priv_rand_range(check, A1)) goto err; if (!BN_add_word(check, 1)) goto err; @@ -290,83 +241,6 @@ int BN_is_prime_fasttest_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed, } BN_MONT_CTX_free(mont); - return (ret); -} - -int bn_probable_prime_dh_retry(BIGNUM *rnd, int bits, BN_CTX *ctx) -{ - int i; - int ret = 0; - - loop: - if (!BN_rand(rnd, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD)) - goto err; - - /* we now have a random number 'rand' to test. */ - - for (i = 1; i < NUMPRIMES; i++) { - /* check that rnd is a prime */ - BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]); - if (mod == (BN_ULONG)-1) - goto err; - if (mod <= 1) { - goto loop; - } - } - ret = 1; - - err: - bn_check_top(rnd); - return (ret); -} - -int bn_probable_prime_dh_coprime(BIGNUM *rnd, int bits, BN_CTX *ctx) -{ - int i; - BIGNUM *offset_index; - BIGNUM *offset_count; - int ret = 0; - - OPENSSL_assert(bits > prime_multiplier_bits); - - BN_CTX_start(ctx); - if ((offset_index = BN_CTX_get(ctx)) == NULL) - goto err; - if ((offset_count = BN_CTX_get(ctx)) == NULL) - goto err; - - if (!BN_add_word(offset_count, prime_offset_count)) - goto err; - - loop: - if (!BN_rand(rnd, bits - prime_multiplier_bits, - BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD)) - goto err; - if (BN_is_bit_set(rnd, bits)) - goto loop; - if (!BN_rand_range(offset_index, offset_count)) - goto err; - - if (!BN_mul_word(rnd, prime_multiplier) - || !BN_add_word(rnd, prime_offsets[BN_get_word(offset_index)])) - goto err; - - /* we now have a random number 'rand' to test. */ - - /* skip coprimes */ - for (i = first_prime_index; i < NUMPRIMES; i++) { - /* check that rnd is a prime */ - BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]); - if (mod == (BN_ULONG)-1) - goto err; - if (mod <= 1) - goto loop; - } - ret = 1; - - err: - BN_CTX_end(ctx); - bn_check_top(rnd); return ret; } @@ -405,8 +279,8 @@ static int probable_prime(BIGNUM *rnd, int bits, prime_t *mods) char is_single_word = bits <= BN_BITS2; again: - if (!BN_rand(rnd, bits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ODD)) - return (0); + if (!BN_priv_rand(rnd, bits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ODD)) + return 0; /* we now have a random number 'rnd' to test. */ for (i = 1; i < NUMPRIMES; i++) { BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]); @@ -472,11 +346,11 @@ static int probable_prime(BIGNUM *rnd, int bits, prime_t *mods) } } if (!BN_add_word(rnd, delta)) - return (0); + return 0; if (BN_num_bits(rnd) != bits) goto again; bn_check_top(rnd); - return (1); + return 1; } int bn_probable_prime_dh(BIGNUM *rnd, int bits, @@ -489,7 +363,7 @@ int bn_probable_prime_dh(BIGNUM *rnd, int bits, if ((t1 = BN_CTX_get(ctx)) == NULL) goto err; - if (!BN_rand(rnd, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD)) + if (!BN_priv_rand(rnd, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD)) goto err; /* we need ((rnd-rem) % add) == 0 */ @@ -525,7 +399,7 @@ int bn_probable_prime_dh(BIGNUM *rnd, int bits, err: BN_CTX_end(ctx); bn_check_top(rnd); - return (ret); + return ret; } static int probable_prime_dh_safe(BIGNUM *p, int bits, const BIGNUM *padd, @@ -545,7 +419,7 @@ static int probable_prime_dh_safe(BIGNUM *p, int bits, const BIGNUM *padd, if (!BN_rshift1(qadd, padd)) goto err; - if (!BN_rand(q, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD)) + if (!BN_priv_rand(q, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD)) goto err; /* we need ((rnd-rem) % add) == 0 */ @@ -592,5 +466,5 @@ static int probable_prime_dh_safe(BIGNUM *p, int bits, const BIGNUM *padd, err: BN_CTX_end(ctx); bn_check_top(p); - return (ret); + return ret; } diff --git a/crypto/bn/bn_prime.h b/crypto/bn/bn_prime.h index 41440fa4..a64c9630 100644 --- a/crypto/bn/bn_prime.h +++ b/crypto/bn/bn_prime.h @@ -2,7 +2,7 @@ * WARNING: do not edit! * Generated by crypto/bn/bn_prime.pl * - * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1998-2018 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 @@ -14,261 +14,260 @@ typedef unsigned short prime_t; # define NUMPRIMES 2048 static const prime_t primes[2048] = { - - 2, 3, 5, 7, 11, 13, 17, 19, - 23, 29, 31, 37, 41, 43, 47, 53, - 59, 61, 67, 71, 73, 79, 83, 89, - 97, 101, 103, 107, 109, 113, 127, 131, - 137, 139, 149, 151, 157, 163, 167, 173, - 179, 181, 191, 193, 197, 199, 211, 223, - 227, 229, 233, 239, 241, 251, 257, 263, - 269, 271, 277, 281, 283, 293, 307, 311, - 313, 317, 331, 337, 347, 349, 353, 359, - 367, 373, 379, 383, 389, 397, 401, 409, - 419, 421, 431, 433, 439, 443, 449, 457, - 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, - 571, 577, 587, 593, 599, 601, 607, 613, - 617, 619, 631, 641, 643, 647, 653, 659, - 661, 673, 677, 683, 691, 701, 709, 719, - 727, 733, 739, 743, 751, 757, 761, 769, - 773, 787, 797, 809, 811, 821, 823, 827, - 829, 839, 853, 857, 859, 863, 877, 881, - 883, 887, 907, 911, 919, 929, 937, 941, - 947, 953, 967, 971, 977, 983, 991, 997, - 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, - 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, - 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, - 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, - 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, - 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, - 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, - 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, - 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, - 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, - 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, - 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, - 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, - 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, - 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, - 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, - 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, - 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, - 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, - 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, - 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, - 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, - 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, - 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, - 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, - 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, - 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, - 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, - 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, - 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, - 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, - 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, - 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, - 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, - 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, - 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, - 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, - 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, - 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, - 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, - 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, - 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, - 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, - 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, - 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, - 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, - 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, - 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, - 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, - 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, - 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, - 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, - 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, - 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, - 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, - 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, - 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, - 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, - 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, - 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, - 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, - 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, - 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, - 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, - 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, - 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, - 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, - 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, - 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, - 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, - 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, - 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, - 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, - 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, - 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, - 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, - 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, - 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, - 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, - 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, - 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, - 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, - 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, - 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, - 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, - 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, - 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, - 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, - 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, - 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, - 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, - 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, - 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, - 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, - 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, - 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, - 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, - 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, - 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, - 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, - 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, - 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, - 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, - 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, - 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, - 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, - 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, - 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, - 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, - 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, - 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, - 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, - 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, - 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, - 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, - 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, - 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, - 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, - 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, - 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, - 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, - 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, - 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, - 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, - 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, - 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, - 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, - 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, - 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, - 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, - 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, - 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, - 9931, 9941, 9949, 9967, 9973, 10007, 10009, 10037, - 10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099, - 10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163, - 10169, 10177, 10181, 10193, 10211, 10223, 10243, 10247, - 10253, 10259, 10267, 10271, 10273, 10289, 10301, 10303, - 10313, 10321, 10331, 10333, 10337, 10343, 10357, 10369, - 10391, 10399, 10427, 10429, 10433, 10453, 10457, 10459, - 10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531, - 10559, 10567, 10589, 10597, 10601, 10607, 10613, 10627, - 10631, 10639, 10651, 10657, 10663, 10667, 10687, 10691, - 10709, 10711, 10723, 10729, 10733, 10739, 10753, 10771, - 10781, 10789, 10799, 10831, 10837, 10847, 10853, 10859, - 10861, 10867, 10883, 10889, 10891, 10903, 10909, 10937, - 10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003, - 11027, 11047, 11057, 11059, 11069, 11071, 11083, 11087, - 11093, 11113, 11117, 11119, 11131, 11149, 11159, 11161, - 11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251, - 11257, 11261, 11273, 11279, 11287, 11299, 11311, 11317, - 11321, 11329, 11351, 11353, 11369, 11383, 11393, 11399, - 11411, 11423, 11437, 11443, 11447, 11467, 11471, 11483, - 11489, 11491, 11497, 11503, 11519, 11527, 11549, 11551, - 11579, 11587, 11593, 11597, 11617, 11621, 11633, 11657, - 11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731, - 11743, 11777, 11779, 11783, 11789, 11801, 11807, 11813, - 11821, 11827, 11831, 11833, 11839, 11863, 11867, 11887, - 11897, 11903, 11909, 11923, 11927, 11933, 11939, 11941, - 11953, 11959, 11969, 11971, 11981, 11987, 12007, 12011, - 12037, 12041, 12043, 12049, 12071, 12073, 12097, 12101, - 12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161, - 12163, 12197, 12203, 12211, 12227, 12239, 12241, 12251, - 12253, 12263, 12269, 12277, 12281, 12289, 12301, 12323, - 12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401, - 12409, 12413, 12421, 12433, 12437, 12451, 12457, 12473, - 12479, 12487, 12491, 12497, 12503, 12511, 12517, 12527, - 12539, 12541, 12547, 12553, 12569, 12577, 12583, 12589, - 12601, 12611, 12613, 12619, 12637, 12641, 12647, 12653, - 12659, 12671, 12689, 12697, 12703, 12713, 12721, 12739, - 12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821, - 12823, 12829, 12841, 12853, 12889, 12893, 12899, 12907, - 12911, 12917, 12919, 12923, 12941, 12953, 12959, 12967, - 12973, 12979, 12983, 13001, 13003, 13007, 13009, 13033, - 13037, 13043, 13049, 13063, 13093, 13099, 13103, 13109, - 13121, 13127, 13147, 13151, 13159, 13163, 13171, 13177, - 13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259, - 13267, 13291, 13297, 13309, 13313, 13327, 13331, 13337, - 13339, 13367, 13381, 13397, 13399, 13411, 13417, 13421, - 13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499, - 13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597, - 13613, 13619, 13627, 13633, 13649, 13669, 13679, 13681, - 13687, 13691, 13693, 13697, 13709, 13711, 13721, 13723, - 13729, 13751, 13757, 13759, 13763, 13781, 13789, 13799, - 13807, 13829, 13831, 13841, 13859, 13873, 13877, 13879, - 13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933, - 13963, 13967, 13997, 13999, 14009, 14011, 14029, 14033, - 14051, 14057, 14071, 14081, 14083, 14087, 14107, 14143, - 14149, 14153, 14159, 14173, 14177, 14197, 14207, 14221, - 14243, 14249, 14251, 14281, 14293, 14303, 14321, 14323, - 14327, 14341, 14347, 14369, 14387, 14389, 14401, 14407, - 14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461, - 14479, 14489, 14503, 14519, 14533, 14537, 14543, 14549, - 14551, 14557, 14561, 14563, 14591, 14593, 14621, 14627, - 14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699, - 14713, 14717, 14723, 14731, 14737, 14741, 14747, 14753, - 14759, 14767, 14771, 14779, 14783, 14797, 14813, 14821, - 14827, 14831, 14843, 14851, 14867, 14869, 14879, 14887, - 14891, 14897, 14923, 14929, 14939, 14947, 14951, 14957, - 14969, 14983, 15013, 15017, 15031, 15053, 15061, 15073, - 15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137, - 15139, 15149, 15161, 15173, 15187, 15193, 15199, 15217, - 15227, 15233, 15241, 15259, 15263, 15269, 15271, 15277, - 15287, 15289, 15299, 15307, 15313, 15319, 15329, 15331, - 15349, 15359, 15361, 15373, 15377, 15383, 15391, 15401, - 15413, 15427, 15439, 15443, 15451, 15461, 15467, 15473, - 15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569, - 15581, 15583, 15601, 15607, 15619, 15629, 15641, 15643, - 15647, 15649, 15661, 15667, 15671, 15679, 15683, 15727, - 15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773, - 15787, 15791, 15797, 15803, 15809, 15817, 15823, 15859, - 15877, 15881, 15887, 15889, 15901, 15907, 15913, 15919, - 15923, 15937, 15959, 15971, 15973, 15991, 16001, 16007, - 16033, 16057, 16061, 16063, 16067, 16069, 16073, 16087, - 16091, 16097, 16103, 16111, 16127, 16139, 16141, 16183, - 16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249, - 16253, 16267, 16273, 16301, 16319, 16333, 16339, 16349, - 16361, 16363, 16369, 16381, 16411, 16417, 16421, 16427, - 16433, 16447, 16451, 16453, 16477, 16481, 16487, 16493, - 16519, 16529, 16547, 16553, 16561, 16567, 16573, 16603, - 16607, 16619, 16631, 16633, 16649, 16651, 16657, 16661, - 16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747, - 16759, 16763, 16787, 16811, 16823, 16829, 16831, 16843, - 16871, 16879, 16883, 16889, 16901, 16903, 16921, 16927, - 16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993, - 17011, 17021, 17027, 17029, 17033, 17041, 17047, 17053, - 17077, 17093, 17099, 17107, 17117, 17123, 17137, 17159, - 17167, 17183, 17189, 17191, 17203, 17207, 17209, 17231, - 17239, 17257, 17291, 17293, 17299, 17317, 17321, 17327, - 17333, 17341, 17351, 17359, 17377, 17383, 17387, 17389, - 17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467, - 17471, 17477, 17483, 17489, 17491, 17497, 17509, 17519, - 17539, 17551, 17569, 17573, 17579, 17581, 17597, 17599, - 17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683, - 17707, 17713, 17729, 17737, 17747, 17749, 17761, 17783, - 17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863, + 2, 3, 5, 7, 11, 13, 17, 19, + 23, 29, 31, 37, 41, 43, 47, 53, + 59, 61, 67, 71, 73, 79, 83, 89, + 97, 101, 103, 107, 109, 113, 127, 131, + 137, 139, 149, 151, 157, 163, 167, 173, + 179, 181, 191, 193, 197, 199, 211, 223, + 227, 229, 233, 239, 241, 251, 257, 263, + 269, 271, 277, 281, 283, 293, 307, 311, + 313, 317, 331, 337, 347, 349, 353, 359, + 367, 373, 379, 383, 389, 397, 401, 409, + 419, 421, 431, 433, 439, 443, 449, 457, + 461, 463, 467, 479, 487, 491, 499, 503, + 509, 521, 523, 541, 547, 557, 563, 569, + 571, 577, 587, 593, 599, 601, 607, 613, + 617, 619, 631, 641, 643, 647, 653, 659, + 661, 673, 677, 683, 691, 701, 709, 719, + 727, 733, 739, 743, 751, 757, 761, 769, + 773, 787, 797, 809, 811, 821, 823, 827, + 829, 839, 853, 857, 859, 863, 877, 881, + 883, 887, 907, 911, 919, 929, 937, 941, + 947, 953, 967, 971, 977, 983, 991, 997, + 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, + 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, + 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, + 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, + 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, + 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, + 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, + 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, + 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, + 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, + 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, + 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, + 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, + 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, + 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, + 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, + 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, + 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, + 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, + 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, + 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, + 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, + 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, + 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, + 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, + 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, + 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, + 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, + 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, + 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, + 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, + 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, + 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, + 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, + 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, + 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, + 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, + 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, + 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, + 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, + 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, + 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, + 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, + 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, + 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, + 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, + 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, + 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, + 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, + 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, + 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, + 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, + 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, + 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, + 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, + 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, + 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, + 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, + 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, + 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, + 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, + 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, + 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, + 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, + 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, + 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, + 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, + 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, + 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, + 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, + 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, + 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, + 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, + 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, + 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, + 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, + 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, + 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, + 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, + 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, + 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, + 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, + 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, + 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, + 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, + 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, + 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, + 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, + 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, + 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, + 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, + 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, + 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, + 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, + 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, + 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, + 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, + 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, + 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, + 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, + 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, + 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, + 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, + 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, + 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, + 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, + 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, + 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, + 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, + 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, + 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, + 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, + 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, + 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, + 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, + 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, + 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, + 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, + 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, + 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, + 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, + 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, + 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, + 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, + 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, + 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, + 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, + 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, + 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, + 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, + 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, + 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, + 9931, 9941, 9949, 9967, 9973, 10007, 10009, 10037, + 10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099, + 10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163, + 10169, 10177, 10181, 10193, 10211, 10223, 10243, 10247, + 10253, 10259, 10267, 10271, 10273, 10289, 10301, 10303, + 10313, 10321, 10331, 10333, 10337, 10343, 10357, 10369, + 10391, 10399, 10427, 10429, 10433, 10453, 10457, 10459, + 10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531, + 10559, 10567, 10589, 10597, 10601, 10607, 10613, 10627, + 10631, 10639, 10651, 10657, 10663, 10667, 10687, 10691, + 10709, 10711, 10723, 10729, 10733, 10739, 10753, 10771, + 10781, 10789, 10799, 10831, 10837, 10847, 10853, 10859, + 10861, 10867, 10883, 10889, 10891, 10903, 10909, 10937, + 10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003, + 11027, 11047, 11057, 11059, 11069, 11071, 11083, 11087, + 11093, 11113, 11117, 11119, 11131, 11149, 11159, 11161, + 11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251, + 11257, 11261, 11273, 11279, 11287, 11299, 11311, 11317, + 11321, 11329, 11351, 11353, 11369, 11383, 11393, 11399, + 11411, 11423, 11437, 11443, 11447, 11467, 11471, 11483, + 11489, 11491, 11497, 11503, 11519, 11527, 11549, 11551, + 11579, 11587, 11593, 11597, 11617, 11621, 11633, 11657, + 11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731, + 11743, 11777, 11779, 11783, 11789, 11801, 11807, 11813, + 11821, 11827, 11831, 11833, 11839, 11863, 11867, 11887, + 11897, 11903, 11909, 11923, 11927, 11933, 11939, 11941, + 11953, 11959, 11969, 11971, 11981, 11987, 12007, 12011, + 12037, 12041, 12043, 12049, 12071, 12073, 12097, 12101, + 12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161, + 12163, 12197, 12203, 12211, 12227, 12239, 12241, 12251, + 12253, 12263, 12269, 12277, 12281, 12289, 12301, 12323, + 12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401, + 12409, 12413, 12421, 12433, 12437, 12451, 12457, 12473, + 12479, 12487, 12491, 12497, 12503, 12511, 12517, 12527, + 12539, 12541, 12547, 12553, 12569, 12577, 12583, 12589, + 12601, 12611, 12613, 12619, 12637, 12641, 12647, 12653, + 12659, 12671, 12689, 12697, 12703, 12713, 12721, 12739, + 12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821, + 12823, 12829, 12841, 12853, 12889, 12893, 12899, 12907, + 12911, 12917, 12919, 12923, 12941, 12953, 12959, 12967, + 12973, 12979, 12983, 13001, 13003, 13007, 13009, 13033, + 13037, 13043, 13049, 13063, 13093, 13099, 13103, 13109, + 13121, 13127, 13147, 13151, 13159, 13163, 13171, 13177, + 13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259, + 13267, 13291, 13297, 13309, 13313, 13327, 13331, 13337, + 13339, 13367, 13381, 13397, 13399, 13411, 13417, 13421, + 13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499, + 13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597, + 13613, 13619, 13627, 13633, 13649, 13669, 13679, 13681, + 13687, 13691, 13693, 13697, 13709, 13711, 13721, 13723, + 13729, 13751, 13757, 13759, 13763, 13781, 13789, 13799, + 13807, 13829, 13831, 13841, 13859, 13873, 13877, 13879, + 13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933, + 13963, 13967, 13997, 13999, 14009, 14011, 14029, 14033, + 14051, 14057, 14071, 14081, 14083, 14087, 14107, 14143, + 14149, 14153, 14159, 14173, 14177, 14197, 14207, 14221, + 14243, 14249, 14251, 14281, 14293, 14303, 14321, 14323, + 14327, 14341, 14347, 14369, 14387, 14389, 14401, 14407, + 14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461, + 14479, 14489, 14503, 14519, 14533, 14537, 14543, 14549, + 14551, 14557, 14561, 14563, 14591, 14593, 14621, 14627, + 14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699, + 14713, 14717, 14723, 14731, 14737, 14741, 14747, 14753, + 14759, 14767, 14771, 14779, 14783, 14797, 14813, 14821, + 14827, 14831, 14843, 14851, 14867, 14869, 14879, 14887, + 14891, 14897, 14923, 14929, 14939, 14947, 14951, 14957, + 14969, 14983, 15013, 15017, 15031, 15053, 15061, 15073, + 15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137, + 15139, 15149, 15161, 15173, 15187, 15193, 15199, 15217, + 15227, 15233, 15241, 15259, 15263, 15269, 15271, 15277, + 15287, 15289, 15299, 15307, 15313, 15319, 15329, 15331, + 15349, 15359, 15361, 15373, 15377, 15383, 15391, 15401, + 15413, 15427, 15439, 15443, 15451, 15461, 15467, 15473, + 15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569, + 15581, 15583, 15601, 15607, 15619, 15629, 15641, 15643, + 15647, 15649, 15661, 15667, 15671, 15679, 15683, 15727, + 15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773, + 15787, 15791, 15797, 15803, 15809, 15817, 15823, 15859, + 15877, 15881, 15887, 15889, 15901, 15907, 15913, 15919, + 15923, 15937, 15959, 15971, 15973, 15991, 16001, 16007, + 16033, 16057, 16061, 16063, 16067, 16069, 16073, 16087, + 16091, 16097, 16103, 16111, 16127, 16139, 16141, 16183, + 16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249, + 16253, 16267, 16273, 16301, 16319, 16333, 16339, 16349, + 16361, 16363, 16369, 16381, 16411, 16417, 16421, 16427, + 16433, 16447, 16451, 16453, 16477, 16481, 16487, 16493, + 16519, 16529, 16547, 16553, 16561, 16567, 16573, 16603, + 16607, 16619, 16631, 16633, 16649, 16651, 16657, 16661, + 16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747, + 16759, 16763, 16787, 16811, 16823, 16829, 16831, 16843, + 16871, 16879, 16883, 16889, 16901, 16903, 16921, 16927, + 16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993, + 17011, 17021, 17027, 17029, 17033, 17041, 17047, 17053, + 17077, 17093, 17099, 17107, 17117, 17123, 17137, 17159, + 17167, 17183, 17189, 17191, 17203, 17207, 17209, 17231, + 17239, 17257, 17291, 17293, 17299, 17317, 17321, 17327, + 17333, 17341, 17351, 17359, 17377, 17383, 17387, 17389, + 17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467, + 17471, 17477, 17483, 17489, 17491, 17497, 17509, 17519, + 17539, 17551, 17569, 17573, 17579, 17581, 17597, 17599, + 17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683, + 17707, 17713, 17729, 17737, 17747, 17749, 17761, 17783, + 17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863, }; diff --git a/crypto/bn/bn_prime.pl b/crypto/bn/bn_prime.pl index 163d4a9d..eeca475b 100644 --- a/crypto/bn/bn_prime.pl +++ b/crypto/bn/bn_prime.pl @@ -1,17 +1,19 @@ #! /usr/bin/env perl -# Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 1998-2018 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 +# Output year depends on the year of the script. +my $YEAR = [localtime([stat($0)]->[9])]->[5] + 1900; print <<"EOF"; /* * WARNING: do not edit! * Generated by crypto/bn/bn_prime.pl * - * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1998-$YEAR 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 @@ -38,9 +40,9 @@ loop: while ($#primes < $num-1) { print "typedef unsigned short prime_t;\n"; printf "# define NUMPRIMES %d\n\n", $num; -printf "static const prime_t primes[%d] = {\n", $num; +printf "static const prime_t primes[%d] = {", $num; for (my $i = 0; $i <= $#primes; $i++) { - printf "\n " if ($i % 8) == 0; - printf "%4d, ", $primes[$i]; + printf "\n " if ($i % 8) == 0; + printf " %5d,", $primes[$i]; } print "\n};\n"; diff --git a/crypto/bn/bn_print.c b/crypto/bn/bn_print.c index 5ffe2fc9..1853269d 100644 --- a/crypto/bn/bn_print.c +++ b/crypto/bn/bn_print.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,7 +8,7 @@ */ #include -#include +#include "internal/ctype.h" #include #include "internal/cryptlib.h" #include @@ -32,27 +32,27 @@ char *BN_bn2hex(const BIGNUM *a) } p = buf; if (a->neg) - *(p++) = '-'; + *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]; + v = (int)((a->d[i] >> j) & 0xff); + if (z || v != 0) { + *p++ = Hex[v >> 4]; + *p++ = Hex[v & 0x0f]; z = 1; } } } *p = '\0'; err: - return (buf); + return buf; } /* Must 'OPENSSL_free' the returned data */ char *BN_bn2dec(const BIGNUM *a) { - int i = 0, num, ok = 0; + int i = 0, num, ok = 0, n, tbytes; char *buf = NULL; char *p; BIGNUM *t = NULL; @@ -67,22 +67,22 @@ char *BN_bn2dec(const BIGNUM *a) */ i = BN_num_bits(a) * 3; num = (i / 10 + i / 1000 + 1) + 1; + tbytes = num + 3; /* negative and terminator and one spare? */ 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)) { + buf = OPENSSL_malloc(tbytes); + 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'; + *p++ = '0'; + *p++ = '\0'; } else { if (BN_is_negative(t)) *p++ = '-'; @@ -101,14 +101,16 @@ char *BN_bn2dec(const BIGNUM *a) * 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++; + n = BIO_snprintf(p, tbytes - (size_t)(p - buf), BN_DEC_FMT1, *lp); + if (n < 0) + goto err; + p += n; while (lp != bn_data) { lp--; - BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp); - while (*p) - p++; + n = BIO_snprintf(p, tbytes - (size_t)(p - buf), BN_DEC_FMT2, *lp); + if (n < 0) + goto err; + p += n; } } ok = 1; @@ -128,28 +130,28 @@ int BN_hex2bn(BIGNUM **bn, const char *a) int neg = 0, h, m, i, j, k, c; int num; - if ((a == NULL) || (*a == '\0')) - return (0); + 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++) + for (i = 0; i <= INT_MAX / 4 && ossl_isxdigit(a[i]); i++) continue; - if (i == 0 || i > INT_MAX/4) + if (i == 0 || i > INT_MAX / 4) goto err; num = i + neg; if (bn == NULL) - return (num); + 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); + return 0; } else { ret = *bn; BN_zero(ret); @@ -163,7 +165,7 @@ int BN_hex2bn(BIGNUM **bn, const char *a) m = 0; h = 0; while (j > 0) { - m = ((BN_BYTES * 2) <= j) ? (BN_BYTES * 2) : j; + m = (BN_BYTES * 2 <= j) ? BN_BYTES * 2 : j; l = 0; for (;;) { c = a[j - m]; @@ -177,7 +179,7 @@ int BN_hex2bn(BIGNUM **bn, const char *a) break; } } - j -= (BN_BYTES * 2); + j -= BN_BYTES * 2; } ret->top = h; bn_correct_top(ret); @@ -187,11 +189,11 @@ int BN_hex2bn(BIGNUM **bn, const char *a) /* Don't set the negative flag if it's zero. */ if (ret->top != 0) ret->neg = neg; - return (num); + return num; err: if (*bn == NULL) BN_free(ret); - return (0); + return 0; } int BN_dec2bn(BIGNUM **bn, const char *a) @@ -201,22 +203,22 @@ int BN_dec2bn(BIGNUM **bn, const char *a) int neg = 0, i, j; int num; - if ((a == NULL) || (*a == '\0')) - return (0); + 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++) + for (i = 0; i <= INT_MAX / 4 && ossl_isdigit(a[i]); i++) continue; - if (i == 0 || i > INT_MAX/4) + if (i == 0 || i > INT_MAX / 4) goto err; num = i + neg; if (bn == NULL) - return (num); + return num; /* * a is the start of the digits, and it is 'i' long. We chop it into @@ -224,7 +226,7 @@ int BN_dec2bn(BIGNUM **bn, const char *a) */ if (*bn == NULL) { if ((ret = BN_new()) == NULL) - return (0); + return 0; } else { ret = *bn; BN_zero(ret); @@ -234,7 +236,7 @@ int BN_dec2bn(BIGNUM **bn, const char *a) if (bn_expand(ret, i * 4) == NULL) goto err; - j = BN_DEC_NUM - (i % BN_DEC_NUM); + j = BN_DEC_NUM - i % BN_DEC_NUM; if (j == BN_DEC_NUM) j = 0; l = 0; @@ -257,11 +259,11 @@ int BN_dec2bn(BIGNUM **bn, const char *a) /* Don't set the negative flag if it's zero. */ if (ret->top != 0) ret->neg = neg; - return (num); + return num; err: if (*bn == NULL) BN_free(ret); - return (0); + return 0; } int BN_asc2bn(BIGNUM **bn, const char *a) @@ -291,11 +293,11 @@ int BN_print_fp(FILE *fp, const BIGNUM *a) int ret; if ((b = BIO_new(BIO_s_file())) == NULL) - return (0); + return 0; BIO_set_fp(b, fp, BIO_NOCLOSE); ret = BN_print(b, a); BIO_free(b); - return (ret); + return ret; } # endif @@ -304,16 +306,16 @@ 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)) + if ((a->neg) && BIO_write(bp, "-", 1) != 1) goto end; - if (BN_is_zero(a) && (BIO_write(bp, "0", 1) != 1)) + 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) + v = (int)((a->d[i] >> j) & 0x0f); + if (z || v != 0) { + if (BIO_write(bp, &Hex[v], 1) != 1) goto end; z = 1; } @@ -321,7 +323,7 @@ int BN_print(BIO *bp, const BIGNUM *a) } ret = 1; end: - return (ret); + return ret; } char *BN_options(void) @@ -332,12 +334,12 @@ char *BN_options(void) if (!init) { init++; #ifdef BN_LLONG - BIO_snprintf(data, sizeof(data), "bn(%d,%d)", - (int)sizeof(BN_ULLONG) * 8, (int)sizeof(BN_ULONG) * 8); + BIO_snprintf(data, sizeof(data), "bn(%zu,%zu)", + sizeof(BN_ULLONG) * 8, sizeof(BN_ULONG) * 8); #else - BIO_snprintf(data, sizeof(data), "bn(%d,%d)", - (int)sizeof(BN_ULONG) * 8, (int)sizeof(BN_ULONG) * 8); + BIO_snprintf(data, sizeof(data), "bn(%zu,%zu)", + sizeof(BN_ULONG) * 8, sizeof(BN_ULONG) * 8); #endif } - return (data); + return data; } diff --git a/crypto/bn/bn_rand.c b/crypto/bn/bn_rand.c index 9ce4c5f6..0be21600 100644 --- a/crypto/bn/bn_rand.c +++ b/crypto/bn/bn_rand.c @@ -14,11 +14,14 @@ #include #include -static int bnrand(int pseudorand, BIGNUM *rnd, int bits, int top, int bottom) +typedef enum bnrand_flag_e { + NORMAL, TESTING, PRIVATE +} BNRAND_FLAG; + +static int bnrand(BNRAND_FLAG flag, BIGNUM *rnd, int bits, int top, int bottom) { unsigned char *buf = NULL; - int ret = 0, bit, bytes, mask; - time_t tim; + int b, ret = 0, bit, bytes, mask; if (bits == 0) { if (top != BN_RAND_TOP_ANY || bottom != BN_RAND_BOTTOM_ANY) @@ -40,13 +43,11 @@ static int bnrand(int pseudorand, BIGNUM *rnd, int bits, int top, int bottom) } /* make a random number and set the top and bottom bits */ - time(&tim); - RAND_add(&tim, sizeof(tim), 0.0); - - if (RAND_bytes(buf, bytes) <= 0) + b = flag == NORMAL ? RAND_bytes(buf, bytes) : RAND_priv_bytes(buf, bytes); + if (b <= 0) goto err; - if (pseudorand == 2) { + if (flag == TESTING) { /* * generate patterns that are more likely to trigger BN library bugs */ @@ -86,7 +87,7 @@ static int bnrand(int pseudorand, BIGNUM *rnd, int bits, int top, int bottom) err: OPENSSL_clear_free(buf, bytes); bn_check_top(rnd); - return (ret); + return ret; toosmall: BNerr(BN_F_BNRAND, BN_R_BITS_TOO_SMALL); @@ -95,29 +96,27 @@ toosmall: int BN_rand(BIGNUM *rnd, int bits, int top, int bottom) { - return bnrand(0, rnd, bits, top, bottom); -} - -int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom) -{ - return bnrand(1, rnd, bits, top, bottom); + return bnrand(NORMAL, rnd, bits, top, bottom); } int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom) { - return bnrand(2, rnd, bits, top, bottom); + return bnrand(TESTING, rnd, bits, top, bottom); +} + +int BN_priv_rand(BIGNUM *rnd, int bits, int top, int bottom) +{ + return bnrand(PRIVATE, rnd, bits, top, bottom); } /* random number r: 0 <= r < range */ -static int bn_rand_range(int pseudo, BIGNUM *r, const BIGNUM *range) +static int bnrand_range(BNRAND_FLAG flag, BIGNUM *r, const BIGNUM *range) { - int (*bn_rand) (BIGNUM *, int, int, int) = - pseudo ? BN_pseudo_rand : BN_rand; - int n; + int b, n; int count = 100; if (range->neg || BN_is_zero(range)) { - BNerr(BN_F_BN_RAND_RANGE, BN_R_INVALID_RANGE); + BNerr(BN_F_BNRAND_RANGE, BN_R_INVALID_RANGE); return 0; } @@ -133,7 +132,10 @@ static int bn_rand_range(int pseudo, BIGNUM *r, const BIGNUM *range) * than range */ do { - if (!bn_rand(r, n + 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY)) + b = flag == NORMAL + ? BN_rand(r, n + 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY) + : BN_priv_rand(r, n + 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY); + if (!b) return 0; /* * If r < 3*range, use r := r MOD range (which is either r, r - @@ -150,7 +152,7 @@ static int bn_rand_range(int pseudo, BIGNUM *r, const BIGNUM *range) } if (!--count) { - BNerr(BN_F_BN_RAND_RANGE, BN_R_TOO_MANY_ITERATIONS); + BNerr(BN_F_BNRAND_RANGE, BN_R_TOO_MANY_ITERATIONS); return 0; } @@ -159,11 +161,11 @@ static int bn_rand_range(int pseudo, BIGNUM *r, const BIGNUM *range) } else { do { /* range = 11..._2 or range = 101..._2 */ - if (!bn_rand(r, n, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY)) + if (!BN_rand(r, n, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY)) return 0; if (!--count) { - BNerr(BN_F_BN_RAND_RANGE, BN_R_TOO_MANY_ITERATIONS); + BNerr(BN_F_BNRAND_RANGE, BN_R_TOO_MANY_ITERATIONS); return 0; } } @@ -176,12 +178,22 @@ static int bn_rand_range(int pseudo, BIGNUM *r, const BIGNUM *range) int BN_rand_range(BIGNUM *r, const BIGNUM *range) { - return bn_rand_range(0, r, range); + return bnrand_range(NORMAL, r, range); +} + +int BN_priv_rand_range(BIGNUM *r, const BIGNUM *range) +{ + return bnrand_range(PRIVATE, r, range); +} + +int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom) +{ + return BN_rand(rnd, bits, top, bottom); } int BN_pseudo_rand_range(BIGNUM *r, const BIGNUM *range) { - return bn_rand_range(1, r, range); + return BN_rand_range(r, range); } /* diff --git a/crypto/bn/bn_recp.c b/crypto/bn/bn_recp.c index 20585b9d..e8736991 100644 --- a/crypto/bn/bn_recp.c +++ b/crypto/bn/bn_recp.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -22,12 +22,12 @@ BN_RECP_CTX *BN_RECP_CTX_new(void) BN_RECP_CTX *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) - return (NULL); + return NULL; bn_init(&(ret->N)); bn_init(&(ret->Nr)); ret->flags = BN_FLG_MALLOCED; - return (ret); + return ret; } void BN_RECP_CTX_free(BN_RECP_CTX *recp) @@ -48,7 +48,7 @@ int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *d, BN_CTX *ctx) BN_zero(&(recp->Nr)); recp->num_bits = BN_num_bits(d); recp->shift = 0; - return (1); + return 1; } int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y, @@ -77,7 +77,7 @@ int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y, err: BN_CTX_end(ctx); bn_check_top(r); - return (ret); + return ret; } int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, @@ -87,17 +87,11 @@ int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, BIGNUM *a, *b, *d, *r; BN_CTX_start(ctx); + d = (dv != NULL) ? dv : BN_CTX_get(ctx); + r = (rem != NULL) ? rem : BN_CTX_get(ctx); a = BN_CTX_get(ctx); b = BN_CTX_get(ctx); - if (dv != NULL) - d = dv; - else - d = BN_CTX_get(ctx); - if (rem != NULL) - r = rem; - else - r = BN_CTX_get(ctx); - if (a == NULL || b == NULL || d == NULL || r == NULL) + if (b == NULL) goto err; if (BN_ucmp(m, &(recp->N)) < 0) { @@ -107,7 +101,7 @@ int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, return 0; } BN_CTX_end(ctx); - return (1); + return 1; } /* @@ -167,7 +161,7 @@ int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, BN_CTX_end(ctx); bn_check_top(dv); bn_check_top(rem); - return (ret); + return ret; } /* @@ -195,5 +189,5 @@ int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx) err: bn_check_top(r); BN_CTX_end(ctx); - return (ret); + return ret; } diff --git a/crypto/bn/bn_shift.c b/crypto/bn/bn_shift.c index 6a1eec80..15d4b321 100644 --- a/crypto/bn/bn_shift.c +++ b/crypto/bn/bn_shift.c @@ -21,11 +21,11 @@ int BN_lshift1(BIGNUM *r, const BIGNUM *a) if (r != a) { r->neg = a->neg; if (bn_wexpand(r, a->top + 1) == NULL) - return (0); + return 0; r->top = a->top; } else { if (bn_wexpand(r, a->top + 1) == NULL) - return (0); + return 0; } ap = a->d; rp = r->d; @@ -40,7 +40,7 @@ int BN_lshift1(BIGNUM *r, const BIGNUM *a) r->top++; } bn_check_top(r); - return (1); + return 1; } int BN_rshift1(BIGNUM *r, const BIGNUM *a) @@ -53,14 +53,14 @@ int BN_rshift1(BIGNUM *r, const BIGNUM *a) if (BN_is_zero(a)) { BN_zero(r); - return (1); + return 1; } i = a->top; ap = a->d; j = i - (ap[i - 1] == 1); if (a != r) { if (bn_wexpand(r, j) == NULL) - return (0); + return 0; r->neg = a->neg; } rp = r->d; @@ -77,7 +77,7 @@ int BN_rshift1(BIGNUM *r, const BIGNUM *a) if (!r->top) r->neg = 0; /* don't allow negative zero */ bn_check_top(r); - return (1); + return 1; } int BN_lshift(BIGNUM *r, const BIGNUM *a, int n) @@ -96,7 +96,7 @@ int BN_lshift(BIGNUM *r, const BIGNUM *a, int n) nw = n / BN_BITS2; if (bn_wexpand(r, a->top + nw + 1) == NULL) - return (0); + return 0; r->neg = a->neg; lb = n % BN_BITS2; rb = BN_BITS2 - lb; @@ -116,7 +116,7 @@ int BN_lshift(BIGNUM *r, const BIGNUM *a, int n) r->top = a->top + nw + 1; bn_correct_top(r); bn_check_top(r); - return (1); + return 1; } int BN_rshift(BIGNUM *r, const BIGNUM *a, int n) @@ -138,12 +138,12 @@ int BN_rshift(BIGNUM *r, const BIGNUM *a, int n) lb = BN_BITS2 - rb; if (nw >= a->top || a->top == 0) { BN_zero(r); - return (1); + return 1; } i = (BN_num_bits(a) - n + (BN_BITS2 - 1)) / BN_BITS2; if (r != a) { if (bn_wexpand(r, i) == NULL) - return (0); + return 0; r->neg = a->neg; } else { if (n == 0) @@ -171,5 +171,5 @@ int BN_rshift(BIGNUM *r, const BIGNUM *a, int n) if (!r->top) r->neg = 0; /* don't allow negative zero */ bn_check_top(r); - return (1); + return 1; } diff --git a/crypto/bn/bn_sqr.c b/crypto/bn/bn_sqr.c index 44e7332a..dbfe9b82 100644 --- a/crypto/bn/bn_sqr.c +++ b/crypto/bn/bn_sqr.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -32,7 +32,7 @@ int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) BN_CTX_start(ctx); rr = (a != r) ? r : BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); - if (!rr || !tmp) + if (rr == NULL || tmp == NULL) goto err; max = 2 * al; /* Non-zero (from above) */ @@ -98,7 +98,7 @@ int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) bn_check_top(rr); bn_check_top(tmp); BN_CTX_end(ctx); - return (ret); + return ret; } /* tmp must have 2*n words */ diff --git a/crypto/bn/bn_sqrt.c b/crypto/bn/bn_sqrt.c index 84376c78..37cdaf87 100644 --- a/crypto/bn/bn_sqrt.c +++ b/crypto/bn/bn_sqrt.c @@ -39,7 +39,7 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) } BNerr(BN_F_BN_MOD_SQRT, BN_R_P_IS_NOT_PRIME); - return (NULL); + return NULL; } if (BN_is_zero(a) || BN_is_one(a)) { @@ -179,7 +179,7 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) if (!BN_set_word(y, i)) goto end; } else { - if (!BN_pseudo_rand(y, BN_num_bits(p), 0, 0)) + if (!BN_rand(y, BN_num_bits(p), 0, 0)) goto end; if (BN_ucmp(y, p) >= 0) { if (!(p->neg ? BN_add : BN_sub) (y, y, p)) diff --git a/crypto/bn/bn_srp.c b/crypto/bn/bn_srp.c index 58b1691e..27b6ebe5 100644 --- a/crypto/bn/bn_srp.c +++ b/crypto/bn/bn_srp.c @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2014-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 @@ -8,12 +8,12 @@ */ #include "bn_lcl.h" -#include "e_os.h" +#include "internal/nelem.h" #ifndef OPENSSL_NO_SRP #include -#include +#include "internal/bn_srp.h" # if (BN_BYTES == 8) # if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__) diff --git a/crypto/bn/bn_word.c b/crypto/bn/bn_word.c index 1af13a53..262d7668 100644 --- a/crypto/bn/bn_word.c +++ b/crypto/bn/bn_word.c @@ -55,7 +55,7 @@ BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w) (BN_ULLONG) w); #endif } - return ((BN_ULONG)ret); + return (BN_ULONG)ret; } BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) @@ -92,7 +92,7 @@ BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) if (!a->top) a->neg = 0; /* don't allow negative zero */ bn_check_top(a); - return (ret); + return ret; } int BN_add_word(BIGNUM *a, BN_ULONG w) @@ -115,7 +115,7 @@ int BN_add_word(BIGNUM *a, BN_ULONG w) i = BN_sub_word(a, w); if (!BN_is_zero(a)) a->neg = !(a->neg); - return (i); + return i; } for (i = 0; w != 0 && i < a->top; i++) { a->d[i] = l = (a->d[i] + w) & BN_MASK2; @@ -128,7 +128,7 @@ int BN_add_word(BIGNUM *a, BN_ULONG w) a->d[i] = w; } bn_check_top(a); - return (1); + return 1; } int BN_sub_word(BIGNUM *a, BN_ULONG w) @@ -153,13 +153,13 @@ int BN_sub_word(BIGNUM *a, BN_ULONG w) a->neg = 0; i = BN_add_word(a, w); a->neg = 1; - return (i); + return i; } if ((a->top == 1) && (a->d[0] < w)) { a->d[0] = w - a->d[0]; a->neg = 1; - return (1); + return 1; } i = 0; for (;;) { @@ -175,7 +175,7 @@ int BN_sub_word(BIGNUM *a, BN_ULONG w) if ((a->d[i] == 0) && (i == (a->top - 1))) a->top--; bn_check_top(a); - return (1); + return 1; } int BN_mul_word(BIGNUM *a, BN_ULONG w) @@ -191,11 +191,11 @@ int BN_mul_word(BIGNUM *a, BN_ULONG w) ll = bn_mul_words(a->d, a->d, a->top, w); if (ll) { if (bn_wexpand(a, a->top + 1) == NULL) - return (0); + return 0; a->d[a->top++] = ll; } } } bn_check_top(a); - return (1); + return 1; } diff --git a/crypto/bn/bn_x931p.c b/crypto/bn/bn_x931p.c index 8bfbcac6..2331b019 100644 --- a/crypto/bn/bn_x931p.c +++ b/crypto/bn/bn_x931p.c @@ -1,5 +1,5 @@ /* - * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2011-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 @@ -62,10 +62,10 @@ int BN_X931_derive_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, return 0; BN_CTX_start(ctx); - if (!p1) + if (p1 == NULL) p1 = BN_CTX_get(ctx); - if (!p2) + if (p2 == NULL) p2 = BN_CTX_get(ctx); t = BN_CTX_get(ctx); @@ -173,7 +173,7 @@ int BN_X931_generate_Xpq(BIGNUM *Xp, BIGNUM *Xq, int nbits, BN_CTX *ctx) * - 1. By setting the top two bits we ensure that the lower bound is * exceeded. */ - if (!BN_rand(Xp, nbits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ANY)) + if (!BN_priv_rand(Xp, nbits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ANY)) goto err; BN_CTX_start(ctx); @@ -182,7 +182,7 @@ int BN_X931_generate_Xpq(BIGNUM *Xp, BIGNUM *Xq, int nbits, BN_CTX *ctx) goto err; for (i = 0; i < 1000; i++) { - if (!BN_rand(Xq, nbits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ANY)) + if (!BN_priv_rand(Xq, nbits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ANY)) goto err; /* Check that |Xp - Xq| > 2^(nbits - 100) */ BN_sub(t, Xp, Xq); @@ -225,9 +225,9 @@ int BN_X931_generate_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, if (Xp1 == NULL || Xp2 == NULL) goto error; - if (!BN_rand(Xp1, 101, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) + if (!BN_priv_rand(Xp1, 101, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) goto error; - if (!BN_rand(Xp2, 101, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) + if (!BN_priv_rand(Xp2, 101, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) goto error; if (!BN_X931_derive_prime_ex(p, p1, p2, Xp, Xp1, Xp2, e, ctx, cb)) goto error; diff --git a/crypto/bn/build.info b/crypto/bn/build.info index c608ecce..a463edda 100644 --- a/crypto/bn/build.info +++ b/crypto/bn/build.info @@ -11,16 +11,16 @@ INCLUDE[../../libcrypto]=../../crypto/include INCLUDE[bn_exp.o]=.. GENERATE[bn-586.s]=asm/bn-586.pl \ - $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[bn-586.s]=../perlasm/x86asm.pl GENERATE[co-586.s]=asm/co-586.pl \ - $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[co-586.s]=../perlasm/x86asm.pl GENERATE[x86-mont.s]=asm/x86-mont.pl \ - $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[x86-mont.s]=../perlasm/x86asm.pl GENERATE[x86-gf2m.s]=asm/x86-gf2m.pl \ - $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[x86-gf2m.s]=../perlasm/x86asm.pl GENERATE[sparcv9a-mont.S]=asm/sparcv9a-mont.pl $(PERLASM_SCHEME) @@ -34,8 +34,10 @@ INCLUDE[sparct4-mont.o]=.. GENERATE[sparcv9-gf2m.S]=asm/sparcv9-gf2m.pl $(PERLASM_SCHEME) INCLUDE[sparcv9-gf2m.o]=.. -GENERATE[bn-mips.s]=asm/mips.pl $(PERLASM_SCHEME) -GENERATE[mips-mont.s]=asm/mips-mont.pl $(PERLASM_SCHEME) +GENERATE[bn-mips.S]=asm/mips.pl $(PERLASM_SCHEME) +INCLUDE[bn-mips.o]=.. +GENERATE[mips-mont.S]=asm/mips-mont.pl $(PERLASM_SCHEME) +INCLUDE[mips-mont.o]=.. GENERATE[s390x-mont.S]=asm/s390x-mont.pl $(PERLASM_SCHEME) GENERATE[s390x-gf2m.s]=asm/s390x-gf2m.pl $(PERLASM_SCHEME) @@ -47,7 +49,7 @@ GENERATE[rsaz-x86_64.s]=asm/rsaz-x86_64.pl $(PERLASM_SCHEME) GENERATE[rsaz-avx2.s]=asm/rsaz-avx2.pl $(PERLASM_SCHEME) GENERATE[bn-ia64.s]=asm/ia64.S -GENERATE[ia64-mont.s]=asm/ia64-mont.pl $(CFLAGS) $(LIB_CFLAGS) +GENERATE[ia64-mont.s]=asm/ia64-mont.pl $(LIB_CFLAGS) $(LIB_CPPFLAGS) GENERATE[parisc-mont.s]=asm/parisc-mont.pl $(PERLASM_SCHEME) @@ -63,22 +65,3 @@ INCLUDE[armv4-mont.o]=.. GENERATE[armv4-gf2m.S]=asm/armv4-gf2m.pl $(PERLASM_SCHEME) INCLUDE[armv4-gf2m.o]=.. GENERATE[armv8-mont.S]=asm/armv8-mont.pl $(PERLASM_SCHEME) - -OVERRIDES=bn-mips3.o pa-risc2W.o pa-risc2.c -BEGINRAW[Makefile] -##### BN assembler implementations - -{- $builddir -}/bn-mips3.o: {- $sourcedir -}/asm/mips3.s - @if [ "$(CC)" = "gcc" ]; then \ - ABI=`expr "$(CFLAGS)" : ".*-mabi=\([n3264]*\)"` && \ - as -$$ABI -O -o $@ {- $sourcedir -}/asm/mips3.s; \ - else $(CC) -c $(CFLAGS) $(LIB_CFLAGS) -o $@ {- $sourcedir -}/asm/mips3.s; fi - -# GNU assembler fails to compile PA-RISC2 modules, insist on calling -# vendor assembler... -{- $builddir -}/pa-risc2W.o: {- $sourcedir -}/asm/pa-risc2W.s - CC="$(CC)" $(PERL) $(SRCDIR)/util/fipsas.pl $(SRCDIR) $< /usr/ccs/bin/as -o pa-risc2W.o {- $sourcedir -}/asm/pa-risc2W.s -{- $builddir -}/pa-risc2.o: {- $sourcedir -}/asm/pa-risc2.s - CC="$(CC)" $(PERL) $(SRCDIR)/util/fipsas.pl $(SRCDIR) $< /usr/ccs/bin/as -o pa-risc2.o {- $sourcedir -}/asm/pa-risc2.s - -ENDRAW[Makefile] diff --git a/crypto/bn/rsaz_exp.c b/crypto/bn/rsaz_exp.c index 1a70f6ca..22455b8a 100644 --- a/crypto/bn/rsaz_exp.c +++ b/crypto/bn/rsaz_exp.c @@ -1,54 +1,17 @@ /* * Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2012, Intel Corporation. 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 + * + * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) + * (1) Intel Corporation, Israel Development Center, Haifa, Israel + * (2) University of Haifa, Israel */ -/***************************************************************************** -* * -* Copyright (c) 2012, Intel Corporation * -* * -* All rights reserved. * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are * -* met: * -* * -* * Redistributions of source code must retain the above copyright * -* notice, this list of conditions and the following disclaimer. * -* * -* * 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. * -* * -* * Neither the name of the Intel Corporation nor the names of its * -* contributors may be used to endorse or promote products derived from * -* this software without specific prior written permission. * -* * -* * -* THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION ""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 INTEL CORPORATION 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. * -* * -****************************************************************************** -* Developers and authors: * -* Shay Gueron (1, 2), and Vlad Krasnov (1) * -* (1) Intel Corporation, Israel Development Center, Haifa, Israel * -* (2) University of Haifa, Israel * -*****************************************************************************/ - #include #include "rsaz_exp.h" diff --git a/crypto/bn/rsaz_exp.h b/crypto/bn/rsaz_exp.h index 9501cc80..1c5e6188 100644 --- a/crypto/bn/rsaz_exp.h +++ b/crypto/bn/rsaz_exp.h @@ -1,54 +1,17 @@ /* * Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2012, Intel Corporation. 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 + * + * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) + * (1) Intel Corporation, Israel Development Center, Haifa, Israel + * (2) University of Haifa, Israel */ -/***************************************************************************** -* * -* Copyright (c) 2012, Intel Corporation * -* * -* All rights reserved. * -* * -* Redistribution and use in source and binary forms, with or without * -* modification, are permitted provided that the following conditions are * -* met: * -* * -* * Redistributions of source code must retain the above copyright * -* notice, this list of conditions and the following disclaimer. * -* * -* * 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. * -* * -* * Neither the name of the Intel Corporation nor the names of its * -* contributors may be used to endorse or promote products derived from * -* this software without specific prior written permission. * -* * -* * -* THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION ""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 INTEL CORPORATION 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. * -* * -****************************************************************************** -* Developers and authors: * -* Shay Gueron (1, 2), and Vlad Krasnov (1) * -* (1) Intel Corporation, Israel Development Center, Haifa, Israel * -* (2) University of Haifa, Israel * -*****************************************************************************/ - #ifndef RSAZ_EXP_H # define RSAZ_EXP_H diff --git a/crypto/buffer/buf_err.c b/crypto/buffer/buf_err.c index a6a2ab88..7e6e5322 100644 --- a/crypto/buffer/buf_err.c +++ b/crypto/buffer/buf_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,24 +8,19 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_BUF,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_BUF,0,reason) - -static ERR_STRING_DATA BUF_str_functs[] = { - {ERR_FUNC(BUF_F_BUF_MEM_GROW), "BUF_MEM_grow"}, - {ERR_FUNC(BUF_F_BUF_MEM_GROW_CLEAN), "BUF_MEM_grow_clean"}, - {ERR_FUNC(BUF_F_BUF_MEM_NEW), "BUF_MEM_new"}, +static const ERR_STRING_DATA BUF_str_functs[] = { + {ERR_PACK(ERR_LIB_BUF, BUF_F_BUF_MEM_GROW, 0), "BUF_MEM_grow"}, + {ERR_PACK(ERR_LIB_BUF, BUF_F_BUF_MEM_GROW_CLEAN, 0), "BUF_MEM_grow_clean"}, + {ERR_PACK(ERR_LIB_BUF, BUF_F_BUF_MEM_NEW, 0), "BUF_MEM_new"}, {0, NULL} }; -static ERR_STRING_DATA BUF_str_reasons[] = { +static const ERR_STRING_DATA BUF_str_reasons[] = { {0, NULL} }; @@ -34,10 +29,9 @@ static ERR_STRING_DATA BUF_str_reasons[] = { int ERR_load_BUF_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(BUF_str_functs[0].error) == NULL) { - ERR_load_strings(0, BUF_str_functs); - ERR_load_strings(0, BUF_str_reasons); + ERR_load_strings_const(BUF_str_functs); + ERR_load_strings_const(BUF_str_reasons); } #endif return 1; diff --git a/crypto/buffer/buffer.c b/crypto/buffer/buffer.c index f3f8a1b5..cbd2e531 100644 --- a/crypto/buffer/buffer.c +++ b/crypto/buffer/buffer.c @@ -25,7 +25,7 @@ BUF_MEM *BUF_MEM_new_ex(unsigned long flags) ret = BUF_MEM_new(); if (ret != NULL) ret->flags = flags; - return (ret); + return ret; } BUF_MEM *BUF_MEM_new(void) @@ -35,9 +35,9 @@ BUF_MEM *BUF_MEM_new(void) ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) { BUFerr(BUF_F_BUF_MEM_NEW, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } - return (ret); + return ret; } void BUF_MEM_free(BUF_MEM *a) @@ -68,7 +68,7 @@ static char *sec_alloc_realloc(BUF_MEM *str, size_t len) str->data = NULL; } } - return (ret); + return ret; } size_t BUF_MEM_grow(BUF_MEM *str, size_t len) @@ -78,13 +78,13 @@ size_t BUF_MEM_grow(BUF_MEM *str, size_t len) if (str->length >= len) { str->length = len; - return (len); + return len; } if (str->max >= len) { if (str->data != NULL) memset(&str->data[str->length], 0, len - str->length); str->length = len; - return (len); + return len; } /* This limit is sufficient to ensure (len+3)/3*4 < 2**31 */ if (len > LIMIT_BEFORE_EXPANSION) { @@ -105,7 +105,7 @@ size_t BUF_MEM_grow(BUF_MEM *str, size_t len) memset(&str->data[str->length], 0, len - str->length); str->length = len; } - return (len); + return len; } size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len) @@ -117,12 +117,12 @@ size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len) if (str->data != NULL) memset(&str->data[len], 0, str->length - len); str->length = len; - return (len); + return len; } if (str->max >= len) { memset(&str->data[str->length], 0, len - str->length); str->length = len; - return (len); + return len; } /* This limit is sufficient to ensure (len+3)/3*4 < 2**31 */ if (len > LIMIT_BEFORE_EXPANSION) { @@ -143,7 +143,7 @@ size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len) memset(&str->data[str->length], 0, len - str->length); str->length = len; } - return (len); + return len; } void BUF_reverse(unsigned char *out, const unsigned char *in, size_t size) diff --git a/crypto/build.info b/crypto/build.info index 916d24f6..0a8f6e22 100644 --- a/crypto/build.info +++ b/crypto/build.info @@ -2,7 +2,7 @@ LIBS=../libcrypto SOURCE[../libcrypto]=\ cryptlib.c mem.c mem_dbg.c cversion.c ex_data.c cpt_err.c \ - ebcdic.c uid.c o_time.c o_str.c o_dir.c o_fopen.c \ + ebcdic.c uid.c o_time.c o_str.c o_dir.c o_fopen.c ctype.c \ threads_pthread.c threads_win.c threads_none.c \ o_init.c o_fips.c mem_sec.c init.c {- $target{cpuid_asm_src} -} \ {- $target{uplink_aux_src} -} @@ -11,14 +11,15 @@ EXTRA= ../ms/uplink-x86.pl ../ms/uplink.c ../ms/applink.c \ ppccpuid.pl pariscid.pl alphacpuid.pl arm64cpuid.pl armv4cpuid.pl DEPEND[cversion.o]=buildinf.h -GENERATE[buildinf.h]=../util/mkbuildinf.pl "$(CC) $(CFLAGS_Q)" "$(PLATFORM)" +GENERATE[buildinf.h]=../util/mkbuildinf.pl "$(CC) $(CFLAGS) $(CPPFLAGS_Q)" "$(PLATFORM)" DEPEND[buildinf.h]=../configdata.pm GENERATE[uplink-x86.s]=../ms/uplink-x86.pl $(PERLASM_SCHEME) GENERATE[uplink-x86_64.s]=../ms/uplink-x86_64.pl $(PERLASM_SCHEME) GENERATE[uplink-ia64.s]=../ms/uplink-ia64.pl $(PERLASM_SCHEME) -GENERATE[x86cpuid.s]=x86cpuid.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[x86cpuid.s]=x86cpuid.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[x86cpuid.s]=perlasm/x86asm.pl GENERATE[x86_64cpuid.s]=x86_64cpuid.pl $(PERLASM_SCHEME) @@ -31,6 +32,8 @@ GENERATE[arm64cpuid.S]=arm64cpuid.pl $(PERLASM_SCHEME) INCLUDE[arm64cpuid.o]=. GENERATE[armv4cpuid.S]=armv4cpuid.pl $(PERLASM_SCHEME) INCLUDE[armv4cpuid.o]=. +GENERATE[s390xcpuid.S]=s390xcpuid.pl $(PERLASM_SCHEME) +INCLUDE[s390xcpuid.o]=. IF[{- $config{target} =~ /^(?:Cygwin|mingw|VC-)/ -}] SHARED_SOURCE[../libcrypto]=dllmain.c diff --git a/crypto/c64xpluscpuid.pl b/crypto/c64xpluscpuid.pl index 9efe1205..b7b11d50 100644 --- a/crypto/c64xpluscpuid.pl +++ b/crypto/c64xpluscpuid.pl @@ -231,7 +231,7 @@ bus_loop1?: _OPENSSL_instrument_bus2: .asmfunc MV A6,B0 ; reassign max -|| MV B4,A6 ; reassing sizeof(output) +|| MV B4,A6 ; reassign sizeof(output) || MVK 0x00004030,A3 MV A4,B4 ; reassign output || MVK 0,A4 ; return value diff --git a/crypto/camellia/asm/cmll-x86.pl b/crypto/camellia/asm/cmll-x86.pl index 59f9ed91..55af9b4e 100644 --- a/crypto/camellia/asm/cmll-x86.pl +++ b/crypto/camellia/asm/cmll-x86.pl @@ -52,7 +52,7 @@ $OPENSSL=1; $output = pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"cmll-586.pl",$ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$ARGV[$#ARGV] eq "386"); @T=("eax","ebx","ecx","edx"); $idx="esi"; @@ -792,9 +792,9 @@ if ($OPENSSL) { 64, 40,211,123,187,201, 67,193, 21,227,173,244,119,199,128,158); sub S1110 { my $i=shift; $i=@SBOX[$i]; return $i<<24|$i<<16|$i<<8; } -sub S4404 { my $i=shift; $i=($i<<1|$i>>7)&0xff; $i=@SBOX[$i]; return $i<<24|$i<<16|$i; } -sub S0222 { my $i=shift; $i=@SBOX[$i]; $i=($i<<1|$i>>7)&0xff; return $i<<16|$i<<8|$i; } -sub S3033 { my $i=shift; $i=@SBOX[$i]; $i=($i>>1|$i<<7)&0xff; return $i<<24|$i<<8|$i; } +sub S4404 { my $i=shift; $i=($i<<1|$i>>7)&0xff; $i=@SBOX[$i]; return $i<<24|$i<<16|$i; } +sub S0222 { my $i=shift; $i=@SBOX[$i]; $i=($i<<1|$i>>7)&0xff; return $i<<16|$i<<8|$i; } +sub S3033 { my $i=shift; $i=@SBOX[$i]; $i=($i>>1|$i<<7)&0xff; return $i<<24|$i<<8|$i; } &set_label("Camellia_SIGMA",64); &data_word( diff --git a/crypto/camellia/asm/cmll-x86_64.pl b/crypto/camellia/asm/cmll-x86_64.pl index da5ad7b7..02c52c3e 100644 --- a/crypto/camellia/asm/cmll-x86_64.pl +++ b/crypto/camellia/asm/cmll-x86_64.pl @@ -137,11 +137,17 @@ Camellia_EncryptBlock: .align 16 .Lenc_rounds: Camellia_EncryptBlock_Rounds: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lenc_prologue: #mov %rsi,$inp # put away arguments @@ -173,13 +179,20 @@ Camellia_EncryptBlock_Rounds: mov @S[3],12($out) mov 0(%rsp),%r15 +.cfi_restore %r15 mov 8(%rsp),%r14 +.cfi_restore %r14 mov 16(%rsp),%r13 +.cfi_restore %r13 mov 24(%rsp),%rbp +.cfi_restore %rbp mov 32(%rsp),%rbx +.cfi_restore %rbx lea 40(%rsp),%rsp +.cfi_adjust_cfa_offset -40 .Lenc_epilogue: ret +.cfi_endproc .size Camellia_EncryptBlock_Rounds,.-Camellia_EncryptBlock_Rounds .type _x86_64_Camellia_encrypt,\@abi-omnipotent @@ -247,11 +260,17 @@ Camellia_DecryptBlock: .align 16 .Ldec_rounds: Camellia_DecryptBlock_Rounds: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Ldec_prologue: #mov %rsi,$inp # put away arguments @@ -283,13 +302,20 @@ Camellia_DecryptBlock_Rounds: mov @S[3],12($out) mov 0(%rsp),%r15 +.cfi_restore %r15 mov 8(%rsp),%r14 +.cfi_restore %r14 mov 16(%rsp),%r13 +.cfi_restore %r13 mov 24(%rsp),%rbp +.cfi_restore %rbp mov 32(%rsp),%rbx +.cfi_restore %rbx lea 40(%rsp),%rsp +.cfi_adjust_cfa_offset -40 .Ldec_epilogue: ret +.cfi_endproc .size Camellia_DecryptBlock_Rounds,.-Camellia_DecryptBlock_Rounds .type _x86_64_Camellia_decrypt,\@abi-omnipotent @@ -409,11 +435,17 @@ $code.=<<___; .type Camellia_Ekeygen,\@function,3 .align 16 Camellia_Ekeygen: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lkey_prologue: mov %edi,${keyend}d # put away arguments, keyBitLength @@ -573,13 +605,20 @@ $code.=<<___; mov \$4,%eax .Ldone: mov 0(%rsp),%r15 +.cfi_restore %r15 mov 8(%rsp),%r14 +.cfi_restore %r14 mov 16(%rsp),%r13 +.cfi_restore %r13 mov 24(%rsp),%rbp +.cfi_restore %rbp mov 32(%rsp),%rbx +.cfi_restore %rbx lea 40(%rsp),%rsp +.cfi_adjust_cfa_offset -40 .Lkey_epilogue: ret +.cfi_endproc .size Camellia_Ekeygen,.-Camellia_Ekeygen ___ } @@ -637,17 +676,25 @@ $code.=<<___; .type Camellia_cbc_encrypt,\@function,6 .align 16 Camellia_cbc_encrypt: +.cfi_startproc cmp \$0,%rdx je .Lcbc_abort push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lcbc_prologue: mov %rsp,%rbp +.cfi_def_cfa_register %rbp sub \$64,%rsp and \$-64,%rsp @@ -668,6 +715,7 @@ Camellia_cbc_encrypt: mov %r8,$_ivp mov %rbp,$_rsp +.cfi_cfa_expression $_rsp,deref,+56 .Lcbc_body: lea .LCamellia_SBOX(%rip),$Tbl @@ -856,15 +904,24 @@ Camellia_cbc_encrypt: .align 16 .Lcbc_done: mov $_rsp,%rcx +.cfi_def_cfa %rcx,56 mov 0(%rcx),%r15 +.cfi_restore %r15 mov 8(%rcx),%r14 +.cfi_restore %r14 mov 16(%rcx),%r13 +.cfi_restore %r13 mov 24(%rcx),%r12 +.cfi_restore %r12 mov 32(%rcx),%rbp +.cfi_restore %rbp mov 40(%rcx),%rbx +.cfi_restore %rbx lea 48(%rcx),%rsp +.cfi_def_cfa %rsp,8 .Lcbc_abort: ret +.cfi_endproc .size Camellia_cbc_encrypt,.-Camellia_cbc_encrypt .asciz "Camellia for x86_64 by " diff --git a/crypto/camellia/asm/cmllt4-sparcv9.pl b/crypto/camellia/asm/cmllt4-sparcv9.pl index ffe4a7d9..6396679a 100644 --- a/crypto/camellia/asm/cmllt4-sparcv9.pl +++ b/crypto/camellia/asm/cmllt4-sparcv9.pl @@ -8,8 +8,8 @@ # ==================================================================== -# Written by David S. Miller and Andy Polyakov -# . The module is licensed under 2-clause BSD +# Written by David S. Miller and Andy Polyakov. +# The module is licensed under 2-clause BSD # license. October 2012. All rights reserved. # ==================================================================== @@ -17,7 +17,7 @@ # Camellia for SPARC T4. # # As with AES below results [for aligned data] are virtually identical -# to critical path lenths for 3-cycle instruction latency: +# to critical path lengths for 3-cycle instruction latency: # # 128-bit key 192/256- # CBC encrypt 4.14/4.21(*) 5.46/5.52 @@ -25,7 +25,7 @@ # misaligned data. # # As with Intel AES-NI, question is if it's possible to improve -# performance of parallelizeable modes by interleaving round +# performance of parallelizable modes by interleaving round # instructions. In Camellia every instruction is dependent on # previous, which means that there is place for 2 additional ones # in between two dependent. Can we expect 3x performance improvement? diff --git a/crypto/camellia/build.info b/crypto/camellia/build.info index fd782724..e36a19bd 100644 --- a/crypto/camellia/build.info +++ b/crypto/camellia/build.info @@ -3,7 +3,9 @@ SOURCE[../../libcrypto]=\ cmll_ecb.c cmll_ofb.c cmll_cfb.c cmll_ctr.c \ {- $target{cmll_asm_src} -} -GENERATE[cmll-x86.s]=asm/cmll-x86.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[cmll-x86.s]=asm/cmll-x86.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) \ + $(PROCESSOR) DEPEND[cmll-x86.s]=../perlasm/x86asm.pl GENERATE[cmll-x86_64.s]=asm/cmll-x86_64.pl $(PERLASM_SCHEME) GENERATE[cmllt4-sparcv9.S]=asm/cmllt4-sparcv9.pl $(PERLASM_SCHEME) diff --git a/crypto/cast/asm/cast-586.pl b/crypto/cast/asm/cast-586.pl index 6beb9c5f..d5d38965 100644 --- a/crypto/cast/asm/cast-586.pl +++ b/crypto/cast/asm/cast-586.pl @@ -7,7 +7,7 @@ # https://www.openssl.org/source/license.html -# This flag makes the inner loop one cycle longer, but generates +# This flag makes the inner loop one cycle longer, but generates # code that runs %30 faster on the pentium pro/II, 44% faster # of PIII, while only %7 slower on the pentium. # By default, this flag is on. @@ -21,7 +21,7 @@ require "cbc.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"cast-586.pl",$ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$ARGV[$#ARGV] eq "386"); $CAST_ROUNDS=16; $L="edi"; @@ -157,7 +157,7 @@ sub E_CAST { if ($ppro) { &xor( $tmp1, $tmp1); &mov( $tmp2, 0xff); - + &movb( &LB($tmp1), &HB($tmp4)); # A &and( $tmp2, $tmp4); @@ -166,7 +166,7 @@ sub E_CAST { } else { &mov( $tmp2, $tmp4); # B &movb( &LB($tmp1), &HB($tmp4)); # A # BAD BAD BAD - + &shr( $tmp4, 16); # &and( $tmp2, 0xff); } diff --git a/crypto/cast/build.info b/crypto/cast/build.info index f6a25c9a..b0f59f38 100644 --- a/crypto/cast/build.info +++ b/crypto/cast/build.info @@ -2,5 +2,6 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ c_skey.c c_ecb.c {- $target{cast_asm_src} -} c_cfb64.c c_ofb64.c -GENERATE[cast-586.s]=asm/cast-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[cast-586.s]=asm/cast-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[cast-586.s]=../perlasm/x86asm.pl ../perlasm/cbc.pl diff --git a/crypto/cast/cast_lcl.h b/crypto/cast/cast_lcl.h index e8cf322d..35e89930 100644 --- a/crypto/cast/cast_lcl.h +++ b/crypto/cast/cast_lcl.h @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -7,8 +7,6 @@ * https://www.openssl.org/source/license.html */ -#include "e_os.h" - #ifdef OPENSSL_SYS_WIN32 # include #endif diff --git a/crypto/cast/cast_s.h b/crypto/cast/cast_s.h index d9fd6ac4..b27415b9 100644 --- a/crypto/cast/cast_s.h +++ b/crypto/cast/cast_s.h @@ -7,7 +7,7 @@ * https://www.openssl.org/source/license.html */ -OPENSSL_GLOBAL const CAST_LONG CAST_S_table0[256] = { +const CAST_LONG CAST_S_table0[256] = { 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, @@ -74,7 +74,7 @@ OPENSSL_GLOBAL const CAST_LONG CAST_S_table0[256] = { 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf, }; -OPENSSL_GLOBAL const CAST_LONG CAST_S_table1[256] = { +const CAST_LONG CAST_S_table1[256] = { 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, @@ -141,7 +141,7 @@ OPENSSL_GLOBAL const CAST_LONG CAST_S_table1[256] = { 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1, }; -OPENSSL_GLOBAL const CAST_LONG CAST_S_table2[256] = { +const CAST_LONG CAST_S_table2[256] = { 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, @@ -208,7 +208,7 @@ OPENSSL_GLOBAL const CAST_LONG CAST_S_table2[256] = { 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783, }; -OPENSSL_GLOBAL const CAST_LONG CAST_S_table3[256] = { +const CAST_LONG CAST_S_table3[256] = { 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, @@ -275,7 +275,7 @@ OPENSSL_GLOBAL const CAST_LONG CAST_S_table3[256] = { 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2, }; -OPENSSL_GLOBAL const CAST_LONG CAST_S_table4[256] = { +const CAST_LONG CAST_S_table4[256] = { 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, @@ -342,7 +342,7 @@ OPENSSL_GLOBAL const CAST_LONG CAST_S_table4[256] = { 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4, }; -OPENSSL_GLOBAL const CAST_LONG CAST_S_table5[256] = { +const CAST_LONG CAST_S_table5[256] = { 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, @@ -409,7 +409,7 @@ OPENSSL_GLOBAL const CAST_LONG CAST_S_table5[256] = { 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f, }; -OPENSSL_GLOBAL const CAST_LONG CAST_S_table6[256] = { +const CAST_LONG CAST_S_table6[256] = { 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, @@ -476,7 +476,7 @@ OPENSSL_GLOBAL const CAST_LONG CAST_S_table6[256] = { 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3, }; -OPENSSL_GLOBAL const CAST_LONG CAST_S_table7[256] = { +const CAST_LONG CAST_S_table7[256] = { 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, diff --git a/crypto/chacha/asm/chacha-armv4.pl b/crypto/chacha/asm/chacha-armv4.pl index b5e21e49..d3fadcc6 100755 --- a/crypto/chacha/asm/chacha-armv4.pl +++ b/crypto/chacha/asm/chacha-armv4.pl @@ -15,7 +15,7 @@ # ==================================================================== # # December 2014 -# +# # ChaCha20 for ARMv4. # # Performance in cycles per byte out of large buffer. @@ -172,8 +172,10 @@ $code.=<<___; #include "arm_arch.h" .text -#if defined(__thumb2__) +#if defined(__thumb2__) || defined(__clang__) .syntax unified +#endif +#if defined(__thumb2__) .thumb #else .code 32 @@ -720,7 +722,7 @@ ChaCha20_neon: vadd.i32 $d2,$d1,$t0 @ counter+2 str @t[3], [sp,#4*(16+15)] mov @t[3],#10 - add @x[12],@x[12],#3 @ counter+3 + add @x[12],@x[12],#3 @ counter+3 b .Loop_neon .align 4 diff --git a/crypto/chacha/asm/chacha-armv8.pl b/crypto/chacha/asm/chacha-armv8.pl index f7e10747..4a838bc2 100755 --- a/crypto/chacha/asm/chacha-armv8.pl +++ b/crypto/chacha/asm/chacha-armv8.pl @@ -15,7 +15,7 @@ # ==================================================================== # # June 2015 -# +# # ChaCha20 for ARMv8. # # Performance in cycles per byte out of large buffer. @@ -28,6 +28,7 @@ # Denver 4.50/+82% 2.63 2.67(*) # X-Gene 9.50/+46% 8.82 8.89(*) # Mongoose 8.00/+44% 3.64 3.25 +# Kryo 8.17/+50% 4.83 4.65 # # (*) it's expected that doubling interleave factor doesn't help # all processors, only those with higher NEON latency and @@ -201,7 +202,7 @@ ChaCha20_ctr32: mov $ctr,#10 subs $len,$len,#64 .Loop: - sub $ctr,$ctr,#1 + sub $ctr,$ctr,#1 ___ foreach (&ROUND(0, 4, 8,12)) { eval; } foreach (&ROUND(0, 5,10,15)) { eval; } diff --git a/crypto/chacha/asm/chacha-c64xplus.pl b/crypto/chacha/asm/chacha-c64xplus.pl index bdb38044..266401eb 100755 --- a/crypto/chacha/asm/chacha-c64xplus.pl +++ b/crypto/chacha/asm/chacha-c64xplus.pl @@ -22,7 +22,7 @@ # faster than code generated by TI compiler. Compiler also disables # interrupts for some reason, thus making interrupt response time # dependent on input length. This module on the other hand is free -# from such limiation. +# from such limitation. $output=pop; open STDOUT,">$output"; diff --git a/crypto/chacha/asm/chacha-ppc.pl b/crypto/chacha/asm/chacha-ppc.pl index 181decda..f972ee47 100755 --- a/crypto/chacha/asm/chacha-ppc.pl +++ b/crypto/chacha/asm/chacha-ppc.pl @@ -15,7 +15,7 @@ # ==================================================================== # # October 2015 -# +# # ChaCha20 for PowerPC/AltiVec. # # Performance in cycles per byte out of large buffer. @@ -525,7 +525,7 @@ $code.=<<___; lwz @d[3],12($ctr) vadduwm @K[5],@K[4],@K[5] - vspltisw $twenty,-12 # synthesize constants + vspltisw $twenty,-12 # synthesize constants vspltisw $twelve,12 vspltisw $twenty5,-7 #vspltisw $seven,7 # synthesized in the loop diff --git a/crypto/chacha/asm/chacha-x86.pl b/crypto/chacha/asm/chacha-x86.pl index 61b32861..e177a222 100755 --- a/crypto/chacha/asm/chacha-x86.pl +++ b/crypto/chacha/asm/chacha-x86.pl @@ -28,6 +28,7 @@ # Westmere 9.50/+45% 3.35 # Sandy Bridge 10.5/+47% 3.20 # Haswell 8.15/+50% 2.83 +# Skylake 7.53/+22% 2.75 # Silvermont 17.4/+36% 8.35 # Goldmont 13.4/+40% 4.36 # Sledgehammer 10.2/+54% @@ -42,7 +43,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"chacha-x86.pl",$ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$ARGV[$#ARGV] eq "386"); $xmm=$ymm=0; for (@ARGV) { $xmm=1 if (/-DOPENSSL_IA32_SSE2/); } diff --git a/crypto/chacha/asm/chacha-x86_64.pl b/crypto/chacha/asm/chacha-x86_64.pl index 347dfcb3..51bb6a96 100755 --- a/crypto/chacha/asm/chacha-x86_64.pl +++ b/crypto/chacha/asm/chacha-x86_64.pl @@ -18,9 +18,17 @@ # # ChaCha20 for x86_64. # +# December 2016 +# +# Add AVX512F code path. +# +# December 2017 +# +# Add AVX512VL code path. +# # Performance in cycles per byte out of large buffer. # -# IALU/gcc 4.8(i) 1xSSSE3/SSE2 4xSSSE3 8xAVX2 +# IALU/gcc 4.8(i) 1xSSSE3/SSE2 4xSSSE3 NxAVX(v) # # P4 9.48/+99% -/22.7(ii) - # Core2 7.83/+55% 7.90/8.08 4.35 @@ -28,10 +36,13 @@ # Sandy Bridge 8.31/+42% 5.45/6.76 2.72 # Ivy Bridge 6.71/+46% 5.40/6.49 2.41 # Haswell 5.92/+43% 5.20/6.45 2.42 1.23 +# Skylake[-X] 5.87/+39% 4.70/- 2.31 1.19[0.80(vi)] # Silvermont 12.0/+33% 7.75/7.40 7.03(iii) +# Knights L 11.7/- - 9.60(iii) 0.80 # Goldmont 10.6/+17% 5.10/- 3.28 # Sledgehammer 7.28/+52% -/14.2(ii) - # Bulldozer 9.66/+28% 9.85/11.1 3.06(iv) +# Ryzen 5.96/+50% 5.19/- 2.40 2.09 # VIA Nano 10.5/+46% 6.72/8.60 6.05 # # (i) compared to older gcc 3.x one can observe >2x improvement on @@ -44,6 +55,9 @@ # limitations, SSE2 can do better, but gain is considered too # low to justify the [maintenance] effort; # (iv) Bulldozer actually executes 4xXOP code path that delivers 2.20; +# (v) 8xAVX2, 8xAVX512VL or 16xAVX512F, whichever best applicable; +# (vi) even though Skylake-X can execute AVX512F code and deliver 0.57 +# cpb in single thread, the corresponding capability is suppressed; $flavour = shift; $output = shift; @@ -58,12 +72,13 @@ die "can't locate x86_64-xlate.pl"; if (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1` =~ /GNU assembler version ([2-9]\.[0-9]+)/) { - $avx = ($1>=2.19) + ($1>=2.22); + $avx = ($1>=2.19) + ($1>=2.22) + ($1>=2.25); } if (!$avx && $win64 && ($flavour =~ /nasm/ || $ENV{ASM} =~ /nasm/) && - `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)/) { - $avx = ($1>=2.09) + ($1>=2.10); + `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)(?:\.([0-9]+))?/) { + $avx = ($1>=2.09) + ($1>=2.10) + ($1>=2.12); + $avx += 1 if ($1==2.11 && $2>=8); } if (!$avx && $win64 && ($flavour =~ /masm/ || $ENV{ASM} =~ /ml64/) && @@ -103,6 +118,17 @@ $code.=<<___; .byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd .Lrot24: .byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe +.Ltwoy: +.long 2,0,0,0, 2,0,0,0 +.align 64 +.Lzeroz: +.long 0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0 +.Lfourz: +.long 4,0,0,0, 4,0,0,0, 4,0,0,0, 4,0,0,0 +.Lincz: +.long 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 +.Lsixteen: +.long 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16 .Lsigma: .asciz "expand 32-byte k" .asciz "ChaCha20 for x86_64, CRYPTOGAMS by " @@ -227,19 +253,36 @@ $code.=<<___; .type ChaCha20_ctr32,\@function,5 .align 64 ChaCha20_ctr32: +.cfi_startproc cmp \$0,$len je .Lno_data mov OPENSSL_ia32cap_P+4(%rip),%r10 +___ +$code.=<<___ if ($avx>2); + bt \$48,%r10 # check for AVX512F + jc .LChaCha20_avx512 + test %r10,%r10 # check for AVX512VL + js .LChaCha20_avx512vl +___ +$code.=<<___; test \$`1<<(41-32)`,%r10d jnz .LChaCha20_ssse3 push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 sub \$64+24,%rsp +.cfi_adjust_cfa_offset 64+24 +.Lctr32_body: #movdqa .Lsigma(%rip),%xmm0 movdqu ($key),%xmm1 @@ -378,15 +421,25 @@ $code.=<<___; jnz .Loop_tail .Ldone: - add \$64+24,%rsp - pop %r15 - pop %r14 - pop %r13 - pop %r12 - pop %rbp - pop %rbx + lea 64+24+48(%rsp),%rsi +.cfi_def_cfa %rsi,8 + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lno_data: ret +.cfi_endproc .size ChaCha20_ctr32,.-ChaCha20_ctr32 ___ @@ -419,13 +472,16 @@ sub SSSE3ROUND { # critical path is 20 "SIMD ticks" per round &por ($b,$t); } -my $xframe = $win64 ? 32+32+8 : 24; +my $xframe = $win64 ? 32+8 : 8; $code.=<<___; .type ChaCha20_ssse3,\@function,5 .align 32 ChaCha20_ssse3: +.cfi_startproc .LChaCha20_ssse3: + mov %rsp,%r9 # frame pointer +.cfi_def_cfa_register %r9 ___ $code.=<<___ if ($avx); test \$`1<<(43-32)`,%r10d @@ -436,18 +492,12 @@ $code.=<<___; ja .LChaCha20_4x # but overall it won't be slower .Ldo_sse3_after_all: - push %rbx - push %rbp - push %r12 - push %r13 - push %r14 - push %r15 - sub \$64+$xframe,%rsp ___ $code.=<<___ if ($win64); - movaps %xmm6,64+32(%rsp) - movaps %xmm7,64+48(%rsp) + movaps %xmm6,-0x28(%r9) + movaps %xmm7,-0x18(%r9) +.Lssse3_body: ___ $code.=<<___; movdqa .Lsigma(%rip),$a @@ -461,7 +511,7 @@ $code.=<<___; movdqa $b,0x10(%rsp) movdqa $c,0x20(%rsp) movdqa $d,0x30(%rsp) - mov \$10,%ebp + mov \$10,$counter # reuse $counter jmp .Loop_ssse3 .align 32 @@ -471,7 +521,7 @@ $code.=<<___; movdqa 0x10(%rsp),$b movdqa 0x20(%rsp),$c paddd 0x30(%rsp),$d - mov \$10,%ebp + mov \$10,$counter movdqa $d,0x30(%rsp) jmp .Loop_ssse3 @@ -489,7 +539,7 @@ ___ &pshufd ($b,$b,0b10010011); &pshufd ($d,$d,0b00111001); - &dec ("%ebp"); + &dec ($counter); &jnz (".Loop_ssse3"); $code.=<<___; @@ -528,32 +578,29 @@ $code.=<<___; movdqa $b,0x10(%rsp) movdqa $c,0x20(%rsp) movdqa $d,0x30(%rsp) - xor %rbx,%rbx + xor $counter,$counter .Loop_tail_ssse3: - movzb ($inp,%rbx),%eax - movzb (%rsp,%rbx),%ecx - lea 1(%rbx),%rbx + movzb ($inp,$counter),%eax + movzb (%rsp,$counter),%ecx + lea 1($counter),$counter xor %ecx,%eax - mov %al,-1($out,%rbx) + mov %al,-1($out,$counter) dec $len jnz .Loop_tail_ssse3 .Ldone_ssse3: ___ $code.=<<___ if ($win64); - movaps 64+32(%rsp),%xmm6 - movaps 64+48(%rsp),%xmm7 + movaps -0x28(%r9),%xmm6 + movaps -0x18(%r9),%xmm7 ___ $code.=<<___; - add \$64+$xframe,%rsp - pop %r15 - pop %r14 - pop %r13 - pop %r12 - pop %rbp - pop %rbx + lea (%r9),%rsp +.cfi_def_cfa_register %rsp +.Lssse3_epilogue: ret +.cfi_endproc .size ChaCha20_ssse3,.-ChaCha20_ssse3 ___ } @@ -689,13 +736,16 @@ my @x=map("\"$_\"",@xx); ); } -my $xframe = $win64 ? 0xa0 : 0; +my $xframe = $win64 ? 0xa8 : 8; $code.=<<___; .type ChaCha20_4x,\@function,5 .align 32 ChaCha20_4x: +.cfi_startproc .LChaCha20_4x: + mov %rsp,%r9 # frame pointer +.cfi_def_cfa_register %r9 mov %r10,%r11 ___ $code.=<<___ if ($avx>1); @@ -712,8 +762,7 @@ $code.=<<___; je .Ldo_sse3_after_all # to detect Atom .Lproceed4x: - lea -0x78(%rsp),%r11 - sub \$0x148+$xframe,%rsp + sub \$0x140+$xframe,%rsp ___ ################ stack layout # +0x00 SIMD equivalent of @x[8-12] @@ -724,16 +773,17 @@ ___ # ... # +0x140 $code.=<<___ if ($win64); - movaps %xmm6,-0x30(%r11) - movaps %xmm7,-0x20(%r11) - movaps %xmm8,-0x10(%r11) - movaps %xmm9,0x00(%r11) - movaps %xmm10,0x10(%r11) - movaps %xmm11,0x20(%r11) - movaps %xmm12,0x30(%r11) - movaps %xmm13,0x40(%r11) - movaps %xmm14,0x50(%r11) - movaps %xmm15,0x60(%r11) + movaps %xmm6,-0xa8(%r9) + movaps %xmm7,-0x98(%r9) + movaps %xmm8,-0x88(%r9) + movaps %xmm9,-0x78(%r9) + movaps %xmm10,-0x68(%r9) + movaps %xmm11,-0x58(%r9) + movaps %xmm12,-0x48(%r9) + movaps %xmm13,-0x38(%r9) + movaps %xmm14,-0x28(%r9) + movaps %xmm15,-0x18(%r9) +.L4x_body: ___ $code.=<<___; movdqa .Lsigma(%rip),$xa3 # key[0] @@ -1122,21 +1172,23 @@ $code.=<<___; .Ldone4x: ___ $code.=<<___ if ($win64); - lea 0x140+0x30(%rsp),%r11 - movaps -0x30(%r11),%xmm6 - movaps -0x20(%r11),%xmm7 - movaps -0x10(%r11),%xmm8 - movaps 0x00(%r11),%xmm9 - movaps 0x10(%r11),%xmm10 - movaps 0x20(%r11),%xmm11 - movaps 0x30(%r11),%xmm12 - movaps 0x40(%r11),%xmm13 - movaps 0x50(%r11),%xmm14 - movaps 0x60(%r11),%xmm15 + movaps -0xa8(%r9),%xmm6 + movaps -0x98(%r9),%xmm7 + movaps -0x88(%r9),%xmm8 + movaps -0x78(%r9),%xmm9 + movaps -0x68(%r9),%xmm10 + movaps -0x58(%r9),%xmm11 + movaps -0x48(%r9),%xmm12 + movaps -0x38(%r9),%xmm13 + movaps -0x28(%r9),%xmm14 + movaps -0x18(%r9),%xmm15 ___ $code.=<<___; - add \$0x148+$xframe,%rsp + lea (%r9),%rsp +.cfi_def_cfa_register %rsp +.L4x_epilogue: ret +.cfi_endproc .size ChaCha20_4x,.-ChaCha20_4x ___ } @@ -1217,15 +1269,17 @@ my @x=map("\"$_\"",@xx); ); } -my $xframe = $win64 ? 0xa0 : 0; +my $xframe = $win64 ? 0xa8 : 8; $code.=<<___; .type ChaCha20_4xop,\@function,5 .align 32 ChaCha20_4xop: +.cfi_startproc .LChaCha20_4xop: - lea -0x78(%rsp),%r11 - sub \$0x148+$xframe,%rsp + mov %rsp,%r9 # frame pointer +.cfi_def_cfa_register %r9 + sub \$0x140+$xframe,%rsp ___ ################ stack layout # +0x00 SIMD equivalent of @x[8-12] @@ -1236,16 +1290,17 @@ ___ # ... # +0x140 $code.=<<___ if ($win64); - movaps %xmm6,-0x30(%r11) - movaps %xmm7,-0x20(%r11) - movaps %xmm8,-0x10(%r11) - movaps %xmm9,0x00(%r11) - movaps %xmm10,0x10(%r11) - movaps %xmm11,0x20(%r11) - movaps %xmm12,0x30(%r11) - movaps %xmm13,0x40(%r11) - movaps %xmm14,0x50(%r11) - movaps %xmm15,0x60(%r11) + movaps %xmm6,-0xa8(%r9) + movaps %xmm7,-0x98(%r9) + movaps %xmm8,-0x88(%r9) + movaps %xmm9,-0x78(%r9) + movaps %xmm10,-0x68(%r9) + movaps %xmm11,-0x58(%r9) + movaps %xmm12,-0x48(%r9) + movaps %xmm13,-0x38(%r9) + movaps %xmm14,-0x28(%r9) + movaps %xmm15,-0x18(%r9) +.L4xop_body: ___ $code.=<<___; vzeroupper @@ -1573,21 +1628,23 @@ $code.=<<___; vzeroupper ___ $code.=<<___ if ($win64); - lea 0x140+0x30(%rsp),%r11 - movaps -0x30(%r11),%xmm6 - movaps -0x20(%r11),%xmm7 - movaps -0x10(%r11),%xmm8 - movaps 0x00(%r11),%xmm9 - movaps 0x10(%r11),%xmm10 - movaps 0x20(%r11),%xmm11 - movaps 0x30(%r11),%xmm12 - movaps 0x40(%r11),%xmm13 - movaps 0x50(%r11),%xmm14 - movaps 0x60(%r11),%xmm15 + movaps -0xa8(%r9),%xmm6 + movaps -0x98(%r9),%xmm7 + movaps -0x88(%r9),%xmm8 + movaps -0x78(%r9),%xmm9 + movaps -0x68(%r9),%xmm10 + movaps -0x58(%r9),%xmm11 + movaps -0x48(%r9),%xmm12 + movaps -0x38(%r9),%xmm13 + movaps -0x28(%r9),%xmm14 + movaps -0x18(%r9),%xmm15 ___ $code.=<<___; - add \$0x148+$xframe,%rsp + lea (%r9),%rsp +.cfi_def_cfa_register %rsp +.L4xop_epilogue: ret +.cfi_endproc .size ChaCha20_4xop,.-ChaCha20_4xop ___ } @@ -1714,33 +1771,34 @@ my @x=map("\"$_\"",@xx); ); } -my $xframe = $win64 ? 0xb0 : 8; +my $xframe = $win64 ? 0xa8 : 8; $code.=<<___; .type ChaCha20_8x,\@function,5 .align 32 ChaCha20_8x: +.cfi_startproc .LChaCha20_8x: - mov %rsp,%r10 + mov %rsp,%r9 # frame register +.cfi_def_cfa_register %r9 sub \$0x280+$xframe,%rsp and \$-32,%rsp ___ $code.=<<___ if ($win64); - lea 0x290+0x30(%rsp),%r11 - movaps %xmm6,-0x30(%r11) - movaps %xmm7,-0x20(%r11) - movaps %xmm8,-0x10(%r11) - movaps %xmm9,0x00(%r11) - movaps %xmm10,0x10(%r11) - movaps %xmm11,0x20(%r11) - movaps %xmm12,0x30(%r11) - movaps %xmm13,0x40(%r11) - movaps %xmm14,0x50(%r11) - movaps %xmm15,0x60(%r11) + movaps %xmm6,-0xa8(%r9) + movaps %xmm7,-0x98(%r9) + movaps %xmm8,-0x88(%r9) + movaps %xmm9,-0x78(%r9) + movaps %xmm10,-0x68(%r9) + movaps %xmm11,-0x58(%r9) + movaps %xmm12,-0x48(%r9) + movaps %xmm13,-0x38(%r9) + movaps %xmm14,-0x28(%r9) + movaps %xmm15,-0x18(%r9) +.L8x_body: ___ $code.=<<___; vzeroupper - mov %r10,0x280(%rsp) ################ stack layout # +0x00 SIMD equivalent of @x[8-12] @@ -1749,7 +1807,7 @@ $code.=<<___; # ... # +0x200 SIMD counters (with nonce smashed by lanes) # ... - # +0x280 saved %rsp + # +0x280 vbroadcasti128 .Lsigma(%rip),$xa3 # key[0] vbroadcasti128 ($key),$xb3 # key[1] @@ -2215,29 +2273,1584 @@ $code.=<<___; vzeroall ___ $code.=<<___ if ($win64); - lea 0x290+0x30(%rsp),%r11 - movaps -0x30(%r11),%xmm6 - movaps -0x20(%r11),%xmm7 - movaps -0x10(%r11),%xmm8 - movaps 0x00(%r11),%xmm9 - movaps 0x10(%r11),%xmm10 - movaps 0x20(%r11),%xmm11 - movaps 0x30(%r11),%xmm12 - movaps 0x40(%r11),%xmm13 - movaps 0x50(%r11),%xmm14 - movaps 0x60(%r11),%xmm15 + movaps -0xa8(%r9),%xmm6 + movaps -0x98(%r9),%xmm7 + movaps -0x88(%r9),%xmm8 + movaps -0x78(%r9),%xmm9 + movaps -0x68(%r9),%xmm10 + movaps -0x58(%r9),%xmm11 + movaps -0x48(%r9),%xmm12 + movaps -0x38(%r9),%xmm13 + movaps -0x28(%r9),%xmm14 + movaps -0x18(%r9),%xmm15 ___ $code.=<<___; - mov 0x280(%rsp),%rsp + lea (%r9),%rsp +.cfi_def_cfa_register %rsp +.L8x_epilogue: ret +.cfi_endproc .size ChaCha20_8x,.-ChaCha20_8x ___ } -foreach (split("\n",$code)) { - s/\`([^\`]*)\`/eval $1/geo; +######################################################################## +# AVX512 code paths +if ($avx>2) { +# This one handles shorter inputs... - s/%x#%y/%x/go; +my ($a,$b,$c,$d, $a_,$b_,$c_,$d_,$fourz) = map("%zmm$_",(0..3,16..20)); +my ($t0,$t1,$t2,$t3) = map("%xmm$_",(4..7)); + +sub vpxord() # size optimization +{ my $opcode = "vpxor"; # adhere to vpxor when possible + + foreach (@_) { + if (/%([zy])mm([0-9]+)/ && ($1 eq "z" || $2>=16)) { + $opcode = "vpxord"; + last; + } + } + + $code .= "\t$opcode\t".join(',',reverse @_)."\n"; +} + +sub AVX512ROUND { # critical path is 14 "SIMD ticks" per round + &vpaddd ($a,$a,$b); + &vpxord ($d,$d,$a); + &vprold ($d,$d,16); + + &vpaddd ($c,$c,$d); + &vpxord ($b,$b,$c); + &vprold ($b,$b,12); + + &vpaddd ($a,$a,$b); + &vpxord ($d,$d,$a); + &vprold ($d,$d,8); + + &vpaddd ($c,$c,$d); + &vpxord ($b,$b,$c); + &vprold ($b,$b,7); +} + +my $xframe = $win64 ? 32+8 : 8; + +$code.=<<___; +.type ChaCha20_avx512,\@function,5 +.align 32 +ChaCha20_avx512: +.cfi_startproc +.LChaCha20_avx512: + mov %rsp,%r9 # frame pointer +.cfi_def_cfa_register %r9 + cmp \$512,$len + ja .LChaCha20_16x + + sub \$64+$xframe,%rsp +___ +$code.=<<___ if ($win64); + movaps %xmm6,-0x28(%r9) + movaps %xmm7,-0x18(%r9) +.Lavx512_body: +___ +$code.=<<___; + vbroadcasti32x4 .Lsigma(%rip),$a + vbroadcasti32x4 ($key),$b + vbroadcasti32x4 16($key),$c + vbroadcasti32x4 ($counter),$d + + vmovdqa32 $a,$a_ + vmovdqa32 $b,$b_ + vmovdqa32 $c,$c_ + vpaddd .Lzeroz(%rip),$d,$d + vmovdqa32 .Lfourz(%rip),$fourz + mov \$10,$counter # reuse $counter + vmovdqa32 $d,$d_ + jmp .Loop_avx512 + +.align 16 +.Loop_outer_avx512: + vmovdqa32 $a_,$a + vmovdqa32 $b_,$b + vmovdqa32 $c_,$c + vpaddd $fourz,$d_,$d + mov \$10,$counter + vmovdqa32 $d,$d_ + jmp .Loop_avx512 + +.align 32 +.Loop_avx512: +___ + &AVX512ROUND(); + &vpshufd ($c,$c,0b01001110); + &vpshufd ($b,$b,0b00111001); + &vpshufd ($d,$d,0b10010011); + + &AVX512ROUND(); + &vpshufd ($c,$c,0b01001110); + &vpshufd ($b,$b,0b10010011); + &vpshufd ($d,$d,0b00111001); + + &dec ($counter); + &jnz (".Loop_avx512"); + +$code.=<<___; + vpaddd $a_,$a,$a + vpaddd $b_,$b,$b + vpaddd $c_,$c,$c + vpaddd $d_,$d,$d + + sub \$64,$len + jb .Ltail64_avx512 + + vpxor 0x00($inp),%x#$a,$t0 # xor with input + vpxor 0x10($inp),%x#$b,$t1 + vpxor 0x20($inp),%x#$c,$t2 + vpxor 0x30($inp),%x#$d,$t3 + lea 0x40($inp),$inp # inp+=64 + + vmovdqu $t0,0x00($out) # write output + vmovdqu $t1,0x10($out) + vmovdqu $t2,0x20($out) + vmovdqu $t3,0x30($out) + lea 0x40($out),$out # out+=64 + + jz .Ldone_avx512 + + vextracti32x4 \$1,$a,$t0 + vextracti32x4 \$1,$b,$t1 + vextracti32x4 \$1,$c,$t2 + vextracti32x4 \$1,$d,$t3 + + sub \$64,$len + jb .Ltail_avx512 + + vpxor 0x00($inp),$t0,$t0 # xor with input + vpxor 0x10($inp),$t1,$t1 + vpxor 0x20($inp),$t2,$t2 + vpxor 0x30($inp),$t3,$t3 + lea 0x40($inp),$inp # inp+=64 + + vmovdqu $t0,0x00($out) # write output + vmovdqu $t1,0x10($out) + vmovdqu $t2,0x20($out) + vmovdqu $t3,0x30($out) + lea 0x40($out),$out # out+=64 + + jz .Ldone_avx512 + + vextracti32x4 \$2,$a,$t0 + vextracti32x4 \$2,$b,$t1 + vextracti32x4 \$2,$c,$t2 + vextracti32x4 \$2,$d,$t3 + + sub \$64,$len + jb .Ltail_avx512 + + vpxor 0x00($inp),$t0,$t0 # xor with input + vpxor 0x10($inp),$t1,$t1 + vpxor 0x20($inp),$t2,$t2 + vpxor 0x30($inp),$t3,$t3 + lea 0x40($inp),$inp # inp+=64 + + vmovdqu $t0,0x00($out) # write output + vmovdqu $t1,0x10($out) + vmovdqu $t2,0x20($out) + vmovdqu $t3,0x30($out) + lea 0x40($out),$out # out+=64 + + jz .Ldone_avx512 + + vextracti32x4 \$3,$a,$t0 + vextracti32x4 \$3,$b,$t1 + vextracti32x4 \$3,$c,$t2 + vextracti32x4 \$3,$d,$t3 + + sub \$64,$len + jb .Ltail_avx512 + + vpxor 0x00($inp),$t0,$t0 # xor with input + vpxor 0x10($inp),$t1,$t1 + vpxor 0x20($inp),$t2,$t2 + vpxor 0x30($inp),$t3,$t3 + lea 0x40($inp),$inp # inp+=64 + + vmovdqu $t0,0x00($out) # write output + vmovdqu $t1,0x10($out) + vmovdqu $t2,0x20($out) + vmovdqu $t3,0x30($out) + lea 0x40($out),$out # out+=64 + + jnz .Loop_outer_avx512 + + jmp .Ldone_avx512 + +.align 16 +.Ltail64_avx512: + vmovdqa %x#$a,0x00(%rsp) + vmovdqa %x#$b,0x10(%rsp) + vmovdqa %x#$c,0x20(%rsp) + vmovdqa %x#$d,0x30(%rsp) + add \$64,$len + jmp .Loop_tail_avx512 + +.align 16 +.Ltail_avx512: + vmovdqa $t0,0x00(%rsp) + vmovdqa $t1,0x10(%rsp) + vmovdqa $t2,0x20(%rsp) + vmovdqa $t3,0x30(%rsp) + add \$64,$len + +.Loop_tail_avx512: + movzb ($inp,$counter),%eax + movzb (%rsp,$counter),%ecx + lea 1($counter),$counter + xor %ecx,%eax + mov %al,-1($out,$counter) + dec $len + jnz .Loop_tail_avx512 + + vmovdqu32 $a_,0x00(%rsp) + +.Ldone_avx512: + vzeroall +___ +$code.=<<___ if ($win64); + movaps -0x28(%r9),%xmm6 + movaps -0x18(%r9),%xmm7 +___ +$code.=<<___; + lea (%r9),%rsp +.cfi_def_cfa_register %rsp +.Lavx512_epilogue: + ret +.cfi_endproc +.size ChaCha20_avx512,.-ChaCha20_avx512 +___ + +map(s/%z/%y/, $a,$b,$c,$d, $a_,$b_,$c_,$d_,$fourz); + +$code.=<<___; +.type ChaCha20_avx512vl,\@function,5 +.align 32 +ChaCha20_avx512vl: +.cfi_startproc +.LChaCha20_avx512vl: + mov %rsp,%r9 # frame pointer +.cfi_def_cfa_register %r9 + cmp \$128,$len + ja .LChaCha20_8xvl + + sub \$64+$xframe,%rsp +___ +$code.=<<___ if ($win64); + movaps %xmm6,-0x28(%r9) + movaps %xmm7,-0x18(%r9) +.Lavx512vl_body: +___ +$code.=<<___; + vbroadcasti128 .Lsigma(%rip),$a + vbroadcasti128 ($key),$b + vbroadcasti128 16($key),$c + vbroadcasti128 ($counter),$d + + vmovdqa32 $a,$a_ + vmovdqa32 $b,$b_ + vmovdqa32 $c,$c_ + vpaddd .Lzeroz(%rip),$d,$d + vmovdqa32 .Ltwoy(%rip),$fourz + mov \$10,$counter # reuse $counter + vmovdqa32 $d,$d_ + jmp .Loop_avx512vl + +.align 16 +.Loop_outer_avx512vl: + vmovdqa32 $c_,$c + vpaddd $fourz,$d_,$d + mov \$10,$counter + vmovdqa32 $d,$d_ + jmp .Loop_avx512vl + +.align 32 +.Loop_avx512vl: +___ + &AVX512ROUND(); + &vpshufd ($c,$c,0b01001110); + &vpshufd ($b,$b,0b00111001); + &vpshufd ($d,$d,0b10010011); + + &AVX512ROUND(); + &vpshufd ($c,$c,0b01001110); + &vpshufd ($b,$b,0b10010011); + &vpshufd ($d,$d,0b00111001); + + &dec ($counter); + &jnz (".Loop_avx512vl"); + +$code.=<<___; + vpaddd $a_,$a,$a + vpaddd $b_,$b,$b + vpaddd $c_,$c,$c + vpaddd $d_,$d,$d + + sub \$64,$len + jb .Ltail64_avx512vl + + vpxor 0x00($inp),%x#$a,$t0 # xor with input + vpxor 0x10($inp),%x#$b,$t1 + vpxor 0x20($inp),%x#$c,$t2 + vpxor 0x30($inp),%x#$d,$t3 + lea 0x40($inp),$inp # inp+=64 + + vmovdqu $t0,0x00($out) # write output + vmovdqu $t1,0x10($out) + vmovdqu $t2,0x20($out) + vmovdqu $t3,0x30($out) + lea 0x40($out),$out # out+=64 + + jz .Ldone_avx512vl + + vextracti128 \$1,$a,$t0 + vextracti128 \$1,$b,$t1 + vextracti128 \$1,$c,$t2 + vextracti128 \$1,$d,$t3 + + sub \$64,$len + jb .Ltail_avx512vl + + vpxor 0x00($inp),$t0,$t0 # xor with input + vpxor 0x10($inp),$t1,$t1 + vpxor 0x20($inp),$t2,$t2 + vpxor 0x30($inp),$t3,$t3 + lea 0x40($inp),$inp # inp+=64 + + vmovdqu $t0,0x00($out) # write output + vmovdqu $t1,0x10($out) + vmovdqu $t2,0x20($out) + vmovdqu $t3,0x30($out) + lea 0x40($out),$out # out+=64 + + vmovdqa32 $a_,$a + vmovdqa32 $b_,$b + jnz .Loop_outer_avx512vl + + jmp .Ldone_avx512vl + +.align 16 +.Ltail64_avx512vl: + vmovdqa %x#$a,0x00(%rsp) + vmovdqa %x#$b,0x10(%rsp) + vmovdqa %x#$c,0x20(%rsp) + vmovdqa %x#$d,0x30(%rsp) + add \$64,$len + jmp .Loop_tail_avx512vl + +.align 16 +.Ltail_avx512vl: + vmovdqa $t0,0x00(%rsp) + vmovdqa $t1,0x10(%rsp) + vmovdqa $t2,0x20(%rsp) + vmovdqa $t3,0x30(%rsp) + add \$64,$len + +.Loop_tail_avx512vl: + movzb ($inp,$counter),%eax + movzb (%rsp,$counter),%ecx + lea 1($counter),$counter + xor %ecx,%eax + mov %al,-1($out,$counter) + dec $len + jnz .Loop_tail_avx512vl + + vmovdqu32 $a_,0x00(%rsp) + vmovdqu32 $a_,0x20(%rsp) + +.Ldone_avx512vl: + vzeroall +___ +$code.=<<___ if ($win64); + movaps -0x28(%r9),%xmm6 + movaps -0x18(%r9),%xmm7 +___ +$code.=<<___; + lea (%r9),%rsp +.cfi_def_cfa_register %rsp +.Lavx512vl_epilogue: + ret +.cfi_endproc +.size ChaCha20_avx512vl,.-ChaCha20_avx512vl +___ +} +if ($avx>2) { +# This one handles longer inputs... + +my ($xa0,$xa1,$xa2,$xa3, $xb0,$xb1,$xb2,$xb3, + $xc0,$xc1,$xc2,$xc3, $xd0,$xd1,$xd2,$xd3)=map("%zmm$_",(0..15)); +my @xx=($xa0,$xa1,$xa2,$xa3, $xb0,$xb1,$xb2,$xb3, + $xc0,$xc1,$xc2,$xc3, $xd0,$xd1,$xd2,$xd3); +my @key=map("%zmm$_",(16..31)); +my ($xt0,$xt1,$xt2,$xt3)=@key[0..3]; + +sub AVX512_lane_ROUND { +my ($a0,$b0,$c0,$d0)=@_; +my ($a1,$b1,$c1,$d1)=map(($_&~3)+(($_+1)&3),($a0,$b0,$c0,$d0)); +my ($a2,$b2,$c2,$d2)=map(($_&~3)+(($_+1)&3),($a1,$b1,$c1,$d1)); +my ($a3,$b3,$c3,$d3)=map(($_&~3)+(($_+1)&3),($a2,$b2,$c2,$d2)); +my @x=map("\"$_\"",@xx); + + ( + "&vpaddd (@x[$a0],@x[$a0],@x[$b0])", # Q1 + "&vpaddd (@x[$a1],@x[$a1],@x[$b1])", # Q2 + "&vpaddd (@x[$a2],@x[$a2],@x[$b2])", # Q3 + "&vpaddd (@x[$a3],@x[$a3],@x[$b3])", # Q4 + "&vpxord (@x[$d0],@x[$d0],@x[$a0])", + "&vpxord (@x[$d1],@x[$d1],@x[$a1])", + "&vpxord (@x[$d2],@x[$d2],@x[$a2])", + "&vpxord (@x[$d3],@x[$d3],@x[$a3])", + "&vprold (@x[$d0],@x[$d0],16)", + "&vprold (@x[$d1],@x[$d1],16)", + "&vprold (@x[$d2],@x[$d2],16)", + "&vprold (@x[$d3],@x[$d3],16)", + + "&vpaddd (@x[$c0],@x[$c0],@x[$d0])", + "&vpaddd (@x[$c1],@x[$c1],@x[$d1])", + "&vpaddd (@x[$c2],@x[$c2],@x[$d2])", + "&vpaddd (@x[$c3],@x[$c3],@x[$d3])", + "&vpxord (@x[$b0],@x[$b0],@x[$c0])", + "&vpxord (@x[$b1],@x[$b1],@x[$c1])", + "&vpxord (@x[$b2],@x[$b2],@x[$c2])", + "&vpxord (@x[$b3],@x[$b3],@x[$c3])", + "&vprold (@x[$b0],@x[$b0],12)", + "&vprold (@x[$b1],@x[$b1],12)", + "&vprold (@x[$b2],@x[$b2],12)", + "&vprold (@x[$b3],@x[$b3],12)", + + "&vpaddd (@x[$a0],@x[$a0],@x[$b0])", + "&vpaddd (@x[$a1],@x[$a1],@x[$b1])", + "&vpaddd (@x[$a2],@x[$a2],@x[$b2])", + "&vpaddd (@x[$a3],@x[$a3],@x[$b3])", + "&vpxord (@x[$d0],@x[$d0],@x[$a0])", + "&vpxord (@x[$d1],@x[$d1],@x[$a1])", + "&vpxord (@x[$d2],@x[$d2],@x[$a2])", + "&vpxord (@x[$d3],@x[$d3],@x[$a3])", + "&vprold (@x[$d0],@x[$d0],8)", + "&vprold (@x[$d1],@x[$d1],8)", + "&vprold (@x[$d2],@x[$d2],8)", + "&vprold (@x[$d3],@x[$d3],8)", + + "&vpaddd (@x[$c0],@x[$c0],@x[$d0])", + "&vpaddd (@x[$c1],@x[$c1],@x[$d1])", + "&vpaddd (@x[$c2],@x[$c2],@x[$d2])", + "&vpaddd (@x[$c3],@x[$c3],@x[$d3])", + "&vpxord (@x[$b0],@x[$b0],@x[$c0])", + "&vpxord (@x[$b1],@x[$b1],@x[$c1])", + "&vpxord (@x[$b2],@x[$b2],@x[$c2])", + "&vpxord (@x[$b3],@x[$b3],@x[$c3])", + "&vprold (@x[$b0],@x[$b0],7)", + "&vprold (@x[$b1],@x[$b1],7)", + "&vprold (@x[$b2],@x[$b2],7)", + "&vprold (@x[$b3],@x[$b3],7)" + ); +} + +my $xframe = $win64 ? 0xa8 : 8; + +$code.=<<___; +.type ChaCha20_16x,\@function,5 +.align 32 +ChaCha20_16x: +.cfi_startproc +.LChaCha20_16x: + mov %rsp,%r9 # frame register +.cfi_def_cfa_register %r9 + sub \$64+$xframe,%rsp + and \$-64,%rsp +___ +$code.=<<___ if ($win64); + movaps %xmm6,-0xa8(%r9) + movaps %xmm7,-0x98(%r9) + movaps %xmm8,-0x88(%r9) + movaps %xmm9,-0x78(%r9) + movaps %xmm10,-0x68(%r9) + movaps %xmm11,-0x58(%r9) + movaps %xmm12,-0x48(%r9) + movaps %xmm13,-0x38(%r9) + movaps %xmm14,-0x28(%r9) + movaps %xmm15,-0x18(%r9) +.L16x_body: +___ +$code.=<<___; + vzeroupper + + lea .Lsigma(%rip),%r10 + vbroadcasti32x4 (%r10),$xa3 # key[0] + vbroadcasti32x4 ($key),$xb3 # key[1] + vbroadcasti32x4 16($key),$xc3 # key[2] + vbroadcasti32x4 ($counter),$xd3 # key[3] + + vpshufd \$0x00,$xa3,$xa0 # smash key by lanes... + vpshufd \$0x55,$xa3,$xa1 + vpshufd \$0xaa,$xa3,$xa2 + vpshufd \$0xff,$xa3,$xa3 + vmovdqa64 $xa0,@key[0] + vmovdqa64 $xa1,@key[1] + vmovdqa64 $xa2,@key[2] + vmovdqa64 $xa3,@key[3] + + vpshufd \$0x00,$xb3,$xb0 + vpshufd \$0x55,$xb3,$xb1 + vpshufd \$0xaa,$xb3,$xb2 + vpshufd \$0xff,$xb3,$xb3 + vmovdqa64 $xb0,@key[4] + vmovdqa64 $xb1,@key[5] + vmovdqa64 $xb2,@key[6] + vmovdqa64 $xb3,@key[7] + + vpshufd \$0x00,$xc3,$xc0 + vpshufd \$0x55,$xc3,$xc1 + vpshufd \$0xaa,$xc3,$xc2 + vpshufd \$0xff,$xc3,$xc3 + vmovdqa64 $xc0,@key[8] + vmovdqa64 $xc1,@key[9] + vmovdqa64 $xc2,@key[10] + vmovdqa64 $xc3,@key[11] + + vpshufd \$0x00,$xd3,$xd0 + vpshufd \$0x55,$xd3,$xd1 + vpshufd \$0xaa,$xd3,$xd2 + vpshufd \$0xff,$xd3,$xd3 + vpaddd .Lincz(%rip),$xd0,$xd0 # don't save counters yet + vmovdqa64 $xd0,@key[12] + vmovdqa64 $xd1,@key[13] + vmovdqa64 $xd2,@key[14] + vmovdqa64 $xd3,@key[15] + + mov \$10,%eax + jmp .Loop16x + +.align 32 +.Loop_outer16x: + vpbroadcastd 0(%r10),$xa0 # reload key + vpbroadcastd 4(%r10),$xa1 + vpbroadcastd 8(%r10),$xa2 + vpbroadcastd 12(%r10),$xa3 + vpaddd .Lsixteen(%rip),@key[12],@key[12] # next SIMD counters + vmovdqa64 @key[4],$xb0 + vmovdqa64 @key[5],$xb1 + vmovdqa64 @key[6],$xb2 + vmovdqa64 @key[7],$xb3 + vmovdqa64 @key[8],$xc0 + vmovdqa64 @key[9],$xc1 + vmovdqa64 @key[10],$xc2 + vmovdqa64 @key[11],$xc3 + vmovdqa64 @key[12],$xd0 + vmovdqa64 @key[13],$xd1 + vmovdqa64 @key[14],$xd2 + vmovdqa64 @key[15],$xd3 + + vmovdqa64 $xa0,@key[0] + vmovdqa64 $xa1,@key[1] + vmovdqa64 $xa2,@key[2] + vmovdqa64 $xa3,@key[3] + + mov \$10,%eax + jmp .Loop16x + +.align 32 +.Loop16x: +___ + foreach (&AVX512_lane_ROUND(0, 4, 8,12)) { eval; } + foreach (&AVX512_lane_ROUND(0, 5,10,15)) { eval; } +$code.=<<___; + dec %eax + jnz .Loop16x + + vpaddd @key[0],$xa0,$xa0 # accumulate key + vpaddd @key[1],$xa1,$xa1 + vpaddd @key[2],$xa2,$xa2 + vpaddd @key[3],$xa3,$xa3 + + vpunpckldq $xa1,$xa0,$xt2 # "de-interlace" data + vpunpckldq $xa3,$xa2,$xt3 + vpunpckhdq $xa1,$xa0,$xa0 + vpunpckhdq $xa3,$xa2,$xa2 + vpunpcklqdq $xt3,$xt2,$xa1 # "a0" + vpunpckhqdq $xt3,$xt2,$xt2 # "a1" + vpunpcklqdq $xa2,$xa0,$xa3 # "a2" + vpunpckhqdq $xa2,$xa0,$xa0 # "a3" +___ + ($xa0,$xa1,$xa2,$xa3,$xt2)=($xa1,$xt2,$xa3,$xa0,$xa2); +$code.=<<___; + vpaddd @key[4],$xb0,$xb0 + vpaddd @key[5],$xb1,$xb1 + vpaddd @key[6],$xb2,$xb2 + vpaddd @key[7],$xb3,$xb3 + + vpunpckldq $xb1,$xb0,$xt2 + vpunpckldq $xb3,$xb2,$xt3 + vpunpckhdq $xb1,$xb0,$xb0 + vpunpckhdq $xb3,$xb2,$xb2 + vpunpcklqdq $xt3,$xt2,$xb1 # "b0" + vpunpckhqdq $xt3,$xt2,$xt2 # "b1" + vpunpcklqdq $xb2,$xb0,$xb3 # "b2" + vpunpckhqdq $xb2,$xb0,$xb0 # "b3" +___ + ($xb0,$xb1,$xb2,$xb3,$xt2)=($xb1,$xt2,$xb3,$xb0,$xb2); +$code.=<<___; + vshufi32x4 \$0x44,$xb0,$xa0,$xt3 # "de-interlace" further + vshufi32x4 \$0xee,$xb0,$xa0,$xb0 + vshufi32x4 \$0x44,$xb1,$xa1,$xa0 + vshufi32x4 \$0xee,$xb1,$xa1,$xb1 + vshufi32x4 \$0x44,$xb2,$xa2,$xa1 + vshufi32x4 \$0xee,$xb2,$xa2,$xb2 + vshufi32x4 \$0x44,$xb3,$xa3,$xa2 + vshufi32x4 \$0xee,$xb3,$xa3,$xb3 +___ + ($xa0,$xa1,$xa2,$xa3,$xt3)=($xt3,$xa0,$xa1,$xa2,$xa3); +$code.=<<___; + vpaddd @key[8],$xc0,$xc0 + vpaddd @key[9],$xc1,$xc1 + vpaddd @key[10],$xc2,$xc2 + vpaddd @key[11],$xc3,$xc3 + + vpunpckldq $xc1,$xc0,$xt2 + vpunpckldq $xc3,$xc2,$xt3 + vpunpckhdq $xc1,$xc0,$xc0 + vpunpckhdq $xc3,$xc2,$xc2 + vpunpcklqdq $xt3,$xt2,$xc1 # "c0" + vpunpckhqdq $xt3,$xt2,$xt2 # "c1" + vpunpcklqdq $xc2,$xc0,$xc3 # "c2" + vpunpckhqdq $xc2,$xc0,$xc0 # "c3" +___ + ($xc0,$xc1,$xc2,$xc3,$xt2)=($xc1,$xt2,$xc3,$xc0,$xc2); +$code.=<<___; + vpaddd @key[12],$xd0,$xd0 + vpaddd @key[13],$xd1,$xd1 + vpaddd @key[14],$xd2,$xd2 + vpaddd @key[15],$xd3,$xd3 + + vpunpckldq $xd1,$xd0,$xt2 + vpunpckldq $xd3,$xd2,$xt3 + vpunpckhdq $xd1,$xd0,$xd0 + vpunpckhdq $xd3,$xd2,$xd2 + vpunpcklqdq $xt3,$xt2,$xd1 # "d0" + vpunpckhqdq $xt3,$xt2,$xt2 # "d1" + vpunpcklqdq $xd2,$xd0,$xd3 # "d2" + vpunpckhqdq $xd2,$xd0,$xd0 # "d3" +___ + ($xd0,$xd1,$xd2,$xd3,$xt2)=($xd1,$xt2,$xd3,$xd0,$xd2); +$code.=<<___; + vshufi32x4 \$0x44,$xd0,$xc0,$xt3 # "de-interlace" further + vshufi32x4 \$0xee,$xd0,$xc0,$xd0 + vshufi32x4 \$0x44,$xd1,$xc1,$xc0 + vshufi32x4 \$0xee,$xd1,$xc1,$xd1 + vshufi32x4 \$0x44,$xd2,$xc2,$xc1 + vshufi32x4 \$0xee,$xd2,$xc2,$xd2 + vshufi32x4 \$0x44,$xd3,$xc3,$xc2 + vshufi32x4 \$0xee,$xd3,$xc3,$xd3 +___ + ($xc0,$xc1,$xc2,$xc3,$xt3)=($xt3,$xc0,$xc1,$xc2,$xc3); +$code.=<<___; + vshufi32x4 \$0x88,$xc0,$xa0,$xt0 # "de-interlace" further + vshufi32x4 \$0xdd,$xc0,$xa0,$xa0 + vshufi32x4 \$0x88,$xd0,$xb0,$xc0 + vshufi32x4 \$0xdd,$xd0,$xb0,$xd0 + vshufi32x4 \$0x88,$xc1,$xa1,$xt1 + vshufi32x4 \$0xdd,$xc1,$xa1,$xa1 + vshufi32x4 \$0x88,$xd1,$xb1,$xc1 + vshufi32x4 \$0xdd,$xd1,$xb1,$xd1 + vshufi32x4 \$0x88,$xc2,$xa2,$xt2 + vshufi32x4 \$0xdd,$xc2,$xa2,$xa2 + vshufi32x4 \$0x88,$xd2,$xb2,$xc2 + vshufi32x4 \$0xdd,$xd2,$xb2,$xd2 + vshufi32x4 \$0x88,$xc3,$xa3,$xt3 + vshufi32x4 \$0xdd,$xc3,$xa3,$xa3 + vshufi32x4 \$0x88,$xd3,$xb3,$xc3 + vshufi32x4 \$0xdd,$xd3,$xb3,$xd3 +___ + ($xa0,$xa1,$xa2,$xa3,$xb0,$xb1,$xb2,$xb3)= + ($xt0,$xt1,$xt2,$xt3,$xa0,$xa1,$xa2,$xa3); + + ($xa0,$xb0,$xc0,$xd0, $xa1,$xb1,$xc1,$xd1, + $xa2,$xb2,$xc2,$xd2, $xa3,$xb3,$xc3,$xd3) = + ($xa0,$xa1,$xa2,$xa3, $xb0,$xb1,$xb2,$xb3, + $xc0,$xc1,$xc2,$xc3, $xd0,$xd1,$xd2,$xd3); +$code.=<<___; + cmp \$64*16,$len + jb .Ltail16x + + vpxord 0x00($inp),$xa0,$xa0 # xor with input + vpxord 0x40($inp),$xb0,$xb0 + vpxord 0x80($inp),$xc0,$xc0 + vpxord 0xc0($inp),$xd0,$xd0 + vmovdqu32 $xa0,0x00($out) + vmovdqu32 $xb0,0x40($out) + vmovdqu32 $xc0,0x80($out) + vmovdqu32 $xd0,0xc0($out) + + vpxord 0x100($inp),$xa1,$xa1 + vpxord 0x140($inp),$xb1,$xb1 + vpxord 0x180($inp),$xc1,$xc1 + vpxord 0x1c0($inp),$xd1,$xd1 + vmovdqu32 $xa1,0x100($out) + vmovdqu32 $xb1,0x140($out) + vmovdqu32 $xc1,0x180($out) + vmovdqu32 $xd1,0x1c0($out) + + vpxord 0x200($inp),$xa2,$xa2 + vpxord 0x240($inp),$xb2,$xb2 + vpxord 0x280($inp),$xc2,$xc2 + vpxord 0x2c0($inp),$xd2,$xd2 + vmovdqu32 $xa2,0x200($out) + vmovdqu32 $xb2,0x240($out) + vmovdqu32 $xc2,0x280($out) + vmovdqu32 $xd2,0x2c0($out) + + vpxord 0x300($inp),$xa3,$xa3 + vpxord 0x340($inp),$xb3,$xb3 + vpxord 0x380($inp),$xc3,$xc3 + vpxord 0x3c0($inp),$xd3,$xd3 + lea 0x400($inp),$inp + vmovdqu32 $xa3,0x300($out) + vmovdqu32 $xb3,0x340($out) + vmovdqu32 $xc3,0x380($out) + vmovdqu32 $xd3,0x3c0($out) + lea 0x400($out),$out + + sub \$64*16,$len + jnz .Loop_outer16x + + jmp .Ldone16x + +.align 32 +.Ltail16x: + xor %r10,%r10 + sub $inp,$out + cmp \$64*1,$len + jb .Less_than_64_16x + vpxord ($inp),$xa0,$xa0 # xor with input + vmovdqu32 $xa0,($out,$inp) + je .Ldone16x + vmovdqa32 $xb0,$xa0 + lea 64($inp),$inp + + cmp \$64*2,$len + jb .Less_than_64_16x + vpxord ($inp),$xb0,$xb0 + vmovdqu32 $xb0,($out,$inp) + je .Ldone16x + vmovdqa32 $xc0,$xa0 + lea 64($inp),$inp + + cmp \$64*3,$len + jb .Less_than_64_16x + vpxord ($inp),$xc0,$xc0 + vmovdqu32 $xc0,($out,$inp) + je .Ldone16x + vmovdqa32 $xd0,$xa0 + lea 64($inp),$inp + + cmp \$64*4,$len + jb .Less_than_64_16x + vpxord ($inp),$xd0,$xd0 + vmovdqu32 $xd0,($out,$inp) + je .Ldone16x + vmovdqa32 $xa1,$xa0 + lea 64($inp),$inp + + cmp \$64*5,$len + jb .Less_than_64_16x + vpxord ($inp),$xa1,$xa1 + vmovdqu32 $xa1,($out,$inp) + je .Ldone16x + vmovdqa32 $xb1,$xa0 + lea 64($inp),$inp + + cmp \$64*6,$len + jb .Less_than_64_16x + vpxord ($inp),$xb1,$xb1 + vmovdqu32 $xb1,($out,$inp) + je .Ldone16x + vmovdqa32 $xc1,$xa0 + lea 64($inp),$inp + + cmp \$64*7,$len + jb .Less_than_64_16x + vpxord ($inp),$xc1,$xc1 + vmovdqu32 $xc1,($out,$inp) + je .Ldone16x + vmovdqa32 $xd1,$xa0 + lea 64($inp),$inp + + cmp \$64*8,$len + jb .Less_than_64_16x + vpxord ($inp),$xd1,$xd1 + vmovdqu32 $xd1,($out,$inp) + je .Ldone16x + vmovdqa32 $xa2,$xa0 + lea 64($inp),$inp + + cmp \$64*9,$len + jb .Less_than_64_16x + vpxord ($inp),$xa2,$xa2 + vmovdqu32 $xa2,($out,$inp) + je .Ldone16x + vmovdqa32 $xb2,$xa0 + lea 64($inp),$inp + + cmp \$64*10,$len + jb .Less_than_64_16x + vpxord ($inp),$xb2,$xb2 + vmovdqu32 $xb2,($out,$inp) + je .Ldone16x + vmovdqa32 $xc2,$xa0 + lea 64($inp),$inp + + cmp \$64*11,$len + jb .Less_than_64_16x + vpxord ($inp),$xc2,$xc2 + vmovdqu32 $xc2,($out,$inp) + je .Ldone16x + vmovdqa32 $xd2,$xa0 + lea 64($inp),$inp + + cmp \$64*12,$len + jb .Less_than_64_16x + vpxord ($inp),$xd2,$xd2 + vmovdqu32 $xd2,($out,$inp) + je .Ldone16x + vmovdqa32 $xa3,$xa0 + lea 64($inp),$inp + + cmp \$64*13,$len + jb .Less_than_64_16x + vpxord ($inp),$xa3,$xa3 + vmovdqu32 $xa3,($out,$inp) + je .Ldone16x + vmovdqa32 $xb3,$xa0 + lea 64($inp),$inp + + cmp \$64*14,$len + jb .Less_than_64_16x + vpxord ($inp),$xb3,$xb3 + vmovdqu32 $xb3,($out,$inp) + je .Ldone16x + vmovdqa32 $xc3,$xa0 + lea 64($inp),$inp + + cmp \$64*15,$len + jb .Less_than_64_16x + vpxord ($inp),$xc3,$xc3 + vmovdqu32 $xc3,($out,$inp) + je .Ldone16x + vmovdqa32 $xd3,$xa0 + lea 64($inp),$inp + +.Less_than_64_16x: + vmovdqa32 $xa0,0x00(%rsp) + lea ($out,$inp),$out + and \$63,$len + +.Loop_tail16x: + movzb ($inp,%r10),%eax + movzb (%rsp,%r10),%ecx + lea 1(%r10),%r10 + xor %ecx,%eax + mov %al,-1($out,%r10) + dec $len + jnz .Loop_tail16x + + vpxord $xa0,$xa0,$xa0 + vmovdqa32 $xa0,0(%rsp) + +.Ldone16x: + vzeroall +___ +$code.=<<___ if ($win64); + movaps -0xa8(%r9),%xmm6 + movaps -0x98(%r9),%xmm7 + movaps -0x88(%r9),%xmm8 + movaps -0x78(%r9),%xmm9 + movaps -0x68(%r9),%xmm10 + movaps -0x58(%r9),%xmm11 + movaps -0x48(%r9),%xmm12 + movaps -0x38(%r9),%xmm13 + movaps -0x28(%r9),%xmm14 + movaps -0x18(%r9),%xmm15 +___ +$code.=<<___; + lea (%r9),%rsp +.cfi_def_cfa_register %rsp +.L16x_epilogue: + ret +.cfi_endproc +.size ChaCha20_16x,.-ChaCha20_16x +___ + +# switch to %ymm domain +($xa0,$xa1,$xa2,$xa3, $xb0,$xb1,$xb2,$xb3, + $xc0,$xc1,$xc2,$xc3, $xd0,$xd1,$xd2,$xd3)=map("%ymm$_",(0..15)); +@xx=($xa0,$xa1,$xa2,$xa3, $xb0,$xb1,$xb2,$xb3, + $xc0,$xc1,$xc2,$xc3, $xd0,$xd1,$xd2,$xd3); +@key=map("%ymm$_",(16..31)); +($xt0,$xt1,$xt2,$xt3)=@key[0..3]; + +$code.=<<___; +.type ChaCha20_8xvl,\@function,5 +.align 32 +ChaCha20_8xvl: +.cfi_startproc +.LChaCha20_8xvl: + mov %rsp,%r9 # frame register +.cfi_def_cfa_register %r9 + sub \$64+$xframe,%rsp + and \$-64,%rsp +___ +$code.=<<___ if ($win64); + movaps %xmm6,-0xa8(%r9) + movaps %xmm7,-0x98(%r9) + movaps %xmm8,-0x88(%r9) + movaps %xmm9,-0x78(%r9) + movaps %xmm10,-0x68(%r9) + movaps %xmm11,-0x58(%r9) + movaps %xmm12,-0x48(%r9) + movaps %xmm13,-0x38(%r9) + movaps %xmm14,-0x28(%r9) + movaps %xmm15,-0x18(%r9) +.L8xvl_body: +___ +$code.=<<___; + vzeroupper + + lea .Lsigma(%rip),%r10 + vbroadcasti128 (%r10),$xa3 # key[0] + vbroadcasti128 ($key),$xb3 # key[1] + vbroadcasti128 16($key),$xc3 # key[2] + vbroadcasti128 ($counter),$xd3 # key[3] + + vpshufd \$0x00,$xa3,$xa0 # smash key by lanes... + vpshufd \$0x55,$xa3,$xa1 + vpshufd \$0xaa,$xa3,$xa2 + vpshufd \$0xff,$xa3,$xa3 + vmovdqa64 $xa0,@key[0] + vmovdqa64 $xa1,@key[1] + vmovdqa64 $xa2,@key[2] + vmovdqa64 $xa3,@key[3] + + vpshufd \$0x00,$xb3,$xb0 + vpshufd \$0x55,$xb3,$xb1 + vpshufd \$0xaa,$xb3,$xb2 + vpshufd \$0xff,$xb3,$xb3 + vmovdqa64 $xb0,@key[4] + vmovdqa64 $xb1,@key[5] + vmovdqa64 $xb2,@key[6] + vmovdqa64 $xb3,@key[7] + + vpshufd \$0x00,$xc3,$xc0 + vpshufd \$0x55,$xc3,$xc1 + vpshufd \$0xaa,$xc3,$xc2 + vpshufd \$0xff,$xc3,$xc3 + vmovdqa64 $xc0,@key[8] + vmovdqa64 $xc1,@key[9] + vmovdqa64 $xc2,@key[10] + vmovdqa64 $xc3,@key[11] + + vpshufd \$0x00,$xd3,$xd0 + vpshufd \$0x55,$xd3,$xd1 + vpshufd \$0xaa,$xd3,$xd2 + vpshufd \$0xff,$xd3,$xd3 + vpaddd .Lincy(%rip),$xd0,$xd0 # don't save counters yet + vmovdqa64 $xd0,@key[12] + vmovdqa64 $xd1,@key[13] + vmovdqa64 $xd2,@key[14] + vmovdqa64 $xd3,@key[15] + + mov \$10,%eax + jmp .Loop8xvl + +.align 32 +.Loop_outer8xvl: + #vpbroadcastd 0(%r10),$xa0 # reload key + #vpbroadcastd 4(%r10),$xa1 + vpbroadcastd 8(%r10),$xa2 + vpbroadcastd 12(%r10),$xa3 + vpaddd .Leight(%rip),@key[12],@key[12] # next SIMD counters + vmovdqa64 @key[4],$xb0 + vmovdqa64 @key[5],$xb1 + vmovdqa64 @key[6],$xb2 + vmovdqa64 @key[7],$xb3 + vmovdqa64 @key[8],$xc0 + vmovdqa64 @key[9],$xc1 + vmovdqa64 @key[10],$xc2 + vmovdqa64 @key[11],$xc3 + vmovdqa64 @key[12],$xd0 + vmovdqa64 @key[13],$xd1 + vmovdqa64 @key[14],$xd2 + vmovdqa64 @key[15],$xd3 + + vmovdqa64 $xa0,@key[0] + vmovdqa64 $xa1,@key[1] + vmovdqa64 $xa2,@key[2] + vmovdqa64 $xa3,@key[3] + + mov \$10,%eax + jmp .Loop8xvl + +.align 32 +.Loop8xvl: +___ + foreach (&AVX512_lane_ROUND(0, 4, 8,12)) { eval; } + foreach (&AVX512_lane_ROUND(0, 5,10,15)) { eval; } +$code.=<<___; + dec %eax + jnz .Loop8xvl + + vpaddd @key[0],$xa0,$xa0 # accumulate key + vpaddd @key[1],$xa1,$xa1 + vpaddd @key[2],$xa2,$xa2 + vpaddd @key[3],$xa3,$xa3 + + vpunpckldq $xa1,$xa0,$xt2 # "de-interlace" data + vpunpckldq $xa3,$xa2,$xt3 + vpunpckhdq $xa1,$xa0,$xa0 + vpunpckhdq $xa3,$xa2,$xa2 + vpunpcklqdq $xt3,$xt2,$xa1 # "a0" + vpunpckhqdq $xt3,$xt2,$xt2 # "a1" + vpunpcklqdq $xa2,$xa0,$xa3 # "a2" + vpunpckhqdq $xa2,$xa0,$xa0 # "a3" +___ + ($xa0,$xa1,$xa2,$xa3,$xt2)=($xa1,$xt2,$xa3,$xa0,$xa2); +$code.=<<___; + vpaddd @key[4],$xb0,$xb0 + vpaddd @key[5],$xb1,$xb1 + vpaddd @key[6],$xb2,$xb2 + vpaddd @key[7],$xb3,$xb3 + + vpunpckldq $xb1,$xb0,$xt2 + vpunpckldq $xb3,$xb2,$xt3 + vpunpckhdq $xb1,$xb0,$xb0 + vpunpckhdq $xb3,$xb2,$xb2 + vpunpcklqdq $xt3,$xt2,$xb1 # "b0" + vpunpckhqdq $xt3,$xt2,$xt2 # "b1" + vpunpcklqdq $xb2,$xb0,$xb3 # "b2" + vpunpckhqdq $xb2,$xb0,$xb0 # "b3" +___ + ($xb0,$xb1,$xb2,$xb3,$xt2)=($xb1,$xt2,$xb3,$xb0,$xb2); +$code.=<<___; + vshufi32x4 \$0,$xb0,$xa0,$xt3 # "de-interlace" further + vshufi32x4 \$3,$xb0,$xa0,$xb0 + vshufi32x4 \$0,$xb1,$xa1,$xa0 + vshufi32x4 \$3,$xb1,$xa1,$xb1 + vshufi32x4 \$0,$xb2,$xa2,$xa1 + vshufi32x4 \$3,$xb2,$xa2,$xb2 + vshufi32x4 \$0,$xb3,$xa3,$xa2 + vshufi32x4 \$3,$xb3,$xa3,$xb3 +___ + ($xa0,$xa1,$xa2,$xa3,$xt3)=($xt3,$xa0,$xa1,$xa2,$xa3); +$code.=<<___; + vpaddd @key[8],$xc0,$xc0 + vpaddd @key[9],$xc1,$xc1 + vpaddd @key[10],$xc2,$xc2 + vpaddd @key[11],$xc3,$xc3 + + vpunpckldq $xc1,$xc0,$xt2 + vpunpckldq $xc3,$xc2,$xt3 + vpunpckhdq $xc1,$xc0,$xc0 + vpunpckhdq $xc3,$xc2,$xc2 + vpunpcklqdq $xt3,$xt2,$xc1 # "c0" + vpunpckhqdq $xt3,$xt2,$xt2 # "c1" + vpunpcklqdq $xc2,$xc0,$xc3 # "c2" + vpunpckhqdq $xc2,$xc0,$xc0 # "c3" +___ + ($xc0,$xc1,$xc2,$xc3,$xt2)=($xc1,$xt2,$xc3,$xc0,$xc2); +$code.=<<___; + vpaddd @key[12],$xd0,$xd0 + vpaddd @key[13],$xd1,$xd1 + vpaddd @key[14],$xd2,$xd2 + vpaddd @key[15],$xd3,$xd3 + + vpunpckldq $xd1,$xd0,$xt2 + vpunpckldq $xd3,$xd2,$xt3 + vpunpckhdq $xd1,$xd0,$xd0 + vpunpckhdq $xd3,$xd2,$xd2 + vpunpcklqdq $xt3,$xt2,$xd1 # "d0" + vpunpckhqdq $xt3,$xt2,$xt2 # "d1" + vpunpcklqdq $xd2,$xd0,$xd3 # "d2" + vpunpckhqdq $xd2,$xd0,$xd0 # "d3" +___ + ($xd0,$xd1,$xd2,$xd3,$xt2)=($xd1,$xt2,$xd3,$xd0,$xd2); +$code.=<<___; + vperm2i128 \$0x20,$xd0,$xc0,$xt3 # "de-interlace" further + vperm2i128 \$0x31,$xd0,$xc0,$xd0 + vperm2i128 \$0x20,$xd1,$xc1,$xc0 + vperm2i128 \$0x31,$xd1,$xc1,$xd1 + vperm2i128 \$0x20,$xd2,$xc2,$xc1 + vperm2i128 \$0x31,$xd2,$xc2,$xd2 + vperm2i128 \$0x20,$xd3,$xc3,$xc2 + vperm2i128 \$0x31,$xd3,$xc3,$xd3 +___ + ($xc0,$xc1,$xc2,$xc3,$xt3)=($xt3,$xc0,$xc1,$xc2,$xc3); + ($xb0,$xb1,$xb2,$xb3,$xc0,$xc1,$xc2,$xc3)= + ($xc0,$xc1,$xc2,$xc3,$xb0,$xb1,$xb2,$xb3); +$code.=<<___; + cmp \$64*8,$len + jb .Ltail8xvl + + mov \$0x80,%eax # size optimization + vpxord 0x00($inp),$xa0,$xa0 # xor with input + vpxor 0x20($inp),$xb0,$xb0 + vpxor 0x40($inp),$xc0,$xc0 + vpxor 0x60($inp),$xd0,$xd0 + lea ($inp,%rax),$inp # size optimization + vmovdqu32 $xa0,0x00($out) + vmovdqu $xb0,0x20($out) + vmovdqu $xc0,0x40($out) + vmovdqu $xd0,0x60($out) + lea ($out,%rax),$out # size optimization + + vpxor 0x00($inp),$xa1,$xa1 + vpxor 0x20($inp),$xb1,$xb1 + vpxor 0x40($inp),$xc1,$xc1 + vpxor 0x60($inp),$xd1,$xd1 + lea ($inp,%rax),$inp # size optimization + vmovdqu $xa1,0x00($out) + vmovdqu $xb1,0x20($out) + vmovdqu $xc1,0x40($out) + vmovdqu $xd1,0x60($out) + lea ($out,%rax),$out # size optimization + + vpxord 0x00($inp),$xa2,$xa2 + vpxor 0x20($inp),$xb2,$xb2 + vpxor 0x40($inp),$xc2,$xc2 + vpxor 0x60($inp),$xd2,$xd2 + lea ($inp,%rax),$inp # size optimization + vmovdqu32 $xa2,0x00($out) + vmovdqu $xb2,0x20($out) + vmovdqu $xc2,0x40($out) + vmovdqu $xd2,0x60($out) + lea ($out,%rax),$out # size optimization + + vpxor 0x00($inp),$xa3,$xa3 + vpxor 0x20($inp),$xb3,$xb3 + vpxor 0x40($inp),$xc3,$xc3 + vpxor 0x60($inp),$xd3,$xd3 + lea ($inp,%rax),$inp # size optimization + vmovdqu $xa3,0x00($out) + vmovdqu $xb3,0x20($out) + vmovdqu $xc3,0x40($out) + vmovdqu $xd3,0x60($out) + lea ($out,%rax),$out # size optimization + + vpbroadcastd 0(%r10),%ymm0 # reload key + vpbroadcastd 4(%r10),%ymm1 + + sub \$64*8,$len + jnz .Loop_outer8xvl + + jmp .Ldone8xvl + +.align 32 +.Ltail8xvl: + vmovdqa64 $xa0,%ymm8 # size optimization +___ +$xa0 = "%ymm8"; +$code.=<<___; + xor %r10,%r10 + sub $inp,$out + cmp \$64*1,$len + jb .Less_than_64_8xvl + vpxor 0x00($inp),$xa0,$xa0 # xor with input + vpxor 0x20($inp),$xb0,$xb0 + vmovdqu $xa0,0x00($out,$inp) + vmovdqu $xb0,0x20($out,$inp) + je .Ldone8xvl + vmovdqa $xc0,$xa0 + vmovdqa $xd0,$xb0 + lea 64($inp),$inp + + cmp \$64*2,$len + jb .Less_than_64_8xvl + vpxor 0x00($inp),$xc0,$xc0 + vpxor 0x20($inp),$xd0,$xd0 + vmovdqu $xc0,0x00($out,$inp) + vmovdqu $xd0,0x20($out,$inp) + je .Ldone8xvl + vmovdqa $xa1,$xa0 + vmovdqa $xb1,$xb0 + lea 64($inp),$inp + + cmp \$64*3,$len + jb .Less_than_64_8xvl + vpxor 0x00($inp),$xa1,$xa1 + vpxor 0x20($inp),$xb1,$xb1 + vmovdqu $xa1,0x00($out,$inp) + vmovdqu $xb1,0x20($out,$inp) + je .Ldone8xvl + vmovdqa $xc1,$xa0 + vmovdqa $xd1,$xb0 + lea 64($inp),$inp + + cmp \$64*4,$len + jb .Less_than_64_8xvl + vpxor 0x00($inp),$xc1,$xc1 + vpxor 0x20($inp),$xd1,$xd1 + vmovdqu $xc1,0x00($out,$inp) + vmovdqu $xd1,0x20($out,$inp) + je .Ldone8xvl + vmovdqa32 $xa2,$xa0 + vmovdqa $xb2,$xb0 + lea 64($inp),$inp + + cmp \$64*5,$len + jb .Less_than_64_8xvl + vpxord 0x00($inp),$xa2,$xa2 + vpxor 0x20($inp),$xb2,$xb2 + vmovdqu32 $xa2,0x00($out,$inp) + vmovdqu $xb2,0x20($out,$inp) + je .Ldone8xvl + vmovdqa $xc2,$xa0 + vmovdqa $xd2,$xb0 + lea 64($inp),$inp + + cmp \$64*6,$len + jb .Less_than_64_8xvl + vpxor 0x00($inp),$xc2,$xc2 + vpxor 0x20($inp),$xd2,$xd2 + vmovdqu $xc2,0x00($out,$inp) + vmovdqu $xd2,0x20($out,$inp) + je .Ldone8xvl + vmovdqa $xa3,$xa0 + vmovdqa $xb3,$xb0 + lea 64($inp),$inp + + cmp \$64*7,$len + jb .Less_than_64_8xvl + vpxor 0x00($inp),$xa3,$xa3 + vpxor 0x20($inp),$xb3,$xb3 + vmovdqu $xa3,0x00($out,$inp) + vmovdqu $xb3,0x20($out,$inp) + je .Ldone8xvl + vmovdqa $xc3,$xa0 + vmovdqa $xd3,$xb0 + lea 64($inp),$inp + +.Less_than_64_8xvl: + vmovdqa $xa0,0x00(%rsp) + vmovdqa $xb0,0x20(%rsp) + lea ($out,$inp),$out + and \$63,$len + +.Loop_tail8xvl: + movzb ($inp,%r10),%eax + movzb (%rsp,%r10),%ecx + lea 1(%r10),%r10 + xor %ecx,%eax + mov %al,-1($out,%r10) + dec $len + jnz .Loop_tail8xvl + + vpxor $xa0,$xa0,$xa0 + vmovdqa $xa0,0x00(%rsp) + vmovdqa $xa0,0x20(%rsp) + +.Ldone8xvl: + vzeroall +___ +$code.=<<___ if ($win64); + movaps -0xa8(%r9),%xmm6 + movaps -0x98(%r9),%xmm7 + movaps -0x88(%r9),%xmm8 + movaps -0x78(%r9),%xmm9 + movaps -0x68(%r9),%xmm10 + movaps -0x58(%r9),%xmm11 + movaps -0x48(%r9),%xmm12 + movaps -0x38(%r9),%xmm13 + movaps -0x28(%r9),%xmm14 + movaps -0x18(%r9),%xmm15 +___ +$code.=<<___; + lea (%r9),%rsp +.cfi_def_cfa_register %rsp +.L8xvl_epilogue: + ret +.cfi_endproc +.size ChaCha20_8xvl,.-ChaCha20_8xvl +___ +} + +# EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame, +# CONTEXT *context,DISPATCHER_CONTEXT *disp) +if ($win64) { +$rec="%rcx"; +$frame="%rdx"; +$context="%r8"; +$disp="%r9"; + +$code.=<<___; +.extern __imp_RtlVirtualUnwind +.type se_handler,\@abi-omnipotent +.align 16 +se_handler: + push %rsi + push %rdi + push %rbx + push %rbp + push %r12 + push %r13 + push %r14 + push %r15 + pushfq + sub \$64,%rsp + + mov 120($context),%rax # pull context->Rax + mov 248($context),%rbx # pull context->Rip + + mov 8($disp),%rsi # disp->ImageBase + mov 56($disp),%r11 # disp->HandlerData + + lea .Lctr32_body(%rip),%r10 + cmp %r10,%rbx # context->Rip<.Lprologue + jb .Lcommon_seh_tail + + mov 152($context),%rax # pull context->Rsp + + lea .Lno_data(%rip),%r10 # epilogue label + cmp %r10,%rbx # context->Rip>=.Lepilogue + jae .Lcommon_seh_tail + + lea 64+24+48(%rax),%rax + + mov -8(%rax),%rbx + mov -16(%rax),%rbp + mov -24(%rax),%r12 + mov -32(%rax),%r13 + mov -40(%rax),%r14 + mov -48(%rax),%r15 + mov %rbx,144($context) # restore context->Rbx + mov %rbp,160($context) # restore context->Rbp + mov %r12,216($context) # restore context->R12 + mov %r13,224($context) # restore context->R13 + mov %r14,232($context) # restore context->R14 + mov %r15,240($context) # restore context->R14 + +.Lcommon_seh_tail: + mov 8(%rax),%rdi + mov 16(%rax),%rsi + mov %rax,152($context) # restore context->Rsp + mov %rsi,168($context) # restore context->Rsi + mov %rdi,176($context) # restore context->Rdi + + mov 40($disp),%rdi # disp->ContextRecord + mov $context,%rsi # context + mov \$154,%ecx # sizeof(CONTEXT) + .long 0xa548f3fc # cld; rep movsq + + mov $disp,%rsi + xor %rcx,%rcx # arg1, UNW_FLAG_NHANDLER + mov 8(%rsi),%rdx # arg2, disp->ImageBase + mov 0(%rsi),%r8 # arg3, disp->ControlPc + mov 16(%rsi),%r9 # arg4, disp->FunctionEntry + mov 40(%rsi),%r10 # disp->ContextRecord + lea 56(%rsi),%r11 # &disp->HandlerData + lea 24(%rsi),%r12 # &disp->EstablisherFrame + mov %r10,32(%rsp) # arg5 + mov %r11,40(%rsp) # arg6 + mov %r12,48(%rsp) # arg7 + mov %rcx,56(%rsp) # arg8, (NULL) + call *__imp_RtlVirtualUnwind(%rip) + + mov \$1,%eax # ExceptionContinueSearch + add \$64,%rsp + popfq + pop %r15 + pop %r14 + pop %r13 + pop %r12 + pop %rbp + pop %rbx + pop %rdi + pop %rsi + ret +.size se_handler,.-se_handler + +.type ssse3_handler,\@abi-omnipotent +.align 16 +ssse3_handler: + push %rsi + push %rdi + push %rbx + push %rbp + push %r12 + push %r13 + push %r14 + push %r15 + pushfq + sub \$64,%rsp + + mov 120($context),%rax # pull context->Rax + mov 248($context),%rbx # pull context->Rip + + mov 8($disp),%rsi # disp->ImageBase + mov 56($disp),%r11 # disp->HandlerData + + mov 0(%r11),%r10d # HandlerData[0] + lea (%rsi,%r10),%r10 # prologue label + cmp %r10,%rbx # context->RipR9 + + mov 4(%r11),%r10d # HandlerData[1] + lea (%rsi,%r10),%r10 # epilogue label + cmp %r10,%rbx # context->Rip>=epilogue label + jae .Lcommon_seh_tail + + lea -0x28(%rax),%rsi + lea 512($context),%rdi # &context.Xmm6 + mov \$4,%ecx + .long 0xa548f3fc # cld; rep movsq + + jmp .Lcommon_seh_tail +.size ssse3_handler,.-ssse3_handler + +.type full_handler,\@abi-omnipotent +.align 16 +full_handler: + push %rsi + push %rdi + push %rbx + push %rbp + push %r12 + push %r13 + push %r14 + push %r15 + pushfq + sub \$64,%rsp + + mov 120($context),%rax # pull context->Rax + mov 248($context),%rbx # pull context->Rip + + mov 8($disp),%rsi # disp->ImageBase + mov 56($disp),%r11 # disp->HandlerData + + mov 0(%r11),%r10d # HandlerData[0] + lea (%rsi,%r10),%r10 # prologue label + cmp %r10,%rbx # context->RipR9 + + mov 4(%r11),%r10d # HandlerData[1] + lea (%rsi,%r10),%r10 # epilogue label + cmp %r10,%rbx # context->Rip>=epilogue label + jae .Lcommon_seh_tail + + lea -0xa8(%rax),%rsi + lea 512($context),%rdi # &context.Xmm6 + mov \$20,%ecx + .long 0xa548f3fc # cld; rep movsq + + jmp .Lcommon_seh_tail +.size full_handler,.-full_handler + +.section .pdata +.align 4 + .rva .LSEH_begin_ChaCha20_ctr32 + .rva .LSEH_end_ChaCha20_ctr32 + .rva .LSEH_info_ChaCha20_ctr32 + + .rva .LSEH_begin_ChaCha20_ssse3 + .rva .LSEH_end_ChaCha20_ssse3 + .rva .LSEH_info_ChaCha20_ssse3 + + .rva .LSEH_begin_ChaCha20_4x + .rva .LSEH_end_ChaCha20_4x + .rva .LSEH_info_ChaCha20_4x +___ +$code.=<<___ if ($avx); + .rva .LSEH_begin_ChaCha20_4xop + .rva .LSEH_end_ChaCha20_4xop + .rva .LSEH_info_ChaCha20_4xop +___ +$code.=<<___ if ($avx>1); + .rva .LSEH_begin_ChaCha20_8x + .rva .LSEH_end_ChaCha20_8x + .rva .LSEH_info_ChaCha20_8x +___ +$code.=<<___ if ($avx>2); + .rva .LSEH_begin_ChaCha20_avx512 + .rva .LSEH_end_ChaCha20_avx512 + .rva .LSEH_info_ChaCha20_avx512 + + .rva .LSEH_begin_ChaCha20_avx512vl + .rva .LSEH_end_ChaCha20_avx512vl + .rva .LSEH_info_ChaCha20_avx512vl + + .rva .LSEH_begin_ChaCha20_16x + .rva .LSEH_end_ChaCha20_16x + .rva .LSEH_info_ChaCha20_16x + + .rva .LSEH_begin_ChaCha20_8xvl + .rva .LSEH_end_ChaCha20_8xvl + .rva .LSEH_info_ChaCha20_8xvl +___ +$code.=<<___; +.section .xdata +.align 8 +.LSEH_info_ChaCha20_ctr32: + .byte 9,0,0,0 + .rva se_handler + +.LSEH_info_ChaCha20_ssse3: + .byte 9,0,0,0 + .rva ssse3_handler + .rva .Lssse3_body,.Lssse3_epilogue + +.LSEH_info_ChaCha20_4x: + .byte 9,0,0,0 + .rva full_handler + .rva .L4x_body,.L4x_epilogue +___ +$code.=<<___ if ($avx); +.LSEH_info_ChaCha20_4xop: + .byte 9,0,0,0 + .rva full_handler + .rva .L4xop_body,.L4xop_epilogue # HandlerData[] +___ +$code.=<<___ if ($avx>1); +.LSEH_info_ChaCha20_8x: + .byte 9,0,0,0 + .rva full_handler + .rva .L8x_body,.L8x_epilogue # HandlerData[] +___ +$code.=<<___ if ($avx>2); +.LSEH_info_ChaCha20_avx512: + .byte 9,0,0,0 + .rva ssse3_handler + .rva .Lavx512_body,.Lavx512_epilogue # HandlerData[] + +.LSEH_info_ChaCha20_avx512vl: + .byte 9,0,0,0 + .rva ssse3_handler + .rva .Lavx512vl_body,.Lavx512vl_epilogue # HandlerData[] + +.LSEH_info_ChaCha20_16x: + .byte 9,0,0,0 + .rva full_handler + .rva .L16x_body,.L16x_epilogue # HandlerData[] + +.LSEH_info_ChaCha20_8xvl: + .byte 9,0,0,0 + .rva full_handler + .rva .L8xvl_body,.L8xvl_epilogue # HandlerData[] +___ +} + +foreach (split("\n",$code)) { + s/\`([^\`]*)\`/eval $1/ge; + + s/%x#%[yz]/%x/g; # "down-shift" print $_,"\n"; } diff --git a/crypto/chacha/build.info b/crypto/chacha/build.info index f99114c1..02f8e518 100644 --- a/crypto/chacha/build.info +++ b/crypto/chacha/build.info @@ -1,7 +1,8 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]={- $target{chacha_asm_src} -} -GENERATE[chacha-x86.s]=asm/chacha-x86.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[chacha-x86.s]=asm/chacha-x86.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) GENERATE[chacha-x86_64.s]=asm/chacha-x86_64.pl $(PERLASM_SCHEME) GENERATE[chacha-ppc.s]=asm/chacha-ppc.pl $(PERLASM_SCHEME) GENERATE[chacha-armv4.S]=asm/chacha-armv4.pl $(PERLASM_SCHEME) diff --git a/crypto/cms/cms_asn1.c b/crypto/cms/cms_asn1.c index 0a594f41..993ea6b2 100644 --- a/crypto/cms/cms_asn1.c +++ b/crypto/cms/cms_asn1.c @@ -56,7 +56,7 @@ static int cms_si_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, } ASN1_SEQUENCE_cb(CMS_SignerInfo, cms_si_cb) = { - ASN1_SIMPLE(CMS_SignerInfo, version, LONG), + ASN1_EMBED(CMS_SignerInfo, version, INT32), ASN1_SIMPLE(CMS_SignerInfo, sid, CMS_SignerIdentifier), ASN1_SIMPLE(CMS_SignerInfo, digestAlgorithm, X509_ALGOR), ASN1_IMP_SET_OF_OPT(CMS_SignerInfo, signedAttrs, X509_ATTRIBUTE, 0), @@ -76,7 +76,7 @@ ASN1_CHOICE(CMS_RevocationInfoChoice) = { } ASN1_CHOICE_END(CMS_RevocationInfoChoice) ASN1_NDEF_SEQUENCE(CMS_SignedData) = { - ASN1_SIMPLE(CMS_SignedData, version, LONG), + ASN1_EMBED(CMS_SignedData, version, INT32), ASN1_SET_OF(CMS_SignedData, digestAlgorithms, X509_ALGOR), ASN1_SIMPLE(CMS_SignedData, encapContentInfo, CMS_EncapsulatedContentInfo), ASN1_IMP_SET_OF_OPT(CMS_SignedData, certificates, CMS_CertificateChoices, 0), @@ -96,7 +96,7 @@ ASN1_NDEF_SEQUENCE(CMS_EncryptedContentInfo) = { } static_ASN1_NDEF_SEQUENCE_END(CMS_EncryptedContentInfo) ASN1_SEQUENCE(CMS_KeyTransRecipientInfo) = { - ASN1_SIMPLE(CMS_KeyTransRecipientInfo, version, LONG), + ASN1_EMBED(CMS_KeyTransRecipientInfo, version, INT32), ASN1_SIMPLE(CMS_KeyTransRecipientInfo, rid, CMS_SignerIdentifier), ASN1_SIMPLE(CMS_KeyTransRecipientInfo, keyEncryptionAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_KeyTransRecipientInfo, encryptedKey, ASN1_OCTET_STRING) @@ -162,7 +162,7 @@ static int cms_kari_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, } ASN1_SEQUENCE_cb(CMS_KeyAgreeRecipientInfo, cms_kari_cb) = { - ASN1_SIMPLE(CMS_KeyAgreeRecipientInfo, version, LONG), + ASN1_EMBED(CMS_KeyAgreeRecipientInfo, version, INT32), ASN1_EXP(CMS_KeyAgreeRecipientInfo, originator, CMS_OriginatorIdentifierOrKey, 0), ASN1_EXP_OPT(CMS_KeyAgreeRecipientInfo, ukm, ASN1_OCTET_STRING, 1), ASN1_SIMPLE(CMS_KeyAgreeRecipientInfo, keyEncryptionAlgorithm, X509_ALGOR), @@ -176,14 +176,14 @@ ASN1_SEQUENCE(CMS_KEKIdentifier) = { } static_ASN1_SEQUENCE_END(CMS_KEKIdentifier) ASN1_SEQUENCE(CMS_KEKRecipientInfo) = { - ASN1_SIMPLE(CMS_KEKRecipientInfo, version, LONG), + ASN1_EMBED(CMS_KEKRecipientInfo, version, INT32), ASN1_SIMPLE(CMS_KEKRecipientInfo, kekid, CMS_KEKIdentifier), ASN1_SIMPLE(CMS_KEKRecipientInfo, keyEncryptionAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_KEKRecipientInfo, encryptedKey, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(CMS_KEKRecipientInfo) ASN1_SEQUENCE(CMS_PasswordRecipientInfo) = { - ASN1_SIMPLE(CMS_PasswordRecipientInfo, version, LONG), + ASN1_EMBED(CMS_PasswordRecipientInfo, version, INT32), ASN1_IMP_OPT(CMS_PasswordRecipientInfo, keyDerivationAlgorithm, X509_ALGOR, 0), ASN1_SIMPLE(CMS_PasswordRecipientInfo, keyEncryptionAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_PasswordRecipientInfo, encryptedKey, ASN1_OCTET_STRING) @@ -225,7 +225,7 @@ ASN1_CHOICE_cb(CMS_RecipientInfo, cms_ri_cb) = { } ASN1_CHOICE_END_cb(CMS_RecipientInfo, CMS_RecipientInfo, type) ASN1_NDEF_SEQUENCE(CMS_EnvelopedData) = { - ASN1_SIMPLE(CMS_EnvelopedData, version, LONG), + ASN1_EMBED(CMS_EnvelopedData, version, INT32), ASN1_IMP_OPT(CMS_EnvelopedData, originatorInfo, CMS_OriginatorInfo, 0), ASN1_SET_OF(CMS_EnvelopedData, recipientInfos, CMS_RecipientInfo), ASN1_SIMPLE(CMS_EnvelopedData, encryptedContentInfo, CMS_EncryptedContentInfo), @@ -233,20 +233,20 @@ ASN1_NDEF_SEQUENCE(CMS_EnvelopedData) = { } ASN1_NDEF_SEQUENCE_END(CMS_EnvelopedData) ASN1_NDEF_SEQUENCE(CMS_DigestedData) = { - ASN1_SIMPLE(CMS_DigestedData, version, LONG), + ASN1_EMBED(CMS_DigestedData, version, INT32), ASN1_SIMPLE(CMS_DigestedData, digestAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_DigestedData, encapContentInfo, CMS_EncapsulatedContentInfo), ASN1_SIMPLE(CMS_DigestedData, digest, ASN1_OCTET_STRING) } ASN1_NDEF_SEQUENCE_END(CMS_DigestedData) ASN1_NDEF_SEQUENCE(CMS_EncryptedData) = { - ASN1_SIMPLE(CMS_EncryptedData, version, LONG), + ASN1_EMBED(CMS_EncryptedData, version, INT32), ASN1_SIMPLE(CMS_EncryptedData, encryptedContentInfo, CMS_EncryptedContentInfo), ASN1_IMP_SET_OF_OPT(CMS_EncryptedData, unprotectedAttrs, X509_ATTRIBUTE, 1) } ASN1_NDEF_SEQUENCE_END(CMS_EncryptedData) ASN1_NDEF_SEQUENCE(CMS_AuthenticatedData) = { - ASN1_SIMPLE(CMS_AuthenticatedData, version, LONG), + ASN1_EMBED(CMS_AuthenticatedData, version, INT32), ASN1_IMP_OPT(CMS_AuthenticatedData, originatorInfo, CMS_OriginatorInfo, 0), ASN1_SET_OF(CMS_AuthenticatedData, recipientInfos, CMS_RecipientInfo), ASN1_SIMPLE(CMS_AuthenticatedData, macAlgorithm, X509_ALGOR), @@ -258,7 +258,7 @@ ASN1_NDEF_SEQUENCE(CMS_AuthenticatedData) = { } static_ASN1_NDEF_SEQUENCE_END(CMS_AuthenticatedData) ASN1_NDEF_SEQUENCE(CMS_CompressedData) = { - ASN1_SIMPLE(CMS_CompressedData, version, LONG), + ASN1_EMBED(CMS_CompressedData, version, INT32), ASN1_SIMPLE(CMS_CompressedData, compressionAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_CompressedData, encapContentInfo, CMS_EncapsulatedContentInfo), } ASN1_NDEF_SEQUENCE_END(CMS_CompressedData) @@ -338,7 +338,7 @@ ASN1_ITEM_TEMPLATE_END(CMS_Attributes_Verify) ASN1_CHOICE(CMS_ReceiptsFrom) = { - ASN1_IMP(CMS_ReceiptsFrom, d.allOrFirstTier, LONG, 0), + ASN1_IMP_EMBED(CMS_ReceiptsFrom, d.allOrFirstTier, INT32, 0), ASN1_IMP_SEQUENCE_OF(CMS_ReceiptsFrom, d.receiptList, GENERAL_NAMES, 1) } static_ASN1_CHOICE_END(CMS_ReceiptsFrom) @@ -349,7 +349,7 @@ ASN1_SEQUENCE(CMS_ReceiptRequest) = { } ASN1_SEQUENCE_END(CMS_ReceiptRequest) ASN1_SEQUENCE(CMS_Receipt) = { - ASN1_SIMPLE(CMS_Receipt, version, LONG), + ASN1_EMBED(CMS_Receipt, version, INT32), ASN1_SIMPLE(CMS_Receipt, contentType, ASN1_OBJECT), ASN1_SIMPLE(CMS_Receipt, signedContentIdentifier, ASN1_OCTET_STRING), ASN1_SIMPLE(CMS_Receipt, originatorSignatureValue, ASN1_OCTET_STRING) diff --git a/crypto/cms/cms_env.c b/crypto/cms/cms_env.c index 8d459435..6ca3be71 100644 --- a/crypto/cms/cms_env.c +++ b/crypto/cms/cms_env.c @@ -749,7 +749,7 @@ int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) default: CMSerr(CMS_F_CMS_RECIPIENTINFO_DECRYPT, - CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE); + CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE); return 0; } } diff --git a/crypto/cms/cms_err.c b/crypto/cms/cms_err.c index c6df1b5a..43a48b62 100644 --- a/crypto/cms/cms_err.c +++ b/crypto/cms/cms_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,238 +8,272 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_CMS,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_CMS,0,reason) - -static ERR_STRING_DATA CMS_str_functs[] = { - {ERR_FUNC(CMS_F_CHECK_CONTENT), "check_content"}, - {ERR_FUNC(CMS_F_CMS_ADD0_CERT), "CMS_add0_cert"}, - {ERR_FUNC(CMS_F_CMS_ADD0_RECIPIENT_KEY), "CMS_add0_recipient_key"}, - {ERR_FUNC(CMS_F_CMS_ADD0_RECIPIENT_PASSWORD), +static const ERR_STRING_DATA CMS_str_functs[] = { + {ERR_PACK(ERR_LIB_CMS, CMS_F_CHECK_CONTENT, 0), "check_content"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD0_CERT, 0), "CMS_add0_cert"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD0_RECIPIENT_KEY, 0), + "CMS_add0_recipient_key"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD0_RECIPIENT_PASSWORD, 0), "CMS_add0_recipient_password"}, - {ERR_FUNC(CMS_F_CMS_ADD1_RECEIPTREQUEST), "CMS_add1_ReceiptRequest"}, - {ERR_FUNC(CMS_F_CMS_ADD1_RECIPIENT_CERT), "CMS_add1_recipient_cert"}, - {ERR_FUNC(CMS_F_CMS_ADD1_SIGNER), "CMS_add1_signer"}, - {ERR_FUNC(CMS_F_CMS_ADD1_SIGNINGTIME), "cms_add1_signingTime"}, - {ERR_FUNC(CMS_F_CMS_COMPRESS), "CMS_compress"}, - {ERR_FUNC(CMS_F_CMS_COMPRESSEDDATA_CREATE), "cms_CompressedData_create"}, - {ERR_FUNC(CMS_F_CMS_COMPRESSEDDATA_INIT_BIO), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD1_RECEIPTREQUEST, 0), + "CMS_add1_ReceiptRequest"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD1_RECIPIENT_CERT, 0), + "CMS_add1_recipient_cert"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD1_SIGNER, 0), "CMS_add1_signer"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ADD1_SIGNINGTIME, 0), + "cms_add1_signingTime"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_COMPRESS, 0), "CMS_compress"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_COMPRESSEDDATA_CREATE, 0), + "cms_CompressedData_create"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_COMPRESSEDDATA_INIT_BIO, 0), "cms_CompressedData_init_bio"}, - {ERR_FUNC(CMS_F_CMS_COPY_CONTENT), "cms_copy_content"}, - {ERR_FUNC(CMS_F_CMS_COPY_MESSAGEDIGEST), "cms_copy_messageDigest"}, - {ERR_FUNC(CMS_F_CMS_DATA), "CMS_data"}, - {ERR_FUNC(CMS_F_CMS_DATAFINAL), "CMS_dataFinal"}, - {ERR_FUNC(CMS_F_CMS_DATAINIT), "CMS_dataInit"}, - {ERR_FUNC(CMS_F_CMS_DECRYPT), "CMS_decrypt"}, - {ERR_FUNC(CMS_F_CMS_DECRYPT_SET1_KEY), "CMS_decrypt_set1_key"}, - {ERR_FUNC(CMS_F_CMS_DECRYPT_SET1_PASSWORD), "CMS_decrypt_set1_password"}, - {ERR_FUNC(CMS_F_CMS_DECRYPT_SET1_PKEY), "CMS_decrypt_set1_pkey"}, - {ERR_FUNC(CMS_F_CMS_DIGESTALGORITHM_FIND_CTX), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_COPY_CONTENT, 0), "cms_copy_content"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_COPY_MESSAGEDIGEST, 0), + "cms_copy_messageDigest"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DATA, 0), "CMS_data"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DATAFINAL, 0), "CMS_dataFinal"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DATAINIT, 0), "CMS_dataInit"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DECRYPT, 0), "CMS_decrypt"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DECRYPT_SET1_KEY, 0), + "CMS_decrypt_set1_key"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DECRYPT_SET1_PASSWORD, 0), + "CMS_decrypt_set1_password"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DECRYPT_SET1_PKEY, 0), + "CMS_decrypt_set1_pkey"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DIGESTALGORITHM_FIND_CTX, 0), "cms_DigestAlgorithm_find_ctx"}, - {ERR_FUNC(CMS_F_CMS_DIGESTALGORITHM_INIT_BIO), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DIGESTALGORITHM_INIT_BIO, 0), "cms_DigestAlgorithm_init_bio"}, - {ERR_FUNC(CMS_F_CMS_DIGESTEDDATA_DO_FINAL), "cms_DigestedData_do_final"}, - {ERR_FUNC(CMS_F_CMS_DIGEST_VERIFY), "CMS_digest_verify"}, - {ERR_FUNC(CMS_F_CMS_ENCODE_RECEIPT), "cms_encode_Receipt"}, - {ERR_FUNC(CMS_F_CMS_ENCRYPT), "CMS_encrypt"}, - {ERR_FUNC(CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DIGESTEDDATA_DO_FINAL, 0), + "cms_DigestedData_do_final"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_DIGEST_VERIFY, 0), "CMS_digest_verify"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCODE_RECEIPT, 0), "cms_encode_Receipt"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPT, 0), "CMS_encrypt"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO, 0), "cms_EncryptedContent_init_bio"}, - {ERR_FUNC(CMS_F_CMS_ENCRYPTEDDATA_DECRYPT), "CMS_EncryptedData_decrypt"}, - {ERR_FUNC(CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT), "CMS_EncryptedData_encrypt"}, - {ERR_FUNC(CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPTEDDATA_DECRYPT, 0), + "CMS_EncryptedData_decrypt"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT, 0), + "CMS_EncryptedData_encrypt"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY, 0), "CMS_EncryptedData_set1_key"}, - {ERR_FUNC(CMS_F_CMS_ENVELOPEDDATA_CREATE), "CMS_EnvelopedData_create"}, - {ERR_FUNC(CMS_F_CMS_ENVELOPEDDATA_INIT_BIO), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENVELOPEDDATA_CREATE, 0), + "CMS_EnvelopedData_create"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENVELOPEDDATA_INIT_BIO, 0), "cms_EnvelopedData_init_bio"}, - {ERR_FUNC(CMS_F_CMS_ENVELOPED_DATA_INIT), "cms_enveloped_data_init"}, - {ERR_FUNC(CMS_F_CMS_ENV_ASN1_CTRL), "cms_env_asn1_ctrl"}, - {ERR_FUNC(CMS_F_CMS_FINAL), "CMS_final"}, - {ERR_FUNC(CMS_F_CMS_GET0_CERTIFICATE_CHOICES), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENVELOPED_DATA_INIT, 0), + "cms_enveloped_data_init"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_ENV_ASN1_CTRL, 0), "cms_env_asn1_ctrl"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_FINAL, 0), "CMS_final"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_CERTIFICATE_CHOICES, 0), "cms_get0_certificate_choices"}, - {ERR_FUNC(CMS_F_CMS_GET0_CONTENT), "CMS_get0_content"}, - {ERR_FUNC(CMS_F_CMS_GET0_ECONTENT_TYPE), "cms_get0_econtent_type"}, - {ERR_FUNC(CMS_F_CMS_GET0_ENVELOPED), "cms_get0_enveloped"}, - {ERR_FUNC(CMS_F_CMS_GET0_REVOCATION_CHOICES), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_CONTENT, 0), "CMS_get0_content"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_ECONTENT_TYPE, 0), + "cms_get0_econtent_type"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_ENVELOPED, 0), "cms_get0_enveloped"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_REVOCATION_CHOICES, 0), "cms_get0_revocation_choices"}, - {ERR_FUNC(CMS_F_CMS_GET0_SIGNED), "cms_get0_signed"}, - {ERR_FUNC(CMS_F_CMS_MSGSIGDIGEST_ADD1), "cms_msgSigDigest_add1"}, - {ERR_FUNC(CMS_F_CMS_RECEIPTREQUEST_CREATE0), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_GET0_SIGNED, 0), "cms_get0_signed"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_MSGSIGDIGEST_ADD1, 0), + "cms_msgSigDigest_add1"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECEIPTREQUEST_CREATE0, 0), "CMS_ReceiptRequest_create0"}, - {ERR_FUNC(CMS_F_CMS_RECEIPT_VERIFY), "cms_Receipt_verify"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_DECRYPT), "CMS_RecipientInfo_decrypt"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_ENCRYPT), "CMS_RecipientInfo_encrypt"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECEIPT_VERIFY, 0), "cms_Receipt_verify"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_DECRYPT, 0), + "CMS_RecipientInfo_decrypt"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_ENCRYPT, 0), + "CMS_RecipientInfo_encrypt"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT, 0), "cms_RecipientInfo_kari_encrypt"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG, 0), "CMS_RecipientInfo_kari_get0_alg"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID, 0), "CMS_RecipientInfo_kari_get0_orig_id"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS, 0), "CMS_RecipientInfo_kari_get0_reks"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP, 0), "CMS_RecipientInfo_kari_orig_id_cmp"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT, 0), "cms_RecipientInfo_kekri_decrypt"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT, 0), "cms_RecipientInfo_kekri_encrypt"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID, 0), "CMS_RecipientInfo_kekri_get0_id"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP, 0), "CMS_RecipientInfo_kekri_id_cmp"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP, 0), "CMS_RecipientInfo_ktri_cert_cmp"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, 0), "cms_RecipientInfo_ktri_decrypt"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT, 0), "cms_RecipientInfo_ktri_encrypt"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS, 0), "CMS_RecipientInfo_ktri_get0_algs"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID, 0), "CMS_RecipientInfo_ktri_get0_signer_id"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT, 0), "cms_RecipientInfo_pwri_crypt"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_SET0_KEY), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_SET0_KEY, 0), "CMS_RecipientInfo_set0_key"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD, 0), "CMS_RecipientInfo_set0_password"}, - {ERR_FUNC(CMS_F_CMS_RECIPIENTINFO_SET0_PKEY), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_RECIPIENTINFO_SET0_PKEY, 0), "CMS_RecipientInfo_set0_pkey"}, - {ERR_FUNC(CMS_F_CMS_SD_ASN1_CTRL), "cms_sd_asn1_ctrl"}, - {ERR_FUNC(CMS_F_CMS_SET1_IAS), "cms_set1_ias"}, - {ERR_FUNC(CMS_F_CMS_SET1_KEYID), "cms_set1_keyid"}, - {ERR_FUNC(CMS_F_CMS_SET1_SIGNERIDENTIFIER), "cms_set1_SignerIdentifier"}, - {ERR_FUNC(CMS_F_CMS_SET_DETACHED), "CMS_set_detached"}, - {ERR_FUNC(CMS_F_CMS_SIGN), "CMS_sign"}, - {ERR_FUNC(CMS_F_CMS_SIGNED_DATA_INIT), "cms_signed_data_init"}, - {ERR_FUNC(CMS_F_CMS_SIGNERINFO_CONTENT_SIGN), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SD_ASN1_CTRL, 0), "cms_sd_asn1_ctrl"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SET1_IAS, 0), "cms_set1_ias"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SET1_KEYID, 0), "cms_set1_keyid"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SET1_SIGNERIDENTIFIER, 0), + "cms_set1_SignerIdentifier"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SET_DETACHED, 0), "CMS_set_detached"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGN, 0), "CMS_sign"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNED_DATA_INIT, 0), + "cms_signed_data_init"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNERINFO_CONTENT_SIGN, 0), "cms_SignerInfo_content_sign"}, - {ERR_FUNC(CMS_F_CMS_SIGNERINFO_SIGN), "CMS_SignerInfo_sign"}, - {ERR_FUNC(CMS_F_CMS_SIGNERINFO_VERIFY), "CMS_SignerInfo_verify"}, - {ERR_FUNC(CMS_F_CMS_SIGNERINFO_VERIFY_CERT), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNERINFO_SIGN, 0), + "CMS_SignerInfo_sign"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNERINFO_VERIFY, 0), + "CMS_SignerInfo_verify"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNERINFO_VERIFY_CERT, 0), "cms_signerinfo_verify_cert"}, - {ERR_FUNC(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT), + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT, 0), "CMS_SignerInfo_verify_content"}, - {ERR_FUNC(CMS_F_CMS_SIGN_RECEIPT), "CMS_sign_receipt"}, - {ERR_FUNC(CMS_F_CMS_STREAM), "CMS_stream"}, - {ERR_FUNC(CMS_F_CMS_UNCOMPRESS), "CMS_uncompress"}, - {ERR_FUNC(CMS_F_CMS_VERIFY), "CMS_verify"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_SIGN_RECEIPT, 0), "CMS_sign_receipt"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_STREAM, 0), "CMS_stream"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_UNCOMPRESS, 0), "CMS_uncompress"}, + {ERR_PACK(ERR_LIB_CMS, CMS_F_CMS_VERIFY, 0), "CMS_verify"}, {0, NULL} }; -static ERR_STRING_DATA CMS_str_reasons[] = { - {ERR_REASON(CMS_R_ADD_SIGNER_ERROR), "add signer error"}, - {ERR_REASON(CMS_R_CERTIFICATE_ALREADY_PRESENT), - "certificate already present"}, - {ERR_REASON(CMS_R_CERTIFICATE_HAS_NO_KEYID), "certificate has no keyid"}, - {ERR_REASON(CMS_R_CERTIFICATE_VERIFY_ERROR), "certificate verify error"}, - {ERR_REASON(CMS_R_CIPHER_INITIALISATION_ERROR), - "cipher initialisation error"}, - {ERR_REASON(CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR), - "cipher parameter initialisation error"}, - {ERR_REASON(CMS_R_CMS_DATAFINAL_ERROR), "cms datafinal error"}, - {ERR_REASON(CMS_R_CMS_LIB), "cms lib"}, - {ERR_REASON(CMS_R_CONTENTIDENTIFIER_MISMATCH), - "contentidentifier mismatch"}, - {ERR_REASON(CMS_R_CONTENT_NOT_FOUND), "content not found"}, - {ERR_REASON(CMS_R_CONTENT_TYPE_MISMATCH), "content type mismatch"}, - {ERR_REASON(CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA), - "content type not compressed data"}, - {ERR_REASON(CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA), - "content type not enveloped data"}, - {ERR_REASON(CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA), - "content type not signed data"}, - {ERR_REASON(CMS_R_CONTENT_VERIFY_ERROR), "content verify error"}, - {ERR_REASON(CMS_R_CTRL_ERROR), "ctrl error"}, - {ERR_REASON(CMS_R_CTRL_FAILURE), "ctrl failure"}, - {ERR_REASON(CMS_R_DECRYPT_ERROR), "decrypt error"}, - {ERR_REASON(CMS_R_ERROR_GETTING_PUBLIC_KEY), "error getting public key"}, - {ERR_REASON(CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE), - "error reading messagedigest attribute"}, - {ERR_REASON(CMS_R_ERROR_SETTING_KEY), "error setting key"}, - {ERR_REASON(CMS_R_ERROR_SETTING_RECIPIENTINFO), - "error setting recipientinfo"}, - {ERR_REASON(CMS_R_INVALID_ENCRYPTED_KEY_LENGTH), - "invalid encrypted key length"}, - {ERR_REASON(CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER), - "invalid key encryption parameter"}, - {ERR_REASON(CMS_R_INVALID_KEY_LENGTH), "invalid key length"}, - {ERR_REASON(CMS_R_MD_BIO_INIT_ERROR), "md bio init error"}, - {ERR_REASON(CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH), - "messagedigest attribute wrong length"}, - {ERR_REASON(CMS_R_MESSAGEDIGEST_WRONG_LENGTH), - "messagedigest wrong length"}, - {ERR_REASON(CMS_R_MSGSIGDIGEST_ERROR), "msgsigdigest error"}, - {ERR_REASON(CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE), - "msgsigdigest verification failure"}, - {ERR_REASON(CMS_R_MSGSIGDIGEST_WRONG_LENGTH), - "msgsigdigest wrong length"}, - {ERR_REASON(CMS_R_NEED_ONE_SIGNER), "need one signer"}, - {ERR_REASON(CMS_R_NOT_A_SIGNED_RECEIPT), "not a signed receipt"}, - {ERR_REASON(CMS_R_NOT_ENCRYPTED_DATA), "not encrypted data"}, - {ERR_REASON(CMS_R_NOT_KEK), "not kek"}, - {ERR_REASON(CMS_R_NOT_KEY_AGREEMENT), "not key agreement"}, - {ERR_REASON(CMS_R_NOT_KEY_TRANSPORT), "not key transport"}, - {ERR_REASON(CMS_R_NOT_PWRI), "not pwri"}, - {ERR_REASON(CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE), - "not supported for this key type"}, - {ERR_REASON(CMS_R_NO_CIPHER), "no cipher"}, - {ERR_REASON(CMS_R_NO_CONTENT), "no content"}, - {ERR_REASON(CMS_R_NO_CONTENT_TYPE), "no content type"}, - {ERR_REASON(CMS_R_NO_DEFAULT_DIGEST), "no default digest"}, - {ERR_REASON(CMS_R_NO_DIGEST_SET), "no digest set"}, - {ERR_REASON(CMS_R_NO_KEY), "no key"}, - {ERR_REASON(CMS_R_NO_KEY_OR_CERT), "no key or cert"}, - {ERR_REASON(CMS_R_NO_MATCHING_DIGEST), "no matching digest"}, - {ERR_REASON(CMS_R_NO_MATCHING_RECIPIENT), "no matching recipient"}, - {ERR_REASON(CMS_R_NO_MATCHING_SIGNATURE), "no matching signature"}, - {ERR_REASON(CMS_R_NO_MSGSIGDIGEST), "no msgsigdigest"}, - {ERR_REASON(CMS_R_NO_PASSWORD), "no password"}, - {ERR_REASON(CMS_R_NO_PRIVATE_KEY), "no private key"}, - {ERR_REASON(CMS_R_NO_PUBLIC_KEY), "no public key"}, - {ERR_REASON(CMS_R_NO_RECEIPT_REQUEST), "no receipt request"}, - {ERR_REASON(CMS_R_NO_SIGNERS), "no signers"}, - {ERR_REASON(CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), - "private key does not match certificate"}, - {ERR_REASON(CMS_R_RECEIPT_DECODE_ERROR), "receipt decode error"}, - {ERR_REASON(CMS_R_RECIPIENT_ERROR), "recipient error"}, - {ERR_REASON(CMS_R_SIGNER_CERTIFICATE_NOT_FOUND), - "signer certificate not found"}, - {ERR_REASON(CMS_R_SIGNFINAL_ERROR), "signfinal error"}, - {ERR_REASON(CMS_R_SMIME_TEXT_ERROR), "smime text error"}, - {ERR_REASON(CMS_R_STORE_INIT_ERROR), "store init error"}, - {ERR_REASON(CMS_R_TYPE_NOT_COMPRESSED_DATA), "type not compressed data"}, - {ERR_REASON(CMS_R_TYPE_NOT_DATA), "type not data"}, - {ERR_REASON(CMS_R_TYPE_NOT_DIGESTED_DATA), "type not digested data"}, - {ERR_REASON(CMS_R_TYPE_NOT_ENCRYPTED_DATA), "type not encrypted data"}, - {ERR_REASON(CMS_R_TYPE_NOT_ENVELOPED_DATA), "type not enveloped data"}, - {ERR_REASON(CMS_R_UNABLE_TO_FINALIZE_CONTEXT), - "unable to finalize context"}, - {ERR_REASON(CMS_R_UNKNOWN_CIPHER), "unknown cipher"}, - {ERR_REASON(CMS_R_UNKNOWN_DIGEST_ALGORIHM), "unknown digest algorihm"}, - {ERR_REASON(CMS_R_UNKNOWN_ID), "unknown id"}, - {ERR_REASON(CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM), - "unsupported compression algorithm"}, - {ERR_REASON(CMS_R_UNSUPPORTED_CONTENT_TYPE), "unsupported content type"}, - {ERR_REASON(CMS_R_UNSUPPORTED_KEK_ALGORITHM), - "unsupported kek algorithm"}, - {ERR_REASON(CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM), - "unsupported key encryption algorithm"}, - {ERR_REASON(CMS_R_UNSUPPORTED_RECIPIENT_TYPE), - "unsupported recipient type"}, - {ERR_REASON(CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE), - "unsupported recpientinfo type"}, - {ERR_REASON(CMS_R_UNSUPPORTED_TYPE), "unsupported type"}, - {ERR_REASON(CMS_R_UNWRAP_ERROR), "unwrap error"}, - {ERR_REASON(CMS_R_UNWRAP_FAILURE), "unwrap failure"}, - {ERR_REASON(CMS_R_VERIFICATION_FAILURE), "verification failure"}, - {ERR_REASON(CMS_R_WRAP_ERROR), "wrap error"}, +static const ERR_STRING_DATA CMS_str_reasons[] = { + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ADD_SIGNER_ERROR), "add signer error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_ALREADY_PRESENT), + "certificate already present"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_HAS_NO_KEYID), + "certificate has no keyid"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_VERIFY_ERROR), + "certificate verify error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_INITIALISATION_ERROR), + "cipher initialisation error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR), + "cipher parameter initialisation error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CMS_DATAFINAL_ERROR), + "cms datafinal error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CMS_LIB), "cms lib"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENTIDENTIFIER_MISMATCH), + "contentidentifier mismatch"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_NOT_FOUND), "content not found"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_MISMATCH), + "content type mismatch"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA), + "content type not compressed data"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA), + "content type not enveloped data"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA), + "content type not signed data"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_VERIFY_ERROR), + "content verify error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CTRL_ERROR), "ctrl error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CTRL_FAILURE), "ctrl failure"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_DECRYPT_ERROR), "decrypt error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_GETTING_PUBLIC_KEY), + "error getting public key"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE), + "error reading messagedigest attribute"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_SETTING_KEY), "error setting key"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_SETTING_RECIPIENTINFO), + "error setting recipientinfo"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_ENCRYPTED_KEY_LENGTH), + "invalid encrypted key length"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER), + "invalid key encryption parameter"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_KEY_LENGTH), "invalid key length"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MD_BIO_INIT_ERROR), "md bio init error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH), + "messagedigest attribute wrong length"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MESSAGEDIGEST_WRONG_LENGTH), + "messagedigest wrong length"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_ERROR), "msgsigdigest error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE), + "msgsigdigest verification failure"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_WRONG_LENGTH), + "msgsigdigest wrong length"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NEED_ONE_SIGNER), "need one signer"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_A_SIGNED_RECEIPT), + "not a signed receipt"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_ENCRYPTED_DATA), "not encrypted data"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEK), "not kek"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEY_AGREEMENT), "not key agreement"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEY_TRANSPORT), "not key transport"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_PWRI), "not pwri"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE), + "not supported for this key type"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CIPHER), "no cipher"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CONTENT), "no content"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CONTENT_TYPE), "no content type"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_DEFAULT_DIGEST), "no default digest"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_DIGEST_SET), "no digest set"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_KEY), "no key"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_KEY_OR_CERT), "no key or cert"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_DIGEST), "no matching digest"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_RECIPIENT), + "no matching recipient"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_SIGNATURE), + "no matching signature"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MSGSIGDIGEST), "no msgsigdigest"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PASSWORD), "no password"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PRIVATE_KEY), "no private key"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PUBLIC_KEY), "no public key"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_RECEIPT_REQUEST), "no receipt request"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_SIGNERS), "no signers"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), + "private key does not match certificate"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_RECEIPT_DECODE_ERROR), + "receipt decode error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_RECIPIENT_ERROR), "recipient error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SIGNER_CERTIFICATE_NOT_FOUND), + "signer certificate not found"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SIGNFINAL_ERROR), "signfinal error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SMIME_TEXT_ERROR), "smime text error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_STORE_INIT_ERROR), "store init error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_COMPRESSED_DATA), + "type not compressed data"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_DATA), "type not data"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_DIGESTED_DATA), + "type not digested data"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_ENCRYPTED_DATA), + "type not encrypted data"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_ENVELOPED_DATA), + "type not enveloped data"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNABLE_TO_FINALIZE_CONTEXT), + "unable to finalize context"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_CIPHER), "unknown cipher"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_DIGEST_ALGORITHM), + "unknown digest algorithm"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_ID), "unknown id"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM), + "unsupported compression algorithm"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_CONTENT_TYPE), + "unsupported content type"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_KEK_ALGORITHM), + "unsupported kek algorithm"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM), + "unsupported key encryption algorithm"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE), + "unsupported recipientinfo type"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_RECIPIENT_TYPE), + "unsupported recipient type"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_TYPE), "unsupported type"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNWRAP_ERROR), "unwrap error"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNWRAP_FAILURE), "unwrap failure"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_VERIFICATION_FAILURE), + "verification failure"}, + {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_WRAP_ERROR), "wrap error"}, {0, NULL} }; @@ -248,10 +282,9 @@ static ERR_STRING_DATA CMS_str_reasons[] = { int ERR_load_CMS_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(CMS_str_functs[0].error) == NULL) { - ERR_load_strings(0, CMS_str_functs); - ERR_load_strings(0, CMS_str_reasons); + ERR_load_strings_const(CMS_str_functs); + ERR_load_strings_const(CMS_str_reasons); } #endif return 1; diff --git a/crypto/cms/cms_lcl.h b/crypto/cms/cms_lcl.h index d0c0e813..c277f713 100644 --- a/crypto/cms/cms_lcl.h +++ b/crypto/cms/cms_lcl.h @@ -67,7 +67,7 @@ struct CMS_ContentInfo_st { DEFINE_STACK_OF(CMS_CertificateChoices) struct CMS_SignedData_st { - long version; + int32_t version; STACK_OF(X509_ALGOR) *digestAlgorithms; CMS_EncapsulatedContentInfo *encapContentInfo; STACK_OF(CMS_CertificateChoices) *certificates; @@ -83,7 +83,7 @@ struct CMS_EncapsulatedContentInfo_st { }; struct CMS_SignerInfo_st { - long version; + int32_t version; CMS_SignerIdentifier *sid; X509_ALGOR *digestAlgorithm; STACK_OF(X509_ATTRIBUTE) *signedAttrs; @@ -107,7 +107,7 @@ struct CMS_SignerIdentifier_st { }; struct CMS_EnvelopedData_st { - long version; + int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncryptedContentInfo *encryptedContentInfo; @@ -145,7 +145,7 @@ struct CMS_RecipientInfo_st { typedef CMS_SignerIdentifier CMS_RecipientIdentifier; struct CMS_KeyTransRecipientInfo_st { - long version; + int32_t version; CMS_RecipientIdentifier *rid; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; @@ -157,7 +157,7 @@ struct CMS_KeyTransRecipientInfo_st { }; struct CMS_KeyAgreeRecipientInfo_st { - long version; + int32_t version; CMS_OriginatorIdentifierOrKey *originator; ASN1_OCTET_STRING *ukm; X509_ALGOR *keyEncryptionAlgorithm; @@ -204,7 +204,7 @@ struct CMS_RecipientKeyIdentifier_st { }; struct CMS_KEKRecipientInfo_st { - long version; + int32_t version; CMS_KEKIdentifier *kekid; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; @@ -220,7 +220,7 @@ struct CMS_KEKIdentifier_st { }; struct CMS_PasswordRecipientInfo_st { - long version; + int32_t version; X509_ALGOR *keyDerivationAlgorithm; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; @@ -235,20 +235,20 @@ struct CMS_OtherRecipientInfo_st { }; struct CMS_DigestedData_st { - long version; + int32_t version; X509_ALGOR *digestAlgorithm; CMS_EncapsulatedContentInfo *encapContentInfo; ASN1_OCTET_STRING *digest; }; struct CMS_EncryptedData_st { - long version; + int32_t version; CMS_EncryptedContentInfo *encryptedContentInfo; STACK_OF(X509_ATTRIBUTE) *unprotectedAttrs; }; struct CMS_AuthenticatedData_st { - long version; + int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; X509_ALGOR *macAlgorithm; @@ -260,7 +260,7 @@ struct CMS_AuthenticatedData_st { }; struct CMS_CompressedData_st { - long version; + int32_t version; X509_ALGOR *compressionAlgorithm; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncapsulatedContentInfo *encapContentInfo; @@ -332,14 +332,14 @@ struct CMS_ReceiptRequest_st { struct CMS_ReceiptsFrom_st { int type; union { - long allOrFirstTier; + int32_t allOrFirstTier; STACK_OF(GENERAL_NAMES) *receiptList; } d; }; # endif struct CMS_Receipt_st { - long version; + int32_t version; ASN1_OBJECT *contentType; ASN1_OCTET_STRING *signedContentIdentifier; ASN1_OCTET_STRING *originatorSignatureValue; diff --git a/crypto/cms/cms_lib.c b/crypto/cms/cms_lib.c index 7395684b..c2cac260 100644 --- a/crypto/cms/cms_lib.c +++ b/crypto/cms/cms_lib.c @@ -292,7 +292,7 @@ BIO *cms_DigestAlgorithm_init_bio(X509_ALGOR *digestAlgorithm) digest = EVP_get_digestbyobj(digestoid); if (!digest) { CMSerr(CMS_F_CMS_DIGESTALGORITHM_INIT_BIO, - CMS_R_UNKNOWN_DIGEST_ALGORIHM); + CMS_R_UNKNOWN_DIGEST_ALGORITHM); goto err; } mdbio = BIO_new(BIO_f_md()); diff --git a/crypto/cms/cms_sd.c b/crypto/cms/cms_sd.c index 4108fe70..ff2d540b 100644 --- a/crypto/cms/cms_sd.c +++ b/crypto/cms/cms_sd.c @@ -635,7 +635,7 @@ int cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain) int CMS_SignerInfo_sign(CMS_SignerInfo *si) { EVP_MD_CTX *mctx = si->mctx; - EVP_PKEY_CTX *pctx; + EVP_PKEY_CTX *pctx = NULL; unsigned char *abuf = NULL; int alen; size_t siglen; @@ -656,6 +656,7 @@ int CMS_SignerInfo_sign(CMS_SignerInfo *si) EVP_MD_CTX_reset(mctx); if (EVP_DigestSignInit(mctx, &pctx, md, NULL, si->pkey) <= 0) goto err; + si->pctx = pctx; } if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN, diff --git a/crypto/comp/c_zlib.c b/crypto/comp/c_zlib.c index 821dc099..d688deee 100644 --- a/crypto/comp/c_zlib.c +++ b/crypto/comp/c_zlib.c @@ -256,14 +256,13 @@ COMP_METHOD *COMP_zlib(void) meth = &zlib_stateful_method; #endif - return (meth); + return meth; } void comp_zlib_cleanup_int(void) { #ifdef ZLIB_SHARED - if (zlib_dso != NULL) - DSO_free(zlib_dso); + DSO_free(zlib_dso); zlib_dso = NULL; #endif } @@ -297,7 +296,11 @@ static long bio_zlib_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp); static const BIO_METHOD bio_meth_zlib = { BIO_TYPE_COMP, "zlib", + /* TODO: Convert to new style write function */ + bwrite_conv, bio_zlib_write, + /* TODO: Convert to new style read function */ + bread_conv, bio_zlib_read, NULL, /* bio_zlib_puts, */ NULL, /* bio_zlib_gets, */ diff --git a/crypto/comp/comp_err.c b/crypto/comp/comp_err.c index 8e2e6956..5aff502b 100644 --- a/crypto/comp/comp_err.c +++ b/crypto/comp/comp_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,28 +8,26 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_COMP,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_COMP,0,reason) - -static ERR_STRING_DATA COMP_str_functs[] = { - {ERR_FUNC(COMP_F_BIO_ZLIB_FLUSH), "bio_zlib_flush"}, - {ERR_FUNC(COMP_F_BIO_ZLIB_NEW), "bio_zlib_new"}, - {ERR_FUNC(COMP_F_BIO_ZLIB_READ), "bio_zlib_read"}, - {ERR_FUNC(COMP_F_BIO_ZLIB_WRITE), "bio_zlib_write"}, +static const ERR_STRING_DATA COMP_str_functs[] = { + {ERR_PACK(ERR_LIB_COMP, COMP_F_BIO_ZLIB_FLUSH, 0), "bio_zlib_flush"}, + {ERR_PACK(ERR_LIB_COMP, COMP_F_BIO_ZLIB_NEW, 0), "bio_zlib_new"}, + {ERR_PACK(ERR_LIB_COMP, COMP_F_BIO_ZLIB_READ, 0), "bio_zlib_read"}, + {ERR_PACK(ERR_LIB_COMP, COMP_F_BIO_ZLIB_WRITE, 0), "bio_zlib_write"}, {0, NULL} }; -static ERR_STRING_DATA COMP_str_reasons[] = { - {ERR_REASON(COMP_R_ZLIB_DEFLATE_ERROR), "zlib deflate error"}, - {ERR_REASON(COMP_R_ZLIB_INFLATE_ERROR), "zlib inflate error"}, - {ERR_REASON(COMP_R_ZLIB_NOT_SUPPORTED), "zlib not supported"}, +static const ERR_STRING_DATA COMP_str_reasons[] = { + {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZLIB_DEFLATE_ERROR), + "zlib deflate error"}, + {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZLIB_INFLATE_ERROR), + "zlib inflate error"}, + {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZLIB_NOT_SUPPORTED), + "zlib not supported"}, {0, NULL} }; @@ -38,10 +36,9 @@ static ERR_STRING_DATA COMP_str_reasons[] = { int ERR_load_COMP_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(COMP_str_functs[0].error) == NULL) { - ERR_load_strings(0, COMP_str_functs); - ERR_load_strings(0, COMP_str_reasons); + ERR_load_strings_const(COMP_str_functs); + ERR_load_strings_const(COMP_str_reasons); } #endif return 1; diff --git a/crypto/comp/comp_lib.c b/crypto/comp/comp_lib.c index 32afd0db..137a5db7 100644 --- a/crypto/comp/comp_lib.c +++ b/crypto/comp/comp_lib.c @@ -19,13 +19,13 @@ COMP_CTX *COMP_CTX_new(COMP_METHOD *meth) COMP_CTX *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) - return (NULL); + return NULL; ret->meth = meth; if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { OPENSSL_free(ret); ret = NULL; } - return (ret); + return ret; } const COMP_METHOD *COMP_CTX_get_method(const COMP_CTX *ctx) @@ -59,14 +59,14 @@ int COMP_compress_block(COMP_CTX *ctx, unsigned char *out, int olen, { int ret; if (ctx->meth->compress == NULL) { - return (-1); + return -1; } ret = ctx->meth->compress(ctx, out, olen, in, ilen); if (ret > 0) { ctx->compress_in += ilen; ctx->compress_out += ret; } - return (ret); + return ret; } int COMP_expand_block(COMP_CTX *ctx, unsigned char *out, int olen, @@ -75,14 +75,14 @@ int COMP_expand_block(COMP_CTX *ctx, unsigned char *out, int olen, int ret; if (ctx->meth->expand == NULL) { - return (-1); + return -1; } ret = ctx->meth->expand(ctx, out, olen, in, ilen); if (ret > 0) { ctx->expand_in += ilen; ctx->expand_out += ret; } - return (ret); + return ret; } int COMP_CTX_get_type(const COMP_CTX* comp) diff --git a/crypto/conf/conf_api.c b/crypto/conf/conf_api.c index 5535416a..ade54839 100644 --- a/crypto/conf/conf_api.c +++ b/crypto/conf/conf_api.c @@ -9,11 +9,11 @@ /* Part of the code in here was originally in conf.c, which is now removed */ +#include "e_os.h" #include #include #include #include -#include "e_os.h" static void value_free_hash(const CONF_VALUE *a, LHASH_OF(CONF_VALUE) *conf); static void value_free_stack_doall(CONF_VALUE *a); @@ -24,11 +24,11 @@ CONF_VALUE *_CONF_get_section(const CONF *conf, const char *section) CONF_VALUE *v, vv; if ((conf == NULL) || (section == NULL)) - return (NULL); + return NULL; vv.name = NULL; vv.section = (char *)section; v = lh_CONF_VALUE_retrieve(conf->data, &vv); - return (v); + return v; } /* Up until OpenSSL 0.9.5a, this was CONF_get_section */ @@ -41,7 +41,7 @@ STACK_OF(CONF_VALUE) *_CONF_get_section_values(const CONF *conf, if (v != NULL) return ((STACK_OF(CONF_VALUE) *)v->value); else - return (NULL); + return NULL; } int _CONF_add_string(CONF *conf, CONF_VALUE *section, CONF_VALUE *value) @@ -73,29 +73,29 @@ char *_CONF_get_string(const CONF *conf, const char *section, char *p; if (name == NULL) - return (NULL); + return NULL; if (conf != NULL) { if (section != NULL) { vv.name = (char *)name; vv.section = (char *)section; v = lh_CONF_VALUE_retrieve(conf->data, &vv); if (v != NULL) - return (v->value); + return v->value; if (strcmp(section, "ENV") == 0) { p = getenv(name); if (p != NULL) - return (p); + return p; } } vv.section = "default"; vv.name = (char *)name; v = lh_CONF_VALUE_retrieve(conf->data, &vv); if (v != NULL) - return (v->value); + return v->value; else - return (NULL); + return NULL; } else - return (getenv(name)); + return getenv(name); } static unsigned long conf_value_hash(const CONF_VALUE *v) @@ -110,14 +110,14 @@ static int conf_value_cmp(const CONF_VALUE *a, const CONF_VALUE *b) if (a->section != b->section) { i = strcmp(a->section, b->section); if (i) - return (i); + return i; } if ((a->name != NULL) && (b->name != NULL)) { i = strcmp(a->name, b->name); - return (i); + return i; } else if (a->name == b->name) - return (0); + return 0; else return ((a->name == NULL) ? -1 : 1); } @@ -204,7 +204,8 @@ CONF_VALUE *_CONF_new_section(CONF *conf, const char *section) v->value = (char *)sk; vv = lh_CONF_VALUE_insert(conf->data, v); - OPENSSL_assert(vv == NULL); + if (vv != NULL) + goto err; return v; err: diff --git a/crypto/conf/conf_def.c b/crypto/conf/conf_def.c index b443903f..82e191ae 100644 --- a/crypto/conf/conf_def.c +++ b/crypto/conf/conf_def.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -12,7 +12,6 @@ #include #include #include "internal/cryptlib.h" -#include #include #include #include @@ -317,13 +316,12 @@ static int def_load_bio(CONF *conf, BIO *in, long *line) } if (psection == NULL) psection = section; - v->name = OPENSSL_malloc(strlen(pname) + 1); + v->name = OPENSSL_strdup(pname); v->value = NULL; if (v->name == NULL) { CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE); goto err; } - OPENSSL_strlcpy(v->name, pname, strlen(pname) + 1); if (!str_copy(conf, psection, &(v->value), start)) goto err; @@ -347,7 +345,7 @@ static int def_load_bio(CONF *conf, BIO *in, long *line) } BUF_MEM_free(buff); OPENSSL_free(section); - return (1); + return 1; err: BUF_MEM_free(buff); OPENSSL_free(section); @@ -364,7 +362,7 @@ static int def_load_bio(CONF *conf, BIO *in, long *line) OPENSSL_free(v->value); OPENSSL_free(v); } - return (0); + return 0; } static void clear_comments(CONF *conf, char *p) @@ -411,7 +409,7 @@ static int str_copy(CONF *conf, char *section, char **pto, char *from) BUF_MEM *buf; if ((buf = BUF_MEM_new()) == NULL) - return (0); + return 0; len = strlen(from) + 1; if (!BUF_MEM_grow(buf, len)) @@ -551,17 +549,17 @@ static int str_copy(CONF *conf, char *section, char **pto, char *from) OPENSSL_free(*pto); *pto = buf->data; OPENSSL_free(buf); - return (1); + return 1; err: BUF_MEM_free(buf); - return (0); + return 0; } static char *eat_ws(CONF *conf, char *p) { while (IS_WS(conf, *p) && (!IS_EOF(conf, *p))) p++; - return (p); + return p; } static char *eat_alpha_numeric(CONF *conf, char *p) @@ -572,7 +570,7 @@ static char *eat_alpha_numeric(CONF *conf, char *p) continue; } if (!IS_ALPHA_NUMERIC_PUNCT(conf, *p)) - return (p); + return p; p++; } } @@ -586,13 +584,13 @@ static char *scan_quote(CONF *conf, char *p) if (IS_ESC(conf, *p)) { p++; if (IS_EOF(conf, *p)) - return (p); + return p; } p++; } if (*p == q) p++; - return (p); + return p; } static char *scan_dquote(CONF *conf, char *p) @@ -612,7 +610,7 @@ static char *scan_dquote(CONF *conf, char *p) } if (*p == q) p++; - return (p); + return p; } static void dump_value_doall_arg(const CONF_VALUE *a, BIO *out) diff --git a/crypto/conf/conf_def.h b/crypto/conf/conf_def.h index da4767e1..ad8894c4 100644 --- a/crypto/conf/conf_def.h +++ b/crypto/conf/conf_def.h @@ -2,7 +2,7 @@ * WARNING: do not edit! * Generated by crypto/conf/keysets.pl * - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 diff --git a/crypto/conf/conf_err.c b/crypto/conf/conf_err.c index 0863bc4d..8ba243ca 100644 --- a/crypto/conf/conf_err.c +++ b/crypto/conf/conf_err.c @@ -8,61 +8,62 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_CONF,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_CONF,0,reason) - -static ERR_STRING_DATA CONF_str_functs[] = { - {ERR_FUNC(CONF_F_CONF_DUMP_FP), "CONF_dump_fp"}, - {ERR_FUNC(CONF_F_CONF_LOAD), "CONF_load"}, - {ERR_FUNC(CONF_F_CONF_LOAD_FP), "CONF_load_fp"}, - {ERR_FUNC(CONF_F_CONF_PARSE_LIST), "CONF_parse_list"}, - {ERR_FUNC(CONF_F_DEF_LOAD), "def_load"}, - {ERR_FUNC(CONF_F_DEF_LOAD_BIO), "def_load_bio"}, - {ERR_FUNC(CONF_F_MODULE_INIT), "module_init"}, - {ERR_FUNC(CONF_F_MODULE_LOAD_DSO), "module_load_dso"}, - {ERR_FUNC(CONF_F_MODULE_RUN), "module_run"}, - {ERR_FUNC(CONF_F_NCONF_DUMP_BIO), "NCONF_dump_bio"}, - {ERR_FUNC(CONF_F_NCONF_DUMP_FP), "NCONF_dump_fp"}, - {ERR_FUNC(CONF_F_NCONF_GET_NUMBER_E), "NCONF_get_number_e"}, - {ERR_FUNC(CONF_F_NCONF_GET_SECTION), "NCONF_get_section"}, - {ERR_FUNC(CONF_F_NCONF_GET_STRING), "NCONF_get_string"}, - {ERR_FUNC(CONF_F_NCONF_LOAD), "NCONF_load"}, - {ERR_FUNC(CONF_F_NCONF_LOAD_BIO), "NCONF_load_bio"}, - {ERR_FUNC(CONF_F_NCONF_LOAD_FP), "NCONF_load_fp"}, - {ERR_FUNC(CONF_F_NCONF_NEW), "NCONF_new"}, - {ERR_FUNC(CONF_F_STR_COPY), "str_copy"}, +static const ERR_STRING_DATA CONF_str_functs[] = { + {ERR_PACK(ERR_LIB_CONF, CONF_F_CONF_DUMP_FP, 0), "CONF_dump_fp"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_CONF_LOAD, 0), "CONF_load"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_CONF_LOAD_FP, 0), "CONF_load_fp"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_CONF_PARSE_LIST, 0), "CONF_parse_list"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_DEF_LOAD, 0), "def_load"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_DEF_LOAD_BIO, 0), "def_load_bio"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_MODULE_INIT, 0), "module_init"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_MODULE_LOAD_DSO, 0), "module_load_dso"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_MODULE_RUN, 0), "module_run"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_NCONF_DUMP_BIO, 0), "NCONF_dump_bio"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_NCONF_DUMP_FP, 0), "NCONF_dump_fp"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_NCONF_GET_NUMBER_E, 0), + "NCONF_get_number_e"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_NCONF_GET_SECTION, 0), "NCONF_get_section"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_NCONF_GET_STRING, 0), "NCONF_get_string"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_NCONF_LOAD, 0), "NCONF_load"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_NCONF_LOAD_BIO, 0), "NCONF_load_bio"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_NCONF_LOAD_FP, 0), "NCONF_load_fp"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_NCONF_NEW, 0), "NCONF_new"}, + {ERR_PACK(ERR_LIB_CONF, CONF_F_STR_COPY, 0), "str_copy"}, {0, NULL} }; -static ERR_STRING_DATA CONF_str_reasons[] = { - {ERR_REASON(CONF_R_ERROR_LOADING_DSO), "error loading dso"}, - {ERR_REASON(CONF_R_LIST_CANNOT_BE_NULL), "list cannot be null"}, - {ERR_REASON(CONF_R_MISSING_CLOSE_SQUARE_BRACKET), - "missing close square bracket"}, - {ERR_REASON(CONF_R_MISSING_EQUAL_SIGN), "missing equal sign"}, - {ERR_REASON(CONF_R_MISSING_INIT_FUNCTION), "missing init function"}, - {ERR_REASON(CONF_R_MODULE_INITIALIZATION_ERROR), - "module initialization error"}, - {ERR_REASON(CONF_R_NO_CLOSE_BRACE), "no close brace"}, - {ERR_REASON(CONF_R_NO_CONF), "no conf"}, - {ERR_REASON(CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE), - "no conf or environment variable"}, - {ERR_REASON(CONF_R_NO_SECTION), "no section"}, - {ERR_REASON(CONF_R_NO_SUCH_FILE), "no such file"}, - {ERR_REASON(CONF_R_NO_VALUE), "no value"}, - {ERR_REASON(CONF_R_UNABLE_TO_CREATE_NEW_SECTION), - "unable to create new section"}, - {ERR_REASON(CONF_R_UNKNOWN_MODULE_NAME), "unknown module name"}, - {ERR_REASON(CONF_R_VARIABLE_EXPANSION_TOO_LONG), - "variable expansion too long"}, - {ERR_REASON(CONF_R_VARIABLE_HAS_NO_VALUE), "variable has no value"}, +static const ERR_STRING_DATA CONF_str_reasons[] = { + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_ERROR_LOADING_DSO), "error loading dso"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_LIST_CANNOT_BE_NULL), + "list cannot be null"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_MISSING_CLOSE_SQUARE_BRACKET), + "missing close square bracket"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_MISSING_EQUAL_SIGN), + "missing equal sign"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_MISSING_INIT_FUNCTION), + "missing init function"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_MODULE_INITIALIZATION_ERROR), + "module initialization error"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_CLOSE_BRACE), "no close brace"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_CONF), "no conf"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE), + "no conf or environment variable"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_SECTION), "no section"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_SUCH_FILE), "no such file"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_VALUE), "no value"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_UNABLE_TO_CREATE_NEW_SECTION), + "unable to create new section"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_UNKNOWN_MODULE_NAME), + "unknown module name"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_VARIABLE_EXPANSION_TOO_LONG), + "variable expansion too long"}, + {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_VARIABLE_HAS_NO_VALUE), + "variable has no value"}, {0, NULL} }; @@ -71,10 +72,9 @@ static ERR_STRING_DATA CONF_str_reasons[] = { int ERR_load_CONF_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(CONF_str_functs[0].error) == NULL) { - ERR_load_strings(0, CONF_str_functs); - ERR_load_strings(0, CONF_str_reasons); + ERR_load_strings_const(CONF_str_functs); + ERR_load_strings_const(CONF_str_reasons); } #endif return 1; diff --git a/crypto/conf/conf_lib.c b/crypto/conf/conf_lib.c index 35321149..c72511ba 100644 --- a/crypto/conf/conf_lib.c +++ b/crypto/conf/conf_lib.c @@ -7,15 +7,15 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" #include #include -#include +#include "internal/conf.h" #include #include #include #include #include -#include "e_os.h" static CONF_METHOD *default_CONF_method = NULL; @@ -186,7 +186,7 @@ CONF *NCONF_new(CONF_METHOD *meth) ret = meth->create(meth); if (ret == NULL) { CONFerr(CONF_F_NCONF_NEW, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } return ret; diff --git a/crypto/conf/conf_mod.c b/crypto/conf/conf_mod.c index 543a8ea4..7622d8e1 100644 --- a/crypto/conf/conf_mod.c +++ b/crypto/conf/conf_mod.c @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2002-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 @@ -7,10 +7,10 @@ * https://www.openssl.org/source/license.html */ +#include "internal/cryptlib.h" #include #include #include -#include "internal/cryptlib.h" #include "internal/conf.h" #include "internal/dso.h" #include @@ -170,6 +170,7 @@ static int module_run(const CONF *cnf, const char *name, const char *value, 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); ERR_add_error_data(6, "module=", name, ", value=", value, @@ -475,7 +476,7 @@ void CONF_module_set_usr_data(CONF_MODULE *pmod, void *usr_data) char *CONF_get1_default_config_file(void) { - char *file; + char *file, *sep = ""; int len; file = getenv("OPENSSL_CONF"); @@ -485,6 +486,7 @@ char *CONF_get1_default_config_file(void) len = strlen(X509_get_default_cert_area()); #ifndef OPENSSL_SYS_VMS len++; + sep = "/"; #endif len += strlen(OPENSSL_CONF); @@ -492,11 +494,8 @@ char *CONF_get1_default_config_file(void) if (file == NULL) return NULL; - OPENSSL_strlcpy(file, X509_get_default_cert_area(), len + 1); -#ifndef OPENSSL_SYS_VMS - OPENSSL_strlcat(file, "/", len + 1); -#endif - OPENSSL_strlcat(file, OPENSSL_CONF, len + 1); + BIO_snprintf(file, len + 1, "%s%s%s", X509_get_default_cert_area(), + sep, OPENSSL_CONF); return file; } diff --git a/crypto/conf/conf_sap.c b/crypto/conf/conf_sap.c index bed95abe..3d2e065e 100644 --- a/crypto/conf/conf_sap.c +++ b/crypto/conf/conf_sap.c @@ -10,11 +10,15 @@ #include #include #include "internal/cryptlib.h" -#include +#include "internal/conf.h" #include #include #include +#ifdef _WIN32 +# define strdup _strdup +#endif + /* * This is the automatic configuration loader: it is called automatically by * OpenSSL when any of a number of standard initialisation functions are diff --git a/crypto/conf/keysets.pl b/crypto/conf/keysets.pl index 5af08ae2..a6d25788 100644 --- a/crypto/conf/keysets.pl +++ b/crypto/conf/keysets.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 1995-2018 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 @@ -57,12 +57,14 @@ foreach (0 .. 255) push(@V_w32,$v); } +# Output year depends on the year of the script. +my $YEAR = [localtime([stat($0)]->[9])]->[5] + 1900; print <<"EOF"; /* * WARNING: do not edit! * Generated by crypto/conf/keysets.pl * - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-$YEAR 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 diff --git a/crypto/cpt_err.c b/crypto/cpt_err.c index c28dcf19..d4d2878e 100644 --- a/crypto/cpt_err.c +++ b/crypto/cpt_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,35 +8,41 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_CRYPTO,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_CRYPTO,0,reason) - -static ERR_STRING_DATA CRYPTO_str_functs[] = { - {ERR_FUNC(CRYPTO_F_CRYPTO_DUP_EX_DATA), "CRYPTO_dup_ex_data"}, - {ERR_FUNC(CRYPTO_F_CRYPTO_FREE_EX_DATA), "CRYPTO_free_ex_data"}, - {ERR_FUNC(CRYPTO_F_CRYPTO_GET_EX_NEW_INDEX), "CRYPTO_get_ex_new_index"}, - {ERR_FUNC(CRYPTO_F_CRYPTO_MEMDUP), "CRYPTO_memdup"}, - {ERR_FUNC(CRYPTO_F_CRYPTO_NEW_EX_DATA), "CRYPTO_new_ex_data"}, - {ERR_FUNC(CRYPTO_F_CRYPTO_SET_EX_DATA), "CRYPTO_set_ex_data"}, - {ERR_FUNC(CRYPTO_F_FIPS_MODE_SET), "FIPS_mode_set"}, - {ERR_FUNC(CRYPTO_F_GET_AND_LOCK), "get_and_lock"}, - {ERR_FUNC(CRYPTO_F_OPENSSL_BUF2HEXSTR), "OPENSSL_buf2hexstr"}, - {ERR_FUNC(CRYPTO_F_OPENSSL_HEXSTR2BUF), "OPENSSL_hexstr2buf"}, - {ERR_FUNC(CRYPTO_F_OPENSSL_INIT_CRYPTO), "OPENSSL_init_crypto"}, +static const ERR_STRING_DATA CRYPTO_str_functs[] = { + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_CRYPTO_DUP_EX_DATA, 0), + "CRYPTO_dup_ex_data"}, + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_CRYPTO_FREE_EX_DATA, 0), + "CRYPTO_free_ex_data"}, + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_CRYPTO_GET_EX_NEW_INDEX, 0), + "CRYPTO_get_ex_new_index"}, + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_CRYPTO_MEMDUP, 0), "CRYPTO_memdup"}, + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_CRYPTO_NEW_EX_DATA, 0), + "CRYPTO_new_ex_data"}, + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_CRYPTO_SET_EX_DATA, 0), + "CRYPTO_set_ex_data"}, + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_FIPS_MODE_SET, 0), "FIPS_mode_set"}, + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_GET_AND_LOCK, 0), "get_and_lock"}, + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_OPENSSL_BUF2HEXSTR, 0), + "OPENSSL_buf2hexstr"}, + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_OPENSSL_HEXSTR2BUF, 0), + "OPENSSL_hexstr2buf"}, + {ERR_PACK(ERR_LIB_CRYPTO, CRYPTO_F_OPENSSL_INIT_CRYPTO, 0), + "OPENSSL_init_crypto"}, {0, NULL} }; -static ERR_STRING_DATA CRYPTO_str_reasons[] = { - {ERR_REASON(CRYPTO_R_FIPS_MODE_NOT_SUPPORTED), "fips mode not supported"}, - {ERR_REASON(CRYPTO_R_ILLEGAL_HEX_DIGIT), "illegal hex digit"}, - {ERR_REASON(CRYPTO_R_ODD_NUMBER_OF_DIGITS), "odd number of digits"}, +static const ERR_STRING_DATA CRYPTO_str_reasons[] = { + {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_FIPS_MODE_NOT_SUPPORTED), + "fips mode not supported"}, + {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_ILLEGAL_HEX_DIGIT), + "illegal hex digit"}, + {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_ODD_NUMBER_OF_DIGITS), + "odd number of digits"}, {0, NULL} }; @@ -45,10 +51,9 @@ static ERR_STRING_DATA CRYPTO_str_reasons[] = { int ERR_load_CRYPTO_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(CRYPTO_str_functs[0].error) == NULL) { - ERR_load_strings(0, CRYPTO_str_functs); - ERR_load_strings(0, CRYPTO_str_reasons); + ERR_load_strings_const(CRYPTO_str_functs); + ERR_load_strings_const(CRYPTO_str_reasons); } #endif return 1; diff --git a/crypto/cryptlib.c b/crypto/cryptlib.c index d93bcd35..a4d96d86 100644 --- a/crypto/cryptlib.c +++ b/crypto/cryptlib.c @@ -1,5 +1,6 @@ /* * Copyright 1998-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,12 +8,7 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * ECDH support in OpenSSL originally developed by - * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. - */ - +#include "e_os.h" #include "internal/cryptlib_int.h" #include @@ -65,16 +61,26 @@ void OPENSSL_cpuid_setup(void) } if ((env = strchr(env, ':'))) { - unsigned int vecx; + IA32CAP vecx; env++; off = (env[0] == '~') ? 1 : 0; - vecx = strtoul(env + off, NULL, 0); - if (off) - OPENSSL_ia32cap_P[2] &= ~vecx; - else - OPENSSL_ia32cap_P[2] = vecx; +# if defined(_WIN32) + if (!sscanf(env + off, "%I64i", &vecx)) + vecx = strtoul(env + off, NULL, 0); +# else + if (!sscanf(env + off, "%lli", (long long *)&vecx)) + vecx = strtoul(env + off, NULL, 0); +# endif + if (off) { + OPENSSL_ia32cap_P[2] &= ~(unsigned int)vecx; + OPENSSL_ia32cap_P[3] &= ~(unsigned int)(vecx >> 32); + } else { + OPENSSL_ia32cap_P[2] = (unsigned int)vecx; + OPENSSL_ia32cap_P[3] = (unsigned int)(vecx >> 32); + } } else { OPENSSL_ia32cap_P[2] = 0; + OPENSSL_ia32cap_P[3] = 0; } } else { vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P); @@ -182,7 +188,13 @@ void OPENSSL_showfatal(const char *fmta, ...) va_list ap; TCHAR buf[256]; const TCHAR *fmt; -# ifdef STD_ERROR_HANDLE /* what a dirty trick! */ + /* + * First check if it's a console application, in which case the + * error message would be printed to standard error. + * Windows CE does not have a concept of a console application, + * so we need to guard the check. + */ +# ifdef STD_ERROR_HANDLE HANDLE h; if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL && @@ -322,26 +334,16 @@ void OPENSSL_die(const char *message, const char *file, int line) } #if !defined(OPENSSL_CPUID_OBJ) -/* volatile unsigned char* pointers are there because - * 1. Accessing a variable declared volatile via a pointer - * that lacks a volatile qualifier causes undefined behavior. - * 2. When the variable itself is not volatile the compiler is - * not required to keep all those reads and can convert - * this into canonical memcmp() which doesn't read the whole block. - * Pointers to volatile resolve the first problem fully. The second - * problem cannot be resolved in any Standard-compliant way but this - * works the problem around. Compilers typically react to - * pointers to volatile by preserving the reads and writes through them. - * The latter is not required by the Standard if the memory pointed to - * is not volatile. - * Pointers themselves are volatile in the function signature to work - * around a subtle bug in gcc 4.6+ which causes writes through - * pointers to volatile to not be emitted in some rare, - * never needed in real life, pieces of code. +/* + * The volatile is used to to ensure that the compiler generates code that reads + * all values from the array and doesn't try to optimize this away. The standard + * doesn't actually require this behavior if the original data pointed to is + * not volatile, but compilers do this in practice anyway. + * + * There are also assembler versions of this function. */ -int CRYPTO_memcmp(const volatile void * volatile in_a, - const volatile void * volatile in_b, - size_t len) +# undef CRYPTO_memcmp +int CRYPTO_memcmp(const void * in_a, const void * in_b, size_t len) { size_t i; const volatile unsigned char *a = in_a; @@ -353,4 +355,12 @@ int CRYPTO_memcmp(const volatile void * volatile in_a, return x; } + +/* + * For systems that don't provide an instruction counter register or equivalent. + */ +uint32_t OPENSSL_rdtsc(void) +{ + return 0; +} #endif diff --git a/crypto/ct/ct_b64.c b/crypto/ct/ct_b64.c index f0bf3aff..109ffcdc 100644 --- a/crypto/ct/ct_b64.c +++ b/crypto/ct/ct_b64.c @@ -24,7 +24,7 @@ static int ct_base64_decode(const char *in, unsigned char **out) { size_t inlen = strlen(in); - int outlen; + int outlen, i; unsigned char *outbuf = NULL; if (inlen == 0) { @@ -45,9 +45,12 @@ static int ct_base64_decode(const char *in, unsigned char **out) goto err; } - /* Subtract padding bytes from |outlen| */ + /* Subtract padding bytes from |outlen|. Any more than 2 is malformed. */ + i = 0; while (in[--inlen] == '=') { --outlen; + if (++i > 2) + goto err; } *out = outbuf; @@ -132,7 +135,7 @@ SCT *SCT_new_from_base64(unsigned char version, const char *logid_base64, int CTLOG_new_from_base64(CTLOG **ct_log, const char *pkey_base64, const char *name) { unsigned char *pkey_der = NULL; - int pkey_der_len = ct_base64_decode(pkey_base64, &pkey_der); + int pkey_der_len; const unsigned char *p; EVP_PKEY *pkey = NULL; @@ -141,7 +144,8 @@ int CTLOG_new_from_base64(CTLOG **ct_log, const char *pkey_base64, const char *n return 0; } - if (pkey_der_len <= 0) { + pkey_der_len = ct_base64_decode(pkey_base64, &pkey_der); + if (pkey_der_len < 0) { CTerr(CT_F_CTLOG_NEW_FROM_BASE64, CT_R_LOG_CONF_INVALID_KEY); return 0; } diff --git a/crypto/ct/ct_err.c b/crypto/ct/ct_err.c index fe0778b2..c0c62fee 100644 --- a/crypto/ct/ct_err.c +++ b/crypto/ct/ct_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,67 +8,77 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_CT,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_CT,0,reason) - -static ERR_STRING_DATA CT_str_functs[] = { - {ERR_FUNC(CT_F_CTLOG_NEW), "CTLOG_new"}, - {ERR_FUNC(CT_F_CTLOG_NEW_FROM_BASE64), "CTLOG_new_from_base64"}, - {ERR_FUNC(CT_F_CTLOG_NEW_FROM_CONF), "ctlog_new_from_conf"}, - {ERR_FUNC(CT_F_CTLOG_STORE_LOAD_CTX_NEW), "ctlog_store_load_ctx_new"}, - {ERR_FUNC(CT_F_CTLOG_STORE_LOAD_FILE), "CTLOG_STORE_load_file"}, - {ERR_FUNC(CT_F_CTLOG_STORE_LOAD_LOG), "ctlog_store_load_log"}, - {ERR_FUNC(CT_F_CTLOG_STORE_NEW), "CTLOG_STORE_new"}, - {ERR_FUNC(CT_F_CT_BASE64_DECODE), "ct_base64_decode"}, - {ERR_FUNC(CT_F_CT_POLICY_EVAL_CTX_NEW), "CT_POLICY_EVAL_CTX_new"}, - {ERR_FUNC(CT_F_CT_V1_LOG_ID_FROM_PKEY), "ct_v1_log_id_from_pkey"}, - {ERR_FUNC(CT_F_I2O_SCT), "i2o_SCT"}, - {ERR_FUNC(CT_F_I2O_SCT_LIST), "i2o_SCT_LIST"}, - {ERR_FUNC(CT_F_I2O_SCT_SIGNATURE), "i2o_SCT_signature"}, - {ERR_FUNC(CT_F_O2I_SCT), "o2i_SCT"}, - {ERR_FUNC(CT_F_O2I_SCT_LIST), "o2i_SCT_LIST"}, - {ERR_FUNC(CT_F_O2I_SCT_SIGNATURE), "o2i_SCT_signature"}, - {ERR_FUNC(CT_F_SCT_CTX_NEW), "SCT_CTX_new"}, - {ERR_FUNC(CT_F_SCT_CTX_VERIFY), "SCT_CTX_verify"}, - {ERR_FUNC(CT_F_SCT_NEW), "SCT_new"}, - {ERR_FUNC(CT_F_SCT_NEW_FROM_BASE64), "SCT_new_from_base64"}, - {ERR_FUNC(CT_F_SCT_SET0_LOG_ID), "SCT_set0_log_id"}, - {ERR_FUNC(CT_F_SCT_SET1_EXTENSIONS), "SCT_set1_extensions"}, - {ERR_FUNC(CT_F_SCT_SET1_LOG_ID), "SCT_set1_log_id"}, - {ERR_FUNC(CT_F_SCT_SET1_SIGNATURE), "SCT_set1_signature"}, - {ERR_FUNC(CT_F_SCT_SET_LOG_ENTRY_TYPE), "SCT_set_log_entry_type"}, - {ERR_FUNC(CT_F_SCT_SET_SIGNATURE_NID), "SCT_set_signature_nid"}, - {ERR_FUNC(CT_F_SCT_SET_VERSION), "SCT_set_version"}, +static const ERR_STRING_DATA CT_str_functs[] = { + {ERR_PACK(ERR_LIB_CT, CT_F_CTLOG_NEW, 0), "CTLOG_new"}, + {ERR_PACK(ERR_LIB_CT, CT_F_CTLOG_NEW_FROM_BASE64, 0), + "CTLOG_new_from_base64"}, + {ERR_PACK(ERR_LIB_CT, CT_F_CTLOG_NEW_FROM_CONF, 0), "ctlog_new_from_conf"}, + {ERR_PACK(ERR_LIB_CT, CT_F_CTLOG_STORE_LOAD_CTX_NEW, 0), + "ctlog_store_load_ctx_new"}, + {ERR_PACK(ERR_LIB_CT, CT_F_CTLOG_STORE_LOAD_FILE, 0), + "CTLOG_STORE_load_file"}, + {ERR_PACK(ERR_LIB_CT, CT_F_CTLOG_STORE_LOAD_LOG, 0), + "ctlog_store_load_log"}, + {ERR_PACK(ERR_LIB_CT, CT_F_CTLOG_STORE_NEW, 0), "CTLOG_STORE_new"}, + {ERR_PACK(ERR_LIB_CT, CT_F_CT_BASE64_DECODE, 0), "ct_base64_decode"}, + {ERR_PACK(ERR_LIB_CT, CT_F_CT_POLICY_EVAL_CTX_NEW, 0), + "CT_POLICY_EVAL_CTX_new"}, + {ERR_PACK(ERR_LIB_CT, CT_F_CT_V1_LOG_ID_FROM_PKEY, 0), + "ct_v1_log_id_from_pkey"}, + {ERR_PACK(ERR_LIB_CT, CT_F_I2O_SCT, 0), "i2o_SCT"}, + {ERR_PACK(ERR_LIB_CT, CT_F_I2O_SCT_LIST, 0), "i2o_SCT_LIST"}, + {ERR_PACK(ERR_LIB_CT, CT_F_I2O_SCT_SIGNATURE, 0), "i2o_SCT_signature"}, + {ERR_PACK(ERR_LIB_CT, CT_F_O2I_SCT, 0), "o2i_SCT"}, + {ERR_PACK(ERR_LIB_CT, CT_F_O2I_SCT_LIST, 0), "o2i_SCT_LIST"}, + {ERR_PACK(ERR_LIB_CT, CT_F_O2I_SCT_SIGNATURE, 0), "o2i_SCT_signature"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_CTX_NEW, 0), "SCT_CTX_new"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_CTX_VERIFY, 0), "SCT_CTX_verify"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_NEW, 0), "SCT_new"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_NEW_FROM_BASE64, 0), "SCT_new_from_base64"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_SET0_LOG_ID, 0), "SCT_set0_log_id"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_SET1_EXTENSIONS, 0), "SCT_set1_extensions"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_SET1_LOG_ID, 0), "SCT_set1_log_id"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_SET1_SIGNATURE, 0), "SCT_set1_signature"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_SET_LOG_ENTRY_TYPE, 0), + "SCT_set_log_entry_type"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_SET_SIGNATURE_NID, 0), + "SCT_set_signature_nid"}, + {ERR_PACK(ERR_LIB_CT, CT_F_SCT_SET_VERSION, 0), "SCT_set_version"}, {0, NULL} }; -static ERR_STRING_DATA CT_str_reasons[] = { - {ERR_REASON(CT_R_BASE64_DECODE_ERROR), "base64 decode error"}, - {ERR_REASON(CT_R_INVALID_LOG_ID_LENGTH), "invalid log id length"}, - {ERR_REASON(CT_R_LOG_CONF_INVALID), "log conf invalid"}, - {ERR_REASON(CT_R_LOG_CONF_INVALID_KEY), "log conf invalid key"}, - {ERR_REASON(CT_R_LOG_CONF_MISSING_DESCRIPTION), - "log conf missing description"}, - {ERR_REASON(CT_R_LOG_CONF_MISSING_KEY), "log conf missing key"}, - {ERR_REASON(CT_R_LOG_KEY_INVALID), "log key invalid"}, - {ERR_REASON(CT_R_SCT_FUTURE_TIMESTAMP), "sct future timestamp"}, - {ERR_REASON(CT_R_SCT_INVALID), "sct invalid"}, - {ERR_REASON(CT_R_SCT_INVALID_SIGNATURE), "sct invalid signature"}, - {ERR_REASON(CT_R_SCT_LIST_INVALID), "sct list invalid"}, - {ERR_REASON(CT_R_SCT_LOG_ID_MISMATCH), "sct log id mismatch"}, - {ERR_REASON(CT_R_SCT_NOT_SET), "sct not set"}, - {ERR_REASON(CT_R_SCT_UNSUPPORTED_VERSION), "sct unsupported version"}, - {ERR_REASON(CT_R_UNRECOGNIZED_SIGNATURE_NID), - "unrecognized signature nid"}, - {ERR_REASON(CT_R_UNSUPPORTED_ENTRY_TYPE), "unsupported entry type"}, - {ERR_REASON(CT_R_UNSUPPORTED_VERSION), "unsupported version"}, +static const ERR_STRING_DATA CT_str_reasons[] = { + {ERR_PACK(ERR_LIB_CT, 0, CT_R_BASE64_DECODE_ERROR), "base64 decode error"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_INVALID_LOG_ID_LENGTH), + "invalid log id length"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_INVALID), "log conf invalid"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_INVALID_KEY), + "log conf invalid key"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_MISSING_DESCRIPTION), + "log conf missing description"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_MISSING_KEY), + "log conf missing key"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_KEY_INVALID), "log key invalid"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_FUTURE_TIMESTAMP), + "sct future timestamp"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_INVALID), "sct invalid"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_INVALID_SIGNATURE), + "sct invalid signature"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_LIST_INVALID), "sct list invalid"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_LOG_ID_MISMATCH), "sct log id mismatch"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_NOT_SET), "sct not set"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_UNSUPPORTED_VERSION), + "sct unsupported version"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_UNRECOGNIZED_SIGNATURE_NID), + "unrecognized signature nid"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_UNSUPPORTED_ENTRY_TYPE), + "unsupported entry type"}, + {ERR_PACK(ERR_LIB_CT, 0, CT_R_UNSUPPORTED_VERSION), "unsupported version"}, {0, NULL} }; @@ -77,10 +87,9 @@ static ERR_STRING_DATA CT_str_reasons[] = { int ERR_load_CT_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(CT_str_functs[0].error) == NULL) { - ERR_load_strings(0, CT_str_functs); - ERR_load_strings(0, CT_str_reasons); + ERR_load_strings_const(CT_str_functs); + ERR_load_strings_const(CT_str_reasons); } #endif return 1; diff --git a/crypto/ct/ct_sct.c b/crypto/ct/ct_sct.c index cd2cf609..1dc16857 100644 --- a/crypto/ct/ct_sct.c +++ b/crypto/ct/ct_sct.c @@ -70,10 +70,11 @@ int SCT_set_log_entry_type(SCT *sct, ct_log_entry_type_t entry_type) case CT_LOG_ENTRY_TYPE_PRECERT: sct->entry_type = entry_type; return 1; - default: - CTerr(CT_F_SCT_SET_LOG_ENTRY_TYPE, CT_R_UNSUPPORTED_ENTRY_TYPE); - return 0; + case CT_LOG_ENTRY_TYPE_NOT_SET: + break; } + CTerr(CT_F_SCT_SET_LOG_ENTRY_TYPE, CT_R_UNSUPPORTED_ENTRY_TYPE); + return 0; } int SCT_set0_log_id(SCT *sct, unsigned char *log_id, size_t log_id_len) @@ -274,9 +275,11 @@ int SCT_set_source(SCT *sct, sct_source_t source) return SCT_set_log_entry_type(sct, CT_LOG_ENTRY_TYPE_X509); case SCT_SOURCE_X509V3_EXTENSION: return SCT_set_log_entry_type(sct, CT_LOG_ENTRY_TYPE_PRECERT); - default: /* if we aren't sure, leave the log entry type alone */ - return 1; + case SCT_SOURCE_UNKNOWN: + break; } + /* if we aren't sure, leave the log entry type alone */ + return 1; } sct_validation_status_t SCT_get_validation_status(const SCT *sct) diff --git a/crypto/ctype.c b/crypto/ctype.c new file mode 100644 index 00000000..813be25a --- /dev/null +++ b/crypto/ctype.c @@ -0,0 +1,274 @@ +/* + * 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 +#include +#include "internal/ctype.h" +#include "openssl/ebcdic.h" + +/* + * Define the character classes for each character in the seven bit ASCII + * character set. This is independent of the host's character set, characters + * are converted to ASCII before being used as an index in to this table. + * Characters outside of the seven bit ASCII range are detected before indexing. + */ +static const unsigned short ctype_char_map[128] = { + /* 00 nul */ CTYPE_MASK_cntrl, + /* 01 soh */ CTYPE_MASK_cntrl, + /* 02 stx */ CTYPE_MASK_cntrl, + /* 03 etx */ CTYPE_MASK_cntrl, + /* 04 eot */ CTYPE_MASK_cntrl, + /* 05 enq */ CTYPE_MASK_cntrl, + /* 06 ack */ CTYPE_MASK_cntrl, + /* 07 \a */ CTYPE_MASK_cntrl, + /* 08 \b */ CTYPE_MASK_cntrl, + /* 09 \t */ CTYPE_MASK_blank | CTYPE_MASK_cntrl | CTYPE_MASK_space, + /* 0A \n */ CTYPE_MASK_cntrl | CTYPE_MASK_space, + /* 0B \v */ CTYPE_MASK_cntrl | CTYPE_MASK_space, + /* 0C \f */ CTYPE_MASK_cntrl | CTYPE_MASK_space, + /* 0D \r */ CTYPE_MASK_cntrl | CTYPE_MASK_space, + /* 0E so */ CTYPE_MASK_cntrl, + /* 0F si */ CTYPE_MASK_cntrl, + /* 10 dle */ CTYPE_MASK_cntrl, + /* 11 dc1 */ CTYPE_MASK_cntrl, + /* 12 dc2 */ CTYPE_MASK_cntrl, + /* 13 dc3 */ CTYPE_MASK_cntrl, + /* 14 dc4 */ CTYPE_MASK_cntrl, + /* 15 nak */ CTYPE_MASK_cntrl, + /* 16 syn */ CTYPE_MASK_cntrl, + /* 17 etb */ CTYPE_MASK_cntrl, + /* 18 can */ CTYPE_MASK_cntrl, + /* 19 em */ CTYPE_MASK_cntrl, + /* 1A sub */ CTYPE_MASK_cntrl, + /* 1B esc */ CTYPE_MASK_cntrl, + /* 1C fs */ CTYPE_MASK_cntrl, + /* 1D gs */ CTYPE_MASK_cntrl, + /* 1E rs */ CTYPE_MASK_cntrl, + /* 1F us */ CTYPE_MASK_cntrl, + /* 20 */ CTYPE_MASK_blank | CTYPE_MASK_print | CTYPE_MASK_space + | CTYPE_MASK_asn1print, + /* 21 ! */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 22 " */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 23 # */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 24 $ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 25 % */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 26 & */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 27 ' */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_asn1print, + /* 28 ( */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_asn1print, + /* 29 ) */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_asn1print, + /* 2A * */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 2B + */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 2C , */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_asn1print, + /* 2D - */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_asn1print, + /* 2E . */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_asn1print, + /* 2F / */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 30 0 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 31 1 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 32 2 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 33 3 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 34 4 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 35 5 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 36 6 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 37 7 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 38 8 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 39 9 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 3A : */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_asn1print, + /* 3B ; */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 3C < */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 3D = */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 3E > */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 3F ? */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct + | CTYPE_MASK_asn1print, + /* 40 @ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 41 A */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 42 B */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 43 C */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 44 D */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 45 E */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 46 F */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 47 G */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 48 H */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 49 I */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 4A J */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 4B K */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 4C L */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 4D M */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 4E N */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 4F O */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 50 P */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 51 Q */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 52 R */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 53 S */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 54 T */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 55 U */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 56 V */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 57 W */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 58 X */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 59 Y */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 5A Z */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 5B [ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 5C \ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 5D ] */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 5E ^ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 5F _ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 60 ` */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 61 a */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 62 b */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 63 c */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 64 d */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 65 e */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 66 f */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 67 g */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 68 h */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 69 i */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 6A j */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 6B k */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 6C l */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 6D m */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 6E n */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 6F o */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 70 p */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 71 q */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 72 r */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 73 s */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 74 t */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 75 u */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 76 v */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 77 w */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 78 x */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 79 y */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 7A z */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print + | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, + /* 7B { */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 7C | */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 7D } */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 7E ~ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, + /* 7F del */ CTYPE_MASK_cntrl +}; + +#ifdef CHARSET_EBCDIC +int ossl_toascii(int c) +{ + if (c < -128 || c > 256 || c == EOF) + return c; + /* + * Adjust negatively signed characters. + * This is not required for ASCII because any character that sign extends + * is not seven bit and all of the checks are on the seven bit characters. + * I.e. any check must fail on sign extension. + */ + if (c < 0) + c += 256; + return os_toascii[c]; +} + +int ossl_fromascii(int c) +{ + if (c < -128 || c > 256 || c == EOF) + return c; + if (c < 0) + c += 256; + return os_toebcdic[c]; +} +#endif + +int ossl_ctype_check(int c, unsigned int mask) +{ + const int max = sizeof(ctype_char_map) / sizeof(*ctype_char_map); + const int a = ossl_toascii(c); + + return a >= 0 && a < max && (ctype_char_map[a] & mask) != 0; +} + +#if defined(CHARSET_EBCDIC) && !defined(CHARSET_EBCDIC_TEST) +static const int case_change = 0x40; +#else +static const int case_change = 0x20; +#endif + +int ossl_tolower(int c) +{ + return ossl_isupper(c) ? c ^ case_change : c; +} + +int ossl_toupper(int c) +{ + return ossl_islower(c) ? c ^ case_change : c; +} diff --git a/crypto/cversion.c b/crypto/cversion.c index 96d8a5b5..534e7eba 100644 --- a/crypto/cversion.c +++ b/crypto/cversion.c @@ -9,9 +9,7 @@ #include "internal/cryptlib.h" -#ifndef NO_WINDOWS_BRAINDEATH -# include "buildinf.h" -#endif +#include "buildinf.h" unsigned long OpenSSL_version_num(void) { @@ -20,46 +18,27 @@ unsigned long OpenSSL_version_num(void) const char *OpenSSL_version(int t) { - if (t == OPENSSL_VERSION) + switch (t) { + case OPENSSL_VERSION: return OPENSSL_VERSION_TEXT; - if (t == OPENSSL_BUILT_ON) { -#ifdef DATE -# ifdef OPENSSL_USE_BUILD_DATE - return (DATE); -# else - return ("built on: reproducible build, date unspecified"); -# endif -#else - return ("built on: date not available"); -#endif - } - if (t == OPENSSL_CFLAGS) { -#ifdef CFLAGS - return (CFLAGS); -#else - return ("compiler: information not available"); -#endif - } - if (t == OPENSSL_PLATFORM) { -#ifdef PLATFORM - return (PLATFORM); -#else - return ("platform: information not available"); -#endif - } - if (t == OPENSSL_DIR) { + case OPENSSL_BUILT_ON: + return DATE; + case OPENSSL_CFLAGS: + return compiler_flags; + case OPENSSL_PLATFORM: + return PLATFORM; + case OPENSSL_DIR: #ifdef OPENSSLDIR return "OPENSSLDIR: \"" OPENSSLDIR "\""; #else return "OPENSSLDIR: N/A"; #endif - } - if (t == OPENSSL_ENGINES_DIR) { + case OPENSSL_ENGINES_DIR: #ifdef ENGINESDIR return "ENGINESDIR: \"" ENGINESDIR "\""; #else return "ENGINESDIR: N/A"; #endif } - return ("not available"); + return "not available"; } diff --git a/crypto/des/asm/crypt586.pl b/crypto/des/asm/crypt586.pl index d5911a18..a02d1806 100644 --- a/crypto/des/asm/crypt586.pl +++ b/crypto/des/asm/crypt586.pl @@ -7,7 +7,7 @@ # https://www.openssl.org/source/license.html # The inner loop instruction sequence and the IP/FP modifications are from -# Svend Olaf Mikkelsen +# Svend Olaf Mikkelsen $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; push(@INC,"${dir}","${dir}../../perlasm"); @@ -16,7 +16,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"crypt586.pl"); +&asm_init($ARGV[0]); $L="edi"; $R="esi"; @@ -111,7 +111,7 @@ sub D_ENCRYPT &and( $u, "0xfcfcfcfc" ); # 2 &xor( $tmp1, $tmp1); # 1 &and( $t, "0xcfcfcfcf" ); # 2 - &xor( $tmp2, $tmp2); + &xor( $tmp2, $tmp2); &movb( &LB($tmp1), &LB($u) ); &movb( &LB($tmp2), &HB($u) ); &rotr( $t, 4 ); @@ -175,7 +175,7 @@ sub IP_new &R_PERM_OP($l,$tt,$r,14,"0x33333333",$r); &R_PERM_OP($tt,$r,$l,22,"0x03fc03fc",$r); &R_PERM_OP($l,$r,$tt, 9,"0xaaaaaaaa",$r); - + if ($lr != 3) { if (($lr-3) < 0) diff --git a/crypto/des/asm/des-586.pl b/crypto/des/asm/des-586.pl index 3d7c7f1b..2bcc54ef 100644 --- a/crypto/des/asm/des-586.pl +++ b/crypto/des/asm/des-586.pl @@ -7,7 +7,7 @@ # https://www.openssl.org/source/license.html # The inner loop instruction sequence and the IP/FP modifications are from -# Svend Olaf Mikkelsen +# Svend Olaf Mikkelsen. $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; push(@INC,"${dir}","${dir}../../perlasm"); @@ -15,7 +15,7 @@ require "x86asm.pl"; require "cbc.pl"; require "desboth.pl"; -# base code is in microsft +# base code is in Microsoft # op dest, source # format. # @@ -23,7 +23,7 @@ require "desboth.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"des-586.pl"); +&asm_init($ARGV[0]); $L="edi"; $R="esi"; @@ -85,7 +85,7 @@ sub DES_encrypt_internal() &function_end_B("_x86_DES_encrypt"); } - + sub DES_decrypt_internal() { &function_begin_B("_x86_DES_decrypt"); @@ -122,7 +122,7 @@ sub DES_decrypt_internal() &function_end_B("_x86_DES_decrypt"); } - + sub DES_encrypt { local($name,$do_ip)=@_; @@ -283,7 +283,7 @@ sub IP_new &R_PERM_OP($l,$tt,$r,14,"0x33333333",$r); &R_PERM_OP($tt,$r,$l,22,"0x03fc03fc",$r); &R_PERM_OP($l,$r,$tt, 9,"0xaaaaaaaa",$r); - + if ($lr != 3) { if (($lr-3) < 0) diff --git a/crypto/des/asm/des_enc.m4 b/crypto/des/asm/des_enc.m4 index 2d794d33..4a0d1562 100644 --- a/crypto/des/asm/des_enc.m4 +++ b/crypto/des/asm/des_enc.m4 @@ -1,4 +1,4 @@ -! Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +! Copyright 2000-2018 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 @@ -31,10 +31,6 @@ #include -#ifdef OPENSSL_FIPSCANISTER -#include -#endif - #if defined(__SUNPRO_C) && defined(__sparcv9) # define ABI64 /* They've said -xarch=v9 at command line */ #elif defined(__GNUC__) && defined(__arch64__) @@ -116,7 +112,7 @@ changequote({,}) ! ! Loads key first round from address in parameter 5 to out0, out1. ! -! After the the original LibDES initial permutation, the resulting left +! After the original LibDES initial permutation, the resulting left ! is in the variable initially used for right and vice versa. The macro ! implements the possibility to keep the halfs in the original registers. ! @@ -532,8 +528,8 @@ $4: ! parameter 3 1 for optional store to [in0] ! parameter 4 1 for load input/output address to local5/7 ! -! The final permutation logic switches the halfes, meaning that -! left and right ends up the the registers originally used. +! The final permutation logic switches the halves, meaning that +! left and right ends up the registers originally used. define(fp_macro, { @@ -735,7 +731,7 @@ define(fp_ip_macro, { sll $4, 3, local2 xor local4, temp2, $2 - ! reload since used as temporar: + ! reload since used as temporary: ld [out2+280], out4 ! loop counter @@ -757,7 +753,7 @@ define(fp_ip_macro, { ! parameter 1 address ! parameter 2 destination left ! parameter 3 destination right -! parameter 4 temporar +! parameter 4 temporary ! parameter 5 label define(load_little_endian, { @@ -806,7 +802,7 @@ $5a: ! parameter 1 address ! parameter 2 destination left ! parameter 3 destination right -! parameter 4 temporar +! parameter 4 temporary ! parameter 4 label ! ! adds 8 to address @@ -931,7 +927,7 @@ $7.jmp.table: ! parameter 1 address ! parameter 2 source left ! parameter 3 source right -! parameter 4 temporar +! parameter 4 temporary define(store_little_endian, { @@ -1521,7 +1517,7 @@ DES_ncbc_encrypt: ! parameter 7 1 for mov in1 to in3 ! parameter 8 1 for mov in3 to in4 - ip_macro(in5, out5, out5, in5, in4, 2, 0, 1) ! include decryprion ks in4 + ip_macro(in5, out5, out5, in5, in4, 2, 0, 1) ! include decryption ks in4 fp_macro(out5, in5, 0, 1) ! 1 for input and output address to local5/7 @@ -1567,7 +1563,7 @@ DES_ncbc_encrypt: .size DES_ncbc_encrypt, .DES_ncbc_encrypt.end-DES_ncbc_encrypt -! void DES_ede3_cbc_encrypt(input, output, lenght, ks1, ks2, ks3, ivec, enc) +! void DES_ede3_cbc_encrypt(input, output, length, ks1, ks2, ks3, ivec, enc) ! ************************************************************************** @@ -1815,7 +1811,7 @@ DES_ede3_cbc_encrypt: .byte 240, 240, 240, 240, 244, 244, 244, 244 .byte 248, 248, 248, 248, 252, 252, 252, 252 - ! 5 numbers for initil/final permutation + ! 5 numbers for initial/final permutation .word 0x0f0f0f0f ! offset 256 .word 0x0000ffff ! 260 diff --git a/crypto/des/asm/desboth.pl b/crypto/des/asm/desboth.pl index 76759fb2..ef7054e2 100644 --- a/crypto/des/asm/desboth.pl +++ b/crypto/des/asm/desboth.pl @@ -34,7 +34,7 @@ sub DES_encrypt3 &IP_new($L,$R,"edx",0); # put them back - + if ($enc) { &mov(&DWP(4,"ebx","",0),$R); diff --git a/crypto/des/asm/dest4-sparcv9.pl b/crypto/des/asm/dest4-sparcv9.pl index 4a6e29fc..fe1fdc70 100644 --- a/crypto/des/asm/dest4-sparcv9.pl +++ b/crypto/des/asm/dest4-sparcv9.pl @@ -8,8 +8,8 @@ # ==================================================================== -# Written by David S. Miller and Andy Polyakov -# . The module is licensed under 2-clause BSD +# Written by David S. Miller and Andy Polyakov. +# The module is licensed under 2-clause BSD # license. March 2013. All rights reserved. # ==================================================================== diff --git a/crypto/des/build.info b/crypto/des/build.info index c0306cfd..05cb154c 100644 --- a/crypto/des/build.info +++ b/crypto/des/build.info @@ -5,13 +5,15 @@ SOURCE[../../libcrypto]=\ ofb64ede.c ofb64enc.c ofb_enc.c \ str2key.c pcbc_enc.c qud_cksm.c rand_key.c \ {- $target{des_asm_src} -} \ - fcrypt.c xcbc_enc.c rpc_enc.c cbc_cksm.c + fcrypt.c xcbc_enc.c cbc_cksm.c GENERATE[des_enc-sparc.S]=asm/des_enc.m4 GENERATE[dest4-sparcv9.S]=asm/dest4-sparcv9.pl $(PERLASM_SCHEME) INCLUDE[dest4-sparcv9.o]=.. -GENERATE[des-586.s]=asm/des-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) +GENERATE[des-586.s]=asm/des-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) DEPEND[des-586.s]=../perlasm/x86asm.pl ../perlasm/cbc.pl -GENERATE[crypt586.s]=asm/crypt586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) +GENERATE[crypt586.s]=asm/crypt586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) DEPEND[crypt586.s]=../perlasm/x86asm.pl ../perlasm/cbc.pl diff --git a/crypto/des/cbc_cksm.c b/crypto/des/cbc_cksm.c index a7bf0689..5a1f72f8 100644 --- a/crypto/des/cbc_cksm.c +++ b/crypto/des/cbc_cksm.c @@ -33,7 +33,6 @@ DES_LONG DES_cbc_cksum(const unsigned char *in, DES_cblock *output, tin1 ^= tout1; tin[1] = tin1; DES_encrypt1((DES_LONG *)tin, schedule, DES_ENCRYPT); - /* fix 15/10/91 eay - thanks to keithr@sco.COM */ tout0 = tin[0]; tout1 = tin[1]; } @@ -50,5 +49,5 @@ DES_LONG DES_cbc_cksum(const unsigned char *in, DES_cblock *output, | ((tout1 >> 8L) & 0x0000FF00) | ((tout1 << 8L) & 0x00FF0000) | ((tout1 << 24L) & 0xFF000000); - return (tout1); + return tout1; } diff --git a/crypto/des/cfb64ede.c b/crypto/des/cfb64ede.c index 5edb979e..21943f61 100644 --- a/crypto/des/cfb64ede.c +++ b/crypto/des/cfb64ede.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,7 +8,6 @@ */ #include "des_locl.h" -#include "e_os.h" /* * The input and output encrypted as though 64bit cfb mode is being used. diff --git a/crypto/des/cfb_enc.c b/crypto/des/cfb_enc.c index 6c428ba6..544392e4 100644 --- a/crypto/des/cfb_enc.c +++ b/crypto/des/cfb_enc.c @@ -37,7 +37,7 @@ void DES_cfb_encrypt(const unsigned char *in, unsigned char *out, int numbits, unsigned int sh[4]; unsigned char *ovec = (unsigned char *)sh; - /* I kind of count that compiler optimizes away this assertioni, */ + /* I kind of count that compiler optimizes away this assertion, */ assert(sizeof(sh[0]) == 4); /* as this holds true for all, */ /* but 16-bit platforms... */ diff --git a/crypto/des/des_enc.c b/crypto/des/des_enc.c index 600f6df4..ed134ace 100644 --- a/crypto/des/des_enc.c +++ b/crypto/des/des_enc.c @@ -24,8 +24,7 @@ void DES_encrypt1(DES_LONG *data, DES_key_schedule *ks, int enc) * Things have been modified so that the initial rotate is done outside * the loop. This required the DES_SPtrans values in sp.h to be rotated * 1 bit to the right. One perl script later and things have a 5% speed - * up on a sparc2. Thanks to Richard Outerbridge - * <71755.204@CompuServe.COM> for pointing this out. + * up on a sparc2. Thanks to Richard Outerbridge for pointing this out. */ /* clear the top bits on machines with 8byte longs */ /* shift left by 2 */ @@ -95,8 +94,7 @@ void DES_encrypt2(DES_LONG *data, DES_key_schedule *ks, int enc) * Things have been modified so that the initial rotate is done outside * the loop. This required the DES_SPtrans values in sp.h to be rotated * 1 bit to the right. One perl script later and things have a 5% speed - * up on a sparc2. Thanks to Richard Outerbridge - * <71755.204@CompuServe.COM> for pointing this out. + * up on a sparc2. Thanks to Richard Outerbridge for pointing this out. */ /* clear the top bits on machines with 8byte longs */ r = ROTATE(r, 29) & 0xffffffffL; diff --git a/crypto/des/des_locl.h b/crypto/des/des_locl.h index 1fe47688..f401e6f3 100644 --- a/crypto/des/des_locl.h +++ b/crypto/des/des_locl.h @@ -26,10 +26,6 @@ # define ITERATIONS 16 # define HALF_ITERATIONS 8 -/* used in des_read and des_write */ -# define MAXWRITE (1024*16) -# define BSIZE (MAXWRITE+4) - # define c2l(c,l) (l =((DES_LONG)(*((c)++))) , \ l|=((DES_LONG)(*((c)++)))<< 8L, \ l|=((DES_LONG)(*((c)++)))<<16L, \ @@ -67,7 +63,6 @@ * replacements for htonl and ntohl since I have no idea what to do when * faced with machines with 8 byte longs. */ -# define HDRSIZE 4 # define n2l(c,l) (l =((DES_LONG)(*((c)++)))<<24L, \ l|=((DES_LONG)(*((c)++)))<<16L, \ @@ -101,7 +96,7 @@ } \ } -# if (defined(OPENSSL_SYS_WIN32) && defined(_MSC_VER)) +# if defined(_MSC_VER) # define ROTATE(a,n) (_lrotr(a,n)) # elif defined(__ICC) # define ROTATE(a,n) (_rotr(a,n)) diff --git a/crypto/des/ecb_enc.c b/crypto/des/ecb_enc.c index 32df4600..5ed079d1 100644 --- a/crypto/des/ecb_enc.c +++ b/crypto/des/ecb_enc.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -15,19 +15,16 @@ const char *DES_options(void) { static int init = 1; - static char buf[32]; + static char buf[12]; if (init) { - const char *size; - if (sizeof(DES_LONG) != sizeof(long)) - size = "int"; + OPENSSL_strlcpy(buf, "des(int)", sizeof(buf)); else - size = "long"; - BIO_snprintf(buf, sizeof(buf), "des(%s)", size); + OPENSSL_strlcpy(buf, "des(long)", sizeof(buf)); init = 0; } - return (buf); + return buf; } void DES_ecb_encrypt(const_DES_cblock *input, DES_cblock *output, diff --git a/crypto/des/fcrypt.c b/crypto/des/fcrypt.c index baede4fc..aaee4bf2 100644 --- a/crypto/des/fcrypt.c +++ b/crypto/des/fcrypt.c @@ -23,7 +23,7 @@ /* * Added more values to handle illegal salt values the way normal crypt() - * implementations do. The patch was sent by Bjorn Gronvall + * implementations do. */ static unsigned const char con_salt[128] = { 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, @@ -60,7 +60,7 @@ char *DES_crypt(const char *buf, const char *salt) static char buff[14]; #ifndef CHARSET_EBCDIC - return (DES_fcrypt(buf, salt, buff)); + return DES_fcrypt(buf, salt, buff); #else char e_salt[2 + 1]; char e_buf[32 + 1]; /* replace 32 by 8 ? */ @@ -145,5 +145,5 @@ char *DES_fcrypt(const char *buf, const char *salt, char *ret) ret[i] = cov_2char[c]; } ret[13] = '\0'; - return (ret); + return ret; } diff --git a/crypto/des/qud_cksm.c b/crypto/des/qud_cksm.c index 8710ceca..81e6be82 100644 --- a/crypto/des/qud_cksm.c +++ b/crypto/des/qud_cksm.c @@ -15,7 +15,6 @@ */ #include "des_locl.h" -/* bug fix for dos - 7/6/91 - Larry hughes@logos.ucs.indiana.edu */ #define Q_B0(a) (((DES_LONG)(a))) #define Q_B1(a) (((DES_LONG)(a))<<8) #define Q_B2(a) (((DES_LONG)(a))<<16) @@ -73,5 +72,5 @@ DES_LONG DES_quad_cksum(const unsigned char *input, DES_cblock output[], *lp++ = z1; } } - return (z0); + return z0; } diff --git a/crypto/des/rand_key.c b/crypto/des/rand_key.c index 61e4f9d0..09d7e4cf 100644 --- a/crypto/des/rand_key.c +++ b/crypto/des/rand_key.c @@ -14,8 +14,8 @@ int DES_random_key(DES_cblock *ret) { do { if (RAND_bytes((unsigned char *)ret, sizeof(DES_cblock)) != 1) - return (0); + return 0; } while (DES_is_weak_key(ret)); DES_set_odd_parity(ret); - return (1); + return 1; } diff --git a/crypto/des/rpc_des.h b/crypto/des/rpc_des.h deleted file mode 100644 index fe59e224..00000000 --- a/crypto/des/rpc_des.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 1995-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 - */ - -/* @(#)des.h 2.2 88/08/10 4.0 RPCSRC; from 2.7 88/02/08 SMI */ -/*- - * Sun RPC is a product of Sun Microsystems, Inc. and is provided for - * unrestricted use provided that this legend is included on all tape - * media and as a part of the software program in whole or part. Users - * may copy or modify Sun RPC without charge, but are not authorized - * to license or distribute it to anyone else except as part of a product or - * program developed by the user. - * - * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE - * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR - * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. - * - * Sun RPC is provided with no support and without any obligation on the - * part of Sun Microsystems, Inc. to assist in its use, correction, - * modification or enhancement. - * - * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE - * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC - * OR ANY PART THEREOF. - * - * In no event will Sun Microsystems, Inc. be liable for any lost revenue - * or profits or other special, indirect and consequential damages, even if - * Sun has been advised of the possibility of such damages. - * - * Sun Microsystems, Inc. - * 2550 Garcia Avenue - * Mountain View, California 94043 - */ -/* - * Generic DES driver interface - * Keep this file hardware independent! - * Copyright (c) 1986 by Sun Microsystems, Inc. - */ - -#define DES_MAXLEN 65536 /* maximum # of bytes to encrypt */ -#define DES_QUICKLEN 16 /* maximum # of bytes to encrypt quickly */ - -enum desdir { ENCRYPT, DECRYPT }; -enum desmode { CBC, ECB }; - -/* - * parameters to ioctl call - */ -struct desparams { - unsigned char des_key[8]; /* key (with low bit parity) */ - enum desdir des_dir; /* direction */ - enum desmode des_mode; /* mode */ - unsigned char des_ivec[8]; /* input vector */ - unsigned des_len; /* number of bytes to crypt */ - union { - unsigned char UDES_data[DES_QUICKLEN]; - unsigned char *UDES_buf; - } UDES; -#define des_data UDES.UDES_data /* direct data here if quick */ -#define des_buf UDES.UDES_buf /* otherwise, pointer to data */ -}; - -/* - * Encrypt an arbitrary sized buffer - */ -#define DESIOCBLOCK _IOWR('d', 6, struct desparams) - -/* - * Encrypt of small amount of data, quickly - */ -#define DESIOCQUICK _IOWR('d', 7, struct desparams) diff --git a/crypto/des/rpc_enc.c b/crypto/des/rpc_enc.c deleted file mode 100644 index bfa85115..00000000 --- a/crypto/des/rpc_enc.c +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 1995-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 - */ - -#include "rpc_des.h" -#include "des_locl.h" - -int _des_crypt(char *buf, int len, struct desparams *desp); -int _des_crypt(char *buf, int len, struct desparams *desp) -{ - DES_key_schedule ks; - int enc; - - DES_set_key_unchecked(&desp->des_key, &ks); - enc = (desp->des_dir == ENCRYPT) ? DES_ENCRYPT : DES_DECRYPT; - - if (desp->des_mode == CBC) - DES_ecb_encrypt((const_DES_cblock *)desp->UDES.UDES_buf, - (DES_cblock *)desp->UDES.UDES_buf, &ks, enc); - else { - DES_ncbc_encrypt(desp->UDES.UDES_buf, desp->UDES.UDES_buf, - len, &ks, &desp->des_ivec, enc); - } - return (1); -} diff --git a/crypto/des/set_key.c b/crypto/des/set_key.c index dc88b8d0..adbad723 100644 --- a/crypto/des/set_key.c +++ b/crypto/des/set_key.c @@ -18,10 +18,9 @@ #include #include "des_locl.h" +/* defaults to false */ 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, @@ -65,9 +64,9 @@ int DES_check_key_parity(const_DES_cblock *key) for (i = 0; i < DES_KEY_SZ; i++) { if ((*key)[i] != odd_parity[(*key)[i]]) - return (0); + return 0; } - return (1); + return 1; } /*- @@ -77,8 +76,6 @@ int DES_check_key_parity(const_DES_cblock *key) * %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] = { @@ -107,15 +104,9 @@ 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); + return 1; + return 0; } /*- @@ -302,9 +293,9 @@ int DES_set_key(const_DES_cblock *key, DES_key_schedule *schedule) int DES_set_key_checked(const_DES_cblock *key, DES_key_schedule *schedule) { if (!DES_check_key_parity(key)) - return (-1); + return -1; if (DES_is_weak_key(key)) - return (-2); + return -2; DES_set_key_unchecked(key, schedule); return 0; } @@ -329,8 +320,8 @@ void DES_set_key_unchecked(const_DES_cblock *key, DES_key_schedule *schedule) c2l(in, d); /* - * do PC1 in 47 simple operations :-) Thanks to John Fletcher - * (john_fletcher@lccmail.ocf.llnl.gov) for the inspiration. :-) + * do PC1 in 47 simple operations. Thanks to John Fletcher + * for the inspiration. */ PERM_OP(d, c, t, 4, 0x0f0f0f0fL); HPERM_OP(c, t, -2, 0xcccc0000L); @@ -377,13 +368,5 @@ void DES_set_key_unchecked(const_DES_cblock *key, DES_key_schedule *schedule) int DES_key_sched(const_DES_cblock *key, DES_key_schedule *schedule) { - return (DES_set_key(key, 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/des/spr.h b/crypto/des/spr.h index 42adfbf6..2404e092 100644 --- a/crypto/des/spr.h +++ b/crypto/des/spr.h @@ -7,7 +7,7 @@ * https://www.openssl.org/source/license.html */ -OPENSSL_GLOBAL const DES_LONG DES_SPtrans[8][64] = { +const DES_LONG DES_SPtrans[8][64] = { { /* nibble 0 */ 0x02080800L, 0x00080000L, 0x02000002L, 0x02080802L, diff --git a/crypto/des/str2key.c b/crypto/des/str2key.c index 78998a1c..e18d7265 100644 --- a/crypto/des/str2key.c +++ b/crypto/des/str2key.c @@ -17,10 +17,6 @@ void DES_string_to_key(const char *str, DES_cblock *key) memset(key, 0, 8); length = strlen(str); -#ifdef OLD_STR_TO_KEY - for (i = 0; i < length; i++) - (*key)[i % 8] ^= (str[i] << 1); -#else /* MIT COMPATIBLE */ for (i = 0; i < length; i++) { register unsigned char j = str[i]; @@ -34,7 +30,6 @@ void DES_string_to_key(const char *str, DES_cblock *key) (*key)[7 - (i % 8)] ^= j; } } -#endif DES_set_odd_parity(key); DES_set_key_unchecked(key, &ks); DES_cbc_cksum((const unsigned char *)str, key, length, &ks, key); @@ -50,20 +45,6 @@ void DES_string_to_2keys(const char *str, DES_cblock *key1, DES_cblock *key2) memset(key1, 0, 8); memset(key2, 0, 8); length = strlen(str); -#ifdef OLD_STR_TO_KEY - if (length <= 8) { - for (i = 0; i < length; i++) { - (*key2)[i] = (*key1)[i] = (str[i] << 1); - } - } else { - for (i = 0; i < length; i++) { - if ((i / 8) & 1) - (*key2)[i % 8] ^= (str[i] << 1); - else - (*key1)[i % 8] ^= (str[i] << 1); - } - } -#else /* MIT COMPATIBLE */ for (i = 0; i < length; i++) { register unsigned char j = str[i]; @@ -84,7 +65,6 @@ void DES_string_to_2keys(const char *str, DES_cblock *key1, DES_cblock *key2) } if (length <= 8) memcpy(key2, key1, 8); -#endif DES_set_odd_parity(key1); DES_set_odd_parity(key2); DES_set_key_unchecked(key1, &ks); diff --git a/crypto/dh/build.info b/crypto/dh/build.info index dba93066..b19ff6db 100644 --- a/crypto/dh/build.info +++ b/crypto/dh/build.info @@ -1,4 +1,5 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ dh_asn1.c dh_gen.c dh_key.c dh_lib.c dh_check.c dh_err.c dh_depr.c \ - dh_ameth.c dh_pmeth.c dh_prn.c dh_rfc5114.c dh_kdf.c dh_meth.c + dh_ameth.c dh_pmeth.c dh_prn.c dh_rfc5114.c dh_kdf.c dh_meth.c \ + dh_rfc7919.c diff --git a/crypto/dh/dh_ameth.c b/crypto/dh/dh_ameth.c index cd77867d..05a1d422 100644 --- a/crypto/dh/dh_ameth.c +++ b/crypto/dh/dh_ameth.c @@ -326,7 +326,7 @@ static int do_dh_print(BIO *bp, const DH *x, int indent, int ptype) goto err; } if (BIO_write(bp, "\n", 1) <= 0) - return (0); + return 0; } if (x->counter && !ASN1_bn_print(bp, "counter:", x->counter, NULL, indent)) goto err; @@ -346,7 +346,7 @@ static int do_dh_print(BIO *bp, const DH *x, int indent, int ptype) static int int_dh_size(const EVP_PKEY *pkey) { - return (DH_size(pkey->pkey.dh)); + return DH_size(pkey->pkey.dh); } static int dh_bits(const EVP_PKEY *pkey) @@ -374,13 +374,19 @@ static int dh_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b) static int int_dh_bn_cpy(BIGNUM **dst, const BIGNUM *src) { BIGNUM *a; - if (src) { - a = BN_dup(src); - if (!a) - return 0; - } else + + /* + * If source is read only just copy the pointer, so + * we don't have to reallocate it. + */ + if (src == NULL) a = NULL; - BN_free(*dst); + else if (BN_get_flags(src, BN_FLG_STATIC_DATA) + && !BN_get_flags(src, BN_FLG_MALLOCED)) + a = (BIGNUM *)src; + else if ((a = BN_dup(src)) == NULL) + return 0; + BN_clear_free(*dst); *dst = a; return 1; } @@ -503,6 +509,25 @@ static int dh_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) } +static int dh_pkey_public_check(const EVP_PKEY *pkey) +{ + DH *dh = pkey->pkey.dh; + + if (dh->pub_key == NULL) { + DHerr(DH_F_DH_PKEY_PUBLIC_CHECK, DH_R_MISSING_PUBKEY); + return 0; + } + + return DH_check_pub_key_ex(dh, dh->pub_key); +} + +static int dh_pkey_param_check(const EVP_PKEY *pkey) +{ + DH *dh = pkey->pkey.dh; + + return DH_check_ex(dh); +} + const EVP_PKEY_ASN1_METHOD dh_asn1_meth = { EVP_PKEY_DH, EVP_PKEY_DH, @@ -533,7 +558,13 @@ const EVP_PKEY_ASN1_METHOD dh_asn1_meth = { 0, int_dh_free, - 0 + 0, + + 0, 0, 0, 0, 0, + + 0, + dh_pkey_public_check, + dh_pkey_param_check }; const EVP_PKEY_ASN1_METHOD dhx_asn1_meth = { @@ -566,7 +597,13 @@ const EVP_PKEY_ASN1_METHOD dhx_asn1_meth = { 0, int_dh_free, - dh_pkey_ctrl + dh_pkey_ctrl, + + 0, 0, 0, 0, 0, + + 0, + dh_pkey_public_check, + dh_pkey_param_check }; #ifndef OPENSSL_NO_CMS diff --git a/crypto/dh/dh_asn1.c b/crypto/dh/dh_asn1.c index 7c72fd64..1a40633b 100644 --- a/crypto/dh/dh_asn1.c +++ b/crypto/dh/dh_asn1.c @@ -34,7 +34,7 @@ static int dh_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, ASN1_SEQUENCE_cb(DHparams, dh_cb) = { ASN1_SIMPLE(DH, p, BIGNUM), ASN1_SIMPLE(DH, g, BIGNUM), - ASN1_OPT(DH, length, ZLONG), + ASN1_OPT_EMBED(DH, length, ZINT32), } ASN1_SEQUENCE_END_cb(DH, DHparams) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DH, DHparams, DHparams) diff --git a/crypto/dh/dh_check.c b/crypto/dh/dh_check.c index 3b0fa590..fc455771 100644 --- a/crypto/dh/dh_check.c +++ b/crypto/dh/dh_check.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -18,6 +18,19 @@ * p is odd * 1 < g < p - 1 */ +int DH_check_params_ex(const DH *dh) +{ + int errflags = 0; + + (void)DH_check_params(dh, &errflags); + + if ((errflags & DH_CHECK_P_NOT_PRIME) != 0) + DHerr(DH_F_DH_CHECK_PARAMS_EX, DH_R_CHECK_P_NOT_PRIME); + if ((errflags & DH_NOT_SUITABLE_GENERATOR) != 0) + DHerr(DH_F_DH_CHECK_PARAMS_EX, DH_R_NOT_SUITABLE_GENERATOR); + + return errflags == 0; +} int DH_check_params(const DH *dh, int *ret) { @@ -49,7 +62,7 @@ int DH_check_params(const DH *dh, int *ret) BN_CTX_end(ctx); BN_CTX_free(ctx); } - return (ok); + return ok; } /*- @@ -61,6 +74,29 @@ int DH_check_params(const DH *dh, int *ret) * for 5, p mod 10 == 3 or 7 * should hold. */ +int DH_check_ex(const DH *dh) +{ + int errflags = 0; + + (void)DH_check(dh, &errflags); + + if ((errflags & DH_NOT_SUITABLE_GENERATOR) != 0) + DHerr(DH_F_DH_CHECK_EX, DH_R_NOT_SUITABLE_GENERATOR); + if ((errflags & DH_CHECK_Q_NOT_PRIME) != 0) + DHerr(DH_F_DH_CHECK_EX, DH_R_CHECK_Q_NOT_PRIME); + if ((errflags & DH_CHECK_INVALID_Q_VALUE) != 0) + DHerr(DH_F_DH_CHECK_EX, DH_R_CHECK_INVALID_Q_VALUE); + if ((errflags & DH_CHECK_INVALID_J_VALUE) != 0) + DHerr(DH_F_DH_CHECK_EX, DH_R_CHECK_INVALID_J_VALUE); + if ((errflags & DH_UNABLE_TO_CHECK_GENERATOR) != 0) + DHerr(DH_F_DH_CHECK_EX, DH_R_UNABLE_TO_CHECK_GENERATOR); + if ((errflags & DH_CHECK_P_NOT_PRIME) != 0) + DHerr(DH_F_DH_CHECK_EX, DH_R_CHECK_P_NOT_PRIME); + if ((errflags & DH_CHECK_P_NOT_SAFE_PRIME) != 0) + DHerr(DH_F_DH_CHECK_EX, DH_R_CHECK_P_NOT_SAFE_PRIME); + + return errflags == 0; +} int DH_check(const DH *dh, int *ret) { @@ -75,8 +111,6 @@ int DH_check(const DH *dh, int *ret) goto err; BN_CTX_start(ctx); t1 = BN_CTX_get(ctx); - if (t1 == NULL) - goto err; t2 = BN_CTX_get(ctx); if (t2 == NULL) goto err; @@ -132,7 +166,7 @@ int DH_check(const DH *dh, int *ret) r = BN_is_prime_ex(t1, BN_prime_checks, ctx, NULL); if (r < 0) goto err; - if (!r) + if (!r) *ret |= DH_CHECK_P_NOT_SAFE_PRIME; } ok = 1; @@ -141,7 +175,23 @@ int DH_check(const DH *dh, int *ret) BN_CTX_end(ctx); BN_CTX_free(ctx); } - return (ok); + return ok; +} + +int DH_check_pub_key_ex(const DH *dh, const BIGNUM *pub_key) +{ + int errflags = 0; + + (void)DH_check(dh, &errflags); + + if ((errflags & DH_CHECK_PUBKEY_TOO_SMALL) != 0) + DHerr(DH_F_DH_CHECK_PUB_KEY_EX, DH_R_CHECK_PUBKEY_TOO_SMALL); + if ((errflags & DH_CHECK_PUBKEY_TOO_LARGE) != 0) + DHerr(DH_F_DH_CHECK_PUB_KEY_EX, DH_R_CHECK_PUBKEY_TOO_LARGE); + if ((errflags & DH_CHECK_PUBKEY_INVALID) != 0) + DHerr(DH_F_DH_CHECK_PUB_KEY_EX, DH_R_CHECK_PUBKEY_INVALID); + + return errflags == 0; } int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *ret) @@ -179,5 +229,5 @@ int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *ret) BN_CTX_end(ctx); BN_CTX_free(ctx); } - return (ok); + return ok; } diff --git a/crypto/dh/dh_err.c b/crypto/dh/dh_err.c index 4e21f284..bbedab59 100644 --- a/crypto/dh/dh_err.c +++ b/crypto/dh/dh_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,53 +8,81 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_DH,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_DH,0,reason) - -static ERR_STRING_DATA DH_str_functs[] = { - {ERR_FUNC(DH_F_COMPUTE_KEY), "compute_key"}, - {ERR_FUNC(DH_F_DHPARAMS_PRINT_FP), "DHparams_print_fp"}, - {ERR_FUNC(DH_F_DH_BUILTIN_GENPARAMS), "dh_builtin_genparams"}, - {ERR_FUNC(DH_F_DH_CMS_DECRYPT), "dh_cms_decrypt"}, - {ERR_FUNC(DH_F_DH_CMS_SET_PEERKEY), "dh_cms_set_peerkey"}, - {ERR_FUNC(DH_F_DH_CMS_SET_SHARED_INFO), "dh_cms_set_shared_info"}, - {ERR_FUNC(DH_F_DH_METH_DUP), "DH_meth_dup"}, - {ERR_FUNC(DH_F_DH_METH_NEW), "DH_meth_new"}, - {ERR_FUNC(DH_F_DH_METH_SET1_NAME), "DH_meth_set1_name"}, - {ERR_FUNC(DH_F_DH_NEW_METHOD), "DH_new_method"}, - {ERR_FUNC(DH_F_DH_PARAM_DECODE), "dh_param_decode"}, - {ERR_FUNC(DH_F_DH_PRIV_DECODE), "dh_priv_decode"}, - {ERR_FUNC(DH_F_DH_PRIV_ENCODE), "dh_priv_encode"}, - {ERR_FUNC(DH_F_DH_PUB_DECODE), "dh_pub_decode"}, - {ERR_FUNC(DH_F_DH_PUB_ENCODE), "dh_pub_encode"}, - {ERR_FUNC(DH_F_DO_DH_PRINT), "do_dh_print"}, - {ERR_FUNC(DH_F_GENERATE_KEY), "generate_key"}, - {ERR_FUNC(DH_F_PKEY_DH_DERIVE), "pkey_dh_derive"}, - {ERR_FUNC(DH_F_PKEY_DH_KEYGEN), "pkey_dh_keygen"}, +static const ERR_STRING_DATA DH_str_functs[] = { + {ERR_PACK(ERR_LIB_DH, DH_F_COMPUTE_KEY, 0), "compute_key"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DHPARAMS_PRINT_FP, 0), "DHparams_print_fp"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS, 0), + "dh_builtin_genparams"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_CHECK_EX, 0), "DH_check_ex"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_CHECK_PARAMS_EX, 0), "DH_check_params_ex"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_CHECK_PUB_KEY_EX, 0), "DH_check_pub_key_ex"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_CMS_DECRYPT, 0), "dh_cms_decrypt"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_CMS_SET_PEERKEY, 0), "dh_cms_set_peerkey"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_CMS_SET_SHARED_INFO, 0), + "dh_cms_set_shared_info"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_METH_DUP, 0), "DH_meth_dup"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_METH_NEW, 0), "DH_meth_new"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_METH_SET1_NAME, 0), "DH_meth_set1_name"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_NEW_BY_NID, 0), "DH_new_by_nid"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_NEW_METHOD, 0), "DH_new_method"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_PARAM_DECODE, 0), "dh_param_decode"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_PKEY_PUBLIC_CHECK, 0), + "dh_pkey_public_check"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_PRIV_DECODE, 0), "dh_priv_decode"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_PRIV_ENCODE, 0), "dh_priv_encode"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_PUB_DECODE, 0), "dh_pub_decode"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DH_PUB_ENCODE, 0), "dh_pub_encode"}, + {ERR_PACK(ERR_LIB_DH, DH_F_DO_DH_PRINT, 0), "do_dh_print"}, + {ERR_PACK(ERR_LIB_DH, DH_F_GENERATE_KEY, 0), "generate_key"}, + {ERR_PACK(ERR_LIB_DH, DH_F_PKEY_DH_CTRL_STR, 0), "pkey_dh_ctrl_str"}, + {ERR_PACK(ERR_LIB_DH, DH_F_PKEY_DH_DERIVE, 0), "pkey_dh_derive"}, + {ERR_PACK(ERR_LIB_DH, DH_F_PKEY_DH_KEYGEN, 0), "pkey_dh_keygen"}, {0, NULL} }; -static ERR_STRING_DATA DH_str_reasons[] = { - {ERR_REASON(DH_R_BAD_GENERATOR), "bad generator"}, - {ERR_REASON(DH_R_BN_DECODE_ERROR), "bn decode error"}, - {ERR_REASON(DH_R_BN_ERROR), "bn error"}, - {ERR_REASON(DH_R_DECODE_ERROR), "decode error"}, - {ERR_REASON(DH_R_INVALID_PUBKEY), "invalid public key"}, - {ERR_REASON(DH_R_KDF_PARAMETER_ERROR), "kdf parameter error"}, - {ERR_REASON(DH_R_KEYS_NOT_SET), "keys not set"}, - {ERR_REASON(DH_R_MODULUS_TOO_LARGE), "modulus too large"}, - {ERR_REASON(DH_R_NO_PARAMETERS_SET), "no parameters set"}, - {ERR_REASON(DH_R_NO_PRIVATE_VALUE), "no private value"}, - {ERR_REASON(DH_R_PARAMETER_ENCODING_ERROR), "parameter encoding error"}, - {ERR_REASON(DH_R_PEER_KEY_ERROR), "peer key error"}, - {ERR_REASON(DH_R_SHARED_INFO_ERROR), "shared info error"}, +static const ERR_STRING_DATA DH_str_reasons[] = { + {ERR_PACK(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR), "bad generator"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_BN_DECODE_ERROR), "bn decode error"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_BN_ERROR), "bn error"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_INVALID_J_VALUE), + "check invalid j value"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_INVALID_Q_VALUE), + "check invalid q value"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_PUBKEY_INVALID), + "check pubkey invalid"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_PUBKEY_TOO_LARGE), + "check pubkey too large"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_PUBKEY_TOO_SMALL), + "check pubkey too small"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_P_NOT_PRIME), "check p not prime"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_P_NOT_SAFE_PRIME), + "check p not safe prime"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_CHECK_Q_NOT_PRIME), "check q not prime"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_DECODE_ERROR), "decode error"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_INVALID_PARAMETER_NAME), + "invalid parameter name"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_INVALID_PARAMETER_NID), + "invalid parameter nid"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_INVALID_PUBKEY), "invalid public key"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_KDF_PARAMETER_ERROR), "kdf parameter error"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_KEYS_NOT_SET), "keys not set"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_MISSING_PUBKEY), "missing pubkey"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_MODULUS_TOO_LARGE), "modulus too large"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_NOT_SUITABLE_GENERATOR), + "not suitable generator"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_NO_PARAMETERS_SET), "no parameters set"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_NO_PRIVATE_VALUE), "no private value"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_PARAMETER_ENCODING_ERROR), + "parameter encoding error"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_PEER_KEY_ERROR), "peer key error"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_SHARED_INFO_ERROR), "shared info error"}, + {ERR_PACK(ERR_LIB_DH, 0, DH_R_UNABLE_TO_CHECK_GENERATOR), + "unable to check generator"}, {0, NULL} }; @@ -63,10 +91,9 @@ static ERR_STRING_DATA DH_str_reasons[] = { int ERR_load_DH_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(DH_str_functs[0].error) == NULL) { - ERR_load_strings(0, DH_str_functs); - ERR_load_strings(0, DH_str_reasons); + ERR_load_strings_const(DH_str_functs); + ERR_load_strings_const(DH_str_reasons); } #endif return 1; diff --git a/crypto/dh/dh_gen.c b/crypto/dh/dh_gen.c index 27ecb983..59137e0f 100644 --- a/crypto/dh/dh_gen.c +++ b/crypto/dh/dh_gen.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -43,7 +43,7 @@ int DH_generate_parameters_ex(DH *ret, int prime_len, int generator, * for 3, p mod 12 == 5 <<<<< does not work for safe primes. * for 5, p mod 10 == 3 or 7 * - * Thanks to Phil Karn for the pointers about the + * Thanks to Phil Karn for the pointers about the * special generators and for answering some of my questions. * * I've implemented the second simple method :-). @@ -68,7 +68,7 @@ static int dh_builtin_genparams(DH *ret, int prime_len, int generator, BN_CTX_start(ctx); t1 = BN_CTX_get(ctx); t2 = BN_CTX_get(ctx); - if (t1 == NULL || t2 == NULL) + if (t2 == NULL) goto err; /* Make sure 'ret' has the necessary elements */ diff --git a/crypto/dh/dh_kdf.c b/crypto/dh/dh_kdf.c index 2782eeee..e17122bc 100644 --- a/crypto/dh/dh_kdf.c +++ b/crypto/dh/dh_kdf.c @@ -7,7 +7,7 @@ * https://www.openssl.org/source/license.html */ -#include +#include "e_os.h" #ifndef OPENSSL_NO_CMS #include diff --git a/crypto/dh/dh_key.c b/crypto/dh/dh_key.c index fce9ff47..6901548e 100644 --- a/crypto/dh/dh_key.c +++ b/crypto/dh/dh_key.c @@ -111,14 +111,14 @@ static int generate_key(DH *dh) if (generate_new_key) { if (dh->q) { do { - if (!BN_rand_range(priv_key, dh->q)) + if (!BN_priv_rand_range(priv_key, dh->q)) goto err; } while (BN_is_zero(priv_key) || BN_is_one(priv_key)); } else { /* secret exponent length */ l = dh->length ? dh->length : BN_num_bits(dh->p) - 1; - if (!BN_rand(priv_key, l, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) + if (!BN_priv_rand(priv_key, l, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)) goto err; } } @@ -150,7 +150,7 @@ static int generate_key(DH *dh) if (priv_key != dh->priv_key) BN_free(priv_key); BN_CTX_free(ctx); - return (ok); + return ok; } static int compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh) @@ -204,7 +204,7 @@ static int compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh) BN_CTX_end(ctx); BN_CTX_free(ctx); } - return (ret); + return ret; } static int dh_bn_mod_exp(const DH *dh, BIGNUM *r, @@ -217,11 +217,11 @@ static int dh_bn_mod_exp(const DH *dh, BIGNUM *r, static int dh_init(DH *dh) { dh->flags |= DH_FLAG_CACHE_MONT_P; - return (1); + return 1; } static int dh_finish(DH *dh) { BN_MONT_CTX_free(dh->method_mont_p); - return (1); + return 1; } diff --git a/crypto/dh/dh_lib.c b/crypto/dh/dh_lib.c index 716f4a4b..a33f3246 100644 --- a/crypto/dh/dh_lib.c +++ b/crypto/dh/dh_lib.c @@ -9,6 +9,7 @@ #include #include "internal/cryptlib.h" +#include "internal/refcount.h" #include #include "dh_locl.h" #include @@ -97,7 +98,7 @@ void DH_free(DH *r) if (r == NULL) return; - CRYPTO_atomic_add(&r->references, -1, &i, r->lock); + CRYPTO_DOWN_REF(&r->references, &i, r->lock); REF_PRINT_COUNT("DH", r); if (i > 0) return; @@ -128,7 +129,7 @@ int DH_up_ref(DH *r) { int i; - if (CRYPTO_atomic_add(&r->references, 1, &i, r->lock) <= 0) + if (CRYPTO_UP_REF(&r->references, &i, r->lock) <= 0) return 0; REF_PRINT_COUNT("DH", r); @@ -138,12 +139,12 @@ int DH_up_ref(DH *r) int DH_set_ex_data(DH *d, int idx, void *arg) { - return (CRYPTO_set_ex_data(&d->ex_data, idx, arg)); + return CRYPTO_set_ex_data(&d->ex_data, idx, arg); } void *DH_get_ex_data(DH *d, int idx) { - return (CRYPTO_get_ex_data(&d->ex_data, idx)); + return CRYPTO_get_ex_data(&d->ex_data, idx); } int DH_bits(const DH *dh) @@ -153,7 +154,7 @@ int DH_bits(const DH *dh) int DH_size(const DH *dh) { - return (BN_num_bytes(dh->p)); + return BN_num_bytes(dh->p); } int DH_security_bits(const DH *dh) diff --git a/crypto/dh/dh_locl.h b/crypto/dh/dh_locl.h index 19301c31..0a8391a6 100644 --- a/crypto/dh/dh_locl.h +++ b/crypto/dh/dh_locl.h @@ -8,6 +8,7 @@ */ #include +#include "internal/refcount.h" struct dh_st { /* @@ -18,7 +19,7 @@ struct dh_st { int version; BIGNUM *p; BIGNUM *g; - long length; /* optional */ + int32_t length; /* optional */ BIGNUM *pub_key; /* g^x % p */ BIGNUM *priv_key; /* x */ int flags; @@ -29,7 +30,7 @@ struct dh_st { unsigned char *seed; int seedlen; BIGNUM *counter; - int references; + CRYPTO_REF_COUNT references; CRYPTO_EX_DATA ex_data; const DH_METHOD *meth; ENGINE *engine; diff --git a/crypto/dh/dh_pmeth.c b/crypto/dh/dh_pmeth.c index c3e03c7a..bd8b8cc6 100644 --- a/crypto/dh/dh_pmeth.c +++ b/crypto/dh/dh_pmeth.c @@ -26,9 +26,11 @@ typedef struct { int generator; int use_dsa; int subprime_len; + int pad; /* message digest used for parameter generation */ const EVP_MD *md; int rfc5114_param; + int param_nid; /* Keygen callback info */ int gentmp[2]; /* KDF (if any) to use for DH */ @@ -85,8 +87,10 @@ static int pkey_dh_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) dctx->subprime_len = sctx->subprime_len; dctx->generator = sctx->generator; dctx->use_dsa = sctx->use_dsa; + dctx->pad = sctx->pad; dctx->md = sctx->md; dctx->rfc5114_param = sctx->rfc5114_param; + dctx->param_nid = sctx->param_nid; dctx->kdf_type = sctx->kdf_type; dctx->kdf_oid = OBJ_dup(sctx->kdf_oid); @@ -119,6 +123,10 @@ static int pkey_dh_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) dctx->subprime_len = p1; return 1; + case EVP_PKEY_CTRL_DH_PAD: + dctx->pad = p1; + return 1; + case EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR: if (dctx->use_dsa) return -2; @@ -137,11 +145,17 @@ static int pkey_dh_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) return 1; case EVP_PKEY_CTRL_DH_RFC5114: - if (p1 < 1 || p1 > 3) + if (p1 < 1 || p1 > 3 || dctx->param_nid != NID_undef) return -2; dctx->rfc5114_param = p1; return 1; + case EVP_PKEY_CTRL_DH_NID: + if (p1 <= 0 || dctx->rfc5114_param != 0) + return -2; + dctx->param_nid = p1; + return 1; + case EVP_PKEY_CTRL_PEER_KEY: /* Default behaviour is OK */ return 1; @@ -221,6 +235,17 @@ static int pkey_dh_ctrl_str(EVP_PKEY_CTX *ctx, dctx->rfc5114_param = len; return 1; } + if (strcmp(type, "dh_param") == 0) { + DH_PKEY_CTX *dctx = ctx->data; + int nid = OBJ_sn2nid(value); + + if (nid == NID_undef) { + DHerr(DH_F_PKEY_DH_CTRL_STR, DH_R_INVALID_PARAMETER_NAME); + return -2; + } + dctx->param_nid = nid; + return 1; + } if (strcmp(type, "dh_paramgen_generator") == 0) { int len; len = atoi(value); @@ -236,6 +261,11 @@ static int pkey_dh_ctrl_str(EVP_PKEY_CTX *ctx, typ = atoi(value); return EVP_PKEY_CTX_set_dh_paramgen_type(ctx, typ); } + if (strcmp(type, "dh_pad") == 0) { + int pad; + pad = atoi(value); + return EVP_PKEY_CTX_set_dh_pad(ctx, pad); + } return -2; } @@ -320,6 +350,13 @@ static int pkey_dh_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) return 1; } + if (dctx->param_nid != 0) { + if ((dh = DH_new_by_nid(dctx->param_nid)) == NULL) + return 0; + EVP_PKEY_assign(pkey, EVP_PKEY_DH, dh); + return 1; + } + if (ctx->pkey_gencb) { pcb = BN_GENCB_new(); if (pcb == NULL) @@ -359,17 +396,22 @@ static int pkey_dh_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) static int pkey_dh_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { + DH_PKEY_CTX *dctx = ctx->data; DH *dh = NULL; - if (ctx->pkey == NULL) { + + if (ctx->pkey == NULL && dctx->param_nid == 0) { DHerr(DH_F_PKEY_DH_KEYGEN, DH_R_NO_PARAMETERS_SET); return 0; } - dh = DH_new(); + if (dctx->param_nid != 0) + dh = DH_new_by_nid(dctx->param_nid); + else + dh = DH_new(); if (dh == NULL) return 0; EVP_PKEY_assign(pkey, ctx->pmeth->pkey_id, dh); /* Note: if error return, pkey is freed by parent routine */ - if (!EVP_PKEY_copy_parameters(pkey, ctx->pkey)) + if (ctx->pkey != NULL && !EVP_PKEY_copy_parameters(pkey, ctx->pkey)) return 0; return DH_generate_key(pkey->pkey.dh); } @@ -392,7 +434,10 @@ static int pkey_dh_derive(EVP_PKEY_CTX *ctx, unsigned char *key, *keylen = DH_size(dh); return 1; } - ret = DH_compute_key(key, dhpub, dh); + if (dctx->pad) + ret = DH_compute_key_padded(key, dhpub, dh); + else + ret = DH_compute_key(key, dhpub, dh); if (ret < 0) return ret; *keylen = ret; diff --git a/crypto/dh/dh_prn.c b/crypto/dh/dh_prn.c index 283fb0f4..aab1733d 100644 --- a/crypto/dh/dh_prn.c +++ b/crypto/dh/dh_prn.c @@ -20,11 +20,11 @@ int DHparams_print_fp(FILE *fp, const DH *x) if ((b = BIO_new(BIO_s_file())) == NULL) { DHerr(DH_F_DHPARAMS_PRINT_FP, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = DHparams_print(b, x); BIO_free(b); - return (ret); + return ret; } #endif diff --git a/crypto/dh/dh_rfc7919.c b/crypto/dh/dh_rfc7919.c new file mode 100644 index 00000000..a54b468e --- /dev/null +++ b/crypto/dh/dh_rfc7919.c @@ -0,0 +1,74 @@ +/* + * 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 +#include "internal/cryptlib.h" +#include "dh_locl.h" +#include +#include +#include "internal/bn_dh.h" + +static DH *dh_param_init(const BIGNUM *p, int32_t nbits) +{ + DH *dh = DH_new(); + if (dh == NULL) + return NULL; + dh->p = (BIGNUM *)p; + dh->g = (BIGNUM *)&_bignum_const_2; + dh->length = nbits; + return dh; +} + +DH *DH_new_by_nid(int nid) +{ + switch (nid) { + case NID_ffdhe2048: + return dh_param_init(&_bignum_ffdhe2048_p, 225); + case NID_ffdhe3072: + return dh_param_init(&_bignum_ffdhe3072_p, 275); + case NID_ffdhe4096: + return dh_param_init(&_bignum_ffdhe4096_p, 325); + case NID_ffdhe6144: + return dh_param_init(&_bignum_ffdhe6144_p, 375); + case NID_ffdhe8192: + return dh_param_init(&_bignum_ffdhe8192_p, 400); + default: + DHerr(DH_F_DH_NEW_BY_NID, DH_R_INVALID_PARAMETER_NID); + return NULL; + } +} + +int DH_get_nid(const DH *dh) +{ + int nid; + + if (BN_get_word(dh->g) != 2) + return NID_undef; + if (!BN_cmp(dh->p, &_bignum_ffdhe2048_p)) + nid = NID_ffdhe2048; + else if (!BN_cmp(dh->p, &_bignum_ffdhe3072_p)) + nid = NID_ffdhe3072; + else if (!BN_cmp(dh->p, &_bignum_ffdhe4096_p)) + nid = NID_ffdhe4096; + else if (!BN_cmp(dh->p, &_bignum_ffdhe6144_p)) + nid = NID_ffdhe6144; + else if (!BN_cmp(dh->p, &_bignum_ffdhe8192_p)) + nid = NID_ffdhe8192; + else + return NID_undef; + if (dh->q != NULL) { + BIGNUM *q = BN_dup(dh->p); + + /* Check q = p * 2 + 1 we already know q is odd, so just shift right */ + if (q == NULL || !BN_rshift1(q, q) || !BN_cmp(dh->q, q)) + nid = NID_undef; + BN_free(q); + } + return nid; +} diff --git a/crypto/dllmain.c b/crypto/dllmain.c index 91904aad..81bcb2d0 100644 --- a/crypto/dllmain.c +++ b/crypto/dllmain.c @@ -1,5 +1,5 @@ /* - * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-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 @@ -7,6 +7,7 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" #include "internal/cryptlib_int.h" #if defined(_WIN32) || defined(__CYGWIN__) @@ -54,7 +55,7 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) case DLL_PROCESS_DETACH: break; } - return (TRUE); + return TRUE; } #endif diff --git a/crypto/dsa/dsa_ameth.c b/crypto/dsa/dsa_ameth.c index d4e4066c..9c5b8aa0 100644 --- a/crypto/dsa/dsa_ameth.c +++ b/crypto/dsa/dsa_ameth.c @@ -254,7 +254,7 @@ static int dsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) static int int_dsa_size(const EVP_PKEY *pkey) { - return (DSA_size(pkey->pkey.dsa)); + return DSA_size(pkey->pkey.dsa); } static int dsa_bits(const EVP_PKEY *pkey) @@ -369,7 +369,7 @@ static int do_dsa_print(BIO *bp, const DSA *x, int off, int ptype) goto err; ret = 1; err: - return (ret); + return ret; } static int dsa_param_decode(EVP_PKEY *pkey, diff --git a/crypto/dsa/dsa_asn1.c b/crypto/dsa/dsa_asn1.c index 551c1075..6499e87e 100644 --- a/crypto/dsa/dsa_asn1.c +++ b/crypto/dsa/dsa_asn1.c @@ -75,7 +75,7 @@ static int dsa_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, } ASN1_SEQUENCE_cb(DSAPrivateKey, dsa_cb) = { - ASN1_SIMPLE(DSA, version, LONG), + ASN1_EMBED(DSA, version, INT32), ASN1_SIMPLE(DSA, p, BIGNUM), ASN1_SIMPLE(DSA, q, BIGNUM), ASN1_SIMPLE(DSA, g, BIGNUM), @@ -111,15 +111,15 @@ int DSA_sign(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, DSA *dsa) { DSA_SIG *s; - RAND_seed(dgst, dlen); + s = DSA_do_sign(dgst, dlen, dsa); if (s == NULL) { *siglen = 0; - return (0); + return 0; } *siglen = i2d_DSA_SIG(s, &sig); DSA_SIG_free(s); - return (1); + return 1; } /* data has already been hashed (probably with SHA or SHA-1). */ @@ -140,7 +140,7 @@ int DSA_verify(int type, const unsigned char *dgst, int dgst_len, s = DSA_SIG_new(); if (s == NULL) - return (ret); + return ret; if (d2i_DSA_SIG(&s, &p, siglen) == NULL) goto err; /* Ensure signature uses DER and doesn't have trailing garbage */ @@ -151,5 +151,5 @@ int DSA_verify(int type, const unsigned char *dgst, int dgst_len, err: OPENSSL_clear_free(der, derlen); DSA_SIG_free(s); - return (ret); + return ret; } diff --git a/crypto/dsa/dsa_err.c b/crypto/dsa/dsa_err.c index b8f0af46..168dadf0 100644 --- a/crypto/dsa/dsa_err.c +++ b/crypto/dsa/dsa_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,56 +8,56 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_DSA,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_DSA,0,reason) - -static ERR_STRING_DATA DSA_str_functs[] = { - {ERR_FUNC(DSA_F_DSAPARAMS_PRINT), "DSAparams_print"}, - {ERR_FUNC(DSA_F_DSAPARAMS_PRINT_FP), "DSAparams_print_fp"}, - {ERR_FUNC(DSA_F_DSA_BUILTIN_PARAMGEN), "dsa_builtin_paramgen"}, - {ERR_FUNC(DSA_F_DSA_BUILTIN_PARAMGEN2), "dsa_builtin_paramgen2"}, - {ERR_FUNC(DSA_F_DSA_DO_SIGN), "DSA_do_sign"}, - {ERR_FUNC(DSA_F_DSA_DO_VERIFY), "DSA_do_verify"}, - {ERR_FUNC(DSA_F_DSA_METH_DUP), "DSA_meth_dup"}, - {ERR_FUNC(DSA_F_DSA_METH_NEW), "DSA_meth_new"}, - {ERR_FUNC(DSA_F_DSA_METH_SET1_NAME), "DSA_meth_set1_name"}, - {ERR_FUNC(DSA_F_DSA_NEW_METHOD), "DSA_new_method"}, - {ERR_FUNC(DSA_F_DSA_PARAM_DECODE), "dsa_param_decode"}, - {ERR_FUNC(DSA_F_DSA_PRINT_FP), "DSA_print_fp"}, - {ERR_FUNC(DSA_F_DSA_PRIV_DECODE), "dsa_priv_decode"}, - {ERR_FUNC(DSA_F_DSA_PRIV_ENCODE), "dsa_priv_encode"}, - {ERR_FUNC(DSA_F_DSA_PUB_DECODE), "dsa_pub_decode"}, - {ERR_FUNC(DSA_F_DSA_PUB_ENCODE), "dsa_pub_encode"}, - {ERR_FUNC(DSA_F_DSA_SIGN), "DSA_sign"}, - {ERR_FUNC(DSA_F_DSA_SIGN_SETUP), "DSA_sign_setup"}, - {ERR_FUNC(DSA_F_DSA_SIG_NEW), "DSA_SIG_new"}, - {ERR_FUNC(DSA_F_OLD_DSA_PRIV_DECODE), "old_dsa_priv_decode"}, - {ERR_FUNC(DSA_F_PKEY_DSA_CTRL), "pkey_dsa_ctrl"}, - {ERR_FUNC(DSA_F_PKEY_DSA_KEYGEN), "pkey_dsa_keygen"}, +static const ERR_STRING_DATA DSA_str_functs[] = { + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSAPARAMS_PRINT, 0), "DSAparams_print"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSAPARAMS_PRINT_FP, 0), "DSAparams_print_fp"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_BUILTIN_PARAMGEN, 0), + "dsa_builtin_paramgen"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_BUILTIN_PARAMGEN2, 0), + "dsa_builtin_paramgen2"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_DO_SIGN, 0), "DSA_do_sign"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_DO_VERIFY, 0), "DSA_do_verify"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_METH_DUP, 0), "DSA_meth_dup"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_METH_NEW, 0), "DSA_meth_new"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_METH_SET1_NAME, 0), "DSA_meth_set1_name"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_NEW_METHOD, 0), "DSA_new_method"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_PARAM_DECODE, 0), "dsa_param_decode"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_PRINT_FP, 0), "DSA_print_fp"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_PRIV_DECODE, 0), "dsa_priv_decode"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_PRIV_ENCODE, 0), "dsa_priv_encode"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_PUB_DECODE, 0), "dsa_pub_decode"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_PUB_ENCODE, 0), "dsa_pub_encode"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_SIGN, 0), "DSA_sign"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_SIGN_SETUP, 0), "DSA_sign_setup"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_DSA_SIG_NEW, 0), "DSA_SIG_new"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_OLD_DSA_PRIV_DECODE, 0), + "old_dsa_priv_decode"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_PKEY_DSA_CTRL, 0), "pkey_dsa_ctrl"}, + {ERR_PACK(ERR_LIB_DSA, DSA_F_PKEY_DSA_KEYGEN, 0), "pkey_dsa_keygen"}, {0, NULL} }; -static ERR_STRING_DATA DSA_str_reasons[] = { - {ERR_REASON(DSA_R_BAD_Q_VALUE), "bad q value"}, - {ERR_REASON(DSA_R_BN_DECODE_ERROR), "bn decode error"}, - {ERR_REASON(DSA_R_BN_ERROR), "bn error"}, - {ERR_REASON(DSA_R_DECODE_ERROR), "decode error"}, - {ERR_REASON(DSA_R_INVALID_DIGEST_TYPE), "invalid digest type"}, - {ERR_REASON(DSA_R_INVALID_PARAMETERS), "invalid parameters"}, - {ERR_REASON(DSA_R_MISSING_PARAMETERS), "missing parameters"}, - {ERR_REASON(DSA_R_MODULUS_TOO_LARGE), "modulus too large"}, - {ERR_REASON(DSA_R_NO_PARAMETERS_SET), "no parameters set"}, - {ERR_REASON(DSA_R_PARAMETER_ENCODING_ERROR), "parameter encoding error"}, - {ERR_REASON(DSA_R_Q_NOT_PRIME), "q not prime"}, - {ERR_REASON(DSA_R_SEED_LEN_SMALL), - "seed_len is less than the length of q"}, +static const ERR_STRING_DATA DSA_str_reasons[] = { + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BAD_Q_VALUE), "bad q value"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BN_DECODE_ERROR), "bn decode error"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_BN_ERROR), "bn error"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_DECODE_ERROR), "decode error"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_INVALID_DIGEST_TYPE), + "invalid digest type"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_INVALID_PARAMETERS), "invalid parameters"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_MISSING_PARAMETERS), "missing parameters"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_MODULUS_TOO_LARGE), "modulus too large"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_NO_PARAMETERS_SET), "no parameters set"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_PARAMETER_ENCODING_ERROR), + "parameter encoding error"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_Q_NOT_PRIME), "q not prime"}, + {ERR_PACK(ERR_LIB_DSA, 0, DSA_R_SEED_LEN_SMALL), + "seed_len is less than the length of q"}, {0, NULL} }; @@ -66,10 +66,9 @@ static ERR_STRING_DATA DSA_str_reasons[] = { int ERR_load_DSA_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(DSA_str_functs[0].error) == NULL) { - ERR_load_strings(0, DSA_str_functs); - ERR_load_strings(0, DSA_str_reasons); + ERR_load_strings_const(DSA_str_functs); + ERR_load_strings_const(DSA_str_reasons); } #endif return 1; diff --git a/crypto/dsa/dsa_key.c b/crypto/dsa/dsa_key.c index 31442b1c..a48af584 100644 --- a/crypto/dsa/dsa_key.c +++ b/crypto/dsa/dsa_key.c @@ -38,7 +38,7 @@ static int dsa_builtin_keygen(DSA *dsa) priv_key = dsa->priv_key; do - if (!BN_rand_range(priv_key, dsa->q)) + if (!BN_priv_rand_range(priv_key, dsa->q)) goto err; while (BN_is_zero(priv_key)) ; @@ -73,5 +73,5 @@ static int dsa_builtin_keygen(DSA *dsa) if (priv_key != dsa->priv_key) BN_free(priv_key); BN_CTX_free(ctx); - return (ok); + return ok; } diff --git a/crypto/dsa/dsa_lib.c b/crypto/dsa/dsa_lib.c index 9598846e..e730e8e6 100644 --- a/crypto/dsa/dsa_lib.c +++ b/crypto/dsa/dsa_lib.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -7,10 +7,9 @@ * https://www.openssl.org/source/license.html */ -/* Original version from Steven Schoch */ - #include #include "internal/cryptlib.h" +#include "internal/refcount.h" #include #include "dsa_locl.h" #include @@ -106,7 +105,7 @@ void DSA_free(DSA *r) if (r == NULL) return; - CRYPTO_atomic_add(&r->references, -1, &i, r->lock); + CRYPTO_DOWN_REF(&r->references, &i, r->lock); REF_PRINT_COUNT("DSA", r); if (i > 0) return; @@ -134,7 +133,7 @@ int DSA_up_ref(DSA *r) { int i; - if (CRYPTO_atomic_add(&r->references, 1, &i, r->lock) <= 0) + if (CRYPTO_UP_REF(&r->references, &i, r->lock) <= 0) return 0; REF_PRINT_COUNT("DSA", r); @@ -161,17 +160,17 @@ int DSA_size(const DSA *r) i = i2d_ASN1_INTEGER(&bs, NULL); i += i; /* r and s */ ret = ASN1_object_size(1, i, V_ASN1_SEQUENCE); - return (ret); + return ret; } int DSA_set_ex_data(DSA *d, int idx, void *arg) { - return (CRYPTO_set_ex_data(&d->ex_data, idx, arg)); + return CRYPTO_set_ex_data(&d->ex_data, idx, arg); } void *DSA_get_ex_data(DSA *d, int idx) { - return (CRYPTO_get_ex_data(&d->ex_data, idx)); + return CRYPTO_get_ex_data(&d->ex_data, idx); } int DSA_security_bits(const DSA *d) diff --git a/crypto/dsa/dsa_locl.h b/crypto/dsa/dsa_locl.h index 9021fce0..a81a4b49 100644 --- a/crypto/dsa/dsa_locl.h +++ b/crypto/dsa/dsa_locl.h @@ -8,6 +8,7 @@ */ #include +#include "internal/refcount.h" struct dsa_st { /* @@ -15,7 +16,7 @@ struct dsa_st { * instead of of a EVP_PKEY */ int pad; - long version; + int32_t version; BIGNUM *p; BIGNUM *q; /* == 20 */ BIGNUM *g; @@ -24,7 +25,7 @@ struct dsa_st { int flags; /* Normally used to cache montgomery values */ BN_MONT_CTX *method_mont_p; - int references; + CRYPTO_REF_COUNT references; CRYPTO_EX_DATA ex_data; const DSA_METHOD *meth; /* functional reference if 'meth' is ENGINE-provided */ diff --git a/crypto/dsa/dsa_meth.c b/crypto/dsa/dsa_meth.c index f0188f20..51a486b2 100644 --- a/crypto/dsa/dsa_meth.c +++ b/crypto/dsa/dsa_meth.c @@ -132,7 +132,7 @@ int DSA_meth_set_sign_setup(DSA_METHOD *dsam, } int (*DSA_meth_get_verify(const DSA_METHOD *dsam)) - (const unsigned char *, int , DSA_SIG *, DSA *) + (const unsigned char *, int, DSA_SIG *, DSA *) { return dsam->dsa_do_verify; } diff --git a/crypto/dsa/dsa_ossl.c b/crypto/dsa/dsa_ossl.c index 7f48cf2e..d78c5f00 100644 --- a/crypto/dsa/dsa_ossl.c +++ b/crypto/dsa/dsa_ossl.c @@ -7,8 +7,6 @@ * https://www.openssl.org/source/license.html */ -/* Original version from Steven Schoch */ - #include #include "internal/cryptlib.h" #include @@ -186,7 +184,7 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, if (!BN_generate_dsa_nonce(k, dsa->q, dsa->priv_key, dgst, dlen, ctx)) goto err; - } else if (!BN_rand_range(k, dsa->q)) + } else if (!BN_priv_rand_range(k, dsa->q)) goto err; } while (BN_is_zero(k)); @@ -349,17 +347,17 @@ static int dsa_do_verify(const unsigned char *dgst, int dgst_len, BN_free(u1); BN_free(u2); BN_free(t1); - return (ret); + return ret; } static int dsa_init(DSA *dsa) { dsa->flags |= DSA_FLAG_CACHE_MONT_P; - return (1); + return 1; } static int dsa_finish(DSA *dsa) { BN_MONT_CTX_free(dsa->method_mont_p); - return (1); + return 1; } diff --git a/crypto/dsa/dsa_pmeth.c b/crypto/dsa/dsa_pmeth.c index 95f088a5..88744a9c 100644 --- a/crypto/dsa/dsa_pmeth.c +++ b/crypto/dsa/dsa_pmeth.c @@ -31,8 +31,8 @@ typedef struct { static int pkey_dsa_init(EVP_PKEY_CTX *ctx) { - DSA_PKEY_CTX *dctx; - dctx = OPENSSL_malloc(sizeof(*dctx)); + DSA_PKEY_CTX *dctx = OPENSSL_malloc(sizeof(*dctx)); + if (dctx == NULL) return 0; dctx->nbits = 1024; @@ -50,6 +50,7 @@ static int pkey_dsa_init(EVP_PKEY_CTX *ctx) static int pkey_dsa_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { DSA_PKEY_CTX *dctx, *sctx; + if (!pkey_dsa_init(dst)) return 0; sctx = src->data; @@ -116,6 +117,7 @@ static int pkey_dsa_verify(EVP_PKEY_CTX *ctx, static int pkey_dsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { DSA_PKEY_CTX *dctx = ctx->data; + switch (type) { case EVP_PKEY_CTRL_DSA_PARAMGEN_BITS: if (p1 < 256) @@ -200,6 +202,7 @@ static int pkey_dsa_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) DSA_PKEY_CTX *dctx = ctx->data; BN_GENCB *pcb; int ret; + if (ctx->pkey_gencb) { pcb = BN_GENCB_new(); if (pcb == NULL) @@ -225,6 +228,7 @@ static int pkey_dsa_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) static int pkey_dsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { DSA *dsa = NULL; + if (ctx->pkey == NULL) { DSAerr(DSA_F_PKEY_DSA_KEYGEN, DSA_R_NO_PARAMETERS_SET); return 0; diff --git a/crypto/dsa/dsa_prn.c b/crypto/dsa/dsa_prn.c index f3c20ea0..a4a1fd56 100644 --- a/crypto/dsa/dsa_prn.c +++ b/crypto/dsa/dsa_prn.c @@ -20,12 +20,12 @@ int DSA_print_fp(FILE *fp, const DSA *x, int off) if ((b = BIO_new(BIO_s_file())) == NULL) { DSAerr(DSA_F_DSA_PRINT_FP, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = DSA_print(b, x, off); BIO_free(b); - return (ret); + return ret; } int DSAparams_print_fp(FILE *fp, const DSA *x) @@ -35,12 +35,12 @@ int DSAparams_print_fp(FILE *fp, const DSA *x) if ((b = BIO_new(BIO_s_file())) == NULL) { DSAerr(DSA_F_DSAPARAMS_PRINT_FP, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = DSAparams_print(b, x); BIO_free(b); - return (ret); + return ret; } #endif diff --git a/crypto/dsa/dsa_sign.c b/crypto/dsa/dsa_sign.c index 2e29d400..7057ea5a 100644 --- a/crypto/dsa/dsa_sign.c +++ b/crypto/dsa/dsa_sign.c @@ -7,8 +7,6 @@ * https://www.openssl.org/source/license.html */ -/* Original version from Steven Schoch */ - #include "internal/cryptlib.h" #include "dsa_locl.h" #include diff --git a/crypto/dsa/dsa_vrf.c b/crypto/dsa/dsa_vrf.c index a84d5212..21f98cd9 100644 --- a/crypto/dsa/dsa_vrf.c +++ b/crypto/dsa/dsa_vrf.c @@ -7,8 +7,6 @@ * https://www.openssl.org/source/license.html */ -/* Original version from Steven Schoch */ - #include "internal/cryptlib.h" #include "dsa_locl.h" diff --git a/crypto/dso/dso_dl.c b/crypto/dso/dso_dl.c index d80bf562..290d73cf 100644 --- a/crypto/dso/dso_dl.c +++ b/crypto/dso/dso_dl.c @@ -83,13 +83,13 @@ static int dl_load(DSO *dso) * (it also serves as the indicator that we are currently loaded). */ dso->loaded_filename = filename; - return (1); + return 1; err: /* Cleanup! */ OPENSSL_free(filename); if (ptr != NULL) shl_unload(ptr); - return (0); + return 0; } static int dl_unload(DSO *dso) @@ -97,10 +97,10 @@ static int dl_unload(DSO *dso) shl_t ptr; if (dso == NULL) { DSOerr(DSO_F_DL_UNLOAD, ERR_R_PASSED_NULL_PARAMETER); - return (0); + return 0; } if (sk_num(dso->meth_data) < 1) - return (1); + return 1; /* Is this statement legal? */ ptr = (shl_t) sk_pop(dso->meth_data); if (ptr == NULL) { @@ -109,10 +109,10 @@ static int dl_unload(DSO *dso) * Should push the value back onto the stack in case of a retry. */ sk_push(dso->meth_data, (char *)ptr); - return (0); + return 0; } shl_unload(ptr); - return (1); + return 1; } static DSO_FUNC_TYPE dl_bind_func(DSO *dso, const char *symname) @@ -122,25 +122,25 @@ static DSO_FUNC_TYPE dl_bind_func(DSO *dso, const char *symname) if ((dso == NULL) || (symname == NULL)) { DSOerr(DSO_F_DL_BIND_FUNC, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } if (sk_num(dso->meth_data) < 1) { DSOerr(DSO_F_DL_BIND_FUNC, DSO_R_STACK_ERROR); - return (NULL); + return NULL; } ptr = (shl_t) sk_value(dso->meth_data, sk_num(dso->meth_data) - 1); if (ptr == NULL) { DSOerr(DSO_F_DL_BIND_FUNC, DSO_R_NULL_HANDLE); - return (NULL); + return NULL; } if (shl_findsym(&ptr, symname, TYPE_UNDEFINED, &sym) < 0) { char errbuf[160]; DSOerr(DSO_F_DL_BIND_FUNC, DSO_R_SYM_FAILURE); if (openssl_strerror_r(errno, errbuf, sizeof(errbuf))) ERR_add_error_data(4, "symname(", symname, "): ", errbuf); - return (NULL); + return NULL; } - return ((DSO_FUNC_TYPE)sym); + return (DSO_FUNC_TYPE)sym; } static char *dl_merger(DSO *dso, const char *filespec1, const char *filespec2) @@ -149,7 +149,7 @@ static char *dl_merger(DSO *dso, const char *filespec1, const char *filespec2) if (!filespec1 && !filespec2) { DSOerr(DSO_F_DL_MERGER, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } /* * If the first file specification is a rooted path, it rules. same goes @@ -159,7 +159,7 @@ static char *dl_merger(DSO *dso, const char *filespec1, const char *filespec2) merged = OPENSSL_strdup(filespec1); if (merged == NULL) { DSOerr(DSO_F_DL_MERGER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } } /* @@ -169,7 +169,7 @@ static char *dl_merger(DSO *dso, const char *filespec1, const char *filespec2) merged = OPENSSL_strdup(filespec2); if (merged == NULL) { DSOerr(DSO_F_DL_MERGER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } } else /* @@ -192,13 +192,13 @@ static char *dl_merger(DSO *dso, const char *filespec1, const char *filespec2) merged = OPENSSL_malloc(len + 2); if (merged == NULL) { DSOerr(DSO_F_DL_MERGER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } strcpy(merged, filespec2); merged[spec2len] = '/'; strcpy(&merged[spec2len + 1], filespec1); } - return (merged); + return merged; } /* @@ -225,7 +225,7 @@ static char *dl_name_converter(DSO *dso, const char *filename) translated = OPENSSL_malloc(rsize); if (translated == NULL) { DSOerr(DSO_F_DL_NAME_CONVERTER, DSO_R_NAME_TRANSLATION_FAILED); - return (NULL); + return NULL; } if (transform) { if ((DSO_flags(dso) & DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == 0) @@ -234,7 +234,7 @@ static char *dl_name_converter(DSO *dso, const char *filename) sprintf(translated, "%s%s", filename, DSO_EXTENSION); } else sprintf(translated, "%s", filename); - return (translated); + return translated; } static int dl_pathbyaddr(void *addr, char *path, int sz) diff --git a/crypto/dso/dso_dlfcn.c b/crypto/dso/dso_dlfcn.c index a4b0cdd9..26f98bfc 100644 --- a/crypto/dso/dso_dlfcn.c +++ b/crypto/dso/dso_dlfcn.c @@ -120,13 +120,13 @@ static int dlfcn_load(DSO *dso) } /* Success */ dso->loaded_filename = filename; - return (1); + return 1; err: /* Cleanup! */ OPENSSL_free(filename); if (ptr != NULL) dlclose(ptr); - return (0); + return 0; } static int dlfcn_unload(DSO *dso) @@ -134,10 +134,10 @@ static int dlfcn_unload(DSO *dso) void *ptr; if (dso == NULL) { DSOerr(DSO_F_DLFCN_UNLOAD, ERR_R_PASSED_NULL_PARAMETER); - return (0); + return 0; } if (sk_void_num(dso->meth_data) < 1) - return (1); + return 1; ptr = sk_void_pop(dso->meth_data); if (ptr == NULL) { DSOerr(DSO_F_DLFCN_UNLOAD, DSO_R_NULL_HANDLE); @@ -145,11 +145,11 @@ static int dlfcn_unload(DSO *dso) * Should push the value back onto the stack in case of a retry. */ sk_void_push(dso->meth_data, ptr); - return (0); + return 0; } /* For now I'm not aware of any errors associated with dlclose() */ dlclose(ptr); - return (1); + return 1; } static DSO_FUNC_TYPE dlfcn_bind_func(DSO *dso, const char *symname) @@ -162,22 +162,22 @@ static DSO_FUNC_TYPE dlfcn_bind_func(DSO *dso, const char *symname) if ((dso == NULL) || (symname == NULL)) { DSOerr(DSO_F_DLFCN_BIND_FUNC, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } if (sk_void_num(dso->meth_data) < 1) { DSOerr(DSO_F_DLFCN_BIND_FUNC, DSO_R_STACK_ERROR); - return (NULL); + return NULL; } ptr = sk_void_value(dso->meth_data, sk_void_num(dso->meth_data) - 1); if (ptr == NULL) { DSOerr(DSO_F_DLFCN_BIND_FUNC, DSO_R_NULL_HANDLE); - return (NULL); + return NULL; } u.dlret = dlsym(ptr, symname); if (u.dlret == NULL) { DSOerr(DSO_F_DLFCN_BIND_FUNC, DSO_R_SYM_FAILURE); ERR_add_error_data(4, "symname(", symname, "): ", dlerror()); - return (NULL); + return NULL; } return u.sym; } @@ -189,7 +189,7 @@ static char *dlfcn_merger(DSO *dso, const char *filespec1, if (!filespec1 && !filespec2) { DSOerr(DSO_F_DLFCN_MERGER, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } /* * If the first file specification is a rooted path, it rules. same goes @@ -199,7 +199,7 @@ static char *dlfcn_merger(DSO *dso, const char *filespec1, merged = OPENSSL_strdup(filespec1); if (merged == NULL) { DSOerr(DSO_F_DLFCN_MERGER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } } /* @@ -209,7 +209,7 @@ static char *dlfcn_merger(DSO *dso, const char *filespec1, merged = OPENSSL_strdup(filespec2); if (merged == NULL) { DSOerr(DSO_F_DLFCN_MERGER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } } else { /* @@ -231,13 +231,13 @@ static char *dlfcn_merger(DSO *dso, const char *filespec1, merged = OPENSSL_malloc(len + 2); if (merged == NULL) { DSOerr(DSO_F_DLFCN_MERGER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } strcpy(merged, filespec2); merged[spec2len] = '/'; strcpy(&merged[spec2len + 1], filespec1); } - return (merged); + return merged; } static char *dlfcn_name_converter(DSO *dso, const char *filename) @@ -257,7 +257,7 @@ static char *dlfcn_name_converter(DSO *dso, const char *filename) translated = OPENSSL_malloc(rsize); if (translated == NULL) { DSOerr(DSO_F_DLFCN_NAME_CONVERTER, DSO_R_NAME_TRANSLATION_FAILED); - return (NULL); + return NULL; } if (transform) { if ((DSO_flags(dso) & DSO_FLAG_NAME_TRANSLATION_EXT_ONLY) == 0) @@ -266,7 +266,7 @@ static char *dlfcn_name_converter(DSO *dso, const char *filename) sprintf(translated, "%s" DSO_EXTENSION, filename); } else sprintf(translated, "%s", filename); - return (translated); + return translated; } # ifdef __sgi diff --git a/crypto/dso/dso_err.c b/crypto/dso/dso_err.c index 07588d5c..613072a8 100644 --- a/crypto/dso/dso_err.c +++ b/crypto/dso/dso_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,73 +8,81 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include "internal/dso.h" +#include "internal/dsoerr.h" -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_DSO,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_DSO,0,reason) - -static ERR_STRING_DATA DSO_str_functs[] = { - {ERR_FUNC(DSO_F_DLFCN_BIND_FUNC), "dlfcn_bind_func"}, - {ERR_FUNC(DSO_F_DLFCN_LOAD), "dlfcn_load"}, - {ERR_FUNC(DSO_F_DLFCN_MERGER), "dlfcn_merger"}, - {ERR_FUNC(DSO_F_DLFCN_NAME_CONVERTER), "dlfcn_name_converter"}, - {ERR_FUNC(DSO_F_DLFCN_UNLOAD), "dlfcn_unload"}, - {ERR_FUNC(DSO_F_DL_BIND_FUNC), "dl_bind_func"}, - {ERR_FUNC(DSO_F_DL_LOAD), "dl_load"}, - {ERR_FUNC(DSO_F_DL_MERGER), "dl_merger"}, - {ERR_FUNC(DSO_F_DL_NAME_CONVERTER), "dl_name_converter"}, - {ERR_FUNC(DSO_F_DL_UNLOAD), "dl_unload"}, - {ERR_FUNC(DSO_F_DSO_BIND_FUNC), "DSO_bind_func"}, - {ERR_FUNC(DSO_F_DSO_CONVERT_FILENAME), "DSO_convert_filename"}, - {ERR_FUNC(DSO_F_DSO_CTRL), "DSO_ctrl"}, - {ERR_FUNC(DSO_F_DSO_FREE), "DSO_free"}, - {ERR_FUNC(DSO_F_DSO_GET_FILENAME), "DSO_get_filename"}, - {ERR_FUNC(DSO_F_DSO_GLOBAL_LOOKUP), "DSO_global_lookup"}, - {ERR_FUNC(DSO_F_DSO_LOAD), "DSO_load"}, - {ERR_FUNC(DSO_F_DSO_MERGE), "DSO_merge"}, - {ERR_FUNC(DSO_F_DSO_NEW_METHOD), "DSO_new_method"}, - {ERR_FUNC(DSO_F_DSO_PATHBYADDR), "DSO_pathbyaddr"}, - {ERR_FUNC(DSO_F_DSO_SET_FILENAME), "DSO_set_filename"}, - {ERR_FUNC(DSO_F_DSO_UP_REF), "DSO_up_ref"}, - {ERR_FUNC(DSO_F_VMS_BIND_SYM), "vms_bind_sym"}, - {ERR_FUNC(DSO_F_VMS_LOAD), "vms_load"}, - {ERR_FUNC(DSO_F_VMS_MERGER), "vms_merger"}, - {ERR_FUNC(DSO_F_VMS_UNLOAD), "vms_unload"}, - {ERR_FUNC(DSO_F_WIN32_BIND_FUNC), "win32_bind_func"}, - {ERR_FUNC(DSO_F_WIN32_GLOBALLOOKUP), "win32_globallookup"}, - {ERR_FUNC(DSO_F_WIN32_JOINER), "win32_joiner"}, - {ERR_FUNC(DSO_F_WIN32_LOAD), "win32_load"}, - {ERR_FUNC(DSO_F_WIN32_MERGER), "win32_merger"}, - {ERR_FUNC(DSO_F_WIN32_NAME_CONVERTER), "win32_name_converter"}, - {ERR_FUNC(DSO_F_WIN32_PATHBYADDR), "win32_pathbyaddr"}, - {ERR_FUNC(DSO_F_WIN32_SPLITTER), "win32_splitter"}, - {ERR_FUNC(DSO_F_WIN32_UNLOAD), "win32_unload"}, +static const ERR_STRING_DATA DSO_str_functs[] = { + {ERR_PACK(ERR_LIB_DSO, DSO_F_DLFCN_BIND_FUNC, 0), "dlfcn_bind_func"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DLFCN_LOAD, 0), "dlfcn_load"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DLFCN_MERGER, 0), "dlfcn_merger"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DLFCN_NAME_CONVERTER, 0), + "dlfcn_name_converter"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DLFCN_UNLOAD, 0), "dlfcn_unload"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DL_BIND_FUNC, 0), "dl_bind_func"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DL_LOAD, 0), "dl_load"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DL_MERGER, 0), "dl_merger"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DL_NAME_CONVERTER, 0), "dl_name_converter"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DL_UNLOAD, 0), "dl_unload"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_BIND_FUNC, 0), "DSO_bind_func"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_CONVERT_FILENAME, 0), + "DSO_convert_filename"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_CTRL, 0), "DSO_ctrl"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_FREE, 0), "DSO_free"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_GET_FILENAME, 0), "DSO_get_filename"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_GLOBAL_LOOKUP, 0), "DSO_global_lookup"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_LOAD, 0), "DSO_load"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_MERGE, 0), "DSO_merge"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_NEW_METHOD, 0), "DSO_new_method"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_PATHBYADDR, 0), "DSO_pathbyaddr"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_SET_FILENAME, 0), "DSO_set_filename"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_DSO_UP_REF, 0), "DSO_up_ref"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_VMS_BIND_SYM, 0), "vms_bind_sym"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_VMS_LOAD, 0), "vms_load"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_VMS_MERGER, 0), "vms_merger"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_VMS_UNLOAD, 0), "vms_unload"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_WIN32_BIND_FUNC, 0), "win32_bind_func"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_WIN32_GLOBALLOOKUP, 0), "win32_globallookup"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_WIN32_JOINER, 0), "win32_joiner"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_WIN32_LOAD, 0), "win32_load"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_WIN32_MERGER, 0), "win32_merger"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_WIN32_NAME_CONVERTER, 0), + "win32_name_converter"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_WIN32_PATHBYADDR, 0), ""}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_WIN32_SPLITTER, 0), "win32_splitter"}, + {ERR_PACK(ERR_LIB_DSO, DSO_F_WIN32_UNLOAD, 0), "win32_unload"}, {0, NULL} }; -static ERR_STRING_DATA DSO_str_reasons[] = { - {ERR_REASON(DSO_R_CTRL_FAILED), "control command failed"}, - {ERR_REASON(DSO_R_DSO_ALREADY_LOADED), "dso already loaded"}, - {ERR_REASON(DSO_R_EMPTY_FILE_STRUCTURE), "empty file structure"}, - {ERR_REASON(DSO_R_FAILURE), "failure"}, - {ERR_REASON(DSO_R_FILENAME_TOO_BIG), "filename too big"}, - {ERR_REASON(DSO_R_FINISH_FAILED), "cleanup method function failed"}, - {ERR_REASON(DSO_R_INCORRECT_FILE_SYNTAX), "incorrect file syntax"}, - {ERR_REASON(DSO_R_LOAD_FAILED), "could not load the shared library"}, - {ERR_REASON(DSO_R_NAME_TRANSLATION_FAILED), "name translation failed"}, - {ERR_REASON(DSO_R_NO_FILENAME), "no filename"}, - {ERR_REASON(DSO_R_NULL_HANDLE), "a null shared library handle was used"}, - {ERR_REASON(DSO_R_SET_FILENAME_FAILED), "set filename failed"}, - {ERR_REASON(DSO_R_STACK_ERROR), "the meth_data stack is corrupt"}, - {ERR_REASON(DSO_R_SYM_FAILURE), - "could not bind to the requested symbol name"}, - {ERR_REASON(DSO_R_UNLOAD_FAILED), "could not unload the shared library"}, - {ERR_REASON(DSO_R_UNSUPPORTED), "functionality not supported"}, +static const ERR_STRING_DATA DSO_str_reasons[] = { + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_CTRL_FAILED), "control command failed"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_DSO_ALREADY_LOADED), "dso already loaded"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_EMPTY_FILE_STRUCTURE), + "empty file structure"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_FAILURE), "failure"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_FILENAME_TOO_BIG), "filename too big"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_FINISH_FAILED), + "cleanup method function failed"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_INCORRECT_FILE_SYNTAX), + "incorrect file syntax"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_LOAD_FAILED), + "could not load the shared library"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_NAME_TRANSLATION_FAILED), + "name translation failed"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_NO_FILENAME), "no filename"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_NULL_HANDLE), + "a null shared library handle was used"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_SET_FILENAME_FAILED), + "set filename failed"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_STACK_ERROR), + "the meth_data stack is corrupt"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_SYM_FAILURE), + "could not bind to the requested symbol name"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_UNLOAD_FAILED), + "could not unload the shared library"}, + {ERR_PACK(ERR_LIB_DSO, 0, DSO_R_UNSUPPORTED), + "functionality not supported"}, {0, NULL} }; @@ -83,10 +91,9 @@ static ERR_STRING_DATA DSO_str_reasons[] = { int ERR_load_DSO_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(DSO_str_functs[0].error) == NULL) { - ERR_load_strings(0, DSO_str_functs); - ERR_load_strings(0, DSO_str_reasons); + ERR_load_strings_const(DSO_str_functs); + ERR_load_strings_const(DSO_str_reasons); } #endif return 1; diff --git a/crypto/dso/dso_lib.c b/crypto/dso/dso_lib.c index f58237d6..2e75021d 100644 --- a/crypto/dso/dso_lib.c +++ b/crypto/dso/dso_lib.c @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-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 @@ -8,6 +8,7 @@ */ #include "dso_locl.h" +#include "internal/refcount.h" static DSO_METHOD *default_DSO_meth = NULL; @@ -26,14 +27,14 @@ static DSO *DSO_new_method(DSO_METHOD *meth) ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) { DSOerr(DSO_F_DSO_NEW_METHOD, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } ret->meth_data = sk_void_new_null(); if (ret->meth_data == NULL) { /* sk_new doesn't generate any errors so we do */ DSOerr(DSO_F_DSO_NEW_METHOD, ERR_R_MALLOC_FAILURE); OPENSSL_free(ret); - return (NULL); + return NULL; } ret->meth = default_DSO_meth; ret->references = 1; @@ -63,9 +64,9 @@ int DSO_free(DSO *dso) int i; if (dso == NULL) - return (1); + return 1; - if (CRYPTO_atomic_add(&dso->references, -1, &i, dso->lock) <= 0) + if (CRYPTO_DOWN_REF(&dso->references, &i, dso->lock) <= 0) return 0; REF_PRINT_COUNT("DSO", dso); @@ -107,7 +108,7 @@ int DSO_up_ref(DSO *dso) return 0; } - if (CRYPTO_atomic_add(&dso->references, 1, &i, dso->lock) <= 0) + if (CRYPTO_UP_REF(&dso->references, &i, dso->lock) <= 0) return 0; REF_PRINT_COUNT("DSO", r); @@ -162,11 +163,11 @@ DSO *DSO_load(DSO *dso, const char *filename, DSO_METHOD *meth, int flags) goto err; } /* Load succeeded */ - return (ret); + return ret; err: if (allocated) DSO_free(ret); - return (NULL); + return NULL; } DSO_FUNC_TYPE DSO_bind_func(DSO *dso, const char *symname) @@ -175,18 +176,18 @@ DSO_FUNC_TYPE DSO_bind_func(DSO *dso, const char *symname) if ((dso == NULL) || (symname == NULL)) { DSOerr(DSO_F_DSO_BIND_FUNC, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } if (dso->meth->dso_bind_func == NULL) { DSOerr(DSO_F_DSO_BIND_FUNC, DSO_R_UNSUPPORTED); - return (NULL); + return NULL; } if ((ret = dso->meth->dso_bind_func(dso, symname)) == NULL) { DSOerr(DSO_F_DSO_BIND_FUNC, DSO_R_SYM_FAILURE); - return (NULL); + return NULL; } /* Success */ - return (ret); + return ret; } /* @@ -202,7 +203,7 @@ long DSO_ctrl(DSO *dso, int cmd, long larg, void *parg) { if (dso == NULL) { DSOerr(DSO_F_DSO_CTRL, ERR_R_PASSED_NULL_PARAMETER); - return (-1); + return -1; } /* * We should intercept certain generic commands and only pass control to @@ -213,27 +214,27 @@ long DSO_ctrl(DSO *dso, int cmd, long larg, void *parg) return dso->flags; case DSO_CTRL_SET_FLAGS: dso->flags = (int)larg; - return (0); + return 0; case DSO_CTRL_OR_FLAGS: dso->flags |= (int)larg; - return (0); + return 0; default: break; } if ((dso->meth == NULL) || (dso->meth->dso_ctrl == NULL)) { DSOerr(DSO_F_DSO_CTRL, DSO_R_UNSUPPORTED); - return (-1); + return -1; } - return (dso->meth->dso_ctrl(dso, cmd, larg, parg)); + return dso->meth->dso_ctrl(dso, cmd, larg, parg); } const char *DSO_get_filename(DSO *dso) { if (dso == NULL) { DSOerr(DSO_F_DSO_GET_FILENAME, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } - return (dso->filename); + return dso->filename; } int DSO_set_filename(DSO *dso, const char *filename) @@ -242,21 +243,21 @@ int DSO_set_filename(DSO *dso, const char *filename) if ((dso == NULL) || (filename == NULL)) { DSOerr(DSO_F_DSO_SET_FILENAME, ERR_R_PASSED_NULL_PARAMETER); - return (0); + return 0; } if (dso->loaded_filename) { DSOerr(DSO_F_DSO_SET_FILENAME, DSO_R_DSO_ALREADY_LOADED); - return (0); + return 0; } /* We'll duplicate filename */ copied = OPENSSL_strdup(filename); if (copied == NULL) { DSOerr(DSO_F_DSO_SET_FILENAME, ERR_R_MALLOC_FAILURE); - return (0); + return 0; } OPENSSL_free(dso->filename); dso->filename = copied; - return (1); + return 1; } char *DSO_merge(DSO *dso, const char *filespec1, const char *filespec2) @@ -265,7 +266,7 @@ char *DSO_merge(DSO *dso, const char *filespec1, const char *filespec2) if (dso == NULL || filespec1 == NULL) { DSOerr(DSO_F_DSO_MERGE, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } if ((dso->flags & DSO_FLAG_NO_NAME_TRANSLATION) == 0) { if (dso->merger != NULL) @@ -273,7 +274,7 @@ char *DSO_merge(DSO *dso, const char *filespec1, const char *filespec2) else if (dso->meth->dso_merger != NULL) result = dso->meth->dso_merger(dso, filespec1, filespec2); } - return (result); + return result; } char *DSO_convert_filename(DSO *dso, const char *filename) @@ -282,13 +283,13 @@ char *DSO_convert_filename(DSO *dso, const char *filename) if (dso == NULL) { DSOerr(DSO_F_DSO_CONVERT_FILENAME, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } if (filename == NULL) filename = dso->filename; if (filename == NULL) { DSOerr(DSO_F_DSO_CONVERT_FILENAME, DSO_R_NO_FILENAME); - return (NULL); + return NULL; } if ((dso->flags & DSO_FLAG_NO_NAME_TRANSLATION) == 0) { if (dso->name_converter != NULL) @@ -300,10 +301,10 @@ char *DSO_convert_filename(DSO *dso, const char *filename) result = OPENSSL_strdup(filename); if (result == NULL) { DSOerr(DSO_F_DSO_CONVERT_FILENAME, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } } - return (result); + return result; } int DSO_pathbyaddr(void *addr, char *path, int sz) diff --git a/crypto/dso/dso_locl.h b/crypto/dso/dso_locl.h index fbfad054..14a0ccb7 100644 --- a/crypto/dso/dso_locl.h +++ b/crypto/dso/dso_locl.h @@ -11,6 +11,7 @@ #include "internal/cryptlib.h" #include "internal/dso.h" #include "internal/dso_conf.h" +#include "internal/refcount.h" /**********************************************************************/ /* The low-level handle type used to refer to a loaded shared library */ @@ -24,7 +25,7 @@ struct dso_st { * "Handles" and such go in a STACK. */ STACK_OF(void) *meth_data; - int references; + CRYPTO_REF_COUNT references; int flags; /* * For use by applications etc ... use this for your bits'n'pieces, don't diff --git a/crypto/dso/dso_vms.c b/crypto/dso/dso_vms.c index b9a98ddd..178e7257 100644 --- a/crypto/dso/dso_vms.c +++ b/crypto/dso/dso_vms.c @@ -207,12 +207,12 @@ static int vms_load(DSO *dso) /* Success (for now, we lie. We actually do not know...) */ dso->loaded_filename = filename; - return (1); + return 1; err: /* Cleanup! */ OPENSSL_free(p); OPENSSL_free(filename); - return (0); + return 0; } /* @@ -225,18 +225,18 @@ static int vms_unload(DSO *dso) DSO_VMS_INTERNAL *p; if (dso == NULL) { DSOerr(DSO_F_VMS_UNLOAD, ERR_R_PASSED_NULL_PARAMETER); - return (0); + return 0; } if (sk_void_num(dso->meth_data) < 1) - return (1); + return 1; p = (DSO_VMS_INTERNAL *)sk_void_pop(dso->meth_data); if (p == NULL) { DSOerr(DSO_F_VMS_UNLOAD, DSO_R_NULL_HANDLE); - return (0); + return 0; } /* Cleanup */ OPENSSL_free(p); - return (1); + return 1; } /* @@ -263,15 +263,13 @@ static int do_find_symbol(DSO_VMS_INTERNAL *ptr, symname_dsc, sym, 0, flags); } +# ifndef LIB$M_FIS_MIXEDCASE +# define LIB$M_FIS_MIXEDCASE (1 << 4); +# endif void vms_bind_sym(DSO *dso, const char *symname, void **sym) { DSO_VMS_INTERNAL *ptr; - int status; -# ifdef LIB$M_FIS_MIXEDCASE - int flags = LIB$M_FIS_MIXEDCASE; -# else - int flags = (1 << 4); -# endif + int status = 0; struct dsc$descriptor_s symname_dsc; /* Arrange 32-bit pointer to (copied) string storage, if needed. */ @@ -314,10 +312,10 @@ void vms_bind_sym(DSO *dso, const char *symname, void **sym) return; } - if (dso->flags & DSO_FLAG_UPCASE_SYMBOL) - flags = 0; + status = do_find_symbol(ptr, &symname_dsc, sym, LIB$M_FIS_MIXEDCASE); - status = do_find_symbol(ptr, &symname_dsc, sym, flags); + if (!$VMS_STATUS_SUCCESS(status)) + status = do_find_symbol(ptr, &symname_dsc, sym, 0); if (!$VMS_STATUS_SUCCESS(status)) { unsigned short length; @@ -443,7 +441,7 @@ static char *vms_merger(DSO *dso, const char *filespec1, "filespec \"", filespec1, "\", ", "defaults \"", filespec2, "\": ", errstring); } - return (NULL); + return NULL; } merged = OPENSSL_malloc(nam.NAMX_ESL + 1); @@ -451,7 +449,7 @@ static char *vms_merger(DSO *dso, const char *filespec1, goto malloc_err; strncpy(merged, nam.NAMX_ESA, nam.NAMX_ESL); merged[nam.NAMX_ESL] = '\0'; - return (merged); + return merged; malloc_err: DSOerr(DSO_F_VMS_MERGER, ERR_R_MALLOC_FAILURE); } @@ -462,7 +460,7 @@ static char *vms_name_converter(DSO *dso, const char *filename) char *not_translated = OPENSSL_malloc(len + 1); if (not_translated != NULL) strcpy(not_translated, filename); - return (not_translated); + return not_translated; } #endif /* OPENSSL_SYS_VMS */ diff --git a/crypto/dso/dso_win32.c b/crypto/dso/dso_win32.c index 4a4c34ab..0bbf5b51 100644 --- a/crypto/dso/dso_win32.c +++ b/crypto/dso/dso_win32.c @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-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 @@ -7,6 +7,7 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" #include "dso_locl.h" #if defined(DSO_WIN32) @@ -119,14 +120,14 @@ static int win32_load(DSO *dso) } /* Success */ dso->loaded_filename = filename; - return (1); + return 1; err: /* Cleanup ! */ OPENSSL_free(filename); OPENSSL_free(p); if (h != NULL) FreeLibrary(h); - return (0); + return 0; } static int win32_unload(DSO *dso) @@ -134,14 +135,14 @@ static int win32_unload(DSO *dso) HINSTANCE *p; if (dso == NULL) { DSOerr(DSO_F_WIN32_UNLOAD, ERR_R_PASSED_NULL_PARAMETER); - return (0); + return 0; } if (sk_void_num(dso->meth_data) < 1) - return (1); + return 1; p = sk_void_pop(dso->meth_data); if (p == NULL) { DSOerr(DSO_F_WIN32_UNLOAD, DSO_R_NULL_HANDLE); - return (0); + return 0; } if (!FreeLibrary(*p)) { DSOerr(DSO_F_WIN32_UNLOAD, DSO_R_UNLOAD_FAILED); @@ -149,11 +150,11 @@ static int win32_unload(DSO *dso) * We should push the value back onto the stack in case of a retry. */ sk_void_push(dso->meth_data, p); - return (0); + return 0; } /* Cleanup */ OPENSSL_free(p); - return (1); + return 1; } static DSO_FUNC_TYPE win32_bind_func(DSO *dso, const char *symname) @@ -166,24 +167,24 @@ static DSO_FUNC_TYPE win32_bind_func(DSO *dso, const char *symname) if ((dso == NULL) || (symname == NULL)) { DSOerr(DSO_F_WIN32_BIND_FUNC, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } if (sk_void_num(dso->meth_data) < 1) { DSOerr(DSO_F_WIN32_BIND_FUNC, DSO_R_STACK_ERROR); - return (NULL); + return NULL; } ptr = sk_void_value(dso->meth_data, sk_void_num(dso->meth_data) - 1); if (ptr == NULL) { DSOerr(DSO_F_WIN32_BIND_FUNC, DSO_R_NULL_HANDLE); - return (NULL); + return NULL; } sym.f = GetProcAddress(*ptr, symname); if (sym.p == NULL) { DSOerr(DSO_F_WIN32_BIND_FUNC, DSO_R_SYM_FAILURE); ERR_add_error_data(3, "symname(", symname, ")"); - return (NULL); + return NULL; } - return ((DSO_FUNC_TYPE)sym.f); + return (DSO_FUNC_TYPE)sym.f; } struct file_st { @@ -209,16 +210,13 @@ static struct file_st *win32_splitter(DSO *dso, const char *filename, if (!filename) { DSOerr(DSO_F_WIN32_SPLITTER, DSO_R_NO_FILENAME); - /* - * goto err; - */ - return (NULL); + return NULL; } result = OPENSSL_zalloc(sizeof(*result)); if (result == NULL) { DSOerr(DSO_F_WIN32_SPLITTER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } position = IN_DEVICE; @@ -237,11 +235,8 @@ static struct file_st *win32_splitter(DSO *dso, const char *filename, case ':': if (position != IN_DEVICE) { DSOerr(DSO_F_WIN32_SPLITTER, DSO_R_INCORRECT_FILE_SYNTAX); - /* - * goto err; - */ OPENSSL_free(result); - return (NULL); + return NULL; } result->device = start; result->devicelen = (int)(filename - start); @@ -302,7 +297,7 @@ static struct file_st *win32_splitter(DSO *dso, const char *filename, if (!result->filelen) result->file = NULL; - return (result); + return result; } static char *win32_joiner(DSO *dso, const struct file_st *file_split) @@ -313,7 +308,7 @@ static char *win32_joiner(DSO *dso, const struct file_st *file_split) if (!file_split) { DSOerr(DSO_F_WIN32_JOINER, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } if (file_split->node) { len += 2 + file_split->nodelen; /* 2 for starting \\ */ @@ -334,13 +329,13 @@ static char *win32_joiner(DSO *dso, const struct file_st *file_split) if (!len) { DSOerr(DSO_F_WIN32_JOINER, DSO_R_EMPTY_FILE_STRUCTURE); - return (NULL); + return NULL; } result = OPENSSL_malloc(len + 1); if (result == NULL) { DSOerr(DSO_F_WIN32_JOINER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } if (file_split->node) { @@ -388,7 +383,7 @@ static char *win32_joiner(DSO *dso, const struct file_st *file_split) strncpy(&result[offset], file_split->file, file_split->filelen); offset += file_split->filelen; result[offset] = '\0'; - return (result); + return result; } static char *win32_merger(DSO *dso, const char *filespec1, @@ -400,33 +395,31 @@ static char *win32_merger(DSO *dso, const char *filespec1, if (!filespec1 && !filespec2) { DSOerr(DSO_F_WIN32_MERGER, ERR_R_PASSED_NULL_PARAMETER); - return (NULL); + return NULL; } if (!filespec2) { - merged = OPENSSL_malloc(strlen(filespec1) + 1); + merged = OPENSSL_strdup(filespec1); if (merged == NULL) { DSOerr(DSO_F_WIN32_MERGER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } - strcpy(merged, filespec1); } else if (!filespec1) { - merged = OPENSSL_malloc(strlen(filespec2) + 1); + merged = OPENSSL_strdup(filespec2); if (merged == NULL) { DSOerr(DSO_F_WIN32_MERGER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } - strcpy(merged, filespec2); } else { filespec1_split = win32_splitter(dso, filespec1, 0); if (!filespec1_split) { DSOerr(DSO_F_WIN32_MERGER, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } filespec2_split = win32_splitter(dso, filespec2, 1); if (!filespec2_split) { DSOerr(DSO_F_WIN32_MERGER, ERR_R_MALLOC_FAILURE); OPENSSL_free(filespec1_split); - return (NULL); + return NULL; } /* Fill in into filespec1_split */ @@ -453,7 +446,7 @@ static char *win32_merger(DSO *dso, const char *filespec1, } OPENSSL_free(filespec1_split); OPENSSL_free(filespec2_split); - return (merged); + return merged; } static char *win32_name_converter(DSO *dso, const char *filename) @@ -473,13 +466,13 @@ static char *win32_name_converter(DSO *dso, const char *filename) translated = OPENSSL_malloc(len + 1); if (translated == NULL) { DSOerr(DSO_F_WIN32_NAME_CONVERTER, DSO_R_NAME_TRANSLATION_FAILED); - return (NULL); + return NULL; } if (transform) sprintf(translated, "%s.dll", filename); else sprintf(translated, "%s", filename); - return (translated); + return translated; } static const char *openssl_strnchr(const char *string, int c, size_t len) diff --git a/crypto/ebcdic.c b/crypto/ebcdic.c index 68719538..2a8ca610 100644 --- a/crypto/ebcdic.c +++ b/crypto/ebcdic.c @@ -14,11 +14,6 @@ NON_EMPTY_TRANSLATION_UNIT # include -/*- - * Initial Port for Apache-1.3 by - * Adapted for OpenSSL-0.9.4 by - */ - # ifdef CHARSET_EBCDIC_TEST /* * Here we're looking to test the EBCDIC code on an ASCII system so we don't do diff --git a/crypto/ec/asm/ecp_nistz256-armv4.pl b/crypto/ec/asm/ecp_nistz256-armv4.pl index 2314b752..c414334d 100755 --- a/crypto/ec/asm/ecp_nistz256-armv4.pl +++ b/crypto/ec/asm/ecp_nistz256-armv4.pl @@ -233,7 +233,7 @@ __ecp_nistz256_add: @ if a+b >= modulus, subtract modulus. @ @ But since comparison implies subtraction, we subtract - @ modulus and then add it back if subraction borrowed. + @ modulus and then add it back if subtraction borrowed. subs $a0,$a0,#-1 sbcs $a1,$a1,#-1 @@ -1222,7 +1222,7 @@ __ecp_nistz256_add_self: @ if a+b >= modulus, subtract modulus. @ @ But since comparison implies subtraction, we subtract - @ modulus and then add it back if subraction borrowed. + @ modulus and then add it back if subtraction borrowed. subs $a0,$a0,#-1 sbcs $a1,$a1,#-1 diff --git a/crypto/ec/asm/ecp_nistz256-armv8.pl b/crypto/ec/asm/ecp_nistz256-armv8.pl index 5ac22825..2705d7cf 100644 --- a/crypto/ec/asm/ecp_nistz256-armv8.pl +++ b/crypto/ec/asm/ecp_nistz256-armv8.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2015-2018 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 @@ -663,7 +663,7 @@ __ecp_nistz256_div_by_2: adc $ap,xzr,xzr // zap $ap tst $acc0,#1 // is a even? - csel $acc0,$acc0,$t0,eq // ret = even ? a : a+modulus + csel $acc0,$acc0,$t0,eq // ret = even ? a : a+modulus csel $acc1,$acc1,$t1,eq csel $acc2,$acc2,$t2,eq csel $acc3,$acc3,$t3,eq diff --git a/crypto/ec/asm/ecp_nistz256-avx2.pl b/crypto/ec/asm/ecp_nistz256-avx2.pl index 3bdd2cf1..9fbc909b 100755 --- a/crypto/ec/asm/ecp_nistz256-avx2.pl +++ b/crypto/ec/asm/ecp_nistz256-avx2.pl @@ -1,39 +1,19 @@ #! /usr/bin/env perl # Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright (c) 2014, Intel Corporation. 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 - - -############################################################################## -# # -# 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" # -# # -############################################################################## +# +# Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) +# (1) Intel Corporation, Israel Development Center, Haifa, Israel +# (2) University of Haifa, Israel +# +# Reference: +# S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with +# 256 Bit Primes" $flavour = shift; $output = shift; @@ -157,7 +137,7 @@ ___ { # This function receives a pointer to an array of four affine points -# (X, Y, <1>) and rearanges the data for AVX2 execution, while +# (X, Y, <1>) and rearranges the data for AVX2 execution, while # converting it to 2^29 radix redundant form my ($X0,$X1,$X2,$X3, $Y0,$Y1,$Y2,$Y3, @@ -309,7 +289,7 @@ ___ { ################################################################################ # This function receives a pointer to an array of four AVX2 formatted points -# (X, Y, Z) convert the data to normal representation, and rearanges the data +# (X, Y, Z) convert the data to normal representation, and rearranges the data my ($D0,$D1,$D2,$D3, $D4,$D5,$D6,$D7, $D8)=map("%ymm$_",(0..8)); my ($T0,$T1,$T2,$T3, $T4,$T5,$T6)=map("%ymm$_",(9..15)); diff --git a/crypto/ec/asm/ecp_nistz256-ppc64.pl b/crypto/ec/asm/ecp_nistz256-ppc64.pl new file mode 100755 index 00000000..0c3c186b --- /dev/null +++ b/crypto/ec/asm/ecp_nistz256-ppc64.pl @@ -0,0 +1,2382 @@ +#! /usr/bin/env perl +# 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 + +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# ECP_NISTZ256 module for PPC64. +# +# August 2016. +# +# Original ECP_NISTZ256 submission targeting x86_64 is detailed in +# http://eprint.iacr.org/2013/816. +# +# with/without -DECP_NISTZ256_ASM +# POWER7 +260-530% +# POWER8 +220-340% + +$flavour = shift; +while (($output=shift) && ($output!~/\w[\w\-]*\.\w+$/)) {} + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +( $xlate="${dir}ppc-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../perlasm/ppc-xlate.pl" and -f $xlate) or +die "can't locate ppc-xlate.pl"; + +open OUT,"| \"$^X\" $xlate $flavour $output"; +*STDOUT=*OUT; + +my $sp="r1"; + +{ +my ($rp,$ap,$bp,$bi,$acc0,$acc1,$acc2,$acc3,$poly1,$poly3, + $acc4,$acc5,$a0,$a1,$a2,$a3,$t0,$t1,$t2,$t3) = + map("r$_",(3..12,22..31)); + +my ($acc6,$acc7)=($bp,$bi); # used in __ecp_nistz256_sqr_mont + +$code.=<<___; +.machine "any" +.text +___ +######################################################################## +# Convert ecp_nistz256_table.c to layout expected by ecp_nistz_gather_w7 +# +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +open TABLE,") { + s/TOBN\(\s*(0x[0-9a-f]+),\s*(0x[0-9a-f]+)\s*\)/push @arr,hex($2),hex($1)/geo; +} +close TABLE; + +# See ecp_nistz256_table.c for explanation for why it's 64*16*37. +# 64*16*37-1 is because $#arr returns last valid index or @arr, not +# amount of elements. +die "insane number of elements" if ($#arr != 64*16*37-1); + +$code.=<<___; +.type ecp_nistz256_precomputed,\@object +.globl ecp_nistz256_precomputed +.align 12 +ecp_nistz256_precomputed: +___ +######################################################################## +# this conversion smashes P256_POINT_AFFINE by individual bytes with +# 64 byte interval, similar to +# 1111222233334444 +# 1234123412341234 +for(1..37) { + @tbl = splice(@arr,0,64*16); + for($i=0;$i<64;$i++) { + undef @line; + for($j=0;$j<64;$j++) { + push @line,(@tbl[$j*16+$i/4]>>(($i%4)*8))&0xff; + } + $code.=".byte\t"; + $code.=join(',',map { sprintf "0x%02x",$_} @line); + $code.="\n"; + } +} + +$code.=<<___; +.size ecp_nistz256_precomputed,.-ecp_nistz256_precomputed +.asciz "ECP_NISTZ256 for PPC64, CRYPTOGAMS by " + +# void ecp_nistz256_mul_mont(BN_ULONG x0[4],const BN_ULONG x1[4], +# const BN_ULONG x2[4]); +.globl ecp_nistz256_mul_mont +.align 5 +ecp_nistz256_mul_mont: + stdu $sp,-128($sp) + mflr r0 + std r22,48($sp) + std r23,56($sp) + std r24,64($sp) + std r25,72($sp) + std r26,80($sp) + std r27,88($sp) + std r28,96($sp) + std r29,104($sp) + std r30,112($sp) + std r31,120($sp) + + ld $a0,0($ap) + ld $bi,0($bp) + ld $a1,8($ap) + ld $a2,16($ap) + ld $a3,24($ap) + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 + + bl __ecp_nistz256_mul_mont + + mtlr r0 + ld r22,48($sp) + ld r23,56($sp) + ld r24,64($sp) + ld r25,72($sp) + ld r26,80($sp) + ld r27,88($sp) + ld r28,96($sp) + ld r29,104($sp) + ld r30,112($sp) + ld r31,120($sp) + addi $sp,$sp,128 + blr + .long 0 + .byte 0,12,4,0,0x80,10,3,0 + .long 0 +.size ecp_nistz256_mul_mont,.-ecp_nistz256_mul_mont + +# void ecp_nistz256_sqr_mont(BN_ULONG x0[4],const BN_ULONG x1[4]); +.globl ecp_nistz256_sqr_mont +.align 4 +ecp_nistz256_sqr_mont: + stdu $sp,-128($sp) + mflr r0 + std r22,48($sp) + std r23,56($sp) + std r24,64($sp) + std r25,72($sp) + std r26,80($sp) + std r27,88($sp) + std r28,96($sp) + std r29,104($sp) + std r30,112($sp) + std r31,120($sp) + + ld $a0,0($ap) + ld $a1,8($ap) + ld $a2,16($ap) + ld $a3,24($ap) + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 + + bl __ecp_nistz256_sqr_mont + + mtlr r0 + ld r22,48($sp) + ld r23,56($sp) + ld r24,64($sp) + ld r25,72($sp) + ld r26,80($sp) + ld r27,88($sp) + ld r28,96($sp) + ld r29,104($sp) + ld r30,112($sp) + ld r31,120($sp) + addi $sp,$sp,128 + blr + .long 0 + .byte 0,12,4,0,0x80,10,2,0 + .long 0 +.size ecp_nistz256_sqr_mont,.-ecp_nistz256_sqr_mont + +# void ecp_nistz256_add(BN_ULONG x0[4],const BN_ULONG x1[4], +# const BN_ULONG x2[4]); +.globl ecp_nistz256_add +.align 4 +ecp_nistz256_add: + stdu $sp,-128($sp) + mflr r0 + std r28,96($sp) + std r29,104($sp) + std r30,112($sp) + std r31,120($sp) + + ld $acc0,0($ap) + ld $t0, 0($bp) + ld $acc1,8($ap) + ld $t1, 8($bp) + ld $acc2,16($ap) + ld $t2, 16($bp) + ld $acc3,24($ap) + ld $t3, 24($bp) + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 + + bl __ecp_nistz256_add + + mtlr r0 + ld r28,96($sp) + ld r29,104($sp) + ld r30,112($sp) + ld r31,120($sp) + addi $sp,$sp,128 + blr + .long 0 + .byte 0,12,4,0,0x80,4,3,0 + .long 0 +.size ecp_nistz256_add,.-ecp_nistz256_add + +# void ecp_nistz256_div_by_2(BN_ULONG x0[4],const BN_ULONG x1[4]); +.globl ecp_nistz256_div_by_2 +.align 4 +ecp_nistz256_div_by_2: + stdu $sp,-128($sp) + mflr r0 + std r28,96($sp) + std r29,104($sp) + std r30,112($sp) + std r31,120($sp) + + ld $acc0,0($ap) + ld $acc1,8($ap) + ld $acc2,16($ap) + ld $acc3,24($ap) + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 + + bl __ecp_nistz256_div_by_2 + + mtlr r0 + ld r28,96($sp) + ld r29,104($sp) + ld r30,112($sp) + ld r31,120($sp) + addi $sp,$sp,128 + blr + .long 0 + .byte 0,12,4,0,0x80,4,2,0 + .long 0 +.size ecp_nistz256_div_by_2,.-ecp_nistz256_div_by_2 + +# void ecp_nistz256_mul_by_2(BN_ULONG x0[4],const BN_ULONG x1[4]); +.globl ecp_nistz256_mul_by_2 +.align 4 +ecp_nistz256_mul_by_2: + stdu $sp,-128($sp) + mflr r0 + std r28,96($sp) + std r29,104($sp) + std r30,112($sp) + std r31,120($sp) + + ld $acc0,0($ap) + ld $acc1,8($ap) + ld $acc2,16($ap) + ld $acc3,24($ap) + + mr $t0,$acc0 + mr $t1,$acc1 + mr $t2,$acc2 + mr $t3,$acc3 + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 + + bl __ecp_nistz256_add # ret = a+a // 2*a + + mtlr r0 + ld r28,96($sp) + ld r29,104($sp) + ld r30,112($sp) + ld r31,120($sp) + addi $sp,$sp,128 + blr + .long 0 + .byte 0,12,4,0,0x80,4,3,0 + .long 0 +.size ecp_nistz256_mul_by_2,.-ecp_nistz256_mul_by_2 + +# void ecp_nistz256_mul_by_3(BN_ULONG x0[4],const BN_ULONG x1[4]); +.globl ecp_nistz256_mul_by_3 +.align 4 +ecp_nistz256_mul_by_3: + stdu $sp,-128($sp) + mflr r0 + std r28,96($sp) + std r29,104($sp) + std r30,112($sp) + std r31,120($sp) + + ld $acc0,0($ap) + ld $acc1,8($ap) + ld $acc2,16($ap) + ld $acc3,24($ap) + + mr $t0,$acc0 + std $acc0,64($sp) + mr $t1,$acc1 + std $acc1,72($sp) + mr $t2,$acc2 + std $acc2,80($sp) + mr $t3,$acc3 + std $acc3,88($sp) + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 + + bl __ecp_nistz256_add # ret = a+a // 2*a + + ld $t0,64($sp) + ld $t1,72($sp) + ld $t2,80($sp) + ld $t3,88($sp) + + bl __ecp_nistz256_add # ret += a // 2*a+a=3*a + + mtlr r0 + ld r28,96($sp) + ld r29,104($sp) + ld r30,112($sp) + ld r31,120($sp) + addi $sp,$sp,128 + blr + .long 0 + .byte 0,12,4,0,0x80,4,2,0 + .long 0 +.size ecp_nistz256_mul_by_3,.-ecp_nistz256_mul_by_3 + +# void ecp_nistz256_sub(BN_ULONG x0[4],const BN_ULONG x1[4], +# const BN_ULONG x2[4]); +.globl ecp_nistz256_sub +.align 4 +ecp_nistz256_sub: + stdu $sp,-128($sp) + mflr r0 + std r28,96($sp) + std r29,104($sp) + std r30,112($sp) + std r31,120($sp) + + ld $acc0,0($ap) + ld $acc1,8($ap) + ld $acc2,16($ap) + ld $acc3,24($ap) + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 + + bl __ecp_nistz256_sub_from + + mtlr r0 + ld r28,96($sp) + ld r29,104($sp) + ld r30,112($sp) + ld r31,120($sp) + addi $sp,$sp,128 + blr + .long 0 + .byte 0,12,4,0,0x80,4,3,0 + .long 0 +.size ecp_nistz256_sub,.-ecp_nistz256_sub + +# void ecp_nistz256_neg(BN_ULONG x0[4],const BN_ULONG x1[4]); +.globl ecp_nistz256_neg +.align 4 +ecp_nistz256_neg: + stdu $sp,-128($sp) + mflr r0 + std r28,96($sp) + std r29,104($sp) + std r30,112($sp) + std r31,120($sp) + + mr $bp,$ap + li $acc0,0 + li $acc1,0 + li $acc2,0 + li $acc3,0 + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 + + bl __ecp_nistz256_sub_from + + mtlr r0 + ld r28,96($sp) + ld r29,104($sp) + ld r30,112($sp) + ld r31,120($sp) + addi $sp,$sp,128 + blr + .long 0 + .byte 0,12,4,0,0x80,4,2,0 + .long 0 +.size ecp_nistz256_neg,.-ecp_nistz256_neg + +# note that __ecp_nistz256_mul_mont expects a[0-3] input pre-loaded +# to $a0-$a3 and b[0] - to $bi +.type __ecp_nistz256_mul_mont,\@function +.align 4 +__ecp_nistz256_mul_mont: + mulld $acc0,$a0,$bi # a[0]*b[0] + mulhdu $t0,$a0,$bi + + mulld $acc1,$a1,$bi # a[1]*b[0] + mulhdu $t1,$a1,$bi + + mulld $acc2,$a2,$bi # a[2]*b[0] + mulhdu $t2,$a2,$bi + + mulld $acc3,$a3,$bi # a[3]*b[0] + mulhdu $t3,$a3,$bi + ld $bi,8($bp) # b[1] + + addc $acc1,$acc1,$t0 # accumulate high parts of multiplication + sldi $t0,$acc0,32 + adde $acc2,$acc2,$t1 + srdi $t1,$acc0,32 + adde $acc3,$acc3,$t2 + addze $acc4,$t3 + li $acc5,0 +___ +for($i=1;$i<4;$i++) { + ################################################################ + # Reduction iteration is normally performed by accumulating + # result of multiplication of modulus by "magic" digit [and + # omitting least significant word, which is guaranteed to + # be 0], but thanks to special form of modulus and "magic" + # digit being equal to least significant word, it can be + # performed with additions and subtractions alone. Indeed: + # + # ffff0001.00000000.0000ffff.ffffffff + # * abcdefgh + # + xxxxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx.abcdefgh + # + # Now observing that ff..ff*x = (2^n-1)*x = 2^n*x-x, we + # rewrite above as: + # + # xxxxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx.abcdefgh + # + abcdefgh.abcdefgh.0000abcd.efgh0000.00000000 + # - 0000abcd.efgh0000.00000000.00000000.abcdefgh + # + # or marking redundant operations: + # + # xxxxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx.-------- + # + abcdefgh.abcdefgh.0000abcd.efgh0000.-------- + # - 0000abcd.efgh0000.--------.--------.-------- + +$code.=<<___; + subfc $t2,$t0,$acc0 # "*0xffff0001" + subfe $t3,$t1,$acc0 + addc $acc0,$acc1,$t0 # +=acc[0]<<96 and omit acc[0] + adde $acc1,$acc2,$t1 + adde $acc2,$acc3,$t2 # +=acc[0]*0xffff0001 + adde $acc3,$acc4,$t3 + addze $acc4,$acc5 + + mulld $t0,$a0,$bi # lo(a[0]*b[i]) + mulld $t1,$a1,$bi # lo(a[1]*b[i]) + mulld $t2,$a2,$bi # lo(a[2]*b[i]) + mulld $t3,$a3,$bi # lo(a[3]*b[i]) + addc $acc0,$acc0,$t0 # accumulate low parts of multiplication + mulhdu $t0,$a0,$bi # hi(a[0]*b[i]) + adde $acc1,$acc1,$t1 + mulhdu $t1,$a1,$bi # hi(a[1]*b[i]) + adde $acc2,$acc2,$t2 + mulhdu $t2,$a2,$bi # hi(a[2]*b[i]) + adde $acc3,$acc3,$t3 + mulhdu $t3,$a3,$bi # hi(a[3]*b[i]) + addze $acc4,$acc4 +___ +$code.=<<___ if ($i<3); + ld $bi,8*($i+1)($bp) # b[$i+1] +___ +$code.=<<___; + addc $acc1,$acc1,$t0 # accumulate high parts of multiplication + sldi $t0,$acc0,32 + adde $acc2,$acc2,$t1 + srdi $t1,$acc0,32 + adde $acc3,$acc3,$t2 + adde $acc4,$acc4,$t3 + li $acc5,0 + addze $acc5,$acc5 +___ +} +$code.=<<___; + # last reduction + subfc $t2,$t0,$acc0 # "*0xffff0001" + subfe $t3,$t1,$acc0 + addc $acc0,$acc1,$t0 # +=acc[0]<<96 and omit acc[0] + adde $acc1,$acc2,$t1 + adde $acc2,$acc3,$t2 # +=acc[0]*0xffff0001 + adde $acc3,$acc4,$t3 + addze $acc4,$acc5 + + li $t2,0 + addic $acc0,$acc0,1 # ret -= modulus + subfe $acc1,$poly1,$acc1 + subfe $acc2,$t2,$acc2 + subfe $acc3,$poly3,$acc3 + subfe $acc4,$t2,$acc4 + + addc $acc0,$acc0,$acc4 # ret += modulus if borrow + and $t1,$poly1,$acc4 + and $t3,$poly3,$acc4 + adde $acc1,$acc1,$t1 + addze $acc2,$acc2 + adde $acc3,$acc3,$t3 + + std $acc0,0($rp) + std $acc1,8($rp) + std $acc2,16($rp) + std $acc3,24($rp) + + blr + .long 0 + .byte 0,12,0x14,0,0,0,1,0 + .long 0 +.size __ecp_nistz256_mul_mont,.-__ecp_nistz256_mul_mont + +# note that __ecp_nistz256_sqr_mont expects a[0-3] input pre-loaded +# to $a0-$a3 +.type __ecp_nistz256_sqr_mont,\@function +.align 4 +__ecp_nistz256_sqr_mont: + ################################################################ + # | | | | | |a1*a0| | + # | | | | |a2*a0| | | + # | |a3*a2|a3*a0| | | | + # | | | |a2*a1| | | | + # | | |a3*a1| | | | | + # *| | | | | | | | 2| + # +|a3*a3|a2*a2|a1*a1|a0*a0| + # |--+--+--+--+--+--+--+--| + # |A7|A6|A5|A4|A3|A2|A1|A0|, where Ax is $accx, i.e. follow $accx + # + # "can't overflow" below mark carrying into high part of + # multiplication result, which can't overflow, because it + # can never be all ones. + + mulld $acc1,$a1,$a0 # a[1]*a[0] + mulhdu $t1,$a1,$a0 + mulld $acc2,$a2,$a0 # a[2]*a[0] + mulhdu $t2,$a2,$a0 + mulld $acc3,$a3,$a0 # a[3]*a[0] + mulhdu $acc4,$a3,$a0 + + addc $acc2,$acc2,$t1 # accumulate high parts of multiplication + mulld $t0,$a2,$a1 # a[2]*a[1] + mulhdu $t1,$a2,$a1 + adde $acc3,$acc3,$t2 + mulld $t2,$a3,$a1 # a[3]*a[1] + mulhdu $t3,$a3,$a1 + addze $acc4,$acc4 # can't overflow + + mulld $acc5,$a3,$a2 # a[3]*a[2] + mulhdu $acc6,$a3,$a2 + + addc $t1,$t1,$t2 # accumulate high parts of multiplication + addze $t2,$t3 # can't overflow + + addc $acc3,$acc3,$t0 # accumulate low parts of multiplication + adde $acc4,$acc4,$t1 + adde $acc5,$acc5,$t2 + addze $acc6,$acc6 # can't overflow + + addc $acc1,$acc1,$acc1 # acc[1-6]*=2 + adde $acc2,$acc2,$acc2 + adde $acc3,$acc3,$acc3 + adde $acc4,$acc4,$acc4 + adde $acc5,$acc5,$acc5 + adde $acc6,$acc6,$acc6 + li $acc7,0 + addze $acc7,$acc7 + + mulld $acc0,$a0,$a0 # a[0]*a[0] + mulhdu $a0,$a0,$a0 + mulld $t1,$a1,$a1 # a[1]*a[1] + mulhdu $a1,$a1,$a1 + mulld $t2,$a2,$a2 # a[2]*a[2] + mulhdu $a2,$a2,$a2 + mulld $t3,$a3,$a3 # a[3]*a[3] + mulhdu $a3,$a3,$a3 + addc $acc1,$acc1,$a0 # +a[i]*a[i] + sldi $t0,$acc0,32 + adde $acc2,$acc2,$t1 + srdi $t1,$acc0,32 + adde $acc3,$acc3,$a1 + adde $acc4,$acc4,$t2 + adde $acc5,$acc5,$a2 + adde $acc6,$acc6,$t3 + adde $acc7,$acc7,$a3 +___ +for($i=0;$i<3;$i++) { # reductions, see commentary in + # multiplication for details +$code.=<<___; + subfc $t2,$t0,$acc0 # "*0xffff0001" + subfe $t3,$t1,$acc0 + addc $acc0,$acc1,$t0 # +=acc[0]<<96 and omit acc[0] + sldi $t0,$acc0,32 + adde $acc1,$acc2,$t1 + srdi $t1,$acc0,32 + adde $acc2,$acc3,$t2 # +=acc[0]*0xffff0001 + addze $acc3,$t3 # can't overflow +___ +} +$code.=<<___; + subfc $t2,$t0,$acc0 # "*0xffff0001" + subfe $t3,$t1,$acc0 + addc $acc0,$acc1,$t0 # +=acc[0]<<96 and omit acc[0] + adde $acc1,$acc2,$t1 + adde $acc2,$acc3,$t2 # +=acc[0]*0xffff0001 + addze $acc3,$t3 # can't overflow + + addc $acc0,$acc0,$acc4 # accumulate upper half + adde $acc1,$acc1,$acc5 + adde $acc2,$acc2,$acc6 + adde $acc3,$acc3,$acc7 + li $t2,0 + addze $acc4,$t2 + + addic $acc0,$acc0,1 # ret -= modulus + subfe $acc1,$poly1,$acc1 + subfe $acc2,$t2,$acc2 + subfe $acc3,$poly3,$acc3 + subfe $acc4,$t2,$acc4 + + addc $acc0,$acc0,$acc4 # ret += modulus if borrow + and $t1,$poly1,$acc4 + and $t3,$poly3,$acc4 + adde $acc1,$acc1,$t1 + addze $acc2,$acc2 + adde $acc3,$acc3,$t3 + + std $acc0,0($rp) + std $acc1,8($rp) + std $acc2,16($rp) + std $acc3,24($rp) + + blr + .long 0 + .byte 0,12,0x14,0,0,0,1,0 + .long 0 +.size __ecp_nistz256_sqr_mont,.-__ecp_nistz256_sqr_mont + +# Note that __ecp_nistz256_add expects both input vectors pre-loaded to +# $a0-$a3 and $t0-$t3. This is done because it's used in multiple +# contexts, e.g. in multiplication by 2 and 3... +.type __ecp_nistz256_add,\@function +.align 4 +__ecp_nistz256_add: + addc $acc0,$acc0,$t0 # ret = a+b + adde $acc1,$acc1,$t1 + adde $acc2,$acc2,$t2 + li $t2,0 + adde $acc3,$acc3,$t3 + addze $t0,$t2 + + # if a+b >= modulus, subtract modulus + # + # But since comparison implies subtraction, we subtract + # modulus and then add it back if subtraction borrowed. + + subic $acc0,$acc0,-1 + subfe $acc1,$poly1,$acc1 + subfe $acc2,$t2,$acc2 + subfe $acc3,$poly3,$acc3 + subfe $t0,$t2,$t0 + + addc $acc0,$acc0,$t0 + and $t1,$poly1,$t0 + and $t3,$poly3,$t0 + adde $acc1,$acc1,$t1 + addze $acc2,$acc2 + adde $acc3,$acc3,$t3 + + std $acc0,0($rp) + std $acc1,8($rp) + std $acc2,16($rp) + std $acc3,24($rp) + + blr + .long 0 + .byte 0,12,0x14,0,0,0,3,0 + .long 0 +.size __ecp_nistz256_add,.-__ecp_nistz256_add + +.type __ecp_nistz256_sub_from,\@function +.align 4 +__ecp_nistz256_sub_from: + ld $t0,0($bp) + ld $t1,8($bp) + ld $t2,16($bp) + ld $t3,24($bp) + subfc $acc0,$t0,$acc0 # ret = a-b + subfe $acc1,$t1,$acc1 + subfe $acc2,$t2,$acc2 + subfe $acc3,$t3,$acc3 + subfe $t0,$t0,$t0 # t0 = borrow ? -1 : 0 + + # if a-b borrowed, add modulus + + addc $acc0,$acc0,$t0 # ret -= modulus & t0 + and $t1,$poly1,$t0 + and $t3,$poly3,$t0 + adde $acc1,$acc1,$t1 + addze $acc2,$acc2 + adde $acc3,$acc3,$t3 + + std $acc0,0($rp) + std $acc1,8($rp) + std $acc2,16($rp) + std $acc3,24($rp) + + blr + .long 0 + .byte 0,12,0x14,0,0,0,3,0 + .long 0 +.size __ecp_nistz256_sub_from,.-__ecp_nistz256_sub_from + +.type __ecp_nistz256_sub_morf,\@function +.align 4 +__ecp_nistz256_sub_morf: + ld $t0,0($bp) + ld $t1,8($bp) + ld $t2,16($bp) + ld $t3,24($bp) + subfc $acc0,$acc0,$t0 # ret = b-a + subfe $acc1,$acc1,$t1 + subfe $acc2,$acc2,$t2 + subfe $acc3,$acc3,$t3 + subfe $t0,$t0,$t0 # t0 = borrow ? -1 : 0 + + # if b-a borrowed, add modulus + + addc $acc0,$acc0,$t0 # ret -= modulus & t0 + and $t1,$poly1,$t0 + and $t3,$poly3,$t0 + adde $acc1,$acc1,$t1 + addze $acc2,$acc2 + adde $acc3,$acc3,$t3 + + std $acc0,0($rp) + std $acc1,8($rp) + std $acc2,16($rp) + std $acc3,24($rp) + + blr + .long 0 + .byte 0,12,0x14,0,0,0,3,0 + .long 0 +.size __ecp_nistz256_sub_morf,.-__ecp_nistz256_sub_morf + +.type __ecp_nistz256_div_by_2,\@function +.align 4 +__ecp_nistz256_div_by_2: + andi. $t0,$acc0,1 + addic $acc0,$acc0,-1 # a += modulus + neg $t0,$t0 + adde $acc1,$acc1,$poly1 + not $t0,$t0 + addze $acc2,$acc2 + li $t2,0 + adde $acc3,$acc3,$poly3 + and $t1,$poly1,$t0 + addze $ap,$t2 # ap = carry + and $t3,$poly3,$t0 + + subfc $acc0,$t0,$acc0 # a -= modulus if a was even + subfe $acc1,$t1,$acc1 + subfe $acc2,$t2,$acc2 + subfe $acc3,$t3,$acc3 + subfe $ap, $t2,$ap + + srdi $acc0,$acc0,1 + sldi $t0,$acc1,63 + srdi $acc1,$acc1,1 + sldi $t1,$acc2,63 + srdi $acc2,$acc2,1 + sldi $t2,$acc3,63 + srdi $acc3,$acc3,1 + sldi $t3,$ap,63 + or $acc0,$acc0,$t0 + or $acc1,$acc1,$t1 + or $acc2,$acc2,$t2 + or $acc3,$acc3,$t3 + + std $acc0,0($rp) + std $acc1,8($rp) + std $acc2,16($rp) + std $acc3,24($rp) + + blr + .long 0 + .byte 0,12,0x14,0,0,0,1,0 + .long 0 +.size __ecp_nistz256_div_by_2,.-__ecp_nistz256_div_by_2 +___ +######################################################################## +# following subroutines are "literal" implementation of those found in +# ecp_nistz256.c +# +######################################################################## +# void ecp_nistz256_point_double(P256_POINT *out,const P256_POINT *inp); +# +if (1) { +my $FRAME=64+32*4+12*8; +my ($S,$M,$Zsqr,$tmp0)=map(64+32*$_,(0..3)); +# above map() describes stack layout with 4 temporary +# 256-bit vectors on top. +my ($rp_real,$ap_real) = map("r$_",(20,21)); + +$code.=<<___; +.globl ecp_nistz256_point_double +.align 5 +ecp_nistz256_point_double: + stdu $sp,-$FRAME($sp) + mflr r0 + std r20,$FRAME-8*12($sp) + std r21,$FRAME-8*11($sp) + std r22,$FRAME-8*10($sp) + std r23,$FRAME-8*9($sp) + std r24,$FRAME-8*8($sp) + std r25,$FRAME-8*7($sp) + std r26,$FRAME-8*6($sp) + std r27,$FRAME-8*5($sp) + std r28,$FRAME-8*4($sp) + std r29,$FRAME-8*3($sp) + std r30,$FRAME-8*2($sp) + std r31,$FRAME-8*1($sp) + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 +.Ldouble_shortcut: + ld $acc0,32($ap) + ld $acc1,40($ap) + ld $acc2,48($ap) + ld $acc3,56($ap) + mr $t0,$acc0 + mr $t1,$acc1 + mr $t2,$acc2 + mr $t3,$acc3 + ld $a0,64($ap) # forward load for p256_sqr_mont + ld $a1,72($ap) + ld $a2,80($ap) + ld $a3,88($ap) + mr $rp_real,$rp + mr $ap_real,$ap + addi $rp,$sp,$S + bl __ecp_nistz256_add # p256_mul_by_2(S, in_y); + + addi $rp,$sp,$Zsqr + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(Zsqr, in_z); + + ld $t0,0($ap_real) + ld $t1,8($ap_real) + ld $t2,16($ap_real) + ld $t3,24($ap_real) + mr $a0,$acc0 # put Zsqr aside for p256_sub + mr $a1,$acc1 + mr $a2,$acc2 + mr $a3,$acc3 + addi $rp,$sp,$M + bl __ecp_nistz256_add # p256_add(M, Zsqr, in_x); + + addi $bp,$ap_real,0 + mr $acc0,$a0 # restore Zsqr + mr $acc1,$a1 + mr $acc2,$a2 + mr $acc3,$a3 + ld $a0,$S+0($sp) # forward load for p256_sqr_mont + ld $a1,$S+8($sp) + ld $a2,$S+16($sp) + ld $a3,$S+24($sp) + addi $rp,$sp,$Zsqr + bl __ecp_nistz256_sub_morf # p256_sub(Zsqr, in_x, Zsqr); + + addi $rp,$sp,$S + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(S, S); + + ld $bi,32($ap_real) + ld $a0,64($ap_real) + ld $a1,72($ap_real) + ld $a2,80($ap_real) + ld $a3,88($ap_real) + addi $bp,$ap_real,32 + addi $rp,$sp,$tmp0 + bl __ecp_nistz256_mul_mont # p256_mul_mont(tmp0, in_z, in_y); + + mr $t0,$acc0 + mr $t1,$acc1 + mr $t2,$acc2 + mr $t3,$acc3 + ld $a0,$S+0($sp) # forward load for p256_sqr_mont + ld $a1,$S+8($sp) + ld $a2,$S+16($sp) + ld $a3,$S+24($sp) + addi $rp,$rp_real,64 + bl __ecp_nistz256_add # p256_mul_by_2(res_z, tmp0); + + addi $rp,$sp,$tmp0 + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(tmp0, S); + + ld $bi,$Zsqr($sp) # forward load for p256_mul_mont + ld $a0,$M+0($sp) + ld $a1,$M+8($sp) + ld $a2,$M+16($sp) + ld $a3,$M+24($sp) + addi $rp,$rp_real,32 + bl __ecp_nistz256_div_by_2 # p256_div_by_2(res_y, tmp0); + + addi $bp,$sp,$Zsqr + addi $rp,$sp,$M + bl __ecp_nistz256_mul_mont # p256_mul_mont(M, M, Zsqr); + + mr $t0,$acc0 # duplicate M + mr $t1,$acc1 + mr $t2,$acc2 + mr $t3,$acc3 + mr $a0,$acc0 # put M aside + mr $a1,$acc1 + mr $a2,$acc2 + mr $a3,$acc3 + addi $rp,$sp,$M + bl __ecp_nistz256_add + mr $t0,$a0 # restore M + mr $t1,$a1 + mr $t2,$a2 + mr $t3,$a3 + ld $bi,0($ap_real) # forward load for p256_mul_mont + ld $a0,$S+0($sp) + ld $a1,$S+8($sp) + ld $a2,$S+16($sp) + ld $a3,$S+24($sp) + bl __ecp_nistz256_add # p256_mul_by_3(M, M); + + addi $bp,$ap_real,0 + addi $rp,$sp,$S + bl __ecp_nistz256_mul_mont # p256_mul_mont(S, S, in_x); + + mr $t0,$acc0 + mr $t1,$acc1 + mr $t2,$acc2 + mr $t3,$acc3 + ld $a0,$M+0($sp) # forward load for p256_sqr_mont + ld $a1,$M+8($sp) + ld $a2,$M+16($sp) + ld $a3,$M+24($sp) + addi $rp,$sp,$tmp0 + bl __ecp_nistz256_add # p256_mul_by_2(tmp0, S); + + addi $rp,$rp_real,0 + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(res_x, M); + + addi $bp,$sp,$tmp0 + bl __ecp_nistz256_sub_from # p256_sub(res_x, res_x, tmp0); + + addi $bp,$sp,$S + addi $rp,$sp,$S + bl __ecp_nistz256_sub_morf # p256_sub(S, S, res_x); + + ld $bi,$M($sp) + mr $a0,$acc0 # copy S + mr $a1,$acc1 + mr $a2,$acc2 + mr $a3,$acc3 + addi $bp,$sp,$M + bl __ecp_nistz256_mul_mont # p256_mul_mont(S, S, M); + + addi $bp,$rp_real,32 + addi $rp,$rp_real,32 + bl __ecp_nistz256_sub_from # p256_sub(res_y, S, res_y); + + mtlr r0 + ld r20,$FRAME-8*12($sp) + ld r21,$FRAME-8*11($sp) + ld r22,$FRAME-8*10($sp) + ld r23,$FRAME-8*9($sp) + ld r24,$FRAME-8*8($sp) + ld r25,$FRAME-8*7($sp) + ld r26,$FRAME-8*6($sp) + ld r27,$FRAME-8*5($sp) + ld r28,$FRAME-8*4($sp) + ld r29,$FRAME-8*3($sp) + ld r30,$FRAME-8*2($sp) + ld r31,$FRAME-8*1($sp) + addi $sp,$sp,$FRAME + blr + .long 0 + .byte 0,12,4,0,0x80,12,2,0 + .long 0 +.size ecp_nistz256_point_double,.-ecp_nistz256_point_double +___ +} + +######################################################################## +# void ecp_nistz256_point_add(P256_POINT *out,const P256_POINT *in1, +# const P256_POINT *in2); +if (1) { +my $FRAME = 64 + 32*12 + 16*8; +my ($res_x,$res_y,$res_z, + $H,$Hsqr,$R,$Rsqr,$Hcub, + $U1,$U2,$S1,$S2)=map(64+32*$_,(0..11)); +my ($Z1sqr, $Z2sqr) = ($Hsqr, $Rsqr); +# above map() describes stack layout with 12 temporary +# 256-bit vectors on top. +my ($rp_real,$ap_real,$bp_real,$in1infty,$in2infty,$temp)=map("r$_",(16..21)); + +$code.=<<___; +.globl ecp_nistz256_point_add +.align 5 +ecp_nistz256_point_add: + stdu $sp,-$FRAME($sp) + mflr r0 + std r16,$FRAME-8*16($sp) + std r17,$FRAME-8*15($sp) + std r18,$FRAME-8*14($sp) + std r19,$FRAME-8*13($sp) + std r20,$FRAME-8*12($sp) + std r21,$FRAME-8*11($sp) + std r22,$FRAME-8*10($sp) + std r23,$FRAME-8*9($sp) + std r24,$FRAME-8*8($sp) + std r25,$FRAME-8*7($sp) + std r26,$FRAME-8*6($sp) + std r27,$FRAME-8*5($sp) + std r28,$FRAME-8*4($sp) + std r29,$FRAME-8*3($sp) + std r30,$FRAME-8*2($sp) + std r31,$FRAME-8*1($sp) + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 + + ld $a0,64($bp) # in2_z + ld $a1,72($bp) + ld $a2,80($bp) + ld $a3,88($bp) + mr $rp_real,$rp + mr $ap_real,$ap + mr $bp_real,$bp + or $t0,$a0,$a1 + or $t2,$a2,$a3 + or $in2infty,$t0,$t2 + neg $t0,$in2infty + or $in2infty,$in2infty,$t0 + sradi $in2infty,$in2infty,63 # !in2infty + addi $rp,$sp,$Z2sqr + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(Z2sqr, in2_z); + + ld $a0,64($ap_real) # in1_z + ld $a1,72($ap_real) + ld $a2,80($ap_real) + ld $a3,88($ap_real) + or $t0,$a0,$a1 + or $t2,$a2,$a3 + or $in1infty,$t0,$t2 + neg $t0,$in1infty + or $in1infty,$in1infty,$t0 + sradi $in1infty,$in1infty,63 # !in1infty + addi $rp,$sp,$Z1sqr + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(Z1sqr, in1_z); + + ld $bi,64($bp_real) + ld $a0,$Z2sqr+0($sp) + ld $a1,$Z2sqr+8($sp) + ld $a2,$Z2sqr+16($sp) + ld $a3,$Z2sqr+24($sp) + addi $bp,$bp_real,64 + addi $rp,$sp,$S1 + bl __ecp_nistz256_mul_mont # p256_mul_mont(S1, Z2sqr, in2_z); + + ld $bi,64($ap_real) + ld $a0,$Z1sqr+0($sp) + ld $a1,$Z1sqr+8($sp) + ld $a2,$Z1sqr+16($sp) + ld $a3,$Z1sqr+24($sp) + addi $bp,$ap_real,64 + addi $rp,$sp,$S2 + bl __ecp_nistz256_mul_mont # p256_mul_mont(S2, Z1sqr, in1_z); + + ld $bi,32($ap_real) + ld $a0,$S1+0($sp) + ld $a1,$S1+8($sp) + ld $a2,$S1+16($sp) + ld $a3,$S1+24($sp) + addi $bp,$ap_real,32 + addi $rp,$sp,$S1 + bl __ecp_nistz256_mul_mont # p256_mul_mont(S1, S1, in1_y); + + ld $bi,32($bp_real) + ld $a0,$S2+0($sp) + ld $a1,$S2+8($sp) + ld $a2,$S2+16($sp) + ld $a3,$S2+24($sp) + addi $bp,$bp_real,32 + addi $rp,$sp,$S2 + bl __ecp_nistz256_mul_mont # p256_mul_mont(S2, S2, in2_y); + + addi $bp,$sp,$S1 + ld $bi,$Z2sqr($sp) # forward load for p256_mul_mont + ld $a0,0($ap_real) + ld $a1,8($ap_real) + ld $a2,16($ap_real) + ld $a3,24($ap_real) + addi $rp,$sp,$R + bl __ecp_nistz256_sub_from # p256_sub(R, S2, S1); + + or $acc0,$acc0,$acc1 # see if result is zero + or $acc2,$acc2,$acc3 + or $temp,$acc0,$acc2 + + addi $bp,$sp,$Z2sqr + addi $rp,$sp,$U1 + bl __ecp_nistz256_mul_mont # p256_mul_mont(U1, in1_x, Z2sqr); + + ld $bi,$Z1sqr($sp) + ld $a0,0($bp_real) + ld $a1,8($bp_real) + ld $a2,16($bp_real) + ld $a3,24($bp_real) + addi $bp,$sp,$Z1sqr + addi $rp,$sp,$U2 + bl __ecp_nistz256_mul_mont # p256_mul_mont(U2, in2_x, Z1sqr); + + addi $bp,$sp,$U1 + ld $a0,$R+0($sp) # forward load for p256_sqr_mont + ld $a1,$R+8($sp) + ld $a2,$R+16($sp) + ld $a3,$R+24($sp) + addi $rp,$sp,$H + bl __ecp_nistz256_sub_from # p256_sub(H, U2, U1); + + or $acc0,$acc0,$acc1 # see if result is zero + or $acc2,$acc2,$acc3 + or. $acc0,$acc0,$acc2 + bne .Ladd_proceed # is_equal(U1,U2)? + + and. $t0,$in1infty,$in2infty + beq .Ladd_proceed # (in1infty || in2infty)? + + cmpldi $temp,0 + beq .Ladd_double # is_equal(S1,S2)? + + xor $a0,$a0,$a0 + std $a0,0($rp_real) + std $a0,8($rp_real) + std $a0,16($rp_real) + std $a0,24($rp_real) + std $a0,32($rp_real) + std $a0,40($rp_real) + std $a0,48($rp_real) + std $a0,56($rp_real) + std $a0,64($rp_real) + std $a0,72($rp_real) + std $a0,80($rp_real) + std $a0,88($rp_real) + b .Ladd_done + +.align 4 +.Ladd_double: + ld $bp,0($sp) # back-link + mr $ap,$ap_real + mr $rp,$rp_real + ld r16,$FRAME-8*16($sp) + ld r17,$FRAME-8*15($sp) + ld r18,$FRAME-8*14($sp) + ld r19,$FRAME-8*13($sp) + stdu $bp,$FRAME-288($sp) # difference in stack frame sizes + b .Ldouble_shortcut + +.align 4 +.Ladd_proceed: + addi $rp,$sp,$Rsqr + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(Rsqr, R); + + ld $bi,64($ap_real) + ld $a0,$H+0($sp) + ld $a1,$H+8($sp) + ld $a2,$H+16($sp) + ld $a3,$H+24($sp) + addi $bp,$ap_real,64 + addi $rp,$sp,$res_z + bl __ecp_nistz256_mul_mont # p256_mul_mont(res_z, H, in1_z); + + ld $a0,$H+0($sp) + ld $a1,$H+8($sp) + ld $a2,$H+16($sp) + ld $a3,$H+24($sp) + addi $rp,$sp,$Hsqr + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(Hsqr, H); + + ld $bi,64($bp_real) + ld $a0,$res_z+0($sp) + ld $a1,$res_z+8($sp) + ld $a2,$res_z+16($sp) + ld $a3,$res_z+24($sp) + addi $bp,$bp_real,64 + addi $rp,$sp,$res_z + bl __ecp_nistz256_mul_mont # p256_mul_mont(res_z, res_z, in2_z); + + ld $bi,$H($sp) + ld $a0,$Hsqr+0($sp) + ld $a1,$Hsqr+8($sp) + ld $a2,$Hsqr+16($sp) + ld $a3,$Hsqr+24($sp) + addi $bp,$sp,$H + addi $rp,$sp,$Hcub + bl __ecp_nistz256_mul_mont # p256_mul_mont(Hcub, Hsqr, H); + + ld $bi,$Hsqr($sp) + ld $a0,$U1+0($sp) + ld $a1,$U1+8($sp) + ld $a2,$U1+16($sp) + ld $a3,$U1+24($sp) + addi $bp,$sp,$Hsqr + addi $rp,$sp,$U2 + bl __ecp_nistz256_mul_mont # p256_mul_mont(U2, U1, Hsqr); + + mr $t0,$acc0 + mr $t1,$acc1 + mr $t2,$acc2 + mr $t3,$acc3 + addi $rp,$sp,$Hsqr + bl __ecp_nistz256_add # p256_mul_by_2(Hsqr, U2); + + addi $bp,$sp,$Rsqr + addi $rp,$sp,$res_x + bl __ecp_nistz256_sub_morf # p256_sub(res_x, Rsqr, Hsqr); + + addi $bp,$sp,$Hcub + bl __ecp_nistz256_sub_from # p256_sub(res_x, res_x, Hcub); + + addi $bp,$sp,$U2 + ld $bi,$Hcub($sp) # forward load for p256_mul_mont + ld $a0,$S1+0($sp) + ld $a1,$S1+8($sp) + ld $a2,$S1+16($sp) + ld $a3,$S1+24($sp) + addi $rp,$sp,$res_y + bl __ecp_nistz256_sub_morf # p256_sub(res_y, U2, res_x); + + addi $bp,$sp,$Hcub + addi $rp,$sp,$S2 + bl __ecp_nistz256_mul_mont # p256_mul_mont(S2, S1, Hcub); + + ld $bi,$R($sp) + ld $a0,$res_y+0($sp) + ld $a1,$res_y+8($sp) + ld $a2,$res_y+16($sp) + ld $a3,$res_y+24($sp) + addi $bp,$sp,$R + addi $rp,$sp,$res_y + bl __ecp_nistz256_mul_mont # p256_mul_mont(res_y, res_y, R); + + addi $bp,$sp,$S2 + bl __ecp_nistz256_sub_from # p256_sub(res_y, res_y, S2); + + ld $t0,0($bp_real) # in2 + ld $t1,8($bp_real) + ld $t2,16($bp_real) + ld $t3,24($bp_real) + ld $a0,$res_x+0($sp) # res + ld $a1,$res_x+8($sp) + ld $a2,$res_x+16($sp) + ld $a3,$res_x+24($sp) +___ +for($i=0;$i<64;$i+=32) { # conditional moves +$code.=<<___; + ld $acc0,$i+0($ap_real) # in1 + ld $acc1,$i+8($ap_real) + ld $acc2,$i+16($ap_real) + ld $acc3,$i+24($ap_real) + andc $t0,$t0,$in1infty + andc $t1,$t1,$in1infty + andc $t2,$t2,$in1infty + andc $t3,$t3,$in1infty + and $a0,$a0,$in1infty + and $a1,$a1,$in1infty + and $a2,$a2,$in1infty + and $a3,$a3,$in1infty + or $t0,$t0,$a0 + or $t1,$t1,$a1 + or $t2,$t2,$a2 + or $t3,$t3,$a3 + andc $acc0,$acc0,$in2infty + andc $acc1,$acc1,$in2infty + andc $acc2,$acc2,$in2infty + andc $acc3,$acc3,$in2infty + and $t0,$t0,$in2infty + and $t1,$t1,$in2infty + and $t2,$t2,$in2infty + and $t3,$t3,$in2infty + or $acc0,$acc0,$t0 + or $acc1,$acc1,$t1 + or $acc2,$acc2,$t2 + or $acc3,$acc3,$t3 + + ld $t0,$i+32($bp_real) # in2 + ld $t1,$i+40($bp_real) + ld $t2,$i+48($bp_real) + ld $t3,$i+56($bp_real) + ld $a0,$res_x+$i+32($sp) + ld $a1,$res_x+$i+40($sp) + ld $a2,$res_x+$i+48($sp) + ld $a3,$res_x+$i+56($sp) + std $acc0,$i+0($rp_real) + std $acc1,$i+8($rp_real) + std $acc2,$i+16($rp_real) + std $acc3,$i+24($rp_real) +___ +} +$code.=<<___; + ld $acc0,$i+0($ap_real) # in1 + ld $acc1,$i+8($ap_real) + ld $acc2,$i+16($ap_real) + ld $acc3,$i+24($ap_real) + andc $t0,$t0,$in1infty + andc $t1,$t1,$in1infty + andc $t2,$t2,$in1infty + andc $t3,$t3,$in1infty + and $a0,$a0,$in1infty + and $a1,$a1,$in1infty + and $a2,$a2,$in1infty + and $a3,$a3,$in1infty + or $t0,$t0,$a0 + or $t1,$t1,$a1 + or $t2,$t2,$a2 + or $t3,$t3,$a3 + andc $acc0,$acc0,$in2infty + andc $acc1,$acc1,$in2infty + andc $acc2,$acc2,$in2infty + andc $acc3,$acc3,$in2infty + and $t0,$t0,$in2infty + and $t1,$t1,$in2infty + and $t2,$t2,$in2infty + and $t3,$t3,$in2infty + or $acc0,$acc0,$t0 + or $acc1,$acc1,$t1 + or $acc2,$acc2,$t2 + or $acc3,$acc3,$t3 + std $acc0,$i+0($rp_real) + std $acc1,$i+8($rp_real) + std $acc2,$i+16($rp_real) + std $acc3,$i+24($rp_real) + +.Ladd_done: + mtlr r0 + ld r16,$FRAME-8*16($sp) + ld r17,$FRAME-8*15($sp) + ld r18,$FRAME-8*14($sp) + ld r19,$FRAME-8*13($sp) + ld r20,$FRAME-8*12($sp) + ld r21,$FRAME-8*11($sp) + ld r22,$FRAME-8*10($sp) + ld r23,$FRAME-8*9($sp) + ld r24,$FRAME-8*8($sp) + ld r25,$FRAME-8*7($sp) + ld r26,$FRAME-8*6($sp) + ld r27,$FRAME-8*5($sp) + ld r28,$FRAME-8*4($sp) + ld r29,$FRAME-8*3($sp) + ld r30,$FRAME-8*2($sp) + ld r31,$FRAME-8*1($sp) + addi $sp,$sp,$FRAME + blr + .long 0 + .byte 0,12,4,0,0x80,16,3,0 + .long 0 +.size ecp_nistz256_point_add,.-ecp_nistz256_point_add +___ +} + +######################################################################## +# void ecp_nistz256_point_add_affine(P256_POINT *out,const P256_POINT *in1, +# const P256_POINT_AFFINE *in2); +if (1) { +my $FRAME = 64 + 32*10 + 16*8; +my ($res_x,$res_y,$res_z, + $U2,$S2,$H,$R,$Hsqr,$Hcub,$Rsqr)=map(64+32*$_,(0..9)); +my $Z1sqr = $S2; +# above map() describes stack layout with 10 temporary +# 256-bit vectors on top. +my ($rp_real,$ap_real,$bp_real,$in1infty,$in2infty,$temp)=map("r$_",(16..21)); + +$code.=<<___; +.globl ecp_nistz256_point_add_affine +.align 5 +ecp_nistz256_point_add_affine: + stdu $sp,-$FRAME($sp) + mflr r0 + std r16,$FRAME-8*16($sp) + std r17,$FRAME-8*15($sp) + std r18,$FRAME-8*14($sp) + std r19,$FRAME-8*13($sp) + std r20,$FRAME-8*12($sp) + std r21,$FRAME-8*11($sp) + std r22,$FRAME-8*10($sp) + std r23,$FRAME-8*9($sp) + std r24,$FRAME-8*8($sp) + std r25,$FRAME-8*7($sp) + std r26,$FRAME-8*6($sp) + std r27,$FRAME-8*5($sp) + std r28,$FRAME-8*4($sp) + std r29,$FRAME-8*3($sp) + std r30,$FRAME-8*2($sp) + std r31,$FRAME-8*1($sp) + + li $poly1,-1 + srdi $poly1,$poly1,32 # 0x00000000ffffffff + li $poly3,1 + orc $poly3,$poly3,$poly1 # 0xffffffff00000001 + + mr $rp_real,$rp + mr $ap_real,$ap + mr $bp_real,$bp + + ld $a0,64($ap) # in1_z + ld $a1,72($ap) + ld $a2,80($ap) + ld $a3,88($ap) + or $t0,$a0,$a1 + or $t2,$a2,$a3 + or $in1infty,$t0,$t2 + neg $t0,$in1infty + or $in1infty,$in1infty,$t0 + sradi $in1infty,$in1infty,63 # !in1infty + + ld $acc0,0($bp) # in2_x + ld $acc1,8($bp) + ld $acc2,16($bp) + ld $acc3,24($bp) + ld $t0,32($bp) # in2_y + ld $t1,40($bp) + ld $t2,48($bp) + ld $t3,56($bp) + or $acc0,$acc0,$acc1 + or $acc2,$acc2,$acc3 + or $acc0,$acc0,$acc2 + or $t0,$t0,$t1 + or $t2,$t2,$t3 + or $t0,$t0,$t2 + or $in2infty,$acc0,$t0 + neg $t0,$in2infty + or $in2infty,$in2infty,$t0 + sradi $in2infty,$in2infty,63 # !in2infty + + addi $rp,$sp,$Z1sqr + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(Z1sqr, in1_z); + + mr $a0,$acc0 + mr $a1,$acc1 + mr $a2,$acc2 + mr $a3,$acc3 + ld $bi,0($bp_real) + addi $bp,$bp_real,0 + addi $rp,$sp,$U2 + bl __ecp_nistz256_mul_mont # p256_mul_mont(U2, Z1sqr, in2_x); + + addi $bp,$ap_real,0 + ld $bi,64($ap_real) # forward load for p256_mul_mont + ld $a0,$Z1sqr+0($sp) + ld $a1,$Z1sqr+8($sp) + ld $a2,$Z1sqr+16($sp) + ld $a3,$Z1sqr+24($sp) + addi $rp,$sp,$H + bl __ecp_nistz256_sub_from # p256_sub(H, U2, in1_x); + + addi $bp,$ap_real,64 + addi $rp,$sp,$S2 + bl __ecp_nistz256_mul_mont # p256_mul_mont(S2, Z1sqr, in1_z); + + ld $bi,64($ap_real) + ld $a0,$H+0($sp) + ld $a1,$H+8($sp) + ld $a2,$H+16($sp) + ld $a3,$H+24($sp) + addi $bp,$ap_real,64 + addi $rp,$sp,$res_z + bl __ecp_nistz256_mul_mont # p256_mul_mont(res_z, H, in1_z); + + ld $bi,32($bp_real) + ld $a0,$S2+0($sp) + ld $a1,$S2+8($sp) + ld $a2,$S2+16($sp) + ld $a3,$S2+24($sp) + addi $bp,$bp_real,32 + addi $rp,$sp,$S2 + bl __ecp_nistz256_mul_mont # p256_mul_mont(S2, S2, in2_y); + + addi $bp,$ap_real,32 + ld $a0,$H+0($sp) # forward load for p256_sqr_mont + ld $a1,$H+8($sp) + ld $a2,$H+16($sp) + ld $a3,$H+24($sp) + addi $rp,$sp,$R + bl __ecp_nistz256_sub_from # p256_sub(R, S2, in1_y); + + addi $rp,$sp,$Hsqr + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(Hsqr, H); + + ld $a0,$R+0($sp) + ld $a1,$R+8($sp) + ld $a2,$R+16($sp) + ld $a3,$R+24($sp) + addi $rp,$sp,$Rsqr + bl __ecp_nistz256_sqr_mont # p256_sqr_mont(Rsqr, R); + + ld $bi,$H($sp) + ld $a0,$Hsqr+0($sp) + ld $a1,$Hsqr+8($sp) + ld $a2,$Hsqr+16($sp) + ld $a3,$Hsqr+24($sp) + addi $bp,$sp,$H + addi $rp,$sp,$Hcub + bl __ecp_nistz256_mul_mont # p256_mul_mont(Hcub, Hsqr, H); + + ld $bi,0($ap_real) + ld $a0,$Hsqr+0($sp) + ld $a1,$Hsqr+8($sp) + ld $a2,$Hsqr+16($sp) + ld $a3,$Hsqr+24($sp) + addi $bp,$ap_real,0 + addi $rp,$sp,$U2 + bl __ecp_nistz256_mul_mont # p256_mul_mont(U2, in1_x, Hsqr); + + mr $t0,$acc0 + mr $t1,$acc1 + mr $t2,$acc2 + mr $t3,$acc3 + addi $rp,$sp,$Hsqr + bl __ecp_nistz256_add # p256_mul_by_2(Hsqr, U2); + + addi $bp,$sp,$Rsqr + addi $rp,$sp,$res_x + bl __ecp_nistz256_sub_morf # p256_sub(res_x, Rsqr, Hsqr); + + addi $bp,$sp,$Hcub + bl __ecp_nistz256_sub_from # p256_sub(res_x, res_x, Hcub); + + addi $bp,$sp,$U2 + ld $bi,32($ap_real) # forward load for p256_mul_mont + ld $a0,$Hcub+0($sp) + ld $a1,$Hcub+8($sp) + ld $a2,$Hcub+16($sp) + ld $a3,$Hcub+24($sp) + addi $rp,$sp,$res_y + bl __ecp_nistz256_sub_morf # p256_sub(res_y, U2, res_x); + + addi $bp,$ap_real,32 + addi $rp,$sp,$S2 + bl __ecp_nistz256_mul_mont # p256_mul_mont(S2, in1_y, Hcub); + + ld $bi,$R($sp) + ld $a0,$res_y+0($sp) + ld $a1,$res_y+8($sp) + ld $a2,$res_y+16($sp) + ld $a3,$res_y+24($sp) + addi $bp,$sp,$R + addi $rp,$sp,$res_y + bl __ecp_nistz256_mul_mont # p256_mul_mont(res_y, res_y, R); + + addi $bp,$sp,$S2 + bl __ecp_nistz256_sub_from # p256_sub(res_y, res_y, S2); + + ld $t0,0($bp_real) # in2 + ld $t1,8($bp_real) + ld $t2,16($bp_real) + ld $t3,24($bp_real) + ld $a0,$res_x+0($sp) # res + ld $a1,$res_x+8($sp) + ld $a2,$res_x+16($sp) + ld $a3,$res_x+24($sp) +___ +for($i=0;$i<64;$i+=32) { # conditional moves +$code.=<<___; + ld $acc0,$i+0($ap_real) # in1 + ld $acc1,$i+8($ap_real) + ld $acc2,$i+16($ap_real) + ld $acc3,$i+24($ap_real) + andc $t0,$t0,$in1infty + andc $t1,$t1,$in1infty + andc $t2,$t2,$in1infty + andc $t3,$t3,$in1infty + and $a0,$a0,$in1infty + and $a1,$a1,$in1infty + and $a2,$a2,$in1infty + and $a3,$a3,$in1infty + or $t0,$t0,$a0 + or $t1,$t1,$a1 + or $t2,$t2,$a2 + or $t3,$t3,$a3 + andc $acc0,$acc0,$in2infty + andc $acc1,$acc1,$in2infty + andc $acc2,$acc2,$in2infty + andc $acc3,$acc3,$in2infty + and $t0,$t0,$in2infty + and $t1,$t1,$in2infty + and $t2,$t2,$in2infty + and $t3,$t3,$in2infty + or $acc0,$acc0,$t0 + or $acc1,$acc1,$t1 + or $acc2,$acc2,$t2 + or $acc3,$acc3,$t3 +___ +$code.=<<___ if ($i==0); + ld $t0,32($bp_real) # in2 + ld $t1,40($bp_real) + ld $t2,48($bp_real) + ld $t3,56($bp_real) +___ +$code.=<<___ if ($i==32); + li $t0,1 # Lone_mont + not $t1,$poly1 + li $t2,-1 + not $t3,$poly3 +___ +$code.=<<___; + ld $a0,$res_x+$i+32($sp) + ld $a1,$res_x+$i+40($sp) + ld $a2,$res_x+$i+48($sp) + ld $a3,$res_x+$i+56($sp) + std $acc0,$i+0($rp_real) + std $acc1,$i+8($rp_real) + std $acc2,$i+16($rp_real) + std $acc3,$i+24($rp_real) +___ +} +$code.=<<___; + ld $acc0,$i+0($ap_real) # in1 + ld $acc1,$i+8($ap_real) + ld $acc2,$i+16($ap_real) + ld $acc3,$i+24($ap_real) + andc $t0,$t0,$in1infty + andc $t1,$t1,$in1infty + andc $t2,$t2,$in1infty + andc $t3,$t3,$in1infty + and $a0,$a0,$in1infty + and $a1,$a1,$in1infty + and $a2,$a2,$in1infty + and $a3,$a3,$in1infty + or $t0,$t0,$a0 + or $t1,$t1,$a1 + or $t2,$t2,$a2 + or $t3,$t3,$a3 + andc $acc0,$acc0,$in2infty + andc $acc1,$acc1,$in2infty + andc $acc2,$acc2,$in2infty + andc $acc3,$acc3,$in2infty + and $t0,$t0,$in2infty + and $t1,$t1,$in2infty + and $t2,$t2,$in2infty + and $t3,$t3,$in2infty + or $acc0,$acc0,$t0 + or $acc1,$acc1,$t1 + or $acc2,$acc2,$t2 + or $acc3,$acc3,$t3 + std $acc0,$i+0($rp_real) + std $acc1,$i+8($rp_real) + std $acc2,$i+16($rp_real) + std $acc3,$i+24($rp_real) + + mtlr r0 + ld r16,$FRAME-8*16($sp) + ld r17,$FRAME-8*15($sp) + ld r18,$FRAME-8*14($sp) + ld r19,$FRAME-8*13($sp) + ld r20,$FRAME-8*12($sp) + ld r21,$FRAME-8*11($sp) + ld r22,$FRAME-8*10($sp) + ld r23,$FRAME-8*9($sp) + ld r24,$FRAME-8*8($sp) + ld r25,$FRAME-8*7($sp) + ld r26,$FRAME-8*6($sp) + ld r27,$FRAME-8*5($sp) + ld r28,$FRAME-8*4($sp) + ld r29,$FRAME-8*3($sp) + ld r30,$FRAME-8*2($sp) + ld r31,$FRAME-8*1($sp) + addi $sp,$sp,$FRAME + blr + .long 0 + .byte 0,12,4,0,0x80,16,3,0 + .long 0 +.size ecp_nistz256_point_add_affine,.-ecp_nistz256_point_add_affine +___ +} +if (1) { +my ($ordk,$ord0,$ord1,$t4) = map("r$_",(18..21)); +my ($ord2,$ord3,$zr) = ($poly1,$poly3,"r0"); + +$code.=<<___; +######################################################################## +# void ecp_nistz256_ord_mul_mont(uint64_t res[4], uint64_t a[4], +# uint64_t b[4]); +.globl ecp_nistz256_ord_mul_mont +.align 5 +ecp_nistz256_ord_mul_mont: + stdu $sp,-160($sp) + std r18,48($sp) + std r19,56($sp) + std r20,64($sp) + std r21,72($sp) + std r22,80($sp) + std r23,88($sp) + std r24,96($sp) + std r25,104($sp) + std r26,112($sp) + std r27,120($sp) + std r28,128($sp) + std r29,136($sp) + std r30,144($sp) + std r31,152($sp) + + ld $a0,0($ap) + ld $bi,0($bp) + ld $a1,8($ap) + ld $a2,16($ap) + ld $a3,24($ap) + + lis $ordk,0xccd1 + lis $ord0,0xf3b9 + lis $ord1,0xbce6 + ori $ordk,$ordk,0xc8aa + ori $ord0,$ord0,0xcac2 + ori $ord1,$ord1,0xfaad + sldi $ordk,$ordk,32 + sldi $ord0,$ord0,32 + sldi $ord1,$ord1,32 + oris $ordk,$ordk,0xee00 + oris $ord0,$ord0,0xfc63 + oris $ord1,$ord1,0xa717 + ori $ordk,$ordk,0xbc4f # 0xccd1c8aaee00bc4f + ori $ord0,$ord0,0x2551 # 0xf3b9cac2fc632551 + ori $ord1,$ord1,0x9e84 # 0xbce6faada7179e84 + li $ord2,-1 # 0xffffffffffffffff + sldi $ord3,$ord2,32 # 0xffffffff00000000 + li $zr,0 + + mulld $acc0,$a0,$bi # a[0]*b[0] + mulhdu $t0,$a0,$bi + + mulld $acc1,$a1,$bi # a[1]*b[0] + mulhdu $t1,$a1,$bi + + mulld $acc2,$a2,$bi # a[2]*b[0] + mulhdu $t2,$a2,$bi + + mulld $acc3,$a3,$bi # a[3]*b[0] + mulhdu $acc4,$a3,$bi + + mulld $t4,$acc0,$ordk + + addc $acc1,$acc1,$t0 # accumulate high parts of multiplication + adde $acc2,$acc2,$t1 + adde $acc3,$acc3,$t2 + addze $acc4,$acc4 + li $acc5,0 +___ +for ($i=1;$i<4;$i++) { + ################################################################ + # ffff0000.ffffffff.yyyyyyyy.zzzzzzzz + # * abcdefgh + # + xxxxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx + # + # Now observing that ff..ff*x = (2^n-1)*x = 2^n*x-x, we + # rewrite above as: + # + # xxxxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx.xxxxxxxx + # - 0000abcd.efgh0000.abcdefgh.00000000.00000000 + # + abcdefgh.abcdefgh.yzayzbyz.cyzdyzey.zfyzgyzh +$code.=<<___; + ld $bi,8*$i($bp) # b[i] + + sldi $t0,$t4,32 + subfc $acc2,$t4,$acc2 + srdi $t1,$t4,32 + subfe $acc3,$t0,$acc3 + subfe $acc4,$t1,$acc4 + subfe $acc5,$zr,$acc5 + + addic $t0,$acc0,-1 # discarded + mulhdu $t1,$ord0,$t4 + mulld $t2,$ord1,$t4 + mulhdu $t3,$ord1,$t4 + + adde $t2,$t2,$t1 + mulld $t0,$a0,$bi + addze $t3,$t3 + mulld $t1,$a1,$bi + + addc $acc0,$acc1,$t2 + mulld $t2,$a2,$bi + adde $acc1,$acc2,$t3 + mulld $t3,$a3,$bi + adde $acc2,$acc3,$t4 + adde $acc3,$acc4,$t4 + addze $acc4,$acc5 + + addc $acc0,$acc0,$t0 # accumulate low parts + mulhdu $t0,$a0,$bi + adde $acc1,$acc1,$t1 + mulhdu $t1,$a1,$bi + adde $acc2,$acc2,$t2 + mulhdu $t2,$a2,$bi + adde $acc3,$acc3,$t3 + mulhdu $t3,$a3,$bi + addze $acc4,$acc4 + mulld $t4,$acc0,$ordk + addc $acc1,$acc1,$t0 # accumulate high parts + adde $acc2,$acc2,$t1 + adde $acc3,$acc3,$t2 + adde $acc4,$acc4,$t3 + addze $acc5,$zr +___ +} +$code.=<<___; + sldi $t0,$t4,32 # last reduction + subfc $acc2,$t4,$acc2 + srdi $t1,$t4,32 + subfe $acc3,$t0,$acc3 + subfe $acc4,$t1,$acc4 + subfe $acc5,$zr,$acc5 + + addic $t0,$acc0,-1 # discarded + mulhdu $t1,$ord0,$t4 + mulld $t2,$ord1,$t4 + mulhdu $t3,$ord1,$t4 + + adde $t2,$t2,$t1 + addze $t3,$t3 + + addc $acc0,$acc1,$t2 + adde $acc1,$acc2,$t3 + adde $acc2,$acc3,$t4 + adde $acc3,$acc4,$t4 + addze $acc4,$acc5 + + subfc $acc0,$ord0,$acc0 # ret -= modulus + subfe $acc1,$ord1,$acc1 + subfe $acc2,$ord2,$acc2 + subfe $acc3,$ord3,$acc3 + subfe $acc4,$zr,$acc4 + + and $t0,$ord0,$acc4 + and $t1,$ord1,$acc4 + addc $acc0,$acc0,$t0 # ret += modulus if borrow + and $t3,$ord3,$acc4 + adde $acc1,$acc1,$t1 + adde $acc2,$acc2,$acc4 + adde $acc3,$acc3,$t3 + + std $acc0,0($rp) + std $acc1,8($rp) + std $acc2,16($rp) + std $acc3,24($rp) + + ld r18,48($sp) + ld r19,56($sp) + ld r20,64($sp) + ld r21,72($sp) + ld r22,80($sp) + ld r23,88($sp) + ld r24,96($sp) + ld r25,104($sp) + ld r26,112($sp) + ld r27,120($sp) + ld r28,128($sp) + ld r29,136($sp) + ld r30,144($sp) + ld r31,152($sp) + addi $sp,$sp,160 + blr + .long 0 + .byte 0,12,4,0,0x80,14,3,0 + .long 0 +.size ecp_nistz256_ord_mul_mont,.-ecp_nistz256_ord_mul_mont + +################################################################################ +# void ecp_nistz256_ord_sqr_mont(uint64_t res[4], uint64_t a[4], +# int rep); +.globl ecp_nistz256_ord_sqr_mont +.align 5 +ecp_nistz256_ord_sqr_mont: + stdu $sp,-160($sp) + std r18,48($sp) + std r19,56($sp) + std r20,64($sp) + std r21,72($sp) + std r22,80($sp) + std r23,88($sp) + std r24,96($sp) + std r25,104($sp) + std r26,112($sp) + std r27,120($sp) + std r28,128($sp) + std r29,136($sp) + std r30,144($sp) + std r31,152($sp) + + mtctr $bp + + ld $a0,0($ap) + ld $a1,8($ap) + ld $a2,16($ap) + ld $a3,24($ap) + + lis $ordk,0xccd1 + lis $ord0,0xf3b9 + lis $ord1,0xbce6 + ori $ordk,$ordk,0xc8aa + ori $ord0,$ord0,0xcac2 + ori $ord1,$ord1,0xfaad + sldi $ordk,$ordk,32 + sldi $ord0,$ord0,32 + sldi $ord1,$ord1,32 + oris $ordk,$ordk,0xee00 + oris $ord0,$ord0,0xfc63 + oris $ord1,$ord1,0xa717 + ori $ordk,$ordk,0xbc4f # 0xccd1c8aaee00bc4f + ori $ord0,$ord0,0x2551 # 0xf3b9cac2fc632551 + ori $ord1,$ord1,0x9e84 # 0xbce6faada7179e84 + li $ord2,-1 # 0xffffffffffffffff + sldi $ord3,$ord2,32 # 0xffffffff00000000 + li $zr,0 + b .Loop_ord_sqr + +.align 5 +.Loop_ord_sqr: + ################################################################ + # | | | | | |a1*a0| | + # | | | | |a2*a0| | | + # | |a3*a2|a3*a0| | | | + # | | | |a2*a1| | | | + # | | |a3*a1| | | | | + # *| | | | | | | | 2| + # +|a3*a3|a2*a2|a1*a1|a0*a0| + # |--+--+--+--+--+--+--+--| + # |A7|A6|A5|A4|A3|A2|A1|A0|, where Ax is $accx, i.e. follow $accx + # + # "can't overflow" below mark carrying into high part of + # multiplication result, which can't overflow, because it + # can never be all ones. + + mulld $acc1,$a1,$a0 # a[1]*a[0] + mulhdu $t1,$a1,$a0 + mulld $acc2,$a2,$a0 # a[2]*a[0] + mulhdu $t2,$a2,$a0 + mulld $acc3,$a3,$a0 # a[3]*a[0] + mulhdu $acc4,$a3,$a0 + + addc $acc2,$acc2,$t1 # accumulate high parts of multiplication + mulld $t0,$a2,$a1 # a[2]*a[1] + mulhdu $t1,$a2,$a1 + adde $acc3,$acc3,$t2 + mulld $t2,$a3,$a1 # a[3]*a[1] + mulhdu $t3,$a3,$a1 + addze $acc4,$acc4 # can't overflow + + mulld $acc5,$a3,$a2 # a[3]*a[2] + mulhdu $acc6,$a3,$a2 + + addc $t1,$t1,$t2 # accumulate high parts of multiplication + mulld $acc0,$a0,$a0 # a[0]*a[0] + addze $t2,$t3 # can't overflow + + addc $acc3,$acc3,$t0 # accumulate low parts of multiplication + mulhdu $a0,$a0,$a0 + adde $acc4,$acc4,$t1 + mulld $t1,$a1,$a1 # a[1]*a[1] + adde $acc5,$acc5,$t2 + mulhdu $a1,$a1,$a1 + addze $acc6,$acc6 # can't overflow + + addc $acc1,$acc1,$acc1 # acc[1-6]*=2 + mulld $t2,$a2,$a2 # a[2]*a[2] + adde $acc2,$acc2,$acc2 + mulhdu $a2,$a2,$a2 + adde $acc3,$acc3,$acc3 + mulld $t3,$a3,$a3 # a[3]*a[3] + adde $acc4,$acc4,$acc4 + mulhdu $a3,$a3,$a3 + adde $acc5,$acc5,$acc5 + adde $acc6,$acc6,$acc6 + addze $acc7,$zr + + addc $acc1,$acc1,$a0 # +a[i]*a[i] + mulld $t4,$acc0,$ordk + adde $acc2,$acc2,$t1 + adde $acc3,$acc3,$a1 + adde $acc4,$acc4,$t2 + adde $acc5,$acc5,$a2 + adde $acc6,$acc6,$t3 + adde $acc7,$acc7,$a3 +___ +for($i=0; $i<4; $i++) { # reductions +$code.=<<___; + addic $t0,$acc0,-1 # discarded + mulhdu $t1,$ord0,$t4 + mulld $t2,$ord1,$t4 + mulhdu $t3,$ord1,$t4 + + adde $t2,$t2,$t1 + addze $t3,$t3 + + addc $acc0,$acc1,$t2 + adde $acc1,$acc2,$t3 + adde $acc2,$acc3,$t4 + adde $acc3,$zr,$t4 # can't overflow +___ +$code.=<<___ if ($i<3); + mulld $t3,$acc0,$ordk +___ +$code.=<<___; + sldi $t0,$t4,32 + subfc $acc1,$t4,$acc1 + srdi $t1,$t4,32 + subfe $acc2,$t0,$acc2 + subfe $acc3,$t1,$acc3 # can't borrow +___ + ($t3,$t4) = ($t4,$t3); +} +$code.=<<___; + addc $acc0,$acc0,$acc4 # accumulate upper half + adde $acc1,$acc1,$acc5 + adde $acc2,$acc2,$acc6 + adde $acc3,$acc3,$acc7 + addze $acc4,$zr + + subfc $acc0,$ord0,$acc0 # ret -= modulus + subfe $acc1,$ord1,$acc1 + subfe $acc2,$ord2,$acc2 + subfe $acc3,$ord3,$acc3 + subfe $acc4,$zr,$acc4 + + and $t0,$ord0,$acc4 + and $t1,$ord1,$acc4 + addc $a0,$acc0,$t0 # ret += modulus if borrow + and $t3,$ord3,$acc4 + adde $a1,$acc1,$t1 + adde $a2,$acc2,$acc4 + adde $a3,$acc3,$t3 + + bdnz .Loop_ord_sqr + + std $a0,0($rp) + std $a1,8($rp) + std $a2,16($rp) + std $a3,24($rp) + + ld r18,48($sp) + ld r19,56($sp) + ld r20,64($sp) + ld r21,72($sp) + ld r22,80($sp) + ld r23,88($sp) + ld r24,96($sp) + ld r25,104($sp) + ld r26,112($sp) + ld r27,120($sp) + ld r28,128($sp) + ld r29,136($sp) + ld r30,144($sp) + ld r31,152($sp) + addi $sp,$sp,160 + blr + .long 0 + .byte 0,12,4,0,0x80,14,3,0 + .long 0 +.size ecp_nistz256_ord_sqr_mont,.-ecp_nistz256_ord_sqr_mont +___ +} } + +######################################################################## +# scatter-gather subroutines +{ +my ($out,$inp,$index,$mask)=map("r$_",(3..7)); +$code.=<<___; +######################################################################## +# void ecp_nistz256_scatter_w5(void *out, const P256_POINT *inp, +# int index); +.globl ecp_nistz256_scatter_w5 +.align 4 +ecp_nistz256_scatter_w5: + slwi $index,$index,2 + add $out,$out,$index + + ld r8, 0($inp) # X + ld r9, 8($inp) + ld r10,16($inp) + ld r11,24($inp) + + stw r8, 64*0-4($out) + srdi r8, r8, 32 + stw r9, 64*1-4($out) + srdi r9, r9, 32 + stw r10,64*2-4($out) + srdi r10,r10,32 + stw r11,64*3-4($out) + srdi r11,r11,32 + stw r8, 64*4-4($out) + stw r9, 64*5-4($out) + stw r10,64*6-4($out) + stw r11,64*7-4($out) + addi $out,$out,64*8 + + ld r8, 32($inp) # Y + ld r9, 40($inp) + ld r10,48($inp) + ld r11,56($inp) + + stw r8, 64*0-4($out) + srdi r8, r8, 32 + stw r9, 64*1-4($out) + srdi r9, r9, 32 + stw r10,64*2-4($out) + srdi r10,r10,32 + stw r11,64*3-4($out) + srdi r11,r11,32 + stw r8, 64*4-4($out) + stw r9, 64*5-4($out) + stw r10,64*6-4($out) + stw r11,64*7-4($out) + addi $out,$out,64*8 + + ld r8, 64($inp) # Z + ld r9, 72($inp) + ld r10,80($inp) + ld r11,88($inp) + + stw r8, 64*0-4($out) + srdi r8, r8, 32 + stw r9, 64*1-4($out) + srdi r9, r9, 32 + stw r10,64*2-4($out) + srdi r10,r10,32 + stw r11,64*3-4($out) + srdi r11,r11,32 + stw r8, 64*4-4($out) + stw r9, 64*5-4($out) + stw r10,64*6-4($out) + stw r11,64*7-4($out) + + blr + .long 0 + .byte 0,12,0x14,0,0,0,3,0 + .long 0 +.size ecp_nistz256_scatter_w5,.-ecp_nistz256_scatter_w5 + +######################################################################## +# void ecp_nistz256_gather_w5(P256_POINT *out, const void *inp, +# int index); +.globl ecp_nistz256_gather_w5 +.align 4 +ecp_nistz256_gather_w5: + neg r0,$index + sradi r0,r0,63 + + add $index,$index,r0 + slwi $index,$index,2 + add $inp,$inp,$index + + lwz r5, 64*0($inp) + lwz r6, 64*1($inp) + lwz r7, 64*2($inp) + lwz r8, 64*3($inp) + lwz r9, 64*4($inp) + lwz r10,64*5($inp) + lwz r11,64*6($inp) + lwz r12,64*7($inp) + addi $inp,$inp,64*8 + sldi r9, r9, 32 + sldi r10,r10,32 + sldi r11,r11,32 + sldi r12,r12,32 + or r5,r5,r9 + or r6,r6,r10 + or r7,r7,r11 + or r8,r8,r12 + and r5,r5,r0 + and r6,r6,r0 + and r7,r7,r0 + and r8,r8,r0 + std r5,0($out) # X + std r6,8($out) + std r7,16($out) + std r8,24($out) + + lwz r5, 64*0($inp) + lwz r6, 64*1($inp) + lwz r7, 64*2($inp) + lwz r8, 64*3($inp) + lwz r9, 64*4($inp) + lwz r10,64*5($inp) + lwz r11,64*6($inp) + lwz r12,64*7($inp) + addi $inp,$inp,64*8 + sldi r9, r9, 32 + sldi r10,r10,32 + sldi r11,r11,32 + sldi r12,r12,32 + or r5,r5,r9 + or r6,r6,r10 + or r7,r7,r11 + or r8,r8,r12 + and r5,r5,r0 + and r6,r6,r0 + and r7,r7,r0 + and r8,r8,r0 + std r5,32($out) # Y + std r6,40($out) + std r7,48($out) + std r8,56($out) + + lwz r5, 64*0($inp) + lwz r6, 64*1($inp) + lwz r7, 64*2($inp) + lwz r8, 64*3($inp) + lwz r9, 64*4($inp) + lwz r10,64*5($inp) + lwz r11,64*6($inp) + lwz r12,64*7($inp) + sldi r9, r9, 32 + sldi r10,r10,32 + sldi r11,r11,32 + sldi r12,r12,32 + or r5,r5,r9 + or r6,r6,r10 + or r7,r7,r11 + or r8,r8,r12 + and r5,r5,r0 + and r6,r6,r0 + and r7,r7,r0 + and r8,r8,r0 + std r5,64($out) # Z + std r6,72($out) + std r7,80($out) + std r8,88($out) + + blr + .long 0 + .byte 0,12,0x14,0,0,0,3,0 + .long 0 +.size ecp_nistz256_gather_w5,.-ecp_nistz256_gather_w5 + +######################################################################## +# void ecp_nistz256_scatter_w7(void *out, const P256_POINT_AFFINE *inp, +# int index); +.globl ecp_nistz256_scatter_w7 +.align 4 +ecp_nistz256_scatter_w7: + li r0,8 + mtctr r0 + add $out,$out,$index + subi $inp,$inp,8 + +.Loop_scatter_w7: + ldu r0,8($inp) + stb r0,64*0-1($out) + srdi r0,r0,8 + stb r0,64*1-1($out) + srdi r0,r0,8 + stb r0,64*2-1($out) + srdi r0,r0,8 + stb r0,64*3-1($out) + srdi r0,r0,8 + stb r0,64*4-1($out) + srdi r0,r0,8 + stb r0,64*5-1($out) + srdi r0,r0,8 + stb r0,64*6-1($out) + srdi r0,r0,8 + stb r0,64*7-1($out) + addi $out,$out,64*8 + bdnz .Loop_scatter_w7 + + blr + .long 0 + .byte 0,12,0x14,0,0,0,3,0 + .long 0 +.size ecp_nistz256_scatter_w7,.-ecp_nistz256_scatter_w7 + +######################################################################## +# void ecp_nistz256_gather_w7(P256_POINT_AFFINE *out, const void *inp, +# int index); +.globl ecp_nistz256_gather_w7 +.align 4 +ecp_nistz256_gather_w7: + li r0,8 + mtctr r0 + neg r0,$index + sradi r0,r0,63 + + add $index,$index,r0 + add $inp,$inp,$index + subi $out,$out,8 + +.Loop_gather_w7: + lbz r5, 64*0($inp) + lbz r6, 64*1($inp) + lbz r7, 64*2($inp) + lbz r8, 64*3($inp) + lbz r9, 64*4($inp) + lbz r10,64*5($inp) + lbz r11,64*6($inp) + lbz r12,64*7($inp) + addi $inp,$inp,64*8 + + sldi r6, r6, 8 + sldi r7, r7, 16 + sldi r8, r8, 24 + sldi r9, r9, 32 + sldi r10,r10,40 + sldi r11,r11,48 + sldi r12,r12,56 + + or r5,r5,r6 + or r7,r7,r8 + or r9,r9,r10 + or r11,r11,r12 + or r5,r5,r7 + or r9,r9,r11 + or r5,r5,r9 + and r5,r5,r0 + stdu r5,8($out) + bdnz .Loop_gather_w7 + + blr + .long 0 + .byte 0,12,0x14,0,0,0,3,0 + .long 0 +.size ecp_nistz256_gather_w7,.-ecp_nistz256_gather_w7 +___ +} + +foreach (split("\n",$code)) { + s/\`([^\`]*)\`/eval $1/ge; + + print $_,"\n"; +} +close STDOUT; # enforce flush diff --git a/crypto/ec/asm/ecp_nistz256-sparcv9.pl b/crypto/ec/asm/ecp_nistz256-sparcv9.pl index 97201cb2..9af1fae8 100755 --- a/crypto/ec/asm/ecp_nistz256-sparcv9.pl +++ b/crypto/ec/asm/ecp_nistz256-sparcv9.pl @@ -413,7 +413,7 @@ __ecp_nistz256_add: ! if a+b >= modulus, subtract modulus. ! ! But since comparison implies subtraction, we subtract - ! modulus and then add it back if subraction borrowed. + ! modulus and then add it back if subtraction borrowed. subcc @acc[0],-1,@acc[0] subccc @acc[1],-1,@acc[1] @@ -1592,7 +1592,7 @@ ___ ######################################################################## # Following subroutines are VIS3 counterparts of those above that # implement ones found in ecp_nistz256.c. Key difference is that they -# use 128-bit muliplication and addition with 64-bit carry, and in order +# use 128-bit multiplication and addition with 64-bit carry, and in order # to do that they perform conversion from uin32_t[8] to uint64_t[4] upon # entry and vice versa on return. # @@ -1874,7 +1874,7 @@ $code.=<<___ if ($i<3); ldx [$bp+8*($i+1)],$bi ! bp[$i+1] ___ $code.=<<___; - addcc $acc1,$t0,$acc1 ! accumulate high parts of multiplication + addcc $acc1,$t0,$acc1 ! accumulate high parts of multiplication sllx $acc0,32,$t0 addxccc $acc2,$t1,$acc2 srlx $acc0,32,$t1 @@ -1977,7 +1977,7 @@ $code.=<<___; srlx $acc0,32,$t1 addxccc $acc3,$t2,$acc2 ! +=acc[0]*0xFFFFFFFF00000001 sub $acc0,$t0,$t2 ! acc0*0xFFFFFFFF00000001, low part - addxc %g0,$t3,$acc3 ! cant't overflow + addxc %g0,$t3,$acc3 ! can't overflow ___ } $code.=<<___; diff --git a/crypto/ec/asm/ecp_nistz256-x86.pl b/crypto/ec/asm/ecp_nistz256-x86.pl index 1d9e0061..a89a9f93 100755 --- a/crypto/ec/asm/ecp_nistz256-x86.pl +++ b/crypto/ec/asm/ecp_nistz256-x86.pl @@ -45,7 +45,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"ecp_nistz256-x86.pl",$ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$ARGV[$#ARGV] eq "386"); $sse2=0; for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } @@ -443,7 +443,7 @@ for(1..37) { &mov (&DWP(20,"esp"),"eax"); &mov (&DWP(24,"esp"),"eax"); &mov (&DWP(28,"esp"),"eax"); - + &call ("_ecp_nistz256_sub"); &stack_pop(8); diff --git a/crypto/ec/asm/ecp_nistz256-x86_64.pl b/crypto/ec/asm/ecp_nistz256-x86_64.pl index e65e8297..eba6ffd4 100755 --- a/crypto/ec/asm/ecp_nistz256-x86_64.pl +++ b/crypto/ec/asm/ecp_nistz256-x86_64.pl @@ -1,15 +1,17 @@ #! /usr/bin/env perl -# Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2014-2018 The OpenSSL Project Authors. All Rights Reserved. # Copyright (c) 2014, Intel Corporation. All Rights Reserved. +# Copyright (c) 2015 CloudFlare, Inc. # # 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 # -# Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) +# Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1, 3) # (1) Intel Corporation, Israel Development Center, Haifa, Israel # (2) University of Haifa, Israel +# (3) CloudFlare, Inc. # # Reference: # S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with diff --git a/crypto/ec/asm/x25519-x86_64.pl b/crypto/ec/asm/x25519-x86_64.pl new file mode 100755 index 00000000..68a7771a --- /dev/null +++ b/crypto/ec/asm/x25519-x86_64.pl @@ -0,0 +1,818 @@ +#!/usr/bin/env perl +# Copyright 2018 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# X25519 lower-level primitives for x86_86. +# +# February 2018. +# +# This module implements radix 2^51 multiplication and squaring, and +# radix 2^64 multiplication, squaring, addition, subtraction and final +# reduction. Latter radix is used on ADCX/ADOX-capable processors such +# as Broadwell. On related note one should mention that there are +# vector implementations that provide significantly better performance +# on some processors(*), but they are large and overly complex. Which +# in combination with them being effectively processor-specific makes +# the undertaking hard to justify. The goal for this implementation +# is rather versatility and simplicity [and ultimately formal +# verification]. +# +# (*) For example sandy2x should provide ~30% improvement on Sandy +# Bridge, but only nominal ~5% on Haswell [and big loss on +# Broadwell and successors]. +# +###################################################################### +# Improvement coefficients: +# +# amd64-51(*) gcc-5.x(**) +# +# P4 +22% +40% +# Sandy Bridge -3% +11% +# Haswell -1% +13% +# Broadwell(***) +26% +30% +# Skylake(***) +30% +47% +# Silvermont +20% +26% +# Goldmont +40% +50% +# Bulldozer +20% +9% +# Ryzen(***) +35% +32% +# VIA +170% +120% +# +# (*) amd64-51 is popular assembly implementation with 2^51 radix, +# only multiplication and squaring subroutines were linked +# for comparison, but not complete ladder step; gain on most +# processors is because this module refrains from shld, and +# minor regression on others is because this does result in +# higher instruction count; +# (**) compiler is free to inline functions, in assembly one would +# need to implement ladder step to do that, and it will improve +# performance by several percent; +# (***) ADCX/ADOX result for 2^64 radix, there is no corresponding +# C implementation, so that comparison is always against +# 2^51 radix; + +$flavour = shift; +$output = shift; +if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } + +$win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or +die "can't locate x86_64-xlate.pl"; + +open OUT,"| \"$^X\" \"$xlate\" $flavour \"$output\""; +*STDOUT=*OUT; + +if (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1` + =~ /GNU assembler version ([2-9]\.[0-9]+)/) { + $addx = ($1>=2.23); +} + +if (!$addx && $win64 && ($flavour =~ /nasm/ || $ENV{ASM} =~ /nasm/) && + `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)/) { + $addx = ($1>=2.10); +} + +if (!$addx && $win64 && ($flavour =~ /masm/ || $ENV{ASM} =~ /ml64/) && + `ml64 2>&1` =~ /Version ([0-9]+)\./) { + $addx = ($1>=12); +} + +if (!$addx && `$ENV{CC} -v 2>&1` =~ /((?:^clang|LLVM) version|.*based on LLVM) ([3-9])\.([0-9]+)/) { + my $ver = $2 + $3/100.0; # 3.1->3.01, 3.10->3.10 + $addx = ($ver>=3.03); +} + +$code.=<<___; +.text + +.globl x25519_fe51_mul +.type x25519_fe51_mul,\@function,3 +.align 32 +x25519_fe51_mul: + push %rbp + push %rbx + push %r12 + push %r13 + push %r14 + push %r15 + lea -8*5(%rsp),%rsp + + mov 8*0(%rsi),%rax # f[0] + mov 8*0(%rdx),%r11 # load g[0-4] + mov 8*1(%rdx),%r12 + mov 8*2(%rdx),%r13 + mov 8*3(%rdx),%rbp + mov 8*4(%rdx),%r14 + + mov %rdi,8*4(%rsp) # offload 1st argument + mov %rax,%rdi + mulq %r11 # f[0]*g[0] + mov %r11,8*0(%rsp) # offload g[0] + mov %rax,%rbx # %rbx:%rcx = h0 + mov %rdi,%rax + mov %rdx,%rcx + mulq %r12 # f[0]*g[1] + mov %r12,8*1(%rsp) # offload g[1] + mov %rax,%r8 # %r8:%r9 = h1 + mov %rdi,%rax + lea (%r14,%r14,8),%r15 + mov %rdx,%r9 + mulq %r13 # f[0]*g[2] + mov %r13,8*2(%rsp) # offload g[2] + mov %rax,%r10 # %r10:%r11 = h2 + mov %rdi,%rax + lea (%r14,%r15,2),%rdi # g[4]*19 + mov %rdx,%r11 + mulq %rbp # f[0]*g[3] + mov %rax,%r12 # %r12:%r13 = h3 + mov 8*0(%rsi),%rax # f[0] + mov %rdx,%r13 + mulq %r14 # f[0]*g[4] + mov %rax,%r14 # %r14:%r15 = h4 + mov 8*1(%rsi),%rax # f[1] + mov %rdx,%r15 + + mulq %rdi # f[1]*g[4]*19 + add %rax,%rbx + mov 8*2(%rsi),%rax # f[2] + adc %rdx,%rcx + mulq %rdi # f[2]*g[4]*19 + add %rax,%r8 + mov 8*3(%rsi),%rax # f[3] + adc %rdx,%r9 + mulq %rdi # f[3]*g[4]*19 + add %rax,%r10 + mov 8*4(%rsi),%rax # f[4] + adc %rdx,%r11 + mulq %rdi # f[4]*g[4]*19 + imulq \$19,%rbp,%rdi # g[3]*19 + add %rax,%r12 + mov 8*1(%rsi),%rax # f[1] + adc %rdx,%r13 + mulq %rbp # f[1]*g[3] + mov 8*2(%rsp),%rbp # g[2] + add %rax,%r14 + mov 8*2(%rsi),%rax # f[2] + adc %rdx,%r15 + + mulq %rdi # f[2]*g[3]*19 + add %rax,%rbx + mov 8*3(%rsi),%rax # f[3] + adc %rdx,%rcx + mulq %rdi # f[3]*g[3]*19 + add %rax,%r8 + mov 8*4(%rsi),%rax # f[4] + adc %rdx,%r9 + mulq %rdi # f[4]*g[3]*19 + imulq \$19,%rbp,%rdi # g[2]*19 + add %rax,%r10 + mov 8*1(%rsi),%rax # f[1] + adc %rdx,%r11 + mulq %rbp # f[1]*g[2] + add %rax,%r12 + mov 8*2(%rsi),%rax # f[2] + adc %rdx,%r13 + mulq %rbp # f[2]*g[2] + mov 8*1(%rsp),%rbp # g[1] + add %rax,%r14 + mov 8*3(%rsi),%rax # f[3] + adc %rdx,%r15 + + mulq %rdi # f[3]*g[2]*19 + add %rax,%rbx + mov 8*4(%rsi),%rax # f[3] + adc %rdx,%rcx + mulq %rdi # f[4]*g[2]*19 + add %rax,%r8 + mov 8*1(%rsi),%rax # f[1] + adc %rdx,%r9 + mulq %rbp # f[1]*g[1] + imulq \$19,%rbp,%rdi + add %rax,%r10 + mov 8*2(%rsi),%rax # f[2] + adc %rdx,%r11 + mulq %rbp # f[2]*g[1] + add %rax,%r12 + mov 8*3(%rsi),%rax # f[3] + adc %rdx,%r13 + mulq %rbp # f[3]*g[1] + mov 8*0(%rsp),%rbp # g[0] + add %rax,%r14 + mov 8*4(%rsi),%rax # f[4] + adc %rdx,%r15 + + mulq %rdi # f[4]*g[1]*19 + add %rax,%rbx + mov 8*1(%rsi),%rax # f[1] + adc %rdx,%rcx + mul %rbp # f[1]*g[0] + add %rax,%r8 + mov 8*2(%rsi),%rax # f[2] + adc %rdx,%r9 + mul %rbp # f[2]*g[0] + add %rax,%r10 + mov 8*3(%rsi),%rax # f[3] + adc %rdx,%r11 + mul %rbp # f[3]*g[0] + add %rax,%r12 + mov 8*4(%rsi),%rax # f[4] + adc %rdx,%r13 + mulq %rbp # f[4]*g[0] + add %rax,%r14 + adc %rdx,%r15 + + mov 8*4(%rsp),%rdi # restore 1st argument + jmp .Lreduce51 +.size x25519_fe51_mul,.-x25519_fe51_mul + +.globl x25519_fe51_sqr +.type x25519_fe51_sqr,\@function,2 +.align 32 +x25519_fe51_sqr: + push %rbp + push %rbx + push %r12 + push %r13 + push %r14 + push %r15 + lea -8*5(%rsp),%rsp + + mov 8*0(%rsi),%rax # g[0] + mov 8*2(%rsi),%r15 # g[2] + mov 8*4(%rsi),%rbp # g[4] + + mov %rdi,8*4(%rsp) # offload 1st argument + lea (%rax,%rax),%r14 + mulq %rax # g[0]*g[0] + mov %rax,%rbx + mov 8*1(%rsi),%rax # g[1] + mov %rdx,%rcx + mulq %r14 # 2*g[0]*g[1] + mov %rax,%r8 + mov %r15,%rax + mov %r15,8*0(%rsp) # offload g[2] + mov %rdx,%r9 + mulq %r14 # 2*g[0]*g[2] + mov %rax,%r10 + mov 8*3(%rsi),%rax + mov %rdx,%r11 + imulq \$19,%rbp,%rdi # g[4]*19 + mulq %r14 # 2*g[0]*g[3] + mov %rax,%r12 + mov %rbp,%rax + mov %rdx,%r13 + mulq %r14 # 2*g[0]*g[4] + mov %rax,%r14 + mov %rbp,%rax + mov %rdx,%r15 + + mulq %rdi # g[4]*g[4]*19 + add %rax,%r12 + mov 8*1(%rsi),%rax # g[1] + adc %rdx,%r13 + + mov 8*3(%rsi),%rsi # g[3] + lea (%rax,%rax),%rbp + mulq %rax # g[1]*g[1] + add %rax,%r10 + mov 8*0(%rsp),%rax # g[2] + adc %rdx,%r11 + mulq %rbp # 2*g[1]*g[2] + add %rax,%r12 + mov %rbp,%rax + adc %rdx,%r13 + mulq %rsi # 2*g[1]*g[3] + add %rax,%r14 + mov %rbp,%rax + adc %rdx,%r15 + imulq \$19,%rsi,%rbp # g[3]*19 + mulq %rdi # 2*g[1]*g[4]*19 + add %rax,%rbx + lea (%rsi,%rsi),%rax + adc %rdx,%rcx + + mulq %rdi # 2*g[3]*g[4]*19 + add %rax,%r10 + mov %rsi,%rax + adc %rdx,%r11 + mulq %rbp # g[3]*g[3]*19 + add %rax,%r8 + mov 8*0(%rsp),%rax # g[2] + adc %rdx,%r9 + + lea (%rax,%rax),%rsi + mulq %rax # g[2]*g[2] + add %rax,%r14 + mov %rbp,%rax + adc %rdx,%r15 + mulq %rsi # 2*g[2]*g[3]*19 + add %rax,%rbx + mov %rsi,%rax + adc %rdx,%rcx + mulq %rdi # 2*g[2]*g[4]*19 + add %rax,%r8 + adc %rdx,%r9 + + mov 8*4(%rsp),%rdi # restore 1st argument + jmp .Lreduce51 + +.align 32 +.Lreduce51: + mov \$0x7ffffffffffff,%rbp + + mov %r10,%rdx + shr \$51,%r10 + shl \$13,%r11 + and %rbp,%rdx # %rdx = g2 = h2 & mask + or %r10,%r11 # h2>>51 + add %r11,%r12 + adc \$0,%r13 # h3 += h2>>51 + + mov %rbx,%rax + shr \$51,%rbx + shl \$13,%rcx + and %rbp,%rax # %rax = g0 = h0 & mask + or %rbx,%rcx # h0>>51 + add %rcx,%r8 # h1 += h0>>51 + adc \$0,%r9 + + mov %r12,%rbx + shr \$51,%r12 + shl \$13,%r13 + and %rbp,%rbx # %rbx = g3 = h3 & mask + or %r12,%r13 # h3>>51 + add %r13,%r14 # h4 += h3>>51 + adc \$0,%r15 + + mov %r8,%rcx + shr \$51,%r8 + shl \$13,%r9 + and %rbp,%rcx # %rcx = g1 = h1 & mask + or %r8,%r9 + add %r9,%rdx # g2 += h1>>51 + + mov %r14,%r10 + shr \$51,%r14 + shl \$13,%r15 + and %rbp,%r10 # %r10 = g4 = h0 & mask + or %r14,%r15 # h0>>51 + + lea (%r15,%r15,8),%r14 + lea (%r15,%r14,2),%r15 + add %r15,%rax # g0 += (h0>>51)*19 + + mov %rdx,%r8 + and %rbp,%rdx # g2 &= mask + shr \$51,%r8 + add %r8,%rbx # g3 += g2>>51 + + mov %rax,%r9 + and %rbp,%rax # g0 &= mask + shr \$51,%r9 + add %r9,%rcx # g1 += g0>>51 + + mov %rax,8*0(%rdi) # save the result + mov %rcx,8*1(%rdi) + mov %rdx,8*2(%rdi) + mov %rbx,8*3(%rdi) + mov %r10,8*4(%rdi) + + mov 8*5(%rsp),%r15 + mov 8*6(%rsp),%r14 + mov 8*7(%rsp),%r13 + mov 8*8(%rsp),%r12 + mov 8*9(%rsp),%rbx + mov 8*10(%rsp),%rbp + lea 8*11(%rsp),%rsp + ret +.size x25519_fe51_sqr,.-x25519_fe51_sqr + +.globl x25519_fe51_mul121666 +.type x25519_fe51_mul121666,\@function,2 +.align 32 +x25519_fe51_mul121666: + push %rbp + push %rbx + push %r12 + push %r13 + push %r14 + push %r15 + mov \$121666,%eax + lea -8*5(%rsp),%rsp + + mulq 8*0(%rsi) + mov %rax,%rbx # %rbx:%rcx = h0 + mov \$121666,%eax + mov %rdx,%rcx + mulq 8*1(%rsi) + mov %rax,%r8 # %r8:%r9 = h1 + mov \$121666,%eax + mov %rdx,%r9 + mulq 8*2(%rsi) + mov %rax,%r10 # %r10:%r11 = h2 + mov \$121666,%eax + mov %rdx,%r11 + mulq 8*3(%rsi) + mov %rax,%r12 # %r12:%r13 = h3 + mov \$121666,%eax # f[0] + mov %rdx,%r13 + mulq 8*4(%rsi) + mov %rax,%r14 # %r14:%r15 = h4 + mov %rdx,%r15 + + jmp .Lreduce51 +.size x25519_fe51_mul121666,.-x25519_fe51_mul121666 +___ +######################################################################## +# Base 2^64 subroutines modulo 2*(2^255-19) +# +if ($addx) { +my ($acc0,$acc1,$acc2,$acc3,$acc4,$acc5,$acc6,$acc7) = map("%r$_",(8..15)); + +$code.=<<___; +.extern OPENSSL_ia32cap_P +.globl x25519_fe64_eligible +.type x25519_fe64_eligible,\@abi-omnipotent +.align 32 +x25519_fe64_eligible: + mov OPENSSL_ia32cap_P+8(%rip),%ecx + xor %eax,%eax + and \$0x80100,%ecx + cmp \$0x80100,%ecx + cmove %ecx,%eax + ret +.size x25519_fe64_eligible,.-x25519_fe64_eligible + +.globl x25519_fe64_mul +.type x25519_fe64_mul,\@function,3 +.align 32 +x25519_fe64_mul: + push %rbp + push %rbx + push %r12 + push %r13 + push %r14 + push %r15 + push %rdi # offload dst + lea -8*2(%rsp),%rsp + + mov %rdx,%rax + mov 8*0(%rdx),%rbp # b[0] + mov 8*0(%rsi),%rdx # a[0] + mov 8*1(%rax),%rcx # b[1] + mov 8*2(%rax),$acc6 # b[2] + mov 8*3(%rax),$acc7 # b[3] + + mulx %rbp,$acc0,%rax # a[0]*b[0] + xor %edi,%edi # cf=0,of=0 + mulx %rcx,$acc1,%rbx # a[0]*b[1] + adcx %rax,$acc1 + mulx $acc6,$acc2,%rax # a[0]*b[2] + adcx %rbx,$acc2 + mulx $acc7,$acc3,$acc4 # a[0]*b[3] + mov 8*1(%rsi),%rdx # a[1] + adcx %rax,$acc3 + mov $acc6,(%rsp) # offload b[2] + adcx %rdi,$acc4 # cf=0 + + mulx %rbp,%rax,%rbx # a[1]*b[0] + adox %rax,$acc1 + adcx %rbx,$acc2 + mulx %rcx,%rax,%rbx # a[1]*b[1] + adox %rax,$acc2 + adcx %rbx,$acc3 + mulx $acc6,%rax,%rbx # a[1]*b[2] + adox %rax,$acc3 + adcx %rbx,$acc4 + mulx $acc7,%rax,$acc5 # a[1]*b[3] + mov 8*2(%rsi),%rdx # a[2] + adox %rax,$acc4 + adcx %rdi,$acc5 # cf=0 + adox %rdi,$acc5 # of=0 + + mulx %rbp,%rax,%rbx # a[2]*b[0] + adcx %rax,$acc2 + adox %rbx,$acc3 + mulx %rcx,%rax,%rbx # a[2]*b[1] + adcx %rax,$acc3 + adox %rbx,$acc4 + mulx $acc6,%rax,%rbx # a[2]*b[2] + adcx %rax,$acc4 + adox %rbx,$acc5 + mulx $acc7,%rax,$acc6 # a[2]*b[3] + mov 8*3(%rsi),%rdx # a[3] + adcx %rax,$acc5 + adox %rdi,$acc6 # of=0 + adcx %rdi,$acc6 # cf=0 + + mulx %rbp,%rax,%rbx # a[3]*b[0] + adox %rax,$acc3 + adcx %rbx,$acc4 + mulx %rcx,%rax,%rbx # a[3]*b[1] + adox %rax,$acc4 + adcx %rbx,$acc5 + mulx (%rsp),%rax,%rbx # a[3]*b[2] + adox %rax,$acc5 + adcx %rbx,$acc6 + mulx $acc7,%rax,$acc7 # a[3]*b[3] + mov \$38,%edx + adox %rax,$acc6 + adcx %rdi,$acc7 # cf=0 + adox %rdi,$acc7 # of=0 + + jmp .Lreduce64 +.size x25519_fe64_mul,.-x25519_fe64_mul + +.globl x25519_fe64_sqr +.type x25519_fe64_sqr,\@function,2 +.align 32 +x25519_fe64_sqr: + push %rbp + push %rbx + push %r12 + push %r13 + push %r14 + push %r15 + push %rdi # offload dst + lea -8*2(%rsp),%rsp + + mov 8*0(%rsi),%rdx # a[0] + mov 8*1(%rsi),%rcx # a[1] + mov 8*2(%rsi),%rbp # a[2] + mov 8*3(%rsi),%rsi # a[3] + + ################################################################ + mulx %rdx,$acc0,$acc7 # a[0]*a[0] + mulx %rcx,$acc1,%rax # a[0]*a[1] + xor %edi,%edi # cf=0,of=0 + mulx %rbp,$acc2,%rbx # a[0]*a[2] + adcx %rax,$acc2 + mulx %rsi,$acc3,$acc4 # a[0]*a[3] + mov %rcx,%rdx # a[1] + adcx %rbx,$acc3 + adcx %rdi,$acc4 # cf=0 + + ################################################################ + mulx %rbp,%rax,%rbx # a[1]*a[2] + adox %rax,$acc3 + adcx %rbx,$acc4 + mulx %rsi,%rax,$acc5 # a[1]*a[3] + mov %rbp,%rdx # a[2] + adox %rax,$acc4 + adcx %rdi,$acc5 + + ################################################################ + mulx %rsi,%rax,$acc6 # a[2]*a[3] + mov %rcx,%rdx # a[1] + adox %rax,$acc5 + adcx %rdi,$acc6 # cf=0 + adox %rdi,$acc6 # of=0 + + adcx $acc1,$acc1 # acc1:6<<1 + adox $acc7,$acc1 + adcx $acc2,$acc2 + mulx %rdx,%rax,%rbx # a[1]*a[1] + mov %rbp,%rdx # a[2] + adcx $acc3,$acc3 + adox %rax,$acc2 + adcx $acc4,$acc4 + adox %rbx,$acc3 + mulx %rdx,%rax,%rbx # a[2]*a[2] + mov %rsi,%rdx # a[3] + adcx $acc5,$acc5 + adox %rax,$acc4 + adcx $acc6,$acc6 + adox %rbx,$acc5 + mulx %rdx,%rax,$acc7 # a[3]*a[3] + mov \$38,%edx + adox %rax,$acc6 + adcx %rdi,$acc7 # cf=0 + adox %rdi,$acc7 # of=0 + jmp .Lreduce64 + +.align 32 +.Lreduce64: + mulx $acc4,%rax,%rbx + adcx %rax,$acc0 + adox %rbx,$acc1 + mulx $acc5,%rax,%rbx + adcx %rax,$acc1 + adox %rbx,$acc2 + mulx $acc6,%rax,%rbx + adcx %rax,$acc2 + adox %rbx,$acc3 + mulx $acc7,%rax,$acc4 + adcx %rax,$acc3 + adox %rdi,$acc4 + adcx %rdi,$acc4 + + mov 8*2(%rsp),%rdi # restore dst + imulq %rdx,$acc4 + + add $acc4,$acc0 + adc \$0,$acc1 + adc \$0,$acc2 + adc \$0,$acc3 + + sbb %rax,%rax # cf -> mask + and \$38,%rax + + add %rax,$acc0 + adc \$0,$acc1 + mov $acc0,8*0(%rdi) + adc \$0,$acc2 + mov $acc1,8*1(%rdi) + adc \$0,$acc3 + mov $acc2,8*2(%rdi) + mov $acc3,8*3(%rdi) + + mov 8*3(%rsp),%r15 + mov 8*4(%rsp),%r14 + mov 8*5(%rsp),%r13 + mov 8*6(%rsp),%r12 + mov 8*7(%rsp),%rbx + mov 8*8(%rsp),%rbp + lea 8*9(%rsp),%rsp + ret +.size x25519_fe64_sqr,.-x25519_fe64_sqr + +.globl x25519_fe64_mul121666 +.type x25519_fe64_mul121666,\@function,2 +.align 32 +x25519_fe64_mul121666: + mov \$121666,%edx + mulx 8*0(%rsi),$acc0,%rcx + mulx 8*1(%rsi),$acc1,%rax + add %rcx,$acc1 + mulx 8*2(%rsi),$acc2,%rcx + adc %rax,$acc2 + mulx 8*3(%rsi),$acc3,%rax + adc %rcx,$acc3 + adc \$0,%rax + + imulq \$38,%rax,%rax + + add %rax,$acc0 + adc \$0,$acc1 + adc \$0,$acc2 + adc \$0,$acc3 + + sbb %rax,%rax # cf -> mask + and \$38,%rax + + add %rax,$acc0 + adc \$0,$acc1 + mov $acc0,8*0(%rdi) + adc \$0,$acc2 + mov $acc1,8*1(%rdi) + adc \$0,$acc3 + mov $acc2,8*2(%rdi) + mov $acc3,8*3(%rdi) + + ret +.size x25519_fe64_mul121666,.-x25519_fe64_mul121666 + +.globl x25519_fe64_add +.type x25519_fe64_add,\@function,3 +.align 32 +x25519_fe64_add: + mov 8*0(%rsi),$acc0 + mov 8*1(%rsi),$acc1 + mov 8*2(%rsi),$acc2 + mov 8*3(%rsi),$acc3 + + add 8*0(%rdx),$acc0 + adc 8*1(%rdx),$acc1 + adc 8*2(%rdx),$acc2 + adc 8*3(%rdx),$acc3 + + sbb %rax,%rax # cf -> mask + and \$38,%rax + + add %rax,$acc0 + adc \$0,$acc1 + mov $acc0,8*0(%rdi) + adc \$0,$acc2 + mov $acc1,8*1(%rdi) + adc \$0,$acc3 + mov $acc2,8*2(%rdi) + mov $acc3,8*3(%rdi) + + ret +.size x25519_fe64_add,.-x25519_fe64_add + +.globl x25519_fe64_sub +.type x25519_fe64_sub,\@function,3 +.align 32 +x25519_fe64_sub: + mov 8*0(%rsi),$acc0 + mov 8*1(%rsi),$acc1 + mov 8*2(%rsi),$acc2 + mov 8*3(%rsi),$acc3 + + sub 8*0(%rdx),$acc0 + sbb 8*1(%rdx),$acc1 + sbb 8*2(%rdx),$acc2 + sbb 8*3(%rdx),$acc3 + + sbb %rax,%rax # cf -> mask + and \$38,%rax + + sub %rax,$acc0 + sbb \$0,$acc1 + mov $acc0,8*0(%rdi) + sbb \$0,$acc2 + mov $acc1,8*1(%rdi) + sbb \$0,$acc3 + mov $acc2,8*2(%rdi) + mov $acc3,8*3(%rdi) + + ret +.size x25519_fe64_sub,.-x25519_fe64_sub + +.globl x25519_fe64_tobytes +.type x25519_fe64_tobytes,\@function,2 +.align 32 +x25519_fe64_tobytes: + mov 8*0(%rsi),$acc0 + mov 8*1(%rsi),$acc1 + mov 8*2(%rsi),$acc2 + mov 8*3(%rsi),$acc3 + + ################################# reduction modulo 2^255-19 + lea ($acc3,$acc3),%rax + sar \$63,$acc3 # most significant bit -> mask + shr \$1,%rax # most significant bit cleared + and \$19,$acc3 + + add $acc3,$acc0 + adc \$0,$acc1 + adc \$0,$acc2 + adc \$0,%rax + + lea (%rax,%rax),$acc3 + sar \$63,%rax # most significant bit -> mask + shr \$1,$acc3 # most significant bit cleared + and \$19,%rax + + add %rax,$acc0 + adc \$0,$acc1 + adc \$0,$acc2 + adc \$0,$acc3 + + mov $acc0,8*0(%rdi) + mov $acc1,8*1(%rdi) + mov $acc2,8*2(%rdi) + mov $acc3,8*3(%rdi) + + ret +.size x25519_fe64_tobytes,.-x25519_fe64_tobytes +___ +} else { +$code.=<<___; +.globl x25519_fe64_eligible +.type x25519_fe64_eligible,\@abi-omnipotent +.align 32 +x25519_fe64_eligible: + xor %eax,%eax + ret +.size x25519_fe64_eligible,.-x25519_fe64_eligible + +.globl x25519_fe64_mul +.type x25519_fe64_mul,\@abi-omnipotent +.globl x25519_fe64_sqr +.globl x25519_fe64_mul121666 +.globl x25519_fe64_add +.globl x25519_fe64_sub +.globl x25519_fe64_tobytes +x25519_fe64_mul: +x25519_fe64_sqr: +x25519_fe64_mul121666: +x25519_fe64_add: +x25519_fe64_sub: +x25519_fe64_tobytes: + .byte 0x0f,0x0b # ud2 + ret +.size x25519_fe64_mul,.-x25519_fe64_mul +___ +} +$code.=<<___; +.asciz "X25519 primitives for x86_64, CRYPTOGAMS by " +___ + +$code =~ s/\`([^\`]*)\`/eval $1/gem; +print $code; +close $STDOUT; diff --git a/crypto/ec/build.info b/crypto/ec/build.info index 970c2922..1e7814f2 100644 --- a/crypto/ec/build.info +++ b/crypto/ec/build.info @@ -6,9 +6,12 @@ SOURCE[../../libcrypto]=\ ecp_nistp224.c ecp_nistp256.c ecp_nistp521.c ecp_nistputil.c \ ecp_oct.c ec2_oct.c ec_oct.c ec_kmeth.c ecdh_ossl.c ecdh_kdf.c \ ecdsa_ossl.c ecdsa_sign.c ecdsa_vrf.c curve25519.c ecx_meth.c \ + curve448/arch_32/f_impl.c curve448/f_generic.c curve448/scalar.c \ + curve448/curve448_tables.c curve448/eddsa.c curve448/curve448.c \ {- $target{ec_asm_src} -} -GENERATE[ecp_nistz256-x86.s]=asm/ecp_nistz256-x86.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[ecp_nistz256-x86.s]=asm/ecp_nistz256-x86.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) GENERATE[ecp_nistz256-x86_64.s]=asm/ecp_nistz256-x86_64.pl $(PERLASM_SCHEME) @@ -21,8 +24,18 @@ GENERATE[ecp_nistz256-armv4.S]=asm/ecp_nistz256-armv4.pl $(PERLASM_SCHEME) INCLUDE[ecp_nistz256-armv4.o]=.. GENERATE[ecp_nistz256-armv8.S]=asm/ecp_nistz256-armv8.pl $(PERLASM_SCHEME) INCLUDE[ecp_nistz256-armv8.o]=.. +GENERATE[ecp_nistz256-ppc64.s]=asm/ecp_nistz256-ppc64.pl $(PERLASM_SCHEME) + +GENERATE[x25519-x86_64.s]=asm/x25519-x86_64.pl $(PERLASM_SCHEME) BEGINRAW[Makefile] {- $builddir -}/ecp_nistz256-%.S: {- $sourcedir -}/asm/ecp_nistz256-%.pl CC="$(CC)" $(PERL) $< $(PERLASM_SCHEME) $@ ENDRAW[Makefile] + +INCLUDE[curve448/arch_32/f_impl.o]=curve448/arch_32 curve448 +INCLUDE[curve448/f_generic.o]=curve448/arch_32 curve448 +INCLUDE[curve448/scalar.o]=curve448/arch_32 curve448 +INCLUDE[curve448/curve448_tables.o]=curve448/arch_32 curve448 +INCLUDE[curve448/eddsa.o]=curve448/arch_32 curve448 +INCLUDE[curve448/curve448.o]=curve448/arch_32 curve448 diff --git a/crypto/ec/curve25519.c b/crypto/ec/curve25519.c index c606a9b5..45525f47 100644 --- a/crypto/ec/curve25519.c +++ b/crypto/ec/curve25519.c @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-2018 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 @@ -11,15 +11,18 @@ #include "ec_lcl.h" #include -#if !defined(PEDANTIC) && \ - (defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16) +#if defined(X25519_ASM) \ + || ( (defined(__SIZEOF_INT128__) && __SIZEOF_INT128__ == 16) \ + && !defined(__sparc__) ) /* * Base 2^51 implementation. */ # define BASE_2_51_IMPLEMENTED typedef uint64_t fe51[5]; -typedef unsigned __int128 u128; +# if !defined(X25519_ASM) +typedef __uint128_t u128; +# endif static const uint64_t MASK51 = 0x7ffffffffffff; @@ -97,40 +100,284 @@ static void fe51_tobytes(uint8_t *s, const fe51 h) h4 &= MASK51; /* smash */ - s[0] = h0 >> 0; - s[1] = h0 >> 8; - s[2] = h0 >> 16; - s[3] = h0 >> 24; - s[4] = h0 >> 32; - s[5] = h0 >> 40; - s[6] = (h0 >> 48) | ((uint32_t)h1 << 3); - s[7] = h1 >> 5; - s[8] = h1 >> 13; - s[9] = h1 >> 21; - s[10] = h1 >> 29; - s[11] = h1 >> 37; - s[12] = (h1 >> 45) | ((uint32_t)h2 << 6); - s[13] = h2 >> 2; - s[14] = h2 >> 10; - s[15] = h2 >> 18; - s[16] = h2 >> 26; - s[17] = h2 >> 34; - s[18] = h2 >> 42; - s[19] = (h2 >> 50) | ((uint32_t)h3 << 1); - s[20] = h3 >> 7; - s[21] = h3 >> 15; - s[22] = h3 >> 23; - s[23] = h3 >> 31; - s[24] = h3 >> 39; - s[25] = (h3 >> 47) | ((uint32_t)h4 << 4); - s[26] = h4 >> 4; - s[27] = h4 >> 12; - s[28] = h4 >> 20; - s[29] = h4 >> 28; - s[30] = h4 >> 36; - s[31] = h4 >> 44; + s[0] = (uint8_t)(h0 >> 0); + s[1] = (uint8_t)(h0 >> 8); + s[2] = (uint8_t)(h0 >> 16); + s[3] = (uint8_t)(h0 >> 24); + s[4] = (uint8_t)(h0 >> 32); + s[5] = (uint8_t)(h0 >> 40); + s[6] = (uint8_t)((h0 >> 48) | ((uint32_t)h1 << 3)); + s[7] = (uint8_t)(h1 >> 5); + s[8] = (uint8_t)(h1 >> 13); + s[9] = (uint8_t)(h1 >> 21); + s[10] = (uint8_t)(h1 >> 29); + s[11] = (uint8_t)(h1 >> 37); + s[12] = (uint8_t)((h1 >> 45) | ((uint32_t)h2 << 6)); + s[13] = (uint8_t)(h2 >> 2); + s[14] = (uint8_t)(h2 >> 10); + s[15] = (uint8_t)(h2 >> 18); + s[16] = (uint8_t)(h2 >> 26); + s[17] = (uint8_t)(h2 >> 34); + s[18] = (uint8_t)(h2 >> 42); + s[19] = (uint8_t)((h2 >> 50) | ((uint32_t)h3 << 1)); + s[20] = (uint8_t)(h3 >> 7); + s[21] = (uint8_t)(h3 >> 15); + s[22] = (uint8_t)(h3 >> 23); + s[23] = (uint8_t)(h3 >> 31); + s[24] = (uint8_t)(h3 >> 39); + s[25] = (uint8_t)((h3 >> 47) | ((uint32_t)h4 << 4)); + s[26] = (uint8_t)(h4 >> 4); + s[27] = (uint8_t)(h4 >> 12); + s[28] = (uint8_t)(h4 >> 20); + s[29] = (uint8_t)(h4 >> 28); + s[30] = (uint8_t)(h4 >> 36); + s[31] = (uint8_t)(h4 >> 44); } +# ifdef X25519_ASM +void x25519_fe51_mul(fe51 h, const fe51 f, const fe51 g); +void x25519_fe51_sqr(fe51 h, const fe51 f); +void x25519_fe51_mul121666(fe51 h, fe51 f); +# define fe51_mul x25519_fe51_mul +# define fe51_sq x25519_fe51_sqr +# define fe51_mul121666 x25519_fe51_mul121666 + +# if defined(__x86_64) || defined(__x86_64__) || \ + defined(_M_AMD64) || defined(_M_X64) + +# define BASE_2_64_IMPLEMENTED + +typedef uint64_t fe64[4]; + +int x25519_fe64_eligible(); + +/* + * There are no reference C implementations for this radix. + */ +void x25519_fe64_mul(fe64 h, const fe64 f, const fe64 g); +void x25519_fe64_sqr(fe64 h, const fe64 f); +void x25519_fe64_mul121666(fe64 h, fe64 f); +void x25519_fe64_add(fe64 h, const fe64 f, const fe64 g); +void x25519_fe64_sub(fe64 h, const fe64 f, const fe64 g); +void x25519_fe64_tobytes(uint8_t *s, const fe64 f); +# define fe64_mul x25519_fe64_mul +# define fe64_sqr x25519_fe64_sqr +# define fe64_mul121666 x25519_fe64_mul121666 +# define fe64_add x25519_fe64_add +# define fe64_sub x25519_fe64_sub +# define fe64_tobytes x25519_fe64_tobytes + +static uint64_t load_8(const uint8_t *in) +{ + uint64_t result; + + result = in[0]; + result |= ((uint64_t)in[1]) << 8; + result |= ((uint64_t)in[2]) << 16; + result |= ((uint64_t)in[3]) << 24; + result |= ((uint64_t)in[4]) << 32; + result |= ((uint64_t)in[5]) << 40; + result |= ((uint64_t)in[6]) << 48; + result |= ((uint64_t)in[7]) << 56; + + return result; +} + +static void fe64_frombytes(fe64 h, const uint8_t *s) +{ + h[0] = load_8(s); + h[1] = load_8(s + 8); + h[2] = load_8(s + 16); + h[3] = load_8(s + 24) & 0x7fffffffffffffff; +} + +static void fe64_0(fe64 h) +{ + h[0] = 0; + h[1] = 0; + h[2] = 0; + h[3] = 0; +} + +static void fe64_1(fe64 h) +{ + h[0] = 1; + h[1] = 0; + h[2] = 0; + h[3] = 0; +} + +static void fe64_copy(fe64 h, const fe64 f) +{ + h[0] = f[0]; + h[1] = f[1]; + h[2] = f[2]; + h[3] = f[3]; +} + +static void fe64_cswap(fe64 f, fe64 g, unsigned int b) +{ + int i; + uint64_t mask = 0 - (uint64_t)b; + + for (i = 0; i < 4; i++) { + uint64_t x = f[i] ^ g[i]; + x &= mask; + f[i] ^= x; + g[i] ^= x; + } +} + +static void fe64_invert(fe64 out, const fe64 z) +{ + fe64 t0; + fe64 t1; + fe64 t2; + fe64 t3; + int i; + + /* + * Compute z ** -1 = z ** (2 ** 255 - 19 - 2) with the exponent as + * 2 ** 255 - 21 = (2 ** 5) * (2 ** 250 - 1) + 11. + */ + + /* t0 = z ** 2 */ + fe64_sqr(t0, z); + + /* t1 = t0 ** (2 ** 2) = z ** 8 */ + fe64_sqr(t1, t0); + fe64_sqr(t1, t1); + + /* t1 = z * t1 = z ** 9 */ + fe64_mul(t1, z, t1); + /* t0 = t0 * t1 = z ** 11 -- stash t0 away for the end. */ + fe64_mul(t0, t0, t1); + + /* t2 = t0 ** 2 = z ** 22 */ + fe64_sqr(t2, t0); + + /* t1 = t1 * t2 = z ** (2 ** 5 - 1) */ + fe64_mul(t1, t1, t2); + + /* t2 = t1 ** (2 ** 5) = z ** ((2 ** 5) * (2 ** 5 - 1)) */ + fe64_sqr(t2, t1); + for (i = 1; i < 5; ++i) + fe64_sqr(t2, t2); + + /* t1 = t1 * t2 = z ** ((2 ** 5 + 1) * (2 ** 5 - 1)) = z ** (2 ** 10 - 1) */ + fe64_mul(t1, t2, t1); + + /* Continuing similarly... */ + + /* t2 = z ** (2 ** 20 - 1) */ + fe64_sqr(t2, t1); + for (i = 1; i < 10; ++i) + fe64_sqr(t2, t2); + + fe64_mul(t2, t2, t1); + + /* t2 = z ** (2 ** 40 - 1) */ + fe64_sqr(t3, t2); + for (i = 1; i < 20; ++i) + fe64_sqr(t3, t3); + + fe64_mul(t2, t3, t2); + + /* t2 = z ** (2 ** 10) * (2 ** 40 - 1) */ + for (i = 0; i < 10; ++i) + fe64_sqr(t2, t2); + + /* t1 = z ** (2 ** 50 - 1) */ + fe64_mul(t1, t2, t1); + + /* t2 = z ** (2 ** 100 - 1) */ + fe64_sqr(t2, t1); + for (i = 1; i < 50; ++i) + fe64_sqr(t2, t2); + + fe64_mul(t2, t2, t1); + + /* t2 = z ** (2 ** 200 - 1) */ + fe64_sqr(t3, t2); + for (i = 1; i < 100; ++i) + fe64_sqr(t3, t3); + + fe64_mul(t2, t3, t2); + + /* t2 = z ** ((2 ** 50) * (2 ** 200 - 1) */ + for (i = 0; i < 50; ++i) + fe64_sqr(t2, t2); + + /* t1 = z ** (2 ** 250 - 1) */ + fe64_mul(t1, t2, t1); + + /* t1 = z ** ((2 ** 5) * (2 ** 250 - 1)) */ + for (i = 0; i < 5; ++i) + fe64_sqr(t1, t1); + + /* Recall t0 = z ** 11; out = z ** (2 ** 255 - 21) */ + fe64_mul(out, t1, t0); +} + +/* + * Duplicate of original x25519_scalar_mult_generic, but using + * fe64_* subroutines. + */ +static void x25519_scalar_mulx(uint8_t out[32], const uint8_t scalar[32], + const uint8_t point[32]) +{ + fe64 x1, x2, z2, x3, z3, tmp0, tmp1; + uint8_t e[32]; + unsigned swap = 0; + int pos; + + memcpy(e, scalar, 32); + e[0] &= 0xf8; + e[31] &= 0x7f; + e[31] |= 0x40; + fe64_frombytes(x1, point); + fe64_1(x2); + fe64_0(z2); + fe64_copy(x3, x1); + fe64_1(z3); + + for (pos = 254; pos >= 0; --pos) { + unsigned int b = 1 & (e[pos / 8] >> (pos & 7)); + + swap ^= b; + fe64_cswap(x2, x3, swap); + fe64_cswap(z2, z3, swap); + swap = b; + fe64_sub(tmp0, x3, z3); + fe64_sub(tmp1, x2, z2); + fe64_add(x2, x2, z2); + fe64_add(z2, x3, z3); + fe64_mul(z3, x2, tmp0); + fe64_mul(z2, z2, tmp1); + fe64_sqr(tmp0, tmp1); + fe64_sqr(tmp1, x2); + fe64_add(x3, z3, z2); + fe64_sub(z2, z3, z2); + fe64_mul(x2, tmp1, tmp0); + fe64_sub(tmp1, tmp1, tmp0); + fe64_sqr(z2, z2); + fe64_mul121666(z3, tmp1); + fe64_sqr(x3, x3); + fe64_add(tmp0, tmp0, z3); + fe64_mul(z3, x1, z2); + fe64_mul(z2, tmp1, tmp0); + } + + fe64_invert(z2, z2); + fe64_mul(x2, x2, z2); + fe64_tobytes(out, x2); + + OPENSSL_cleanse(e, sizeof(e)); +} +# endif + +# else + static void fe51_mul(fe51 h, const fe51 f, const fe51 g) { u128 h0, h1, h2, h3, h4; @@ -191,9 +438,9 @@ static void fe51_mul(fe51 h, const fe51 f, const fe51 g) static void fe51_sq(fe51 h, const fe51 f) { -# if defined(OPENSSL_SMALL_FOOTPRINT) +# if defined(OPENSSL_SMALL_FOOTPRINT) fe51_mul(h, f, f); -# else +# else /* dedicated squaring gives 16-25% overall improvement */ uint64_t g0 = f[0]; uint64_t g1 = f[1]; @@ -221,7 +468,7 @@ static void fe51_sq(fe51 h, const fe51 f) h2 += (u128)(g0 * 2) * g4; h4 += (u128)g2 * g2; g2 *= 2; - h0 += (u128)g2 * g3; + h0 += (u128)g2 * g3; h1 += (u128)g2 * g4; /* partial [lazy] reduction */ @@ -240,9 +487,36 @@ static void fe51_sq(fe51 h, const fe51 f) h[2] = g2; h[3] = g3; h[4] = g4; -# endif +# endif } +static void fe51_mul121666(fe51 h, fe51 f) +{ + u128 h0 = f[0] * (u128)121666; + u128 h1 = f[1] * (u128)121666; + u128 h2 = f[2] * (u128)121666; + u128 h3 = f[3] * (u128)121666; + u128 h4 = f[4] * (u128)121666; + uint64_t g0, g1, g2, g3, g4; + + h3 += (uint64_t)(h2 >> 51); g2 = (uint64_t)h2 & MASK51; + h1 += (uint64_t)(h0 >> 51); g0 = (uint64_t)h0 & MASK51; + + h4 += (uint64_t)(h3 >> 51); g3 = (uint64_t)h3 & MASK51; + g2 += (uint64_t)(h1 >> 51); g1 = (uint64_t)h1 & MASK51; + + g0 += (uint64_t)(h4 >> 51) * 19; g4 = (uint64_t)h4 & MASK51; + g3 += g2 >> 51; g2 &= MASK51; + g1 += g0 >> 51; g0 &= MASK51; + + h[0] = g0; + h[1] = g1; + h[2] = g2; + h[3] = g3; + h[4] = g4; +} +# endif + static void fe51_add(fe51 h, const fe51 f, const fe51 g) { h[0] = f[0] + g[0]; @@ -258,8 +532,8 @@ static void fe51_sub(fe51 h, const fe51 f, const fe51 g) * Add 2*modulus to ensure that result remains positive * even if subtrahend is partially reduced. */ - h[0] = (f[0] + 0xfffffffffffda) - g[0]; - h[1] = (f[1] + 0xffffffffffffe) - g[1]; + h[0] = (f[0] + 0xfffffffffffda) - g[0]; + h[1] = (f[1] + 0xffffffffffffe) - g[1]; h[2] = (f[2] + 0xffffffffffffe) - g[2]; h[3] = (f[3] + 0xffffffffffffe) - g[3]; h[4] = (f[4] + 0xffffffffffffe) - g[4]; @@ -396,32 +670,6 @@ static void fe51_invert(fe51 out, const fe51 z) fe51_mul(out, t1, t0); } -static void fe51_mul121666(fe51 h, fe51 f) -{ - u128 h0 = f[0] * (u128)121666; - u128 h1 = f[1] * (u128)121666; - u128 h2 = f[2] * (u128)121666; - u128 h3 = f[3] * (u128)121666; - u128 h4 = f[4] * (u128)121666; - uint64_t g0, g1, g2, g3, g4; - - h3 += (uint64_t)(h2 >> 51); g2 = (uint64_t)h2 & MASK51; - h1 += (uint64_t)(h0 >> 51); g0 = (uint64_t)h0 & MASK51; - - h4 += (uint64_t)(h3 >> 51); g3 = (uint64_t)h3 & MASK51; - g2 += (uint64_t)(h1 >> 51); g1 = (uint64_t)h1 & MASK51; - - g0 += (uint64_t)(h4 >> 51) * 19; g4 = (uint64_t)h4 & MASK51; - g3 += g2 >> 51; g2 &= MASK51; - g1 += g0 >> 51; g0 &= MASK51; - - h[0] = g0; - h[1] = g1; - h[2] = g2; - h[3] = g3; - h[4] = g4; -} - /* * Duplicate of original x25519_scalar_mult_generic, but using * fe51_* subroutines. @@ -434,6 +682,13 @@ static void x25519_scalar_mult(uint8_t out[32], const uint8_t scalar[32], unsigned swap = 0; int pos; +# ifdef BASE_2_64_IMPLEMENTED + if (x25519_fe64_eligible()) { + x25519_scalar_mulx(out, scalar, point); + return; + } +# endif + memcpy(e, scalar, 32); e[0] &= 0xf8; e[31] &= 0x7f; @@ -470,8 +725,6 @@ static void x25519_scalar_mult(uint8_t out[32], const uint8_t scalar[32], fe51_mul(z3, x1, z2); fe51_mul(z2, tmp1, tmp0); } - fe51_cswap(x2, x3, swap); - fe51_cswap(z2, z3, swap); fe51_invert(z2, z2); fe51_mul(x2, x2, z2); @@ -554,16 +807,16 @@ static void fe_frombytes(fe h, const uint8_t *s) { carry6 = h6 + (1 << 25); h7 += carry6 >> 26; h6 -= carry6 & kTop38Bits; carry8 = h8 + (1 << 25); h9 += carry8 >> 26; h8 -= carry8 & kTop38Bits; - h[0] = h0; - h[1] = h1; - h[2] = h2; - h[3] = h3; - h[4] = h4; - h[5] = h5; - h[6] = h6; - h[7] = h7; - h[8] = h8; - h[9] = h9; + h[0] = (int32_t)h0; + h[1] = (int32_t)h1; + h[2] = (int32_t)h2; + h[3] = (int32_t)h3; + h[4] = (int32_t)h4; + h[5] = (int32_t)h5; + h[6] = (int32_t)h6; + h[7] = (int32_t)h7; + h[8] = (int32_t)h8; + h[9] = (int32_t)h9; } /* Preconditions: @@ -634,38 +887,38 @@ static void fe_tobytes(uint8_t *s, const fe h) { * evidently 2^255 h10-2^255 q = 0. * Goal: Output h0+...+2^230 h9. */ - s[0] = h0 >> 0; - s[1] = h0 >> 8; - s[2] = h0 >> 16; - s[3] = (h0 >> 24) | ((uint32_t)(h1) << 2); - s[4] = h1 >> 6; - s[5] = h1 >> 14; - s[6] = (h1 >> 22) | ((uint32_t)(h2) << 3); - s[7] = h2 >> 5; - s[8] = h2 >> 13; - s[9] = (h2 >> 21) | ((uint32_t)(h3) << 5); - s[10] = h3 >> 3; - s[11] = h3 >> 11; - s[12] = (h3 >> 19) | ((uint32_t)(h4) << 6); - s[13] = h4 >> 2; - s[14] = h4 >> 10; - s[15] = h4 >> 18; - s[16] = h5 >> 0; - s[17] = h5 >> 8; - s[18] = h5 >> 16; - s[19] = (h5 >> 24) | ((uint32_t)(h6) << 1); - s[20] = h6 >> 7; - s[21] = h6 >> 15; - s[22] = (h6 >> 23) | ((uint32_t)(h7) << 3); - s[23] = h7 >> 5; - s[24] = h7 >> 13; - s[25] = (h7 >> 21) | ((uint32_t)(h8) << 4); - s[26] = h8 >> 4; - s[27] = h8 >> 12; - s[28] = (h8 >> 20) | ((uint32_t)(h9) << 6); - s[29] = h9 >> 2; - s[30] = h9 >> 10; - s[31] = h9 >> 18; + s[0] = (uint8_t)(h0 >> 0); + s[1] = (uint8_t)(h0 >> 8); + s[2] = (uint8_t)(h0 >> 16); + s[3] = (uint8_t)((h0 >> 24) | ((uint32_t)(h1) << 2)); + s[4] = (uint8_t)(h1 >> 6); + s[5] = (uint8_t)(h1 >> 14); + s[6] = (uint8_t)((h1 >> 22) | ((uint32_t)(h2) << 3)); + s[7] = (uint8_t)(h2 >> 5); + s[8] = (uint8_t)(h2 >> 13); + s[9] = (uint8_t)((h2 >> 21) | ((uint32_t)(h3) << 5)); + s[10] = (uint8_t)(h3 >> 3); + s[11] = (uint8_t)(h3 >> 11); + s[12] = (uint8_t)((h3 >> 19) | ((uint32_t)(h4) << 6)); + s[13] = (uint8_t)(h4 >> 2); + s[14] = (uint8_t)(h4 >> 10); + s[15] = (uint8_t)(h4 >> 18); + s[16] = (uint8_t)(h5 >> 0); + s[17] = (uint8_t)(h5 >> 8); + s[18] = (uint8_t)(h5 >> 16); + s[19] = (uint8_t)((h5 >> 24) | ((uint32_t)(h6) << 1)); + s[20] = (uint8_t)(h6 >> 7); + s[21] = (uint8_t)(h6 >> 15); + s[22] = (uint8_t)((h6 >> 23) | ((uint32_t)(h7) << 3)); + s[23] = (uint8_t)(h7 >> 5); + s[24] = (uint8_t)(h7 >> 13); + s[25] = (uint8_t)((h7 >> 21) | ((uint32_t)(h8) << 4)); + s[26] = (uint8_t)(h8 >> 4); + s[27] = (uint8_t)(h8 >> 12); + s[28] = (uint8_t)((h8 >> 20) | ((uint32_t)(h9) << 6)); + s[29] = (uint8_t)(h9 >> 2); + s[30] = (uint8_t)(h9 >> 10); + s[31] = (uint8_t)(h9 >> 18); } /* h = f */ @@ -945,16 +1198,16 @@ static void fe_mul(fe h, const fe f, const fe g) { /* |h0| <= 2^25; from now on fits into int32 unchanged */ /* |h1| <= 1.01*2^24 */ - h[0] = h0; - h[1] = h1; - h[2] = h2; - h[3] = h3; - h[4] = h4; - h[5] = h5; - h[6] = h6; - h[7] = h7; - h[8] = h8; - h[9] = h9; + h[0] = (int32_t)h0; + h[1] = (int32_t)h1; + h[2] = (int32_t)h2; + h[3] = (int32_t)h3; + h[4] = (int32_t)h4; + h[5] = (int32_t)h5; + h[6] = (int32_t)h6; + h[7] = (int32_t)h7; + h[8] = (int32_t)h8; + h[9] = (int32_t)h9; } /* h = f * f @@ -1086,16 +1339,16 @@ static void fe_sq(fe h, const fe f) { carry0 = h0 + (1 << 25); h1 += carry0 >> 26; h0 -= carry0 & kTop38Bits; - h[0] = h0; - h[1] = h1; - h[2] = h2; - h[3] = h3; - h[4] = h4; - h[5] = h5; - h[6] = h6; - h[7] = h7; - h[8] = h8; - h[9] = h9; + h[0] = (int32_t)h0; + h[1] = (int32_t)h1; + h[2] = (int32_t)h2; + h[3] = (int32_t)h3; + h[4] = (int32_t)h4; + h[5] = (int32_t)h5; + h[6] = (int32_t)h6; + h[7] = (int32_t)h7; + h[8] = (int32_t)h8; + h[9] = (int32_t)h9; } static void fe_invert(fe out, const fe z) { @@ -1221,6 +1474,30 @@ static void fe_cmov(fe f, const fe g, unsigned b) { } } +/* return 0 if f == 0 + * return 1 if f != 0 + * + * Preconditions: + * |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. */ +static int fe_isnonzero(const fe f) { + uint8_t s[32]; + static const uint8_t zero[32] = {0}; + fe_tobytes(s, f); + + return CRYPTO_memcmp(s, zero, sizeof(zero)) != 0; +} + +/* return 1 if f is in {1,3,5,...,q-2} + * return 0 if f is in {0,2,4,...,q-1} + * + * Preconditions: + * |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. */ +static int fe_isnegative(const fe f) { + uint8_t s[32]; + fe_tobytes(s, f); + return s[0] & 1; +} + /* h = 2 * f * f * Can overlap h with f. * @@ -1361,16 +1638,73 @@ static void fe_sq2(fe h, const fe f) { carry0 = h0 + (1 << 25); h1 += carry0 >> 26; h0 -= carry0 & kTop38Bits; - h[0] = h0; - h[1] = h1; - h[2] = h2; - h[3] = h3; - h[4] = h4; - h[5] = h5; - h[6] = h6; - h[7] = h7; - h[8] = h8; - h[9] = h9; + h[0] = (int32_t)h0; + h[1] = (int32_t)h1; + h[2] = (int32_t)h2; + h[3] = (int32_t)h3; + h[4] = (int32_t)h4; + h[5] = (int32_t)h5; + h[6] = (int32_t)h6; + h[7] = (int32_t)h7; + h[8] = (int32_t)h8; + h[9] = (int32_t)h9; +} + +static void fe_pow22523(fe out, const fe z) { + fe t0; + fe t1; + fe t2; + int i; + + fe_sq(t0, z); + fe_sq(t1, t0); + for (i = 1; i < 2; ++i) { + fe_sq(t1, t1); + } + fe_mul(t1, z, t1); + fe_mul(t0, t0, t1); + fe_sq(t0, t0); + fe_mul(t0, t1, t0); + fe_sq(t1, t0); + for (i = 1; i < 5; ++i) { + fe_sq(t1, t1); + } + fe_mul(t0, t1, t0); + fe_sq(t1, t0); + for (i = 1; i < 10; ++i) { + fe_sq(t1, t1); + } + fe_mul(t1, t1, t0); + fe_sq(t2, t1); + for (i = 1; i < 20; ++i) { + fe_sq(t2, t2); + } + fe_mul(t1, t2, t1); + fe_sq(t1, t1); + for (i = 1; i < 10; ++i) { + fe_sq(t1, t1); + } + fe_mul(t0, t1, t0); + fe_sq(t1, t0); + for (i = 1; i < 50; ++i) { + fe_sq(t1, t1); + } + fe_mul(t1, t1, t0); + fe_sq(t2, t1); + for (i = 1; i < 100; ++i) { + fe_sq(t2, t2); + } + fe_mul(t1, t2, t1); + fe_sq(t1, t1); + for (i = 1; i < 50; ++i) { + fe_sq(t1, t1); + } + fe_mul(t0, t1, t0); + fe_sq(t0, t0); + for (i = 1; i < 2; ++i) { + fe_sq(t0, t0); + } + fe_mul(out, t0, z); } /* ge means group element. @@ -1418,6 +1752,85 @@ typedef struct { fe T2d; } ge_cached; +static void ge_tobytes(uint8_t *s, const ge_p2 *h) { + fe recip; + fe x; + fe y; + + fe_invert(recip, h->Z); + fe_mul(x, h->X, recip); + fe_mul(y, h->Y, recip); + fe_tobytes(s, y); + s[31] ^= fe_isnegative(x) << 7; +} + +static void ge_p3_tobytes(uint8_t *s, const ge_p3 *h) { + fe recip; + fe x; + fe y; + + fe_invert(recip, h->Z); + fe_mul(x, h->X, recip); + fe_mul(y, h->Y, recip); + fe_tobytes(s, y); + s[31] ^= fe_isnegative(x) << 7; +} + +static const fe d = {-10913610, 13857413, -15372611, 6949391, 114729, + -8787816, -6275908, -3247719, -18696448, -12055116}; + +static const fe sqrtm1 = {-32595792, -7943725, 9377950, 3500415, 12389472, + -272473, -25146209, -2005654, 326686, 11406482}; + +static int ge_frombytes_vartime(ge_p3 *h, const uint8_t *s) { + fe u; + fe v; + fe v3; + fe vxx; + fe check; + + fe_frombytes(h->Y, s); + fe_1(h->Z); + fe_sq(u, h->Y); + fe_mul(v, u, d); + fe_sub(u, u, h->Z); /* u = y^2-1 */ + fe_add(v, v, h->Z); /* v = dy^2+1 */ + + fe_sq(v3, v); + fe_mul(v3, v3, v); /* v3 = v^3 */ + fe_sq(h->X, v3); + fe_mul(h->X, h->X, v); + fe_mul(h->X, h->X, u); /* x = uv^7 */ + + fe_pow22523(h->X, h->X); /* x = (uv^7)^((q-5)/8) */ + fe_mul(h->X, h->X, v3); + fe_mul(h->X, h->X, u); /* x = uv^3(uv^7)^((q-5)/8) */ + + fe_sq(vxx, h->X); + fe_mul(vxx, vxx, v); + fe_sub(check, vxx, u); /* vx^2-u */ + if (fe_isnonzero(check)) { + fe_add(check, vxx, u); /* vx^2+u */ + if (fe_isnonzero(check)) { + return -1; + } + fe_mul(h->X, h->X, sqrtm1); + } + + if (fe_isnegative(h->X) != (s[31] >> 7)) { + fe_neg(h->X, h->X); + } + + fe_mul(h->T, h->X, h->Y); + return 0; +} + +static void ge_p2_0(ge_p2 *h) { + fe_0(h->X); + fe_1(h->Y); + fe_1(h->Z); +} + static void ge_p3_0(ge_p3 *h) { fe_0(h->X); fe_1(h->Y); @@ -1438,6 +1851,17 @@ static void ge_p3_to_p2(ge_p2 *r, const ge_p3 *p) { fe_copy(r->Z, p->Z); } +static const fe d2 = {-21827239, -5839606, -30745221, 13898782, 229458, + 15978800, -12551817, -6495438, 29715968, 9444199}; + +/* r = p */ +static void ge_p3_to_cached(ge_cached *r, const ge_p3 *p) { + fe_add(r->YplusX, p->Y, p->X); + fe_sub(r->YminusX, p->Y, p->X); + fe_copy(r->Z, p->Z); + fe_mul(r->T2d, p->T, d2); +} + /* r = p */ static void ge_p1p1_to_p2(ge_p2 *r, const ge_p1p1 *p) { fe_mul(r->X, p->X, p->T); @@ -1491,6 +1915,56 @@ static void ge_madd(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { fe_sub(r->T, t0, r->T); } +/* r = p - q */ +static void ge_msub(ge_p1p1 *r, const ge_p3 *p, const ge_precomp *q) { + fe t0; + + fe_add(r->X, p->Y, p->X); + fe_sub(r->Y, p->Y, p->X); + fe_mul(r->Z, r->X, q->yminusx); + fe_mul(r->Y, r->Y, q->yplusx); + fe_mul(r->T, q->xy2d, p->T); + fe_add(t0, p->Z, p->Z); + fe_sub(r->X, r->Z, r->Y); + fe_add(r->Y, r->Z, r->Y); + fe_sub(r->Z, t0, r->T); + fe_add(r->T, t0, r->T); +} + +/* r = p + q */ +static void ge_add(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { + fe t0; + + fe_add(r->X, p->Y, p->X); + fe_sub(r->Y, p->Y, p->X); + fe_mul(r->Z, r->X, q->YplusX); + fe_mul(r->Y, r->Y, q->YminusX); + fe_mul(r->T, q->T2d, p->T); + fe_mul(r->X, p->Z, q->Z); + fe_add(t0, r->X, r->X); + fe_sub(r->X, r->Z, r->Y); + fe_add(r->Y, r->Z, r->Y); + fe_add(r->Z, t0, r->T); + fe_sub(r->T, t0, r->T); +} + +/* r = p - q */ +static void ge_sub(ge_p1p1 *r, const ge_p3 *p, const ge_cached *q) { + fe t0; + + fe_add(r->X, p->Y, p->X); + fe_sub(r->Y, p->Y, p->X); + fe_mul(r->Z, r->X, q->YminusX); + fe_mul(r->Y, r->Y, q->YplusX); + fe_mul(r->T, q->T2d, p->T); + fe_mul(r->X, p->Z, q->Z); + fe_add(t0, r->X, r->X); + fe_sub(r->X, r->Z, r->Y); + fe_add(r->Y, r->Z, r->Y); + fe_sub(r->Z, t0, r->T); + fe_add(r->T, t0, r->T); +} + static uint8_t equal(signed char b, signed char c) { uint8_t ub = b; uint8_t uc = c; @@ -3773,16 +4247,16 @@ static void fe_mul121666(fe h, fe f) { carry6 = h6 + (1 << 25); h7 += carry6 >> 26; h6 -= carry6 & kTop38Bits; carry8 = h8 + (1 << 25); h9 += carry8 >> 26; h8 -= carry8 & kTop38Bits; - h[0] = h0; - h[1] = h1; - h[2] = h2; - h[3] = h3; - h[4] = h4; - h[5] = h5; - h[6] = h6; - h[7] = h7; - h[8] = h8; - h[9] = h9; + h[0] = (int32_t)h0; + h[1] = (int32_t)h1; + h[2] = (int32_t)h2; + h[3] = (int32_t)h3; + h[4] = (int32_t)h4; + h[5] = (int32_t)h5; + h[6] = (int32_t)h6; + h[7] = (int32_t)h7; + h[8] = (int32_t)h8; + h[9] = (int32_t)h9; } static void x25519_scalar_mult_generic(uint8_t out[32], @@ -3828,8 +4302,6 @@ static void x25519_scalar_mult_generic(uint8_t out[32], fe_mul(z3, x1, z2); fe_mul(z2, tmp1, tmp0); } - fe_cswap(x2, x3, swap); - fe_cswap(z2, z3, swap); fe_invert(z2, z2); fe_mul(x2, x2, z2); @@ -3844,6 +4316,1106 @@ static void x25519_scalar_mult(uint8_t out[32], const uint8_t scalar[32], } #endif +static void slide(signed char *r, const uint8_t *a) { + int i; + int b; + int k; + + for (i = 0; i < 256; ++i) { + r[i] = 1 & (a[i >> 3] >> (i & 7)); + } + + for (i = 0; i < 256; ++i) { + if (r[i]) { + for (b = 1; b <= 6 && i + b < 256; ++b) { + if (r[i + b]) { + if (r[i] + (r[i + b] << b) <= 15) { + r[i] += r[i + b] << b; + r[i + b] = 0; + } else if (r[i] - (r[i + b] << b) >= -15) { + r[i] -= r[i + b] << b; + for (k = i + b; k < 256; ++k) { + if (!r[k]) { + r[k] = 1; + break; + } + r[k] = 0; + } + } else { + break; + } + } + } + } + } +} + +static const ge_precomp Bi[8] = { + { + {25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, + -11754271, -6079156, 2047605}, + {-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, + 5043384, 19500929, -15469378}, + {-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, + 11864899, -24514362, -4438546}, + }, + { + {15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, + -14772189, 28944400, -1550024}, + {16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, + -11775962, 7689662, 11199574}, + {30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, + 10017326, -17749093, -9920357}, + }, + { + {10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, + 14515107, -15438304, 10819380}, + {4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, + 12483688, -12668491, 5581306}, + {19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, + 13850243, -23678021, -15815942}, + }, + { + {5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, + 5230134, -23952439, -15175766}, + {-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, + 16520125, 30598449, 7715701}, + {28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, + 1370708, 29794553, -1409300}, + }, + { + {-22518993, -6692182, 14201702, -8745502, -23510406, 8844726, 18474211, + -1361450, -13062696, 13821877}, + {-6455177, -7839871, 3374702, -4740862, -27098617, -10571707, 31655028, + -7212327, 18853322, -14220951}, + {4566830, -12963868, -28974889, -12240689, -7602672, -2830569, -8514358, + -10431137, 2207753, -3209784}, + }, + { + {-25154831, -4185821, 29681144, 7868801, -6854661, -9423865, -12437364, + -663000, -31111463, -16132436}, + {25576264, -2703214, 7349804, -11814844, 16472782, 9300885, 3844789, + 15725684, 171356, 6466918}, + {23103977, 13316479, 9739013, -16149481, 817875, -15038942, 8965339, + -14088058, -30714912, 16193877}, + }, + { + {-33521811, 3180713, -2394130, 14003687, -16903474, -16270840, 17238398, + 4729455, -18074513, 9256800}, + {-25182317, -4174131, 32336398, 5036987, -21236817, 11360617, 22616405, + 9761698, -19827198, 630305}, + {-13720693, 2639453, -24237460, -7406481, 9494427, -5774029, -6554551, + -15960994, -2449256, -14291300}, + }, + { + {-3151181, -5046075, 9282714, 6866145, -31907062, -863023, -18940575, + 15033784, 25105118, -7894876}, + {-24326370, 15950226, -31801215, -14592823, -11662737, -5090925, + 1573892, -2625887, 2198790, -15804619}, + {-3099351, 10324967, -2241613, 7453183, -5446979, -2735503, -13812022, + -16236442, -32461234, -12290683}, + }, +}; + +/* r = a * A + b * B + * where a = a[0]+256*a[1]+...+256^31 a[31]. + * and b = b[0]+256*b[1]+...+256^31 b[31]. + * B is the Ed25519 base point (x,4/5) with x positive. */ +static void ge_double_scalarmult_vartime(ge_p2 *r, const uint8_t *a, + const ge_p3 *A, const uint8_t *b) { + signed char aslide[256]; + signed char bslide[256]; + ge_cached Ai[8]; /* A,3A,5A,7A,9A,11A,13A,15A */ + ge_p1p1 t; + ge_p3 u; + ge_p3 A2; + int i; + + slide(aslide, a); + slide(bslide, b); + + ge_p3_to_cached(&Ai[0], A); + ge_p3_dbl(&t, A); + ge_p1p1_to_p3(&A2, &t); + ge_add(&t, &A2, &Ai[0]); + ge_p1p1_to_p3(&u, &t); + ge_p3_to_cached(&Ai[1], &u); + ge_add(&t, &A2, &Ai[1]); + ge_p1p1_to_p3(&u, &t); + ge_p3_to_cached(&Ai[2], &u); + ge_add(&t, &A2, &Ai[2]); + ge_p1p1_to_p3(&u, &t); + ge_p3_to_cached(&Ai[3], &u); + ge_add(&t, &A2, &Ai[3]); + ge_p1p1_to_p3(&u, &t); + ge_p3_to_cached(&Ai[4], &u); + ge_add(&t, &A2, &Ai[4]); + ge_p1p1_to_p3(&u, &t); + ge_p3_to_cached(&Ai[5], &u); + ge_add(&t, &A2, &Ai[5]); + ge_p1p1_to_p3(&u, &t); + ge_p3_to_cached(&Ai[6], &u); + ge_add(&t, &A2, &Ai[6]); + ge_p1p1_to_p3(&u, &t); + ge_p3_to_cached(&Ai[7], &u); + + ge_p2_0(r); + + for (i = 255; i >= 0; --i) { + if (aslide[i] || bslide[i]) { + break; + } + } + + for (; i >= 0; --i) { + ge_p2_dbl(&t, r); + + if (aslide[i] > 0) { + ge_p1p1_to_p3(&u, &t); + ge_add(&t, &u, &Ai[aslide[i] / 2]); + } else if (aslide[i] < 0) { + ge_p1p1_to_p3(&u, &t); + ge_sub(&t, &u, &Ai[(-aslide[i]) / 2]); + } + + if (bslide[i] > 0) { + ge_p1p1_to_p3(&u, &t); + ge_madd(&t, &u, &Bi[bslide[i] / 2]); + } else if (bslide[i] < 0) { + ge_p1p1_to_p3(&u, &t); + ge_msub(&t, &u, &Bi[(-bslide[i]) / 2]); + } + + ge_p1p1_to_p2(r, &t); + } +} + +/* The set of scalars is \Z/l + * where l = 2^252 + 27742317777372353535851937790883648493. */ + +/* Input: + * s[0]+256*s[1]+...+256^63*s[63] = s + * + * Output: + * s[0]+256*s[1]+...+256^31*s[31] = s mod l + * where l = 2^252 + 27742317777372353535851937790883648493. + * Overwrites s in place. */ +static void x25519_sc_reduce(uint8_t *s) { + int64_t s0 = 2097151 & load_3(s); + int64_t s1 = 2097151 & (load_4(s + 2) >> 5); + int64_t s2 = 2097151 & (load_3(s + 5) >> 2); + int64_t s3 = 2097151 & (load_4(s + 7) >> 7); + int64_t s4 = 2097151 & (load_4(s + 10) >> 4); + int64_t s5 = 2097151 & (load_3(s + 13) >> 1); + int64_t s6 = 2097151 & (load_4(s + 15) >> 6); + int64_t s7 = 2097151 & (load_3(s + 18) >> 3); + int64_t s8 = 2097151 & load_3(s + 21); + int64_t s9 = 2097151 & (load_4(s + 23) >> 5); + int64_t s10 = 2097151 & (load_3(s + 26) >> 2); + int64_t s11 = 2097151 & (load_4(s + 28) >> 7); + int64_t s12 = 2097151 & (load_4(s + 31) >> 4); + int64_t s13 = 2097151 & (load_3(s + 34) >> 1); + int64_t s14 = 2097151 & (load_4(s + 36) >> 6); + int64_t s15 = 2097151 & (load_3(s + 39) >> 3); + int64_t s16 = 2097151 & load_3(s + 42); + int64_t s17 = 2097151 & (load_4(s + 44) >> 5); + int64_t s18 = 2097151 & (load_3(s + 47) >> 2); + int64_t s19 = 2097151 & (load_4(s + 49) >> 7); + int64_t s20 = 2097151 & (load_4(s + 52) >> 4); + int64_t s21 = 2097151 & (load_3(s + 55) >> 1); + int64_t s22 = 2097151 & (load_4(s + 57) >> 6); + int64_t s23 = (load_4(s + 60) >> 3); + int64_t carry0; + int64_t carry1; + int64_t carry2; + int64_t carry3; + int64_t carry4; + int64_t carry5; + int64_t carry6; + int64_t carry7; + int64_t carry8; + int64_t carry9; + int64_t carry10; + int64_t carry11; + int64_t carry12; + int64_t carry13; + int64_t carry14; + int64_t carry15; + int64_t carry16; + + s11 += s23 * 666643; + s12 += s23 * 470296; + s13 += s23 * 654183; + s14 -= s23 * 997805; + s15 += s23 * 136657; + s16 -= s23 * 683901; + s23 = 0; + + s10 += s22 * 666643; + s11 += s22 * 470296; + s12 += s22 * 654183; + s13 -= s22 * 997805; + s14 += s22 * 136657; + s15 -= s22 * 683901; + s22 = 0; + + s9 += s21 * 666643; + s10 += s21 * 470296; + s11 += s21 * 654183; + s12 -= s21 * 997805; + s13 += s21 * 136657; + s14 -= s21 * 683901; + s21 = 0; + + s8 += s20 * 666643; + s9 += s20 * 470296; + s10 += s20 * 654183; + s11 -= s20 * 997805; + s12 += s20 * 136657; + s13 -= s20 * 683901; + s20 = 0; + + s7 += s19 * 666643; + s8 += s19 * 470296; + s9 += s19 * 654183; + s10 -= s19 * 997805; + s11 += s19 * 136657; + s12 -= s19 * 683901; + s19 = 0; + + s6 += s18 * 666643; + s7 += s18 * 470296; + s8 += s18 * 654183; + s9 -= s18 * 997805; + s10 += s18 * 136657; + s11 -= s18 * 683901; + s18 = 0; + + carry6 = (s6 + (1 << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * (1 << 21); + carry8 = (s8 + (1 << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * (1 << 21); + carry10 = (s10 + (1 << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * (1 << 21); + carry12 = (s12 + (1 << 20)) >> 21; + s13 += carry12; + s12 -= carry12 * (1 << 21); + carry14 = (s14 + (1 << 20)) >> 21; + s15 += carry14; + s14 -= carry14 * (1 << 21); + carry16 = (s16 + (1 << 20)) >> 21; + s17 += carry16; + s16 -= carry16 * (1 << 21); + + carry7 = (s7 + (1 << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * (1 << 21); + carry9 = (s9 + (1 << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * (1 << 21); + carry11 = (s11 + (1 << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * (1 << 21); + carry13 = (s13 + (1 << 20)) >> 21; + s14 += carry13; + s13 -= carry13 * (1 << 21); + carry15 = (s15 + (1 << 20)) >> 21; + s16 += carry15; + s15 -= carry15 * (1 << 21); + + s5 += s17 * 666643; + s6 += s17 * 470296; + s7 += s17 * 654183; + s8 -= s17 * 997805; + s9 += s17 * 136657; + s10 -= s17 * 683901; + s17 = 0; + + s4 += s16 * 666643; + s5 += s16 * 470296; + s6 += s16 * 654183; + s7 -= s16 * 997805; + s8 += s16 * 136657; + s9 -= s16 * 683901; + s16 = 0; + + s3 += s15 * 666643; + s4 += s15 * 470296; + s5 += s15 * 654183; + s6 -= s15 * 997805; + s7 += s15 * 136657; + s8 -= s15 * 683901; + s15 = 0; + + s2 += s14 * 666643; + s3 += s14 * 470296; + s4 += s14 * 654183; + s5 -= s14 * 997805; + s6 += s14 * 136657; + s7 -= s14 * 683901; + s14 = 0; + + s1 += s13 * 666643; + s2 += s13 * 470296; + s3 += s13 * 654183; + s4 -= s13 * 997805; + s5 += s13 * 136657; + s6 -= s13 * 683901; + s13 = 0; + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = (s0 + (1 << 20)) >> 21; + s1 += carry0; + s0 -= carry0 * (1 << 21); + carry2 = (s2 + (1 << 20)) >> 21; + s3 += carry2; + s2 -= carry2 * (1 << 21); + carry4 = (s4 + (1 << 20)) >> 21; + s5 += carry4; + s4 -= carry4 * (1 << 21); + carry6 = (s6 + (1 << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * (1 << 21); + carry8 = (s8 + (1 << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * (1 << 21); + carry10 = (s10 + (1 << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * (1 << 21); + + carry1 = (s1 + (1 << 20)) >> 21; + s2 += carry1; + s1 -= carry1 * (1 << 21); + carry3 = (s3 + (1 << 20)) >> 21; + s4 += carry3; + s3 -= carry3 * (1 << 21); + carry5 = (s5 + (1 << 20)) >> 21; + s6 += carry5; + s5 -= carry5 * (1 << 21); + carry7 = (s7 + (1 << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * (1 << 21); + carry9 = (s9 + (1 << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * (1 << 21); + carry11 = (s11 + (1 << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * (1 << 21); + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = s0 >> 21; + s1 += carry0; + s0 -= carry0 * (1 << 21); + carry1 = s1 >> 21; + s2 += carry1; + s1 -= carry1 * (1 << 21); + carry2 = s2 >> 21; + s3 += carry2; + s2 -= carry2 * (1 << 21); + carry3 = s3 >> 21; + s4 += carry3; + s3 -= carry3 * (1 << 21); + carry4 = s4 >> 21; + s5 += carry4; + s4 -= carry4 * (1 << 21); + carry5 = s5 >> 21; + s6 += carry5; + s5 -= carry5 * (1 << 21); + carry6 = s6 >> 21; + s7 += carry6; + s6 -= carry6 * (1 << 21); + carry7 = s7 >> 21; + s8 += carry7; + s7 -= carry7 * (1 << 21); + carry8 = s8 >> 21; + s9 += carry8; + s8 -= carry8 * (1 << 21); + carry9 = s9 >> 21; + s10 += carry9; + s9 -= carry9 * (1 << 21); + carry10 = s10 >> 21; + s11 += carry10; + s10 -= carry10 * (1 << 21); + carry11 = s11 >> 21; + s12 += carry11; + s11 -= carry11 * (1 << 21); + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = s0 >> 21; + s1 += carry0; + s0 -= carry0 * (1 << 21); + carry1 = s1 >> 21; + s2 += carry1; + s1 -= carry1 * (1 << 21); + carry2 = s2 >> 21; + s3 += carry2; + s2 -= carry2 * (1 << 21); + carry3 = s3 >> 21; + s4 += carry3; + s3 -= carry3 * (1 << 21); + carry4 = s4 >> 21; + s5 += carry4; + s4 -= carry4 * (1 << 21); + carry5 = s5 >> 21; + s6 += carry5; + s5 -= carry5 * (1 << 21); + carry6 = s6 >> 21; + s7 += carry6; + s6 -= carry6 * (1 << 21); + carry7 = s7 >> 21; + s8 += carry7; + s7 -= carry7 * (1 << 21); + carry8 = s8 >> 21; + s9 += carry8; + s8 -= carry8 * (1 << 21); + carry9 = s9 >> 21; + s10 += carry9; + s9 -= carry9 * (1 << 21); + carry10 = s10 >> 21; + s11 += carry10; + s10 -= carry10 * (1 << 21); + + s[0] = (uint8_t)(s0 >> 0); + s[1] = (uint8_t)(s0 >> 8); + s[2] = (uint8_t)((s0 >> 16) | (s1 << 5)); + s[3] = (uint8_t)(s1 >> 3); + s[4] = (uint8_t)(s1 >> 11); + s[5] = (uint8_t)((s1 >> 19) | (s2 << 2)); + s[6] = (uint8_t)(s2 >> 6); + s[7] = (uint8_t)((s2 >> 14) | (s3 << 7)); + s[8] = (uint8_t)(s3 >> 1); + s[9] = (uint8_t)(s3 >> 9); + s[10] = (uint8_t)((s3 >> 17) | (s4 << 4)); + s[11] = (uint8_t)(s4 >> 4); + s[12] = (uint8_t)(s4 >> 12); + s[13] = (uint8_t)((s4 >> 20) | (s5 << 1)); + s[14] = (uint8_t)(s5 >> 7); + s[15] = (uint8_t)((s5 >> 15) | (s6 << 6)); + s[16] = (uint8_t)(s6 >> 2); + s[17] = (uint8_t)(s6 >> 10); + s[18] = (uint8_t)((s6 >> 18) | (s7 << 3)); + s[19] = (uint8_t)(s7 >> 5); + s[20] = (uint8_t)(s7 >> 13); + s[21] = (uint8_t)(s8 >> 0); + s[22] = (uint8_t)(s8 >> 8); + s[23] = (uint8_t)((s8 >> 16) | (s9 << 5)); + s[24] = (uint8_t)(s9 >> 3); + s[25] = (uint8_t)(s9 >> 11); + s[26] = (uint8_t)((s9 >> 19) | (s10 << 2)); + s[27] = (uint8_t)(s10 >> 6); + s[28] = (uint8_t)((s10 >> 14) | (s11 << 7)); + s[29] = (uint8_t)(s11 >> 1); + s[30] = (uint8_t)(s11 >> 9); + s[31] = (uint8_t)(s11 >> 17); +} + +/* Input: + * a[0]+256*a[1]+...+256^31*a[31] = a + * b[0]+256*b[1]+...+256^31*b[31] = b + * c[0]+256*c[1]+...+256^31*c[31] = c + * + * Output: + * s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l + * where l = 2^252 + 27742317777372353535851937790883648493. */ +static void sc_muladd(uint8_t *s, const uint8_t *a, const uint8_t *b, + const uint8_t *c) { + int64_t a0 = 2097151 & load_3(a); + int64_t a1 = 2097151 & (load_4(a + 2) >> 5); + int64_t a2 = 2097151 & (load_3(a + 5) >> 2); + int64_t a3 = 2097151 & (load_4(a + 7) >> 7); + int64_t a4 = 2097151 & (load_4(a + 10) >> 4); + int64_t a5 = 2097151 & (load_3(a + 13) >> 1); + int64_t a6 = 2097151 & (load_4(a + 15) >> 6); + int64_t a7 = 2097151 & (load_3(a + 18) >> 3); + int64_t a8 = 2097151 & load_3(a + 21); + int64_t a9 = 2097151 & (load_4(a + 23) >> 5); + int64_t a10 = 2097151 & (load_3(a + 26) >> 2); + int64_t a11 = (load_4(a + 28) >> 7); + int64_t b0 = 2097151 & load_3(b); + int64_t b1 = 2097151 & (load_4(b + 2) >> 5); + int64_t b2 = 2097151 & (load_3(b + 5) >> 2); + int64_t b3 = 2097151 & (load_4(b + 7) >> 7); + int64_t b4 = 2097151 & (load_4(b + 10) >> 4); + int64_t b5 = 2097151 & (load_3(b + 13) >> 1); + int64_t b6 = 2097151 & (load_4(b + 15) >> 6); + int64_t b7 = 2097151 & (load_3(b + 18) >> 3); + int64_t b8 = 2097151 & load_3(b + 21); + int64_t b9 = 2097151 & (load_4(b + 23) >> 5); + int64_t b10 = 2097151 & (load_3(b + 26) >> 2); + int64_t b11 = (load_4(b + 28) >> 7); + int64_t c0 = 2097151 & load_3(c); + int64_t c1 = 2097151 & (load_4(c + 2) >> 5); + int64_t c2 = 2097151 & (load_3(c + 5) >> 2); + int64_t c3 = 2097151 & (load_4(c + 7) >> 7); + int64_t c4 = 2097151 & (load_4(c + 10) >> 4); + int64_t c5 = 2097151 & (load_3(c + 13) >> 1); + int64_t c6 = 2097151 & (load_4(c + 15) >> 6); + int64_t c7 = 2097151 & (load_3(c + 18) >> 3); + int64_t c8 = 2097151 & load_3(c + 21); + int64_t c9 = 2097151 & (load_4(c + 23) >> 5); + int64_t c10 = 2097151 & (load_3(c + 26) >> 2); + int64_t c11 = (load_4(c + 28) >> 7); + int64_t s0; + int64_t s1; + int64_t s2; + int64_t s3; + int64_t s4; + int64_t s5; + int64_t s6; + int64_t s7; + int64_t s8; + int64_t s9; + int64_t s10; + int64_t s11; + int64_t s12; + int64_t s13; + int64_t s14; + int64_t s15; + int64_t s16; + int64_t s17; + int64_t s18; + int64_t s19; + int64_t s20; + int64_t s21; + int64_t s22; + int64_t s23; + int64_t carry0; + int64_t carry1; + int64_t carry2; + int64_t carry3; + int64_t carry4; + int64_t carry5; + int64_t carry6; + int64_t carry7; + int64_t carry8; + int64_t carry9; + int64_t carry10; + int64_t carry11; + int64_t carry12; + int64_t carry13; + int64_t carry14; + int64_t carry15; + int64_t carry16; + int64_t carry17; + int64_t carry18; + int64_t carry19; + int64_t carry20; + int64_t carry21; + int64_t carry22; + + s0 = c0 + a0 * b0; + s1 = c1 + a0 * b1 + a1 * b0; + s2 = c2 + a0 * b2 + a1 * b1 + a2 * b0; + s3 = c3 + a0 * b3 + a1 * b2 + a2 * b1 + a3 * b0; + s4 = c4 + a0 * b4 + a1 * b3 + a2 * b2 + a3 * b1 + a4 * b0; + s5 = c5 + a0 * b5 + a1 * b4 + a2 * b3 + a3 * b2 + a4 * b1 + a5 * b0; + s6 = c6 + a0 * b6 + a1 * b5 + a2 * b4 + a3 * b3 + a4 * b2 + a5 * b1 + a6 * b0; + s7 = c7 + a0 * b7 + a1 * b6 + a2 * b5 + a3 * b4 + a4 * b3 + a5 * b2 + + a6 * b1 + a7 * b0; + s8 = c8 + a0 * b8 + a1 * b7 + a2 * b6 + a3 * b5 + a4 * b4 + a5 * b3 + + a6 * b2 + a7 * b1 + a8 * b0; + s9 = c9 + a0 * b9 + a1 * b8 + a2 * b7 + a3 * b6 + a4 * b5 + a5 * b4 + + a6 * b3 + a7 * b2 + a8 * b1 + a9 * b0; + s10 = c10 + a0 * b10 + a1 * b9 + a2 * b8 + a3 * b7 + a4 * b6 + a5 * b5 + + a6 * b4 + a7 * b3 + a8 * b2 + a9 * b1 + a10 * b0; + s11 = c11 + a0 * b11 + a1 * b10 + a2 * b9 + a3 * b8 + a4 * b7 + a5 * b6 + + a6 * b5 + a7 * b4 + a8 * b3 + a9 * b2 + a10 * b1 + a11 * b0; + s12 = a1 * b11 + a2 * b10 + a3 * b9 + a4 * b8 + a5 * b7 + a6 * b6 + a7 * b5 + + a8 * b4 + a9 * b3 + a10 * b2 + a11 * b1; + s13 = a2 * b11 + a3 * b10 + a4 * b9 + a5 * b8 + a6 * b7 + a7 * b6 + a8 * b5 + + a9 * b4 + a10 * b3 + a11 * b2; + s14 = a3 * b11 + a4 * b10 + a5 * b9 + a6 * b8 + a7 * b7 + a8 * b6 + a9 * b5 + + a10 * b4 + a11 * b3; + s15 = a4 * b11 + a5 * b10 + a6 * b9 + a7 * b8 + a8 * b7 + a9 * b6 + a10 * b5 + + a11 * b4; + s16 = a5 * b11 + a6 * b10 + a7 * b9 + a8 * b8 + a9 * b7 + a10 * b6 + a11 * b5; + s17 = a6 * b11 + a7 * b10 + a8 * b9 + a9 * b8 + a10 * b7 + a11 * b6; + s18 = a7 * b11 + a8 * b10 + a9 * b9 + a10 * b8 + a11 * b7; + s19 = a8 * b11 + a9 * b10 + a10 * b9 + a11 * b8; + s20 = a9 * b11 + a10 * b10 + a11 * b9; + s21 = a10 * b11 + a11 * b10; + s22 = a11 * b11; + s23 = 0; + + carry0 = (s0 + (1 << 20)) >> 21; + s1 += carry0; + s0 -= carry0 * (1 << 21); + carry2 = (s2 + (1 << 20)) >> 21; + s3 += carry2; + s2 -= carry2 * (1 << 21); + carry4 = (s4 + (1 << 20)) >> 21; + s5 += carry4; + s4 -= carry4 * (1 << 21); + carry6 = (s6 + (1 << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * (1 << 21); + carry8 = (s8 + (1 << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * (1 << 21); + carry10 = (s10 + (1 << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * (1 << 21); + carry12 = (s12 + (1 << 20)) >> 21; + s13 += carry12; + s12 -= carry12 * (1 << 21); + carry14 = (s14 + (1 << 20)) >> 21; + s15 += carry14; + s14 -= carry14 * (1 << 21); + carry16 = (s16 + (1 << 20)) >> 21; + s17 += carry16; + s16 -= carry16 * (1 << 21); + carry18 = (s18 + (1 << 20)) >> 21; + s19 += carry18; + s18 -= carry18 * (1 << 21); + carry20 = (s20 + (1 << 20)) >> 21; + s21 += carry20; + s20 -= carry20 * (1 << 21); + carry22 = (s22 + (1 << 20)) >> 21; + s23 += carry22; + s22 -= carry22 * (1 << 21); + + carry1 = (s1 + (1 << 20)) >> 21; + s2 += carry1; + s1 -= carry1 * (1 << 21); + carry3 = (s3 + (1 << 20)) >> 21; + s4 += carry3; + s3 -= carry3 * (1 << 21); + carry5 = (s5 + (1 << 20)) >> 21; + s6 += carry5; + s5 -= carry5 * (1 << 21); + carry7 = (s7 + (1 << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * (1 << 21); + carry9 = (s9 + (1 << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * (1 << 21); + carry11 = (s11 + (1 << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * (1 << 21); + carry13 = (s13 + (1 << 20)) >> 21; + s14 += carry13; + s13 -= carry13 * (1 << 21); + carry15 = (s15 + (1 << 20)) >> 21; + s16 += carry15; + s15 -= carry15 * (1 << 21); + carry17 = (s17 + (1 << 20)) >> 21; + s18 += carry17; + s17 -= carry17 * (1 << 21); + carry19 = (s19 + (1 << 20)) >> 21; + s20 += carry19; + s19 -= carry19 * (1 << 21); + carry21 = (s21 + (1 << 20)) >> 21; + s22 += carry21; + s21 -= carry21 * (1 << 21); + + s11 += s23 * 666643; + s12 += s23 * 470296; + s13 += s23 * 654183; + s14 -= s23 * 997805; + s15 += s23 * 136657; + s16 -= s23 * 683901; + s23 = 0; + + s10 += s22 * 666643; + s11 += s22 * 470296; + s12 += s22 * 654183; + s13 -= s22 * 997805; + s14 += s22 * 136657; + s15 -= s22 * 683901; + s22 = 0; + + s9 += s21 * 666643; + s10 += s21 * 470296; + s11 += s21 * 654183; + s12 -= s21 * 997805; + s13 += s21 * 136657; + s14 -= s21 * 683901; + s21 = 0; + + s8 += s20 * 666643; + s9 += s20 * 470296; + s10 += s20 * 654183; + s11 -= s20 * 997805; + s12 += s20 * 136657; + s13 -= s20 * 683901; + s20 = 0; + + s7 += s19 * 666643; + s8 += s19 * 470296; + s9 += s19 * 654183; + s10 -= s19 * 997805; + s11 += s19 * 136657; + s12 -= s19 * 683901; + s19 = 0; + + s6 += s18 * 666643; + s7 += s18 * 470296; + s8 += s18 * 654183; + s9 -= s18 * 997805; + s10 += s18 * 136657; + s11 -= s18 * 683901; + s18 = 0; + + carry6 = (s6 + (1 << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * (1 << 21); + carry8 = (s8 + (1 << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * (1 << 21); + carry10 = (s10 + (1 << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * (1 << 21); + carry12 = (s12 + (1 << 20)) >> 21; + s13 += carry12; + s12 -= carry12 * (1 << 21); + carry14 = (s14 + (1 << 20)) >> 21; + s15 += carry14; + s14 -= carry14 * (1 << 21); + carry16 = (s16 + (1 << 20)) >> 21; + s17 += carry16; + s16 -= carry16 * (1 << 21); + + carry7 = (s7 + (1 << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * (1 << 21); + carry9 = (s9 + (1 << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * (1 << 21); + carry11 = (s11 + (1 << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * (1 << 21); + carry13 = (s13 + (1 << 20)) >> 21; + s14 += carry13; + s13 -= carry13 * (1 << 21); + carry15 = (s15 + (1 << 20)) >> 21; + s16 += carry15; + s15 -= carry15 * (1 << 21); + + s5 += s17 * 666643; + s6 += s17 * 470296; + s7 += s17 * 654183; + s8 -= s17 * 997805; + s9 += s17 * 136657; + s10 -= s17 * 683901; + s17 = 0; + + s4 += s16 * 666643; + s5 += s16 * 470296; + s6 += s16 * 654183; + s7 -= s16 * 997805; + s8 += s16 * 136657; + s9 -= s16 * 683901; + s16 = 0; + + s3 += s15 * 666643; + s4 += s15 * 470296; + s5 += s15 * 654183; + s6 -= s15 * 997805; + s7 += s15 * 136657; + s8 -= s15 * 683901; + s15 = 0; + + s2 += s14 * 666643; + s3 += s14 * 470296; + s4 += s14 * 654183; + s5 -= s14 * 997805; + s6 += s14 * 136657; + s7 -= s14 * 683901; + s14 = 0; + + s1 += s13 * 666643; + s2 += s13 * 470296; + s3 += s13 * 654183; + s4 -= s13 * 997805; + s5 += s13 * 136657; + s6 -= s13 * 683901; + s13 = 0; + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = (s0 + (1 << 20)) >> 21; + s1 += carry0; + s0 -= carry0 * (1 << 21); + carry2 = (s2 + (1 << 20)) >> 21; + s3 += carry2; + s2 -= carry2 * (1 << 21); + carry4 = (s4 + (1 << 20)) >> 21; + s5 += carry4; + s4 -= carry4 * (1 << 21); + carry6 = (s6 + (1 << 20)) >> 21; + s7 += carry6; + s6 -= carry6 * (1 << 21); + carry8 = (s8 + (1 << 20)) >> 21; + s9 += carry8; + s8 -= carry8 * (1 << 21); + carry10 = (s10 + (1 << 20)) >> 21; + s11 += carry10; + s10 -= carry10 * (1 << 21); + + carry1 = (s1 + (1 << 20)) >> 21; + s2 += carry1; + s1 -= carry1 * (1 << 21); + carry3 = (s3 + (1 << 20)) >> 21; + s4 += carry3; + s3 -= carry3 * (1 << 21); + carry5 = (s5 + (1 << 20)) >> 21; + s6 += carry5; + s5 -= carry5 * (1 << 21); + carry7 = (s7 + (1 << 20)) >> 21; + s8 += carry7; + s7 -= carry7 * (1 << 21); + carry9 = (s9 + (1 << 20)) >> 21; + s10 += carry9; + s9 -= carry9 * (1 << 21); + carry11 = (s11 + (1 << 20)) >> 21; + s12 += carry11; + s11 -= carry11 * (1 << 21); + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = s0 >> 21; + s1 += carry0; + s0 -= carry0 * (1 << 21); + carry1 = s1 >> 21; + s2 += carry1; + s1 -= carry1 * (1 << 21); + carry2 = s2 >> 21; + s3 += carry2; + s2 -= carry2 * (1 << 21); + carry3 = s3 >> 21; + s4 += carry3; + s3 -= carry3 * (1 << 21); + carry4 = s4 >> 21; + s5 += carry4; + s4 -= carry4 * (1 << 21); + carry5 = s5 >> 21; + s6 += carry5; + s5 -= carry5 * (1 << 21); + carry6 = s6 >> 21; + s7 += carry6; + s6 -= carry6 * (1 << 21); + carry7 = s7 >> 21; + s8 += carry7; + s7 -= carry7 * (1 << 21); + carry8 = s8 >> 21; + s9 += carry8; + s8 -= carry8 * (1 << 21); + carry9 = s9 >> 21; + s10 += carry9; + s9 -= carry9 * (1 << 21); + carry10 = s10 >> 21; + s11 += carry10; + s10 -= carry10 * (1 << 21); + carry11 = s11 >> 21; + s12 += carry11; + s11 -= carry11 * (1 << 21); + + s0 += s12 * 666643; + s1 += s12 * 470296; + s2 += s12 * 654183; + s3 -= s12 * 997805; + s4 += s12 * 136657; + s5 -= s12 * 683901; + s12 = 0; + + carry0 = s0 >> 21; + s1 += carry0; + s0 -= carry0 * (1 << 21); + carry1 = s1 >> 21; + s2 += carry1; + s1 -= carry1 * (1 << 21); + carry2 = s2 >> 21; + s3 += carry2; + s2 -= carry2 * (1 << 21); + carry3 = s3 >> 21; + s4 += carry3; + s3 -= carry3 * (1 << 21); + carry4 = s4 >> 21; + s5 += carry4; + s4 -= carry4 * (1 << 21); + carry5 = s5 >> 21; + s6 += carry5; + s5 -= carry5 * (1 << 21); + carry6 = s6 >> 21; + s7 += carry6; + s6 -= carry6 * (1 << 21); + carry7 = s7 >> 21; + s8 += carry7; + s7 -= carry7 * (1 << 21); + carry8 = s8 >> 21; + s9 += carry8; + s8 -= carry8 * (1 << 21); + carry9 = s9 >> 21; + s10 += carry9; + s9 -= carry9 * (1 << 21); + carry10 = s10 >> 21; + s11 += carry10; + s10 -= carry10 * (1 << 21); + + s[0] = (uint8_t)(s0 >> 0); + s[1] = (uint8_t)(s0 >> 8); + s[2] = (uint8_t)((s0 >> 16) | (s1 << 5)); + s[3] = (uint8_t)(s1 >> 3); + s[4] = (uint8_t)(s1 >> 11); + s[5] = (uint8_t)((s1 >> 19) | (s2 << 2)); + s[6] = (uint8_t)(s2 >> 6); + s[7] = (uint8_t)((s2 >> 14) | (s3 << 7)); + s[8] = (uint8_t)(s3 >> 1); + s[9] = (uint8_t)(s3 >> 9); + s[10] = (uint8_t)((s3 >> 17) | (s4 << 4)); + s[11] = (uint8_t)(s4 >> 4); + s[12] = (uint8_t)(s4 >> 12); + s[13] = (uint8_t)((s4 >> 20) | (s5 << 1)); + s[14] = (uint8_t)(s5 >> 7); + s[15] = (uint8_t)((s5 >> 15) | (s6 << 6)); + s[16] = (uint8_t)(s6 >> 2); + s[17] = (uint8_t)(s6 >> 10); + s[18] = (uint8_t)((s6 >> 18) | (s7 << 3)); + s[19] = (uint8_t)(s7 >> 5); + s[20] = (uint8_t)(s7 >> 13); + s[21] = (uint8_t)(s8 >> 0); + s[22] = (uint8_t)(s8 >> 8); + s[23] = (uint8_t)((s8 >> 16) | (s9 << 5)); + s[24] = (uint8_t)(s9 >> 3); + s[25] = (uint8_t)(s9 >> 11); + s[26] = (uint8_t)((s9 >> 19) | (s10 << 2)); + s[27] = (uint8_t)(s10 >> 6); + s[28] = (uint8_t)((s10 >> 14) | (s11 << 7)); + s[29] = (uint8_t)(s11 >> 1); + s[30] = (uint8_t)(s11 >> 9); + s[31] = (uint8_t)(s11 >> 17); +} + +int ED25519_sign(uint8_t *out_sig, const uint8_t *message, size_t message_len, + const uint8_t public_key[32], const uint8_t private_key[32]) { + uint8_t az[SHA512_DIGEST_LENGTH]; + uint8_t nonce[SHA512_DIGEST_LENGTH]; + ge_p3 R; + uint8_t hram[SHA512_DIGEST_LENGTH]; + SHA512_CTX hash_ctx; + + SHA512_Init(&hash_ctx); + SHA512_Update(&hash_ctx, private_key, 32); + SHA512_Final(az, &hash_ctx); + + az[0] &= 248; + az[31] &= 63; + az[31] |= 64; + + SHA512_Init(&hash_ctx); + SHA512_Update(&hash_ctx, az + 32, 32); + SHA512_Update(&hash_ctx, message, message_len); + SHA512_Final(nonce, &hash_ctx); + + x25519_sc_reduce(nonce); + ge_scalarmult_base(&R, nonce); + ge_p3_tobytes(out_sig, &R); + + SHA512_Init(&hash_ctx); + SHA512_Update(&hash_ctx, out_sig, 32); + SHA512_Update(&hash_ctx, public_key, 32); + SHA512_Update(&hash_ctx, message, message_len); + SHA512_Final(hram, &hash_ctx); + + x25519_sc_reduce(hram); + sc_muladd(out_sig + 32, hram, az, nonce); + + OPENSSL_cleanse(&hash_ctx, sizeof(hash_ctx)); + OPENSSL_cleanse(nonce, sizeof(nonce)); + OPENSSL_cleanse(az, sizeof(az)); + + return 1; +} + +int ED25519_verify(const uint8_t *message, size_t message_len, + const uint8_t signature[64], const uint8_t public_key[32]) { + ge_p3 A; + uint8_t rcopy[32]; + uint8_t scopy[32]; + SHA512_CTX hash_ctx; + ge_p2 R; + uint8_t rcheck[32]; + uint8_t h[SHA512_DIGEST_LENGTH]; + + if ((signature[63] & 224) != 0 || + ge_frombytes_vartime(&A, public_key) != 0) { + return 0; + } + + fe_neg(A.X, A.X); + fe_neg(A.T, A.T); + + memcpy(rcopy, signature, 32); + memcpy(scopy, signature + 32, 32); + + SHA512_Init(&hash_ctx); + SHA512_Update(&hash_ctx, signature, 32); + SHA512_Update(&hash_ctx, public_key, 32); + SHA512_Update(&hash_ctx, message, message_len); + SHA512_Final(h, &hash_ctx); + + x25519_sc_reduce(h); + + ge_double_scalarmult_vartime(&R, h, &A, scopy); + + ge_tobytes(rcheck, &R); + + return CRYPTO_memcmp(rcheck, rcopy, sizeof(rcheck)) == 0; +} + +void ED25519_public_from_private(uint8_t out_public_key[32], + const uint8_t private_key[32]) { + uint8_t az[SHA512_DIGEST_LENGTH]; + ge_p3 A; + + SHA512(private_key, 32, az); + + az[0] &= 248; + az[31] &= 63; + az[31] |= 64; + + ge_scalarmult_base(&A, az); + ge_p3_tobytes(out_public_key, &A); + + OPENSSL_cleanse(az, sizeof(az)); +} + int X25519(uint8_t out_shared_key[32], const uint8_t private_key[32], const uint8_t peer_public_value[32]) { static const uint8_t kZeros[32] = {0}; diff --git a/crypto/ec/curve448/arch_32/arch_intrinsics.h b/crypto/ec/curve448/arch_32/arch_intrinsics.h new file mode 100644 index 00000000..48081c77 --- /dev/null +++ b/crypto/ec/curve448/arch_32/arch_intrinsics.h @@ -0,0 +1,27 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ + +#ifndef HEADER_ARCH_32_ARCH_INTRINSICS_H +# define HEADER_ARCH_32_ARCH_INTRINSICS_H + +#include "internal/constant_time_locl.h" + +# define ARCH_WORD_BITS 32 + +#define word_is_zero(a) constant_time_is_zero_32(a) + +static ossl_inline uint64_t widemul(uint32_t a, uint32_t b) +{ + return ((uint64_t)a) * b; +} + +#endif /* HEADER_ARCH_32_ARCH_INTRINSICS_H */ diff --git a/crypto/ec/curve448/arch_32/f_impl.c b/crypto/ec/curve448/arch_32/f_impl.c new file mode 100644 index 00000000..8a89d276 --- /dev/null +++ b/crypto/ec/curve448/arch_32/f_impl.c @@ -0,0 +1,95 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2014 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ + +#include "field.h" + +void gf_mul(gf_s * RESTRICT cs, const gf as, const gf bs) +{ + const uint32_t *a = as->limb, *b = bs->limb; + uint32_t *c = cs->limb; + uint64_t accum0 = 0, accum1 = 0, accum2 = 0; + uint32_t mask = (1 << 28) - 1; + uint32_t aa[8], bb[8]; + int i, j; + + for (i = 0; i < 8; i++) { + aa[i] = a[i] + a[i + 8]; + bb[i] = b[i] + b[i + 8]; + } + + for (j = 0; j < 8; j++) { + accum2 = 0; + for (i = 0; i < j + 1; i++) { + accum2 += widemul(a[j - i], b[i]); + accum1 += widemul(aa[j - i], bb[i]); + accum0 += widemul(a[8 + j - i], b[8 + i]); + } + accum1 -= accum2; + accum0 += accum2; + accum2 = 0; + for (i = j + 1; i < 8; i++) { + accum0 -= widemul(a[8 + j - i], b[i]); + accum2 += widemul(aa[8 + j - i], bb[i]); + accum1 += widemul(a[16 + j - i], b[8 + i]); + } + accum1 += accum2; + accum0 += accum2; + c[j] = ((uint32_t)(accum0)) & mask; + c[j + 8] = ((uint32_t)(accum1)) & mask; + accum0 >>= 28; + accum1 >>= 28; + } + + accum0 += accum1; + accum0 += c[8]; + accum1 += c[0]; + c[8] = ((uint32_t)(accum0)) & mask; + c[0] = ((uint32_t)(accum1)) & mask; + + accum0 >>= 28; + accum1 >>= 28; + c[9] += ((uint32_t)(accum0)); + c[1] += ((uint32_t)(accum1)); +} + +void gf_mulw_unsigned(gf_s * RESTRICT cs, const gf as, uint32_t b) +{ + const uint32_t *a = as->limb; + uint32_t *c = cs->limb; + uint64_t accum0 = 0, accum8 = 0; + uint32_t mask = (1 << 28) - 1; + int i; + + assert(b <= mask); + + for (i = 0; i < 8; i++) { + accum0 += widemul(b, a[i]); + accum8 += widemul(b, a[i + 8]); + c[i] = accum0 & mask; + accum0 >>= 28; + c[i + 8] = accum8 & mask; + accum8 >>= 28; + } + + accum0 += accum8 + c[8]; + c[8] = ((uint32_t)accum0) & mask; + c[9] += (uint32_t)(accum0 >> 28); + + accum8 += c[0]; + c[0] = ((uint32_t)accum8) & mask; + c[1] += (uint32_t)(accum8 >> 28); +} + +void gf_sqr(gf_s * RESTRICT cs, const gf as) +{ + gf_mul(cs, as, as); /* Performs better with a dedicated square */ +} diff --git a/crypto/ec/curve448/arch_32/f_impl.h b/crypto/ec/curve448/arch_32/f_impl.h new file mode 100644 index 00000000..bbde84a0 --- /dev/null +++ b/crypto/ec/curve448/arch_32/f_impl.h @@ -0,0 +1,60 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2014-2016 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ + +#ifndef HEADER_ARCH_32_F_IMPL_H +# define HEADER_ARCH_32_F_IMPL_H + +# define GF_HEADROOM 2 +# define LIMB(x) ((x) & ((1 << 28) - 1)), ((x) >> 28) +# define FIELD_LITERAL(a, b, c, d, e, f, g, h) \ + {{LIMB(a), LIMB(b), LIMB(c), LIMB(d), LIMB(e), LIMB(f), LIMB(g), LIMB(h)}} + +# define LIMB_PLACE_VALUE(i) 28 + +void gf_add_RAW(gf out, const gf a, const gf b) +{ + unsigned int i; + + for (i = 0; i < NLIMBS; i++) + out->limb[i] = a->limb[i] + b->limb[i]; +} + +void gf_sub_RAW(gf out, const gf a, const gf b) +{ + unsigned int i; + + for (i = 0; i < NLIMBS; i++) + out->limb[i] = a->limb[i] - b->limb[i]; +} + +void gf_bias(gf a, int amt) +{ + unsigned int i; + uint32_t co1 = ((1 << 28) - 1) * amt, co2 = co1 - amt; + + for (i = 0; i < NLIMBS; i++) + a->limb[i] += (i == NLIMBS / 2) ? co2 : co1; +} + +void gf_weak_reduce(gf a) +{ + uint32_t mask = (1 << 28) - 1; + uint32_t tmp = a->limb[NLIMBS - 1] >> 28; + unsigned int i; + + a->limb[NLIMBS / 2] += tmp; + for (i = NLIMBS - 1; i > 0; i--) + a->limb[i] = (a->limb[i] & mask) + (a->limb[i - 1] >> 28); + a->limb[0] = (a->limb[0] & mask) + tmp; +} + +#endif /* HEADER_ARCH_32_F_IMPL_H */ diff --git a/crypto/ec/curve448/curve448.c b/crypto/ec/curve448/curve448.c new file mode 100644 index 00000000..8ced622b --- /dev/null +++ b/crypto/ec/curve448/curve448.c @@ -0,0 +1,727 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2016 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ +#include +#include "word.h" +#include "field.h" + +#include "point_448.h" +#include "ed448.h" +#include "curve448_lcl.h" + +#define COFACTOR 4 + +#define C448_WNAF_FIXED_TABLE_BITS 5 +#define C448_WNAF_VAR_TABLE_BITS 3 + +#define EDWARDS_D (-39081) + +static const curve448_scalar_t precomputed_scalarmul_adjustment = { + { + { + SC_LIMB(0xc873d6d54a7bb0cf), SC_LIMB(0xe933d8d723a70aad), + SC_LIMB(0xbb124b65129c96fd), SC_LIMB(0x00000008335dc163) + } + } +}; + +#define TWISTED_D (EDWARDS_D - 1) + +#define WBITS C448_WORD_BITS /* NB this may be different from ARCH_WORD_BITS */ + +/* Inverse. */ +static void gf_invert(gf y, const gf x, int assert_nonzero) +{ + mask_t ret; + gf t1, t2; + + gf_sqr(t1, x); /* o^2 */ + ret = gf_isr(t2, t1); /* +-1/sqrt(o^2) = +-1/o */ + (void)ret; + if (assert_nonzero) + assert(ret); + gf_sqr(t1, t2); + gf_mul(t2, t1, x); /* not direct to y in case of alias. */ + gf_copy(y, t2); +} + +/** identity = (0,1) */ +const curve448_point_t curve448_point_identity = + { {{{{0}}}, {{{1}}}, {{{1}}}, {{{0}}}} }; + +static void point_double_internal(curve448_point_t p, const curve448_point_t q, + int before_double) +{ + gf a, b, c, d; + + gf_sqr(c, q->x); + gf_sqr(a, q->y); + gf_add_nr(d, c, a); /* 2+e */ + gf_add_nr(p->t, q->y, q->x); /* 2+e */ + gf_sqr(b, p->t); + gf_subx_nr(b, b, d, 3); /* 4+e */ + gf_sub_nr(p->t, a, c); /* 3+e */ + gf_sqr(p->x, q->z); + gf_add_nr(p->z, p->x, p->x); /* 2+e */ + gf_subx_nr(a, p->z, p->t, 4); /* 6+e */ + if (GF_HEADROOM == 5) + gf_weak_reduce(a); /* or 1+e */ + gf_mul(p->x, a, b); + gf_mul(p->z, p->t, a); + gf_mul(p->y, p->t, d); + if (!before_double) + gf_mul(p->t, b, d); +} + +void curve448_point_double(curve448_point_t p, const curve448_point_t q) +{ + point_double_internal(p, q, 0); +} + +/* Operations on [p]niels */ +static ossl_inline void cond_neg_niels(niels_t n, mask_t neg) +{ + gf_cond_swap(n->a, n->b, neg); + gf_cond_neg(n->c, neg); +} + +static void pt_to_pniels(pniels_t b, const curve448_point_t a) +{ + gf_sub(b->n->a, a->y, a->x); + gf_add(b->n->b, a->x, a->y); + gf_mulw(b->n->c, a->t, 2 * TWISTED_D); + gf_add(b->z, a->z, a->z); +} + +static void pniels_to_pt(curve448_point_t e, const pniels_t d) +{ + gf eu; + + gf_add(eu, d->n->b, d->n->a); + gf_sub(e->y, d->n->b, d->n->a); + gf_mul(e->t, e->y, eu); + gf_mul(e->x, d->z, e->y); + gf_mul(e->y, d->z, eu); + gf_sqr(e->z, d->z); +} + +static void niels_to_pt(curve448_point_t e, const niels_t n) +{ + gf_add(e->y, n->b, n->a); + gf_sub(e->x, n->b, n->a); + gf_mul(e->t, e->y, e->x); + gf_copy(e->z, ONE); +} + +static void add_niels_to_pt(curve448_point_t d, const niels_t e, + int before_double) +{ + gf a, b, c; + + gf_sub_nr(b, d->y, d->x); /* 3+e */ + gf_mul(a, e->a, b); + gf_add_nr(b, d->x, d->y); /* 2+e */ + gf_mul(d->y, e->b, b); + gf_mul(d->x, e->c, d->t); + gf_add_nr(c, a, d->y); /* 2+e */ + gf_sub_nr(b, d->y, a); /* 3+e */ + gf_sub_nr(d->y, d->z, d->x); /* 3+e */ + gf_add_nr(a, d->x, d->z); /* 2+e */ + gf_mul(d->z, a, d->y); + gf_mul(d->x, d->y, b); + gf_mul(d->y, a, c); + if (!before_double) + gf_mul(d->t, b, c); +} + +static void sub_niels_from_pt(curve448_point_t d, const niels_t e, + int before_double) +{ + gf a, b, c; + + gf_sub_nr(b, d->y, d->x); /* 3+e */ + gf_mul(a, e->b, b); + gf_add_nr(b, d->x, d->y); /* 2+e */ + gf_mul(d->y, e->a, b); + gf_mul(d->x, e->c, d->t); + gf_add_nr(c, a, d->y); /* 2+e */ + gf_sub_nr(b, d->y, a); /* 3+e */ + gf_add_nr(d->y, d->z, d->x); /* 2+e */ + gf_sub_nr(a, d->z, d->x); /* 3+e */ + gf_mul(d->z, a, d->y); + gf_mul(d->x, d->y, b); + gf_mul(d->y, a, c); + if (!before_double) + gf_mul(d->t, b, c); +} + +static void add_pniels_to_pt(curve448_point_t p, const pniels_t pn, + int before_double) +{ + gf L0; + + gf_mul(L0, p->z, pn->z); + gf_copy(p->z, L0); + add_niels_to_pt(p, pn->n, before_double); +} + +static void sub_pniels_from_pt(curve448_point_t p, const pniels_t pn, + int before_double) +{ + gf L0; + + gf_mul(L0, p->z, pn->z); + gf_copy(p->z, L0); + sub_niels_from_pt(p, pn->n, before_double); +} + +c448_bool_t curve448_point_eq(const curve448_point_t p, + const curve448_point_t q) +{ + mask_t succ; + gf a, b; + + /* equality mod 2-torsion compares x/y */ + gf_mul(a, p->y, q->x); + gf_mul(b, q->y, p->x); + succ = gf_eq(a, b); + + return mask_to_bool(succ); +} + +c448_bool_t curve448_point_valid(const curve448_point_t p) +{ + mask_t out; + gf a, b, c; + + gf_mul(a, p->x, p->y); + gf_mul(b, p->z, p->t); + out = gf_eq(a, b); + gf_sqr(a, p->x); + gf_sqr(b, p->y); + gf_sub(a, b, a); + gf_sqr(b, p->t); + gf_mulw(c, b, TWISTED_D); + gf_sqr(b, p->z); + gf_add(b, b, c); + out &= gf_eq(a, b); + out &= ~gf_eq(p->z, ZERO); + return mask_to_bool(out); +} + +static ossl_inline void constant_time_lookup_niels(niels_s * RESTRICT ni, + const niels_t * table, + int nelts, int idx) +{ + constant_time_lookup(ni, table, sizeof(niels_s), nelts, idx); +} + +void curve448_precomputed_scalarmul(curve448_point_t out, + const curve448_precomputed_s * table, + const curve448_scalar_t scalar) +{ + unsigned int i, j, k; + const unsigned int n = COMBS_N, t = COMBS_T, s = COMBS_S; + niels_t ni; + curve448_scalar_t scalar1x; + + curve448_scalar_add(scalar1x, scalar, precomputed_scalarmul_adjustment); + curve448_scalar_halve(scalar1x, scalar1x); + + for (i = s; i > 0; i--) { + if (i != s) + point_double_internal(out, out, 0); + + for (j = 0; j < n; j++) { + int tab = 0; + mask_t invert; + + for (k = 0; k < t; k++) { + unsigned int bit = (i - 1) + s * (k + j * t); + + if (bit < C448_SCALAR_BITS) + tab |= + (scalar1x->limb[bit / WBITS] >> (bit % WBITS) & 1) << k; + } + + invert = (tab >> (t - 1)) - 1; + tab ^= invert; + tab &= (1 << (t - 1)) - 1; + + constant_time_lookup_niels(ni, &table->table[j << (t - 1)], + 1 << (t - 1), tab); + + cond_neg_niels(ni, invert); + if ((i != s) || j != 0) + add_niels_to_pt(out, ni, j == n - 1 && i != 1); + else + niels_to_pt(out, ni); + } + } + + OPENSSL_cleanse(ni, sizeof(ni)); + OPENSSL_cleanse(scalar1x, sizeof(scalar1x)); +} + +void curve448_point_mul_by_ratio_and_encode_like_eddsa( + uint8_t enc[EDDSA_448_PUBLIC_BYTES], + const curve448_point_t p) +{ + gf x, y, z, t; + curve448_point_t q; + + /* The point is now on the twisted curve. Move it to untwisted. */ + curve448_point_copy(q, p); + + { + /* 4-isogeny: 2xy/(y^+x^2), (y^2-x^2)/(2z^2-y^2+x^2) */ + gf u; + + gf_sqr(x, q->x); + gf_sqr(t, q->y); + gf_add(u, x, t); + gf_add(z, q->y, q->x); + gf_sqr(y, z); + gf_sub(y, y, u); + gf_sub(z, t, x); + gf_sqr(x, q->z); + gf_add(t, x, x); + gf_sub(t, t, z); + gf_mul(x, t, y); + gf_mul(y, z, u); + gf_mul(z, u, t); + OPENSSL_cleanse(u, sizeof(u)); + } + + /* Affinize */ + gf_invert(z, z, 1); + gf_mul(t, x, z); + gf_mul(x, y, z); + + /* Encode */ + enc[EDDSA_448_PRIVATE_BYTES - 1] = 0; + gf_serialize(enc, x, 1); + enc[EDDSA_448_PRIVATE_BYTES - 1] |= 0x80 & gf_lobit(t); + + OPENSSL_cleanse(x, sizeof(x)); + OPENSSL_cleanse(y, sizeof(y)); + OPENSSL_cleanse(z, sizeof(z)); + OPENSSL_cleanse(t, sizeof(t)); + curve448_point_destroy(q); +} + +c448_error_t curve448_point_decode_like_eddsa_and_mul_by_ratio( + curve448_point_t p, + const uint8_t enc[EDDSA_448_PUBLIC_BYTES]) +{ + uint8_t enc2[EDDSA_448_PUBLIC_BYTES]; + mask_t low; + mask_t succ; + + memcpy(enc2, enc, sizeof(enc2)); + + low = ~word_is_zero(enc2[EDDSA_448_PRIVATE_BYTES - 1] & 0x80); + enc2[EDDSA_448_PRIVATE_BYTES - 1] &= ~0x80; + + succ = gf_deserialize(p->y, enc2, 1, 0); + succ &= word_is_zero(enc2[EDDSA_448_PRIVATE_BYTES - 1]); + + gf_sqr(p->x, p->y); + gf_sub(p->z, ONE, p->x); /* num = 1-y^2 */ + gf_mulw(p->t, p->x, EDWARDS_D); /* dy^2 */ + gf_sub(p->t, ONE, p->t); /* denom = 1-dy^2 or 1-d + dy^2 */ + + gf_mul(p->x, p->z, p->t); + succ &= gf_isr(p->t, p->x); /* 1/sqrt(num * denom) */ + + gf_mul(p->x, p->t, p->z); /* sqrt(num / denom) */ + gf_cond_neg(p->x, gf_lobit(p->x) ^ low); + gf_copy(p->z, ONE); + + { + gf a, b, c, d; + + /* 4-isogeny 2xy/(y^2-ax^2), (y^2+ax^2)/(2-y^2-ax^2) */ + gf_sqr(c, p->x); + gf_sqr(a, p->y); + gf_add(d, c, a); + gf_add(p->t, p->y, p->x); + gf_sqr(b, p->t); + gf_sub(b, b, d); + gf_sub(p->t, a, c); + gf_sqr(p->x, p->z); + gf_add(p->z, p->x, p->x); + gf_sub(a, p->z, d); + gf_mul(p->x, a, b); + gf_mul(p->z, p->t, a); + gf_mul(p->y, p->t, d); + gf_mul(p->t, b, d); + OPENSSL_cleanse(a, sizeof(a)); + OPENSSL_cleanse(b, sizeof(b)); + OPENSSL_cleanse(c, sizeof(c)); + OPENSSL_cleanse(d, sizeof(d)); + } + + OPENSSL_cleanse(enc2, sizeof(enc2)); + assert(curve448_point_valid(p) || ~succ); + + return c448_succeed_if(mask_to_bool(succ)); +} + +c448_error_t x448_int(uint8_t out[X_PUBLIC_BYTES], + const uint8_t base[X_PUBLIC_BYTES], + const uint8_t scalar[X_PRIVATE_BYTES]) +{ + gf x1, x2, z2, x3, z3, t1, t2; + int t; + mask_t swap = 0; + mask_t nz; + + (void)gf_deserialize(x1, base, 1, 0); + gf_copy(x2, ONE); + gf_copy(z2, ZERO); + gf_copy(x3, x1); + gf_copy(z3, ONE); + + for (t = X_PRIVATE_BITS - 1; t >= 0; t--) { + uint8_t sb = scalar[t / 8]; + mask_t k_t; + + /* Scalar conditioning */ + if (t / 8 == 0) + sb &= -(uint8_t)COFACTOR; + else if (t == X_PRIVATE_BITS - 1) + sb = -1; + + k_t = (sb >> (t % 8)) & 1; + k_t = 0 - k_t; /* set to all 0s or all 1s */ + + swap ^= k_t; + gf_cond_swap(x2, x3, swap); + gf_cond_swap(z2, z3, swap); + swap = k_t; + + /* + * The "_nr" below skips coefficient reduction. In the following + * comments, "2+e" is saying that the coefficients are at most 2+epsilon + * times the reduction limit. + */ + gf_add_nr(t1, x2, z2); /* A = x2 + z2 */ /* 2+e */ + gf_sub_nr(t2, x2, z2); /* B = x2 - z2 */ /* 3+e */ + gf_sub_nr(z2, x3, z3); /* D = x3 - z3 */ /* 3+e */ + gf_mul(x2, t1, z2); /* DA */ + gf_add_nr(z2, z3, x3); /* C = x3 + z3 */ /* 2+e */ + gf_mul(x3, t2, z2); /* CB */ + gf_sub_nr(z3, x2, x3); /* DA-CB */ /* 3+e */ + gf_sqr(z2, z3); /* (DA-CB)^2 */ + gf_mul(z3, x1, z2); /* z3 = x1(DA-CB)^2 */ + gf_add_nr(z2, x2, x3); /* (DA+CB) */ /* 2+e */ + gf_sqr(x3, z2); /* x3 = (DA+CB)^2 */ + + gf_sqr(z2, t1); /* AA = A^2 */ + gf_sqr(t1, t2); /* BB = B^2 */ + gf_mul(x2, z2, t1); /* x2 = AA*BB */ + gf_sub_nr(t2, z2, t1); /* E = AA-BB */ /* 3+e */ + + gf_mulw(t1, t2, -EDWARDS_D); /* E*-d = a24*E */ + gf_add_nr(t1, t1, z2); /* AA + a24*E */ /* 2+e */ + gf_mul(z2, t2, t1); /* z2 = E(AA+a24*E) */ + } + + /* Finish */ + gf_cond_swap(x2, x3, swap); + gf_cond_swap(z2, z3, swap); + gf_invert(z2, z2, 0); + gf_mul(x1, x2, z2); + gf_serialize(out, x1, 1); + nz = ~gf_eq(x1, ZERO); + + OPENSSL_cleanse(x1, sizeof(x1)); + OPENSSL_cleanse(x2, sizeof(x2)); + OPENSSL_cleanse(z2, sizeof(z2)); + OPENSSL_cleanse(x3, sizeof(x3)); + OPENSSL_cleanse(z3, sizeof(z3)); + OPENSSL_cleanse(t1, sizeof(t1)); + OPENSSL_cleanse(t2, sizeof(t2)); + + return c448_succeed_if(mask_to_bool(nz)); +} + +void curve448_point_mul_by_ratio_and_encode_like_x448(uint8_t + out[X_PUBLIC_BYTES], + const curve448_point_t p) +{ + curve448_point_t q; + + curve448_point_copy(q, p); + gf_invert(q->t, q->x, 0); /* 1/x */ + gf_mul(q->z, q->t, q->y); /* y/x */ + gf_sqr(q->y, q->z); /* (y/x)^2 */ + gf_serialize(out, q->y, 1); + curve448_point_destroy(q); +} + +void x448_derive_public_key(uint8_t out[X_PUBLIC_BYTES], + const uint8_t scalar[X_PRIVATE_BYTES]) +{ + /* Scalar conditioning */ + uint8_t scalar2[X_PRIVATE_BYTES]; + curve448_scalar_t the_scalar; + curve448_point_t p; + unsigned int i; + + memcpy(scalar2, scalar, sizeof(scalar2)); + scalar2[0] &= -(uint8_t)COFACTOR; + + scalar2[X_PRIVATE_BYTES - 1] &= ~((0u - 1u) << ((X_PRIVATE_BITS + 7) % 8)); + scalar2[X_PRIVATE_BYTES - 1] |= 1 << ((X_PRIVATE_BITS + 7) % 8); + + curve448_scalar_decode_long(the_scalar, scalar2, sizeof(scalar2)); + + /* Compensate for the encoding ratio */ + for (i = 1; i < X448_ENCODE_RATIO; i <<= 1) + curve448_scalar_halve(the_scalar, the_scalar); + + curve448_precomputed_scalarmul(p, curve448_precomputed_base, the_scalar); + curve448_point_mul_by_ratio_and_encode_like_x448(out, p); + curve448_point_destroy(p); +} + +/* Control for variable-time scalar multiply algorithms. */ +struct smvt_control { + int power, addend; +}; + +#if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3)) +# define NUMTRAILINGZEROS __builtin_ctz +#else +# define NUMTRAILINGZEROS numtrailingzeros +static uint32_t numtrailingzeros(uint32_t i) +{ + uint32_t tmp; + uint32_t num = 31; + + if (i == 0) + return 32; + + tmp = i << 16; + if (tmp != 0) { + i = tmp; + num -= 16; + } + tmp = i << 8; + if (tmp != 0) { + i = tmp; + num -= 8; + } + tmp = i << 4; + if (tmp != 0) { + i = tmp; + num -= 4; + } + tmp = i << 2; + if (tmp != 0) { + i = tmp; + num -= 2; + } + tmp = i << 1; + if (tmp != 0) + num--; + + return num; +} +#endif + +static int recode_wnaf(struct smvt_control *control, + /* [nbits/(table_bits + 1) + 3] */ + const curve448_scalar_t scalar, + unsigned int table_bits) +{ + unsigned int table_size = C448_SCALAR_BITS / (table_bits + 1) + 3; + int position = table_size - 1; /* at the end */ + uint64_t current = scalar->limb[0] & 0xFFFF; + uint32_t mask = (1 << (table_bits + 1)) - 1; + unsigned int w; + const unsigned int B_OVER_16 = sizeof(scalar->limb[0]) / 2; + unsigned int n, i; + + /* place the end marker */ + control[position].power = -1; + control[position].addend = 0; + position--; + + /* + * PERF: Could negate scalar if it's large. But then would need more cases + * in the actual code that uses it, all for an expected reduction of like + * 1/5 op. Probably not worth it. + */ + + for (w = 1; w < (C448_SCALAR_BITS - 1) / 16 + 3; w++) { + if (w < (C448_SCALAR_BITS - 1) / 16 + 1) { + /* Refill the 16 high bits of current */ + current += (uint32_t)((scalar->limb[w / B_OVER_16] + >> (16 * (w % B_OVER_16))) << 16); + } + + while (current & 0xFFFF) { + uint32_t pos = NUMTRAILINGZEROS((uint32_t)current); + uint32_t odd = (uint32_t)current >> pos; + int32_t delta = odd & mask; + + assert(position >= 0); + if (odd & (1 << (table_bits + 1))) + delta -= (1 << (table_bits + 1)); + current -= delta << pos; + control[position].power = pos + 16 * (w - 1); + control[position].addend = delta; + position--; + } + current >>= 16; + } + assert(current == 0); + + position++; + n = table_size - position; + for (i = 0; i < n; i++) + control[i] = control[i + position]; + + return n - 1; +} + +static void prepare_wnaf_table(pniels_t * output, + const curve448_point_t working, + unsigned int tbits) +{ + curve448_point_t tmp; + int i; + pniels_t twop; + + pt_to_pniels(output[0], working); + + if (tbits == 0) + return; + + curve448_point_double(tmp, working); + pt_to_pniels(twop, tmp); + + add_pniels_to_pt(tmp, output[0], 0); + pt_to_pniels(output[1], tmp); + + for (i = 2; i < 1 << tbits; i++) { + add_pniels_to_pt(tmp, twop, 0); + pt_to_pniels(output[i], tmp); + } + + curve448_point_destroy(tmp); + OPENSSL_cleanse(twop, sizeof(twop)); +} + +void curve448_base_double_scalarmul_non_secret(curve448_point_t combo, + const curve448_scalar_t scalar1, + const curve448_point_t base2, + const curve448_scalar_t scalar2) +{ + const int table_bits_var = C448_WNAF_VAR_TABLE_BITS; + const int table_bits_pre = C448_WNAF_FIXED_TABLE_BITS; + struct smvt_control control_var[C448_SCALAR_BITS / + (C448_WNAF_VAR_TABLE_BITS + 1) + 3]; + struct smvt_control control_pre[C448_SCALAR_BITS / + (C448_WNAF_FIXED_TABLE_BITS + 1) + 3]; + int ncb_pre = recode_wnaf(control_pre, scalar1, table_bits_pre); + int ncb_var = recode_wnaf(control_var, scalar2, table_bits_var); + pniels_t precmp_var[1 << C448_WNAF_VAR_TABLE_BITS]; + int contp = 0, contv = 0, i; + + prepare_wnaf_table(precmp_var, base2, table_bits_var); + i = control_var[0].power; + + if (i < 0) { + curve448_point_copy(combo, curve448_point_identity); + return; + } + if (i > control_pre[0].power) { + pniels_to_pt(combo, precmp_var[control_var[0].addend >> 1]); + contv++; + } else if (i == control_pre[0].power && i >= 0) { + pniels_to_pt(combo, precmp_var[control_var[0].addend >> 1]); + add_niels_to_pt(combo, curve448_wnaf_base[control_pre[0].addend >> 1], + i); + contv++; + contp++; + } else { + i = control_pre[0].power; + niels_to_pt(combo, curve448_wnaf_base[control_pre[0].addend >> 1]); + contp++; + } + + for (i--; i >= 0; i--) { + int cv = (i == control_var[contv].power); + int cp = (i == control_pre[contp].power); + + point_double_internal(combo, combo, i && !(cv || cp)); + + if (cv) { + assert(control_var[contv].addend); + + if (control_var[contv].addend > 0) + add_pniels_to_pt(combo, + precmp_var[control_var[contv].addend >> 1], + i && !cp); + else + sub_pniels_from_pt(combo, + precmp_var[(-control_var[contv].addend) + >> 1], i && !cp); + contv++; + } + + if (cp) { + assert(control_pre[contp].addend); + + if (control_pre[contp].addend > 0) + add_niels_to_pt(combo, + curve448_wnaf_base[control_pre[contp].addend + >> 1], i); + else + sub_niels_from_pt(combo, + curve448_wnaf_base[(-control_pre + [contp].addend) >> 1], i); + contp++; + } + } + + /* This function is non-secret, but whatever this is cheap. */ + OPENSSL_cleanse(control_var, sizeof(control_var)); + OPENSSL_cleanse(control_pre, sizeof(control_pre)); + OPENSSL_cleanse(precmp_var, sizeof(precmp_var)); + + assert(contv == ncb_var); + (void)ncb_var; + assert(contp == ncb_pre); + (void)ncb_pre; +} + +void curve448_point_destroy(curve448_point_t point) +{ + OPENSSL_cleanse(point, sizeof(curve448_point_t)); +} + +int X448(uint8_t out_shared_key[56], const uint8_t private_key[56], + const uint8_t peer_public_value[56]) +{ + return x448_int(out_shared_key, peer_public_value, private_key) + == C448_SUCCESS; +} + +void X448_public_from_private(uint8_t out_public_value[56], + const uint8_t private_key[56]) +{ + x448_derive_public_key(out_public_value, private_key); +} diff --git a/crypto/ec/curve448/curve448_lcl.h b/crypto/ec/curve448/curve448_lcl.h new file mode 100644 index 00000000..2bc3bd84 --- /dev/null +++ b/crypto/ec/curve448/curve448_lcl.h @@ -0,0 +1,38 @@ +/* + * Copyright 2017-2018 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 + */ +#ifndef HEADER_CURVE448_LCL_H +# define HEADER_CURVE448_LCL_H +# include "curve448utils.h" + +int X448(uint8_t out_shared_key[56], const uint8_t private_key[56], + const uint8_t peer_public_value[56]); + +void X448_public_from_private(uint8_t out_public_value[56], + const uint8_t private_key[56]); + +int ED448_sign(uint8_t *out_sig, const uint8_t *message, size_t message_len, + const uint8_t public_key[57], const uint8_t private_key[57], + const uint8_t *context, size_t context_len); + +int ED448_verify(const uint8_t *message, size_t message_len, + const uint8_t signature[114], const uint8_t public_key[57], + const uint8_t *context, size_t context_len); + +int ED448ph_sign(uint8_t *out_sig, const uint8_t hash[64], + const uint8_t public_key[57], const uint8_t private_key[57], + const uint8_t *context, size_t context_len); + +int ED448ph_verify(const uint8_t hash[64], const uint8_t signature[114], + const uint8_t public_key[57], const uint8_t *context, + size_t context_len); + +int ED448_public_from_private(uint8_t out_public_key[57], + const uint8_t private_key[57]); + +#endif /* HEADER_CURVE448_LCL_H */ diff --git a/crypto/ec/curve448/curve448_tables.c b/crypto/ec/curve448/curve448_tables.c new file mode 100644 index 00000000..a1185b1e --- /dev/null +++ b/crypto/ec/curve448/curve448_tables.c @@ -0,0 +1,475 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2016 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ +#include "field.h" + +#include "point_448.h" + +static const curve448_precomputed_s curve448_precomputed_base_table = { + { + {{ + {FIELD_LITERAL(0x00cc3b062366f4cc,0x003d6e34e314aa3c,0x00d51c0a7521774d,0x0094e060eec6ab8b,0x00d21291b4d80082,0x00befed12b55ef1e,0x00c3dd2df5c94518,0x00e0a7b112b8d4e6)}, + {FIELD_LITERAL(0x0019eb5608d8723a,0x00d1bab52fb3aedb,0x00270a7311ebc90c,0x0037c12b91be7f13,0x005be16cd8b5c704,0x003e181acda888e1,0x00bc1f00fc3fc6d0,0x00d3839bfa319e20)}, + {FIELD_LITERAL(0x003caeb88611909f,0x00ea8b378c4df3d4,0x00b3295b95a5a19a,0x00a65f97514bdfb5,0x00b39efba743cab1,0x0016ba98b862fd2d,0x0001508812ee71d7,0x000a75740eea114a)}, + }}, {{ + {FIELD_LITERAL(0x00ebcf0eb649f823,0x00166d332e98ea03,0x0059ddf64f5cd5f6,0x0047763123d9471b,0x00a64065c53ef62f,0x00978e44c480153d,0x000b5b2a0265f194,0x0046a24b9f32965a)}, + {FIELD_LITERAL(0x00b9eef787034df0,0x0020bc24de3390cd,0x000022160bae99bb,0x00ae66e886e97946,0x0048d4bbe02cbb8b,0x0072ba97b34e38d4,0x00eae7ec8f03e85a,0x005ba92ecf808b2c)}, + {FIELD_LITERAL(0x00c9cfbbe74258fd,0x00843a979ea9eaa7,0x000cbb4371cfbe90,0x0059bac8f7f0a628,0x004b3dff882ff530,0x0011869df4d90733,0x00595aa71f4abfc2,0x0070e2d38990c2e6)}, + }}, {{ + {FIELD_LITERAL(0x00de2010c0a01733,0x00c739a612e24297,0x00a7212643141d7c,0x00f88444f6b67c11,0x00484b7b16ec28f2,0x009c1b8856af9c68,0x00ff4669591fe9d6,0x0054974be08a32c8)}, + {FIELD_LITERAL(0x0010de3fd682ceed,0x008c07642d83ca4e,0x0013bb064e00a1cc,0x009411ae27870e11,0x00ea8e5b4d531223,0x0032fe7d2aaece2e,0x00d989e243e7bb41,0x000fe79a508e9b8b)}, + {FIELD_LITERAL(0x005e0426b9bfc5b1,0x0041a5b1d29ee4fa,0x0015b0def7774391,0x00bc164f1f51af01,0x00d543b0942797b9,0x003c129b6398099c,0x002b114c6e5adf18,0x00b4e630e4018a7b)}, + }}, {{ + {FIELD_LITERAL(0x00d490afc95f8420,0x00b096bf50c1d9b9,0x00799fd707679866,0x007c74d9334afbea,0x00efaa8be80ff4ed,0x0075c4943bb81694,0x00c21c2fca161f36,0x00e77035d492bfee)}, + {FIELD_LITERAL(0x006658a190dd6661,0x00e0e9bab38609a6,0x0028895c802237ed,0x006a0229c494f587,0x002dcde96c9916b7,0x00d158822de16218,0x00173b917a06856f,0x00ca78a79ae07326)}, + {FIELD_LITERAL(0x00e35bfc79caced4,0x0087238a3e1fe3bb,0x00bcbf0ff4ceff5b,0x00a19c1c94099b91,0x0071e102b49db976,0x0059e3d004eada1e,0x008da78afa58a47e,0x00579c8ebf269187)}, + }}, {{ + {FIELD_LITERAL(0x00a16c2905eee75f,0x009d4bcaea2c7e1d,0x00d3bd79bfad19df,0x0050da745193342c,0x006abdb8f6b29ab1,0x00a24fe0a4fef7ef,0x0063730da1057dfb,0x00a08c312c8eb108)}, + {FIELD_LITERAL(0x00b583be005375be,0x00a40c8f8a4e3df4,0x003fac4a8f5bdbf7,0x00d4481d872cd718,0x004dc8749cdbaefe,0x00cce740d5e5c975,0x000b1c1f4241fd21,0x00a76de1b4e1cd07)}, + {FIELD_LITERAL(0x007a076500d30b62,0x000a6e117b7f090f,0x00c8712ae7eebd9a,0x000fbd6c1d5f6ff7,0x003a7977246ebf11,0x00166ed969c6600e,0x00aa42e469c98bec,0x00dc58f307cf0666)}, + }}, {{ + {FIELD_LITERAL(0x004b491f65a9a28b,0x006a10309e8a55b7,0x00b67210185187ef,0x00cf6497b12d9b8f,0x0085778c56e2b1ba,0x0015b4c07a814d85,0x00686479e62da561,0x008de5d88f114916)}, + {FIELD_LITERAL(0x00e37c88d6bba7b1,0x003e4577e1b8d433,0x0050d8ea5f510ec0,0x0042fc9f2da9ef59,0x003bd074c1141420,0x00561b8b7b68774e,0x00232e5e5d1013a3,0x006b7f2cb3d7e73f)}, + {FIELD_LITERAL(0x004bdd0f0b41e6a0,0x001773057c405d24,0x006029f99915bd97,0x006a5ba70a17fe2f,0x0046111977df7e08,0x004d8124c89fb6b7,0x00580983b2bb2724,0x00207bf330d6f3fe)}, + }}, {{ + {FIELD_LITERAL(0x007efdc93972a48b,0x002f5e50e78d5fee,0x0080dc11d61c7fe5,0x0065aa598707245b,0x009abba2300641be,0x000c68787656543a,0x00ffe0fef2dc0a17,0x00007ffbd6cb4f3a)}, + {FIELD_LITERAL(0x0036012f2b836efc,0x00458c126d6b5fbc,0x00a34436d719ad1e,0x0097be6167117dea,0x0009c219c879cff3,0x0065564493e60755,0x00993ac94a8cdec0,0x002d4885a4d0dbaf)}, + {FIELD_LITERAL(0x00598b60b4c068ba,0x00c547a0be7f1afd,0x009582164acf12af,0x00af4acac4fbbe40,0x005f6ca7c539121a,0x003b6e752ebf9d66,0x00f08a30d5cac5d4,0x00e399bb5f97c5a9)}, + }}, {{ + {FIELD_LITERAL(0x007445a0409c0a66,0x00a65c369f3829c0,0x0031d248a4f74826,0x006817f34defbe8e,0x00649741d95ebf2e,0x00d46466ab16b397,0x00fdc35703bee414,0x00343b43334525f8)}, + {FIELD_LITERAL(0x001796bea93f6401,0x00090c5a42e85269,0x00672412ba1252ed,0x001201d47b6de7de,0x006877bccfe66497,0x00b554fd97a4c161,0x009753f42dbac3cf,0x00e983e3e378270a)}, + {FIELD_LITERAL(0x00ac3eff18849872,0x00f0eea3bff05690,0x00a6d72c21dd505d,0x001b832642424169,0x00a6813017b540e5,0x00a744bd71b385cd,0x0022a7d089130a7b,0x004edeec9a133486)}, + }}, {{ + {FIELD_LITERAL(0x00b2d6729196e8a9,0x0088a9bb2031cef4,0x00579e7787dc1567,0x0030f49feb059190,0x00a0b1d69c7f7d8f,0x0040bdcc6d9d806f,0x00d76c4037edd095,0x00bbf24376415dd7)}, + {FIELD_LITERAL(0x00240465ff5a7197,0x00bb97e76caf27d0,0x004b4edbf8116d39,0x001d8586f708cbaa,0x000f8ee8ff8e4a50,0x00dde5a1945dd622,0x00e6fc1c0957e07c,0x0041c9cdabfd88a0)}, + {FIELD_LITERAL(0x005344b0bf5b548c,0x002957d0b705cc99,0x00f586a70390553d,0x0075b3229f583cc3,0x00a1aa78227490e4,0x001bf09cf7957717,0x00cf6bf344325f52,0x0065bd1c23ca3ecf)}, + }}, {{ + {FIELD_LITERAL(0x009bff3b3239363c,0x00e17368796ef7c0,0x00528b0fe0971f3a,0x0008014fc8d4a095,0x00d09f2e8a521ec4,0x006713ab5dde5987,0x0003015758e0dbb1,0x00215999f1ba212d)}, + {FIELD_LITERAL(0x002c88e93527da0e,0x0077c78f3456aad5,0x0071087a0a389d1c,0x00934dac1fb96dbd,0x008470e801162697,0x005bc2196cd4ad49,0x00e535601d5087c3,0x00769888700f497f)}, + {FIELD_LITERAL(0x00da7a4b557298ad,0x0019d2589ea5df76,0x00ef3e38be0c6497,0x00a9644e1312609a,0x004592f61b2558da,0x0082c1df510d7e46,0x0042809a535c0023,0x00215bcb5afd7757)}, + }}, {{ + {FIELD_LITERAL(0x002b9df55a1a4213,0x00dcfc3b464a26be,0x00c4f9e07a8144d5,0x00c8e0617a92b602,0x008e3c93accafae0,0x00bf1bcb95b2ca60,0x004ce2426a613bf3,0x00266cac58e40921)}, + {FIELD_LITERAL(0x008456d5db76e8f0,0x0032ca9cab2ce163,0x0059f2b8bf91abcf,0x0063c2a021712788,0x00f86155af22f72d,0x00db98b2a6c005a0,0x00ac6e416a693ac4,0x007a93572af53226)}, + {FIELD_LITERAL(0x0087767520f0de22,0x0091f64012279fb5,0x001050f1f0644999,0x004f097a2477ad3c,0x006b37913a9947bd,0x001a3d78645af241,0x0057832bbb3008a7,0x002c1d902b80dc20)}, + }}, {{ + {FIELD_LITERAL(0x001a6002bf178877,0x009bce168aa5af50,0x005fc318ff04a7f5,0x0052818f55c36461,0x008768f5d4b24afb,0x0037ffbae7b69c85,0x0018195a4b61edc0,0x001e12ea088434b2)}, + {FIELD_LITERAL(0x0047d3f804e7ab07,0x00a809ab5f905260,0x00b3ffc7cdaf306d,0x00746e8ec2d6e509,0x00d0dade8887a645,0x00acceeebde0dd37,0x009bc2579054686b,0x0023804f97f1c2bf)}, + {FIELD_LITERAL(0x0043e2e2e50b80d7,0x00143aafe4427e0f,0x005594aaecab855b,0x008b12ccaaecbc01,0x002deeb091082bc3,0x009cca4be2ae7514,0x00142b96e696d047,0x00ad2a2b1c05256a)}, + }}, {{ + {FIELD_LITERAL(0x003914f2f144b78b,0x007a95dd8bee6f68,0x00c7f4384d61c8e6,0x004e51eb60f1bdb2,0x00f64be7aa4621d8,0x006797bfec2f0ac0,0x007d17aab3c75900,0x001893e73cac8bc5)}, + {FIELD_LITERAL(0x00140360b768665b,0x00b68aca4967f977,0x0001089b66195ae4,0x00fe71122185e725,0x000bca2618d49637,0x00a54f0557d7e98a,0x00cdcd2f91d6f417,0x00ab8c13741fd793)}, + {FIELD_LITERAL(0x00725ee6b1e549e0,0x007124a0769777fa,0x000b68fdad07ae42,0x0085b909cd4952df,0x0092d2e3c81606f4,0x009f22f6cac099a0,0x00f59da57f2799a8,0x00f06c090122f777)}, + }}, {{ + {FIELD_LITERAL(0x00ce0bed0a3532bc,0x001a5048a22df16b,0x00e31db4cbad8bf1,0x00e89292120cf00e,0x007d1dd1a9b00034,0x00e2a9041ff8f680,0x006a4c837ae596e7,0x00713af1068070b3)}, + {FIELD_LITERAL(0x00c4fe64ce66d04b,0x00b095d52e09b3d7,0x00758bbecb1a3a8e,0x00f35cce8d0650c0,0x002b878aa5984473,0x0062e0a3b7544ddc,0x00b25b290ed116fe,0x007b0f6abe0bebf2)}, + {FIELD_LITERAL(0x0081d4e3addae0a8,0x003410c836c7ffcc,0x00c8129ad89e4314,0x000e3d5a23922dcd,0x00d91e46f29c31f3,0x006c728cde8c5947,0x002bc655ba2566c0,0x002ca94721533108)}, + }}, {{ + {FIELD_LITERAL(0x0051e4b3f764d8a9,0x0019792d46e904a0,0x00853bc13dbc8227,0x000840208179f12d,0x0068243474879235,0x0013856fbfe374d0,0x00bda12fe8676424,0x00bbb43635926eb2)}, + {FIELD_LITERAL(0x0012cdc880a93982,0x003c495b21cd1b58,0x00b7e5c93f22a26e,0x0044aa82dfb99458,0x009ba092cdffe9c0,0x00a14b3ab2083b73,0x000271c2f70e1c4b,0x00eea9cac0f66eb8)}, + {FIELD_LITERAL(0x001a1847c4ac5480,0x00b1b412935bb03a,0x00f74285983bf2b2,0x00624138b5b5d0f1,0x008820c0b03d38bf,0x00b94e50a18c1572,0x0060f6934841798f,0x00c52f5d66d6ebe2)}, + }}, {{ + {FIELD_LITERAL(0x00da23d59f9bcea6,0x00e0f27007a06a4b,0x00128b5b43a6758c,0x000cf50190fa8b56,0x00fc877aba2b2d72,0x00623bef52edf53f,0x00e6af6b819669e2,0x00e314dc34fcaa4f)}, + {FIELD_LITERAL(0x0066e5eddd164d1e,0x00418a7c6fe28238,0x0002e2f37e962c25,0x00f01f56b5975306,0x0048842fa503875c,0x0057b0e968078143,0x00ff683024f3d134,0x0082ae28fcad12e4)}, + {FIELD_LITERAL(0x0011ddfd21260e42,0x00d05b0319a76892,0x00183ea4368e9b8f,0x00b0815662affc96,0x00b466a5e7ce7c88,0x00db93b07506e6ee,0x0033885f82f62401,0x0086f9090ec9b419)}, + }}, {{ + {FIELD_LITERAL(0x00d95d1c5fcb435a,0x0016d1ed6b5086f9,0x00792aa0b7e54d71,0x0067b65715f1925d,0x00a219755ec6176b,0x00bc3f026b12c28f,0x00700c897ffeb93e,0x0089b83f6ec50b46)}, + {FIELD_LITERAL(0x003c97e6384da36e,0x00423d53eac81a09,0x00b70d68f3cdce35,0x00ee7959b354b92c,0x00f4e9718819c8ca,0x009349f12acbffe9,0x005aee7b62cb7da6,0x00d97764154ffc86)}, + {FIELD_LITERAL(0x00526324babb46dc,0x002ee99b38d7bf9e,0x007ea51794706ef4,0x00abeb04da6e3c39,0x006b457c1d281060,0x00fe243e9a66c793,0x00378de0fb6c6ee4,0x003e4194b9c3cb93)}, + }}, {{ + {FIELD_LITERAL(0x00fed3cd80ca2292,0x0015b043a73ca613,0x000a9fd7bf9be227,0x003b5e03de2db983,0x005af72d46904ef7,0x00c0f1b5c49faa99,0x00dc86fc3bd305e1,0x00c92f08c1cb1797)}, + {FIELD_LITERAL(0x0079680ce111ed3b,0x001a1ed82806122c,0x000c2e7466d15df3,0x002c407f6f7150fd,0x00c5e7c96b1b0ce3,0x009aa44626863ff9,0x00887b8b5b80be42,0x00b6023cec964825)}, + {FIELD_LITERAL(0x00e4a8e1048970c8,0x0062887b7830a302,0x00bcf1c8cd81402b,0x0056dbb81a68f5be,0x0014eced83f12452,0x00139e1a510150df,0x00bb81140a82d1a3,0x000febcc1aaf1aa7)}, + }}, {{ + {FIELD_LITERAL(0x00a7527958238159,0x0013ec9537a84cd6,0x001d7fee7d562525,0x00b9eefa6191d5e5,0x00dbc97db70bcb8a,0x00481affc7a4d395,0x006f73d3e70c31bb,0x00183f324ed96a61)}, + {FIELD_LITERAL(0x0039dd7ce7fc6860,0x00d64f6425653da1,0x003e037c7f57d0af,0x0063477a06e2bcf2,0x001727dbb7ac67e6,0x0049589f5efafe2e,0x00fc0fef2e813d54,0x008baa5d087fb50d)}, + {FIELD_LITERAL(0x0024fb59d9b457c7,0x00a7d4e060223e4c,0x00c118d1b555fd80,0x0082e216c732f22a,0x00cd2a2993089504,0x003638e836a3e13d,0x000d855ee89b4729,0x008ec5b7d4810c91)}, + }}, {{ + {FIELD_LITERAL(0x001bf51f7d65cdfd,0x00d14cdafa16a97d,0x002c38e60fcd10e7,0x00a27446e393efbd,0x000b5d8946a71fdd,0x0063df2cde128f2f,0x006c8679569b1888,0x0059ffc4925d732d)}, + {FIELD_LITERAL(0x00ece96f95f2b66f,0x00ece7952813a27b,0x0026fc36592e489e,0x007157d1a2de0f66,0x00759dc111d86ddf,0x0012881e5780bb0f,0x00c8ccc83ad29496,0x0012b9bd1929eb71)}, + {FIELD_LITERAL(0x000fa15a20da5df0,0x00349ddb1a46cd31,0x002c512ad1d8e726,0x00047611f669318d,0x009e68fba591e17e,0x004320dffa803906,0x00a640874951a3d3,0x00b6353478baa24f)}, + }}, {{ + {FIELD_LITERAL(0x009696510000d333,0x00ec2f788bc04826,0x000e4d02b1f67ba5,0x00659aa8dace08b6,0x00d7a38a3a3ae533,0x008856defa8c746b,0x004d7a4402d3da1a,0x00ea82e06229260f)}, + {FIELD_LITERAL(0x006a15bb20f75c0c,0x0079a144027a5d0c,0x00d19116ce0b4d70,0x0059b83bcb0b268e,0x005f58f63f16c127,0x0079958318ee2c37,0x00defbb063d07f82,0x00f1f0b931d2d446)}, + {FIELD_LITERAL(0x00cb5e4c3c35d422,0x008df885ca43577f,0x00fa50b16ca3e471,0x005a0e58e17488c8,0x00b2ceccd6d34d19,0x00f01d5d235e36e9,0x00db2e7e4be6ca44,0x00260ab77f35fccd)}, + }}, {{ + {FIELD_LITERAL(0x006f6fd9baac61d5,0x002a7710a020a895,0x009de0db7fc03d4d,0x00cdedcb1875f40b,0x00050caf9b6b1e22,0x005e3a6654456ab0,0x00775fdf8c4423d4,0x0028701ea5738b5d)}, + {FIELD_LITERAL(0x009ffd90abfeae96,0x00cba3c2b624a516,0x005ef08bcee46c91,0x00e6fde30afb6185,0x00f0b4db4f818ce4,0x006c54f45d2127f5,0x00040125035854c7,0x00372658a3287e13)}, + {FIELD_LITERAL(0x00d7070fb1beb2ab,0x0078fc845a93896b,0x006894a4b2f224a6,0x005bdd8192b9dbde,0x00b38839874b3a9e,0x00f93618b04b7a57,0x003e3ec75fd2c67e,0x00bf5e6bfc29494a)}, + }}, {{ + {FIELD_LITERAL(0x00f19224ebba2aa5,0x0074f89d358e694d,0x00eea486597135ad,0x0081579a4555c7e1,0x0010b9b872930a9d,0x00f002e87a30ecc0,0x009b9d66b6de56e2,0x00a3c4f45e8004eb)}, + {FIELD_LITERAL(0x0045e8dda9400888,0x002ff12e5fc05db7,0x00a7098d54afe69c,0x00cdbe846a500585,0x00879c1593ca1882,0x003f7a7fea76c8b0,0x002cd73dd0c8e0a1,0x00645d6ce96f51fe)}, + {FIELD_LITERAL(0x002b7e83e123d6d6,0x00398346f7419c80,0x0042922e55940163,0x005e7fc5601886a3,0x00e88f2cee1d3103,0x00e7fab135f2e377,0x00b059984dbf0ded,0x0009ce080faa5bb8)}, + }}, {{ + {FIELD_LITERAL(0x0085e78af7758979,0x00275a4ee1631a3a,0x00d26bc0ed78b683,0x004f8355ea21064f,0x00d618e1a32696e5,0x008d8d7b150e5680,0x00a74cd854b278d2,0x001dd62702203ea0)}, + {FIELD_LITERAL(0x00f89335c2a59286,0x00a0f5c905d55141,0x00b41fb836ee9382,0x00e235d51730ca43,0x00a5cb37b5c0a69a,0x009b966ffe136c45,0x00cb2ea10bf80ed1,0x00fb2b370b40dc35)}, + {FIELD_LITERAL(0x00d687d16d4ee8ba,0x0071520bdd069dff,0x00de85c60d32355d,0x0087d2e3565102f4,0x00cde391b8dfc9aa,0x00e18d69efdfefe5,0x004a9d0591954e91,0x00fa36dd8b50eee5)}, + }}, {{ + {FIELD_LITERAL(0x002e788749a865f7,0x006e4dc3116861ea,0x009f1428c37276e6,0x00e7d2e0fc1e1226,0x003aeebc6b6c45f6,0x0071a8073bf500c9,0x004b22ad986b530c,0x00f439e63c0d79d4)}, + {FIELD_LITERAL(0x006bc3d53011f470,0x00032d6e692b83e8,0x00059722f497cd0b,0x0009b4e6f0c497cc,0x0058a804b7cce6c0,0x002b71d3302bbd5d,0x00e2f82a36765fce,0x008dded99524c703)}, + {FIELD_LITERAL(0x004d058953747d64,0x00701940fe79aa6f,0x00a620ac71c760bf,0x009532b611158b75,0x00547ed7f466f300,0x003cb5ab53a8401a,0x00c7763168ce3120,0x007e48e33e4b9ab2)}, + }}, {{ + {FIELD_LITERAL(0x001b2fc57bf3c738,0x006a3f918993fb80,0x0026f7a14fdec288,0x0075a2cdccef08db,0x00d3ecbc9eecdbf1,0x0048c40f06e5bf7f,0x00d63e423009896b,0x000598bc99c056a8)}, + {FIELD_LITERAL(0x002f194eaafa46dc,0x008e38f57fe87613,0x00dc8e5ae25f4ab2,0x000a17809575e6bd,0x00d3ec7923ba366a,0x003a7e72e0ad75e3,0x0010024b88436e0a,0x00ed3c5444b64051)}, + {FIELD_LITERAL(0x00831fc1340af342,0x00c9645669466d35,0x007692b4cc5a080f,0x009fd4a47ac9259f,0x001eeddf7d45928b,0x003c0446fc45f28b,0x002c0713aa3e2507,0x0095706935f0f41e)}, + }}, {{ + {FIELD_LITERAL(0x00766ae4190ec6d8,0x0065768cabc71380,0x00b902598416cdc2,0x00380021ad38df52,0x008f0b89d6551134,0x004254d4cc62c5a5,0x000d79f4484b9b94,0x00b516732ae3c50e)}, + {FIELD_LITERAL(0x001fb73475c45509,0x00d2b2e5ea43345a,0x00cb3c3842077bd1,0x0029f90ad820946e,0x007c11b2380778aa,0x009e54ece62c1704,0x004bc60c41ca01c3,0x004525679a5a0b03)}, + {FIELD_LITERAL(0x00c64fbddbed87b3,0x0040601d11731faa,0x009c22475b6f9d67,0x0024b79dae875f15,0x00616fed3f02c3b0,0x0000cf39f6af2d3b,0x00c46bac0aa9a688,0x00ab23e2800da204)}, + }}, {{ + {FIELD_LITERAL(0x000b3a37617632b0,0x00597199fe1cfb6c,0x0042a7ccdfeafdd6,0x004cc9f15ebcea17,0x00f436e596a6b4a4,0x00168861142df0d8,0x000753edfec26af5,0x000c495d7e388116)}, + {FIELD_LITERAL(0x0017085f4a346148,0x00c7cf7a37f62272,0x001776e129bc5c30,0x009955134c9eef2a,0x001ba5bdf1df07be,0x00ec39497103a55c,0x006578354fda6cfb,0x005f02719d4f15ee)}, + {FIELD_LITERAL(0x0052b9d9b5d9655d,0x00d4ec7ba1b461c3,0x00f95df4974f280b,0x003d8e5ca11aeb51,0x00d4981eb5a70b26,0x000af9a4f6659f29,0x004598c846faeb43,0x0049d9a183a47670)}, + }}, {{ + {FIELD_LITERAL(0x000a72d23dcb3f1f,0x00a3737f84011727,0x00f870c0fbbf4a47,0x00a7aadd04b5c9ca,0x000c7715c67bd072,0x00015a136afcd74e,0x0080d5caea499634,0x0026b448ec7514b7)}, + {FIELD_LITERAL(0x00b60167d9e7d065,0x00e60ba0d07381e8,0x003a4f17b725c2d4,0x006c19fe176b64fa,0x003b57b31af86ccb,0x0021047c286180fd,0x00bdc8fb00c6dbb6,0x00fe4a9f4bab4f3f)}, + {FIELD_LITERAL(0x0088ffc3a16111f7,0x009155e4245d0bc8,0x00851d68220572d5,0x00557ace1e514d29,0x0031d7c339d91022,0x00101d0ae2eaceea,0x00246ab3f837b66a,0x00d5216d381ff530)}, + }}, {{ + {FIELD_LITERAL(0x0057e7ea35f36dae,0x00f47d7ad15de22e,0x00d757ea4b105115,0x008311457d579d7e,0x00b49b75b1edd4eb,0x0081c7ff742fd63a,0x00ddda3187433df6,0x00475727d55f9c66)}, + {FIELD_LITERAL(0x00a6295218dc136a,0x00563b3af0e9c012,0x00d3753b0145db1b,0x004550389c043dc1,0x00ea94ae27401bdf,0x002b0b949f2b7956,0x00c63f780ad8e23c,0x00e591c47d6bab15)}, + {FIELD_LITERAL(0x00416c582b058eb6,0x004107da5b2cc695,0x00b3cd2556aeec64,0x00c0b418267e57a1,0x001799293579bd2e,0x0046ed44590e4d07,0x001d7459b3630a1e,0x00c6afba8b6696aa)}, + }}, {{ + {FIELD_LITERAL(0x008d6009b26da3f8,0x00898e88ca06b1ca,0x00edb22b2ed7fe62,0x00fbc93516aabe80,0x008b4b470c42ce0d,0x00e0032ba7d0dcbb,0x00d76da3a956ecc8,0x007f20fe74e3852a)}, + {FIELD_LITERAL(0x002419222c607674,0x00a7f23af89188b3,0x00ad127284e73d1c,0x008bba582fae1c51,0x00fc6aa7ca9ecab1,0x003df5319eb6c2ba,0x002a05af8a8b199a,0x004bf8354558407c)}, + {FIELD_LITERAL(0x00ce7d4a30f0fcbf,0x00d02c272629f03d,0x0048c001f7400bc2,0x002c21368011958d,0x0098a550391e96b5,0x002d80b66390f379,0x001fa878760cc785,0x001adfce54b613d5)}, + }}, {{ + {FIELD_LITERAL(0x001ed4dc71fa2523,0x005d0bff19bf9b5c,0x00c3801cee065a64,0x001ed0b504323fbf,0x0003ab9fdcbbc593,0x00df82070178b8d2,0x00a2bcaa9c251f85,0x00c628a3674bd02e)}, + {FIELD_LITERAL(0x006b7a0674f9f8de,0x00a742414e5c7cff,0x0041cbf3c6e13221,0x00e3a64fd207af24,0x0087c05f15fbe8d1,0x004c50936d9e8a33,0x001306ec21042b6d,0x00a4f4137d1141c2)}, + {FIELD_LITERAL(0x0009e6fb921568b0,0x00b3c60120219118,0x002a6c3460dd503a,0x009db1ef11654b54,0x0063e4bf0be79601,0x00670d34bb2592b9,0x00dcee2f6c4130ce,0x00b2682e88e77f54)}, + }}, {{ + {FIELD_LITERAL(0x000d5b4b3da135ab,0x00838f3e5064d81d,0x00d44eb50f6d94ed,0x0008931ab502ac6d,0x00debe01ca3d3586,0x0025c206775f0641,0x005ad4b6ae912763,0x007e2c318ad8f247)}, + {FIELD_LITERAL(0x00ddbe0750dd1add,0x004b3c7b885844b8,0x00363e7ecf12f1ae,0x0062e953e6438f9d,0x0023cc73b076afe9,0x00b09fa083b4da32,0x00c7c3d2456c541d,0x005b591ec6b694d4)}, + {FIELD_LITERAL(0x0028656e19d62fcf,0x0052a4af03df148d,0x00122765ddd14e42,0x00f2252904f67157,0x004741965b636f3a,0x006441d296132cb9,0x005e2106f956a5b7,0x00247029592d335c)}, + }}, {{ + {FIELD_LITERAL(0x003fe038eb92f894,0x000e6da1b72e8e32,0x003a1411bfcbe0fa,0x00b55d473164a9e4,0x00b9a775ac2df48d,0x0002ddf350659e21,0x00a279a69eb19cb3,0x00f844eab25cba44)}, + {FIELD_LITERAL(0x00c41d1f9c1f1ac1,0x007b2df4e9f19146,0x00b469355fd5ba7a,0x00b5e1965afc852a,0x00388d5f1e2d8217,0x0022079e4c09ae93,0x0014268acd4ef518,0x00c1dd8d9640464c)}, + {FIELD_LITERAL(0x0038526adeed0c55,0x00dd68c607e3fe85,0x00f746ddd48a5d57,0x0042f2952b963b7c,0x001cbbd6876d5ec2,0x005e341470bca5c2,0x00871d41e085f413,0x00e53ab098f45732)}, + }}, {{ + {FIELD_LITERAL(0x004d51124797c831,0x008f5ae3750347ad,0x0070ced94c1a0c8e,0x00f6db2043898e64,0x000d00c9a5750cd0,0x000741ec59bad712,0x003c9d11aab37b7f,0x00a67ba169807714)}, + {FIELD_LITERAL(0x00adb2c1566e8b8f,0x0096c68a35771a9a,0x00869933356f334a,0x00ba9c93459f5962,0x009ec73fb6e8ca4b,0x003c3802c27202e1,0x0031f5b733e0c008,0x00f9058c19611fa9)}, + {FIELD_LITERAL(0x00238f01814a3421,0x00c325a44b6cce28,0x002136f97aeb0e73,0x000cac8268a4afe2,0x0022fd218da471b3,0x009dcd8dfff8def9,0x00cb9f8181d999bb,0x00143ae56edea349)}, + }}, {{ + {FIELD_LITERAL(0x0000623bf87622c5,0x00a1966fdd069496,0x00c315b7b812f9fc,0x00bdf5efcd128b97,0x001d464f532e3e16,0x003cd94f081bfd7e,0x00ed9dae12ce4009,0x002756f5736eee70)}, + {FIELD_LITERAL(0x00a5187e6ee7341b,0x00e6d52e82d83b6e,0x00df3c41323094a7,0x00b3324f444e9de9,0x00689eb21a35bfe5,0x00f16363becd548d,0x00e187cc98e7f60f,0x00127d9062f0ccab)}, + {FIELD_LITERAL(0x004ad71b31c29e40,0x00a5fcace12fae29,0x004425b5597280ed,0x00e7ef5d716c3346,0x0010b53ada410ac8,0x0092310226060c9b,0x0091c26128729c7e,0x0088b42900f8ec3b)}, + }}, {{ + {FIELD_LITERAL(0x00f1e26e9762d4a8,0x00d9d74082183414,0x00ffec9bd57a0282,0x000919e128fd497a,0x00ab7ae7d00fe5f8,0x0054dc442851ff68,0x00c9ebeb3b861687,0x00507f7cab8b698f)}, + {FIELD_LITERAL(0x00c13c5aae3ae341,0x009c6c9ed98373e7,0x00098f26864577a8,0x0015b886e9488b45,0x0037692c42aadba5,0x00b83170b8e7791c,0x001670952ece1b44,0x00fd932a39276da2)}, + {FIELD_LITERAL(0x0081a3259bef3398,0x005480fff416107b,0x00ce4f607d21be98,0x003ffc084b41df9b,0x0043d0bb100502d1,0x00ec35f575ba3261,0x00ca18f677300ef3,0x00e8bb0a827d8548)}, + }}, {{ + {FIELD_LITERAL(0x00df76b3328ada72,0x002e20621604a7c2,0x00f910638a105b09,0x00ef4724d96ef2cd,0x00377d83d6b8a2f7,0x00b4f48805ade324,0x001cd5da8b152018,0x0045af671a20ca7f)}, + {FIELD_LITERAL(0x009ae3b93a56c404,0x004a410b7a456699,0x00023a619355e6b2,0x009cdc7297387257,0x0055b94d4ae70d04,0x002cbd607f65b005,0x003208b489697166,0x00ea2aa058867370)}, + {FIELD_LITERAL(0x00f29d2598ee3f32,0x00b4ac5385d82adc,0x007633eaf04df19b,0x00aa2d3d77ceab01,0x004a2302fcbb778a,0x00927f225d5afa34,0x004a8e9d5047f237,0x008224ae9dbce530)}, + }}, {{ + {FIELD_LITERAL(0x001cf640859b02f8,0x00758d1d5d5ce427,0x00763c784ef4604c,0x005fa81aee205270,0x00ac537bfdfc44cb,0x004b919bd342d670,0x00238508d9bf4b7a,0x00154888795644f3)}, + {FIELD_LITERAL(0x00c845923c084294,0x00072419a201bc25,0x0045f408b5f8e669,0x00e9d6a186b74dfe,0x00e19108c68fa075,0x0017b91d874177b7,0x002f0ca2c7912c5a,0x009400aa385a90a2)}, + {FIELD_LITERAL(0x0071110b01482184,0x00cfed0044f2bef8,0x0034f2901cf4662e,0x003b4ae2a67f9834,0x00cca9b96fe94810,0x00522507ae77abd0,0x00bac7422721e73e,0x0066622b0f3a62b0)}, + }}, {{ + {FIELD_LITERAL(0x00f8ac5cf4705b6a,0x00867d82dcb457e3,0x007e13ab2ccc2ce9,0x009ee9a018d3930e,0x008370f8ecb42df8,0x002d9f019add263e,0x003302385b92d196,0x00a15654536e2c0c)}, + {FIELD_LITERAL(0x0026ef1614e160af,0x00c023f9edfc9c76,0x00cff090da5f57ba,0x0076db7a66643ae9,0x0019462f8c646999,0x008fec00b3854b22,0x00d55041692a0a1c,0x0065db894215ca00)}, + {FIELD_LITERAL(0x00a925036e0a451c,0x002a0390c36b6cc1,0x00f27020d90894f4,0x008d90d52cbd3d7f,0x00e1d0137392f3b8,0x00f017c158b51a8f,0x00cac313d3ed7dbc,0x00b99a81e3eb42d3)}, + }}, {{ + {FIELD_LITERAL(0x00b54850275fe626,0x0053a3fd1ec71140,0x00e3d2d7dbe096fa,0x00e4ac7b595cce4c,0x0077bad449c0a494,0x00b7c98814afd5b3,0x0057226f58486cf9,0x00b1557154f0cc57)}, + {FIELD_LITERAL(0x008cc9cd236315c0,0x0031d9c5b39fda54,0x00a5713ef37e1171,0x00293d5ae2886325,0x00c4aba3e05015e1,0x0003f35ef78e4fc6,0x0039d6bd3ac1527b,0x0019d7c3afb77106)}, + {FIELD_LITERAL(0x007b162931a985af,0x00ad40a2e0daa713,0x006df27c4009f118,0x00503e9f4e2e8bec,0x00751a77c82c182d,0x000298937769245b,0x00ffb1e8fabf9ee5,0x0008334706e09abe)}, + }}, {{ + {FIELD_LITERAL(0x00dbca4e98a7dcd9,0x00ee29cfc78bde99,0x00e4a3b6995f52e9,0x0045d70189ae8096,0x00fd2a8a3b9b0d1b,0x00af1793b107d8e1,0x00dbf92cbe4afa20,0x00da60f798e3681d)}, + {FIELD_LITERAL(0x004246bfcecc627a,0x004ba431246c03a4,0x00bd1d101872d497,0x003b73d3f185ee16,0x001feb2e2678c0e3,0x00ff13c5a89dec76,0x00ed06042e771d8f,0x00a4fd2a897a83dd)}, + {FIELD_LITERAL(0x009a4a3be50d6597,0x00de3165fc5a1096,0x004f3f56e345b0c7,0x00f7bf721d5ab8bc,0x004313e47b098c50,0x00e4c7d5c0e1adbb,0x002e3e3db365051e,0x00a480c2cd6a96fb)}, + }}, {{ + {FIELD_LITERAL(0x00417fa30a7119ed,0x00af257758419751,0x00d358a487b463d4,0x0089703cc720b00d,0x00ce56314ff7f271,0x0064db171ade62c1,0x00640b36d4a22fed,0x00424eb88696d23f)}, + {FIELD_LITERAL(0x004ede34af2813f3,0x00d4a8e11c9e8216,0x004796d5041de8a5,0x00c4c6b4d21cc987,0x00e8a433ee07fa1e,0x0055720b5abcc5a1,0x008873ea9c74b080,0x005b3fec1ab65d48)}, + {FIELD_LITERAL(0x0047e5277db70ec5,0x000a096c66db7d6b,0x00b4164cc1730159,0x004a9f783fe720fe,0x00a8177b94449dbc,0x0095a24ff49a599f,0x0069c1c578250cbc,0x00452019213debf4)}, + }}, {{ + {FIELD_LITERAL(0x0021ce99e09ebda3,0x00fcbd9f91875ad0,0x009bbf6b7b7a0b5f,0x00388886a69b1940,0x00926a56d0f81f12,0x00e12903c3358d46,0x005dfce4e8e1ce9d,0x0044cfa94e2f7e23)}, + {FIELD_LITERAL(0x001bd59c09e982ea,0x00f72daeb937b289,0x0018b76dca908e0e,0x00edb498512384ad,0x00ce0243b6cc9538,0x00f96ff690cb4e70,0x007c77bf9f673c8d,0x005bf704c088a528)}, + {FIELD_LITERAL(0x0093d4628dcb33be,0x0095263d51d42582,0x0049b3222458fe06,0x00e7fce73b653a7f,0x003ca2ebce60b369,0x00c5de239a32bea4,0x0063b8b3d71fb6bf,0x0039aeeb78a1a839)}, + }}, {{ + {FIELD_LITERAL(0x007dc52da400336c,0x001fded1e15b9457,0x00902e00f5568e3a,0x00219bef40456d2d,0x005684161fb3dbc9,0x004a4e9be49a76ea,0x006e685ae88b78ff,0x0021c42f13042d3c)}, + {FIELD_LITERAL(0x00fb22bb5fd3ce50,0x0017b48aada7ae54,0x00fd5c44ad19a536,0x000ccc4e4e55e45c,0x00fd637d45b4c3f5,0x0038914e023c37cf,0x00ac1881d6a8d898,0x00611ed8d3d943a8)}, + {FIELD_LITERAL(0x0056e2259d113d2b,0x00594819b284ec16,0x00c7bf794bb36696,0x00721ee75097cdc6,0x00f71be9047a2892,0x00df6ba142564edf,0x0069580b7a184e8d,0x00f056e38fca0fee)}, + }}, {{ + {FIELD_LITERAL(0x009df98566a18c6d,0x00cf3a200968f219,0x0044ba60da6d9086,0x00dbc9c0e344da03,0x000f9401c4466855,0x00d46a57c5b0a8d1,0x00875a635d7ac7c6,0x00ef4a933b7e0ae6)}, + {FIELD_LITERAL(0x005e8694077a1535,0x008bef75f71c8f1d,0x000a7c1316423511,0x00906e1d70604320,0x003fc46c1a2ffbd6,0x00d1d5022e68f360,0x002515fba37bbf46,0x00ca16234e023b44)}, + {FIELD_LITERAL(0x00787c99561f4690,0x00a857a8c1561f27,0x00a10df9223c09fe,0x00b98a9562e3b154,0x004330b8744c3ed2,0x00e06812807ec5c4,0x00e4cf6a7db9f1e3,0x00d95b089f132a34)}, + }}, {{ + {FIELD_LITERAL(0x002922b39ca33eec,0x0090d12a5f3ab194,0x00ab60c02fb5f8ed,0x00188d292abba1cf,0x00e10edec9698f6e,0x0069a4d9934133c8,0x0024aac40e6d3d06,0x001702c2177661b0)}, + {FIELD_LITERAL(0x00139078397030bd,0x000e3c447e859a00,0x0064a5b334c82393,0x00b8aabeb7358093,0x00020778bb9ae73b,0x0032ee94c7892a18,0x008215253cb41bda,0x005e2797593517ae)}, + {FIELD_LITERAL(0x0083765a5f855d4a,0x0051b6d1351b8ee2,0x00116de548b0f7bb,0x0087bd88703affa0,0x0095b2cc34d7fdd2,0x0084cd81b53f0bc8,0x008562fc995350ed,0x00a39abb193651e3)}, + }}, {{ + {FIELD_LITERAL(0x0019e23f0474b114,0x00eb94c2ad3b437e,0x006ddb34683b75ac,0x00391f9209b564c6,0x00083b3bb3bff7aa,0x00eedcd0f6dceefc,0x00b50817f794fe01,0x0036474deaaa75c9)}, + {FIELD_LITERAL(0x0091868594265aa2,0x00797accae98ca6d,0x0008d8c5f0f8a184,0x00d1f4f1c2b2fe6e,0x0036783dfb48a006,0x008c165120503527,0x0025fd780058ce9b,0x0068beb007be7d27)}, + {FIELD_LITERAL(0x00d0ff88aa7c90c2,0x00b2c60dacf53394,0x0094a7284d9666d6,0x00bed9022ce7a19d,0x00c51553f0cd7682,0x00c3fb870b124992,0x008d0bc539956c9b,0x00fc8cf258bb8885)}, + }}, {{ + {FIELD_LITERAL(0x003667bf998406f8,0x0000115c43a12975,0x001e662f3b20e8fd,0x0019ffa534cb24eb,0x00016be0dc8efb45,0x00ff76a8b26243f5,0x00ae20d241a541e3,0x0069bd6af13cd430)}, + {FIELD_LITERAL(0x0045fdc16487cda3,0x00b2d8e844cf2ed7,0x00612c50e88c1607,0x00a08aabc66c1672,0x006031fdcbb24d97,0x001b639525744b93,0x004409d62639ab17,0x00a1853d0347ab1d)}, + {FIELD_LITERAL(0x0075a1a56ebf5c21,0x00a3e72be9ac53ed,0x00efcde1629170c2,0x0004225fe91ef535,0x0088049fc73dfda7,0x004abc74857e1288,0x0024e2434657317c,0x00d98cb3d3e5543c)}, + }}, {{ + {FIELD_LITERAL(0x00b4b53eab6bdb19,0x009b22d8b43711d0,0x00d948b9d961785d,0x00cb167b6f279ead,0x00191de3a678e1c9,0x00d9dd9511095c2e,0x00f284324cd43067,0x00ed74fa535151dd)}, + {FIELD_LITERAL(0x007e32c049b5c477,0x009d2bfdbd9bcfd8,0x00636e93045938c6,0x007fde4af7687298,0x0046a5184fafa5d3,0x0079b1e7f13a359b,0x00875adf1fb927d6,0x00333e21c61bcad2)}, + {FIELD_LITERAL(0x00048014f73d8b8d,0x0075684aa0966388,0x0092be7df06dc47c,0x0097cebcd0f5568a,0x005a7004d9c4c6a9,0x00b0ecbb659924c7,0x00d90332dd492a7c,0x0057fc14df11493d)}, + }}, {{ + {FIELD_LITERAL(0x0008ed8ea0ad95be,0x0041d324b9709645,0x00e25412257a19b4,0x0058df9f3423d8d2,0x00a9ab20def71304,0x009ae0dbf8ac4a81,0x00c9565977e4392a,0x003c9269444baf55)}, + {FIELD_LITERAL(0x007df6cbb926830b,0x00d336058ae37865,0x007af47dac696423,0x0048d3011ec64ac8,0x006b87666e40049f,0x0036a2e0e51303d7,0x00ba319bd79dbc55,0x003e2737ecc94f53)}, + {FIELD_LITERAL(0x00d296ff726272d9,0x00f6d097928fcf57,0x00e0e616a55d7013,0x00deaf454ed9eac7,0x0073a56bedef4d92,0x006ccfdf6fc92e19,0x009d1ee1371a7218,0x00ee3c2ee4462d80)}, + }}, {{ + {FIELD_LITERAL(0x00437bce9bccdf9d,0x00e0c8e2f85dc0a3,0x00c91a7073995a19,0x00856ec9fe294559,0x009e4b33394b156e,0x00e245b0dc497e5c,0x006a54e687eeaeff,0x00f1cd1cd00fdb7c)}, + {FIELD_LITERAL(0x008132ae5c5d8cd1,0x00121d68324a1d9f,0x00d6be9dafcb8c76,0x00684d9070edf745,0x00519fbc96d7448e,0x00388182fdc1f27e,0x000235baed41f158,0x00bf6cf6f1a1796a)}, + {FIELD_LITERAL(0x002adc4b4d148219,0x003084ada0d3a90a,0x0046de8aab0f2e4e,0x00452d342a67b5fd,0x00d4b50f01d4de21,0x00db6d9fc0cefb79,0x008c184c86a462cd,0x00e17c83764d42da)}, + }}, {{ + {FIELD_LITERAL(0x007b2743b9a1e01a,0x007847ffd42688c4,0x006c7844d610a316,0x00f0cb8b250aa4b0,0x00a19060143b3ae6,0x0014eb10b77cfd80,0x000170905729dd06,0x00063b5b9cd72477)}, + {FIELD_LITERAL(0x00ce382dc7993d92,0x00021153e938b4c8,0x00096f7567f48f51,0x0058f81ddfe4b0d5,0x00cc379a56b355c7,0x002c760770d3e819,0x00ee22d1d26e5a40,0x00de6d93d5b082d7)}, + {FIELD_LITERAL(0x000a91a42c52e056,0x00185f6b77fce7ea,0x000803c51962f6b5,0x0022528582ba563d,0x0043f8040e9856d6,0x0085a29ec81fb860,0x005f9a611549f5ff,0x00c1f974ecbd4b06)}, + }}, {{ + {FIELD_LITERAL(0x005b64c6fd65ec97,0x00c1fdd7f877bc7f,0x000d9cc6c89f841c,0x005c97b7f1aff9ad,0x0075e3c61475d47e,0x001ecb1ba8153011,0x00fe7f1c8d71d40d,0x003fa9757a229832)}, + {FIELD_LITERAL(0x00ffc5c89d2b0cba,0x00d363d42e3e6fc3,0x0019a1a0118e2e8a,0x00f7baeff48882e1,0x001bd5af28c6b514,0x0055476ca2253cb2,0x00d8eb1977e2ddf3,0x00b173b1adb228a1)}, + {FIELD_LITERAL(0x00f2cb99dd0ad707,0x00e1e08b6859ddd8,0x000008f2d0650bcc,0x00d7ed392f8615c3,0x00976750a94da27f,0x003e83bb0ecb69ba,0x00df8e8d15c14ac6,0x00f9f7174295d9c2)}, + }}, {{ + {FIELD_LITERAL(0x00f11cc8e0e70bcb,0x00e5dc689974e7dd,0x0014e409f9ee5870,0x00826e6689acbd63,0x008a6f4e3d895d88,0x00b26a8da41fd4ad,0x000fb7723f83efd7,0x009c749db0a5f6c3)}, + {FIELD_LITERAL(0x002389319450f9ba,0x003677f31aa1250a,0x0092c3db642f38cb,0x00f8b64c0dfc9773,0x00cd49fe3505b795,0x0068105a4090a510,0x00df0ba2072a8bb6,0x00eb396143afd8be)}, + {FIELD_LITERAL(0x00a0d4ecfb24cdff,0x00ddaf8008ba6479,0x00f0b3e36d4b0f44,0x003734bd3af1f146,0x00b87e2efc75527e,0x00d230df55ddab50,0x002613257ae56c1d,0x00bc0946d135934d)}, + }}, {{ + {FIELD_LITERAL(0x00468711bd994651,0x0033108fa67561bf,0x0089d760192a54b4,0x00adc433de9f1871,0x000467d05f36e050,0x007847e0f0579f7f,0x00a2314ad320052d,0x00b3a93649f0b243)}, + {FIELD_LITERAL(0x0067f8f0c4fe26c9,0x0079c4a3cc8f67b9,0x0082b1e62f23550d,0x00f2d409caefd7f5,0x0080e67dcdb26e81,0x0087ae993ea1f98a,0x00aa108becf61d03,0x001acf11efb608a3)}, + {FIELD_LITERAL(0x008225febbab50d9,0x00f3b605e4dd2083,0x00a32b28189e23d2,0x00d507e5e5eb4c97,0x005a1a84e302821f,0x0006f54c1c5f08c7,0x00a347c8cb2843f0,0x0009f73e9544bfa5)}, + }}, {{ + {FIELD_LITERAL(0x006c59c9ae744185,0x009fc32f1b4282cd,0x004d6348ca59b1ac,0x00105376881be067,0x00af4096013147dc,0x004abfb5a5cb3124,0x000d2a7f8626c354,0x009c6ed568e07431)}, + {FIELD_LITERAL(0x00e828333c297f8b,0x009ef3cf8c3f7e1f,0x00ab45f8fff31cb9,0x00c8b4178cb0b013,0x00d0c50dd3260a3f,0x0097126ac257f5bc,0x0042376cc90c705a,0x001d96fdb4a1071e)}, + {FIELD_LITERAL(0x00542d44d89ee1a8,0x00306642e0442d98,0x0090853872b87338,0x002362cbf22dc044,0x002c222adff663b8,0x0067c924495fcb79,0x000e621d983c977c,0x00df77a9eccb66fb)}, + }}, {{ + {FIELD_LITERAL(0x002809e4bbf1814a,0x00b9e854f9fafb32,0x00d35e67c10f7a67,0x008f1bcb76e748cf,0x004224d9515687d2,0x005ba0b774e620c4,0x00b5e57db5d54119,0x00e15babe5683282)}, + {FIELD_LITERAL(0x00832d02369b482c,0x00cba52ff0d93450,0x003fa9c908d554db,0x008d1e357b54122f,0x00abd91c2dc950c6,0x007eff1df4c0ec69,0x003f6aeb13fb2d31,0x00002d6179fc5b2c)}, + {FIELD_LITERAL(0x0046c9eda81c9c89,0x00b60cb71c8f62fc,0x0022f5a683baa558,0x00f87319fccdf997,0x009ca09b51ce6a22,0x005b12baf4af7d77,0x008a46524a1e33e2,0x00035a77e988be0d)}, + }}, {{ + {FIELD_LITERAL(0x00a7efe46a7dbe2f,0x002f66fd55014fe7,0x006a428afa1ff026,0x0056caaa9604ab72,0x0033f3bcd7fac8ae,0x00ccb1aa01c86764,0x00158d1edf13bf40,0x009848ee76fcf3b4)}, + {FIELD_LITERAL(0x00a9e7730a819691,0x00d9cc73c4992b70,0x00e299bde067de5a,0x008c314eb705192a,0x00e7226f17e8a3cc,0x0029dfd956e65a47,0x0053a8e839073b12,0x006f942b2ab1597e)}, + {FIELD_LITERAL(0x001c3d780ecd5e39,0x0094f247fbdcc5fe,0x00d5c786fd527764,0x00b6f4da74f0db2a,0x0080f1f8badcd5fc,0x00f36a373ad2e23b,0x00f804f9f4343bf2,0x00d1af40ec623982)}, + }}, {{ + {FIELD_LITERAL(0x0082aeace5f1b144,0x00f68b3108cf4dd3,0x00634af01dde3020,0x000beab5df5c2355,0x00e8b790d1b49b0b,0x00e48d15854e36f4,0x0040ab2d95f3db9f,0x002711c4ed9e899a)}, + {FIELD_LITERAL(0x0039343746531ebe,0x00c8509d835d429d,0x00e79eceff6b0018,0x004abfd31e8efce5,0x007bbfaaa1e20210,0x00e3be89c193e179,0x001c420f4c31d585,0x00f414a315bef5ae)}, + {FIELD_LITERAL(0x007c296a24990df8,0x00d5d07525a75588,0x00dd8e113e94b7e7,0x007bbc58febe0cc8,0x0029f51af9bfcad3,0x007e9311ec7ab6f3,0x009a884de1676343,0x0050d5f2dce84be9)}, + }}, {{ + {FIELD_LITERAL(0x005fa020cca2450a,0x00491c29db6416d8,0x0037cefe3f9f9a85,0x003d405230647066,0x0049e835f0fdbe89,0x00feb78ac1a0815c,0x00828e4b32dc9724,0x00db84f2dc8d6fd4)}, + {FIELD_LITERAL(0x0098cddc8b39549a,0x006da37e3b05d22c,0x00ce633cfd4eb3cb,0x00fda288ef526acd,0x0025338878c5d30a,0x00f34438c4e5a1b4,0x00584efea7c310f1,0x0041a551f1b660ad)}, + {FIELD_LITERAL(0x00d7f7a8fbd6437a,0x0062872413bf3753,0x00ad4bbcb43c584b,0x007fe49be601d7e3,0x0077c659789babf4,0x00eb45fcb06a741b,0x005ce244913f9708,0x0088426401736326)}, + }}, {{ + {FIELD_LITERAL(0x007bf562ca768d7c,0x006c1f3a174e387c,0x00f024b447fee939,0x007e7af75f01143f,0x003adb70b4eed89d,0x00e43544021ad79a,0x0091f7f7042011f6,0x0093c1a1ee3a0ddc)}, + {FIELD_LITERAL(0x00a0b68ec1eb72d2,0x002c03235c0d45a0,0x00553627323fe8c5,0x006186e94b17af94,0x00a9906196e29f14,0x0025b3aee6567733,0x007e0dd840080517,0x0018eb5801a4ba93)}, + {FIELD_LITERAL(0x00d7fe7017bf6a40,0x006e3f0624be0c42,0x00ffbba205358245,0x00f9fc2cf8194239,0x008d93b37bf15b4e,0x006ddf2e38be8e95,0x002b6e79bf5fcff9,0x00ab355da425e2de)}, + }}, {{ + {FIELD_LITERAL(0x00938f97e20be973,0x0099141a36aaf306,0x0057b0ca29e545a1,0x0085db571f9fbc13,0x008b333c554b4693,0x0043ab6ef3e241cb,0x0054fb20aa1e5c70,0x00be0ff852760adf)}, + {FIELD_LITERAL(0x003973d8938971d6,0x002aca26fa80c1f5,0x00108af1faa6b513,0x00daae275d7924e6,0x0053634ced721308,0x00d2355fe0bbd443,0x00357612b2d22095,0x00f9bb9dd4136cf3)}, + {FIELD_LITERAL(0x002bff12cf5e03a5,0x001bdb1fa8a19cf8,0x00c91c6793f84d39,0x00f869f1b2eba9af,0x0059bc547dc3236b,0x00d91611d6d38689,0x00e062daaa2c0214,0x00ed3c047cc2bc82)}, + }}, {{ + {FIELD_LITERAL(0x000050d70c32b31a,0x001939d576d437b3,0x00d709e598bf9fe6,0x00a885b34bd2ee9e,0x00dd4b5c08ab1a50,0x0091bebd50b55639,0x00cf79ff64acdbc6,0x006067a39d826336)}, + {FIELD_LITERAL(0x0062dd0fb31be374,0x00fcc96b84c8e727,0x003f64f1375e6ae3,0x0057d9b6dd1af004,0x00d6a167b1103c7b,0x00dd28f3180fb537,0x004ff27ad7167128,0x008934c33461f2ac)}, + {FIELD_LITERAL(0x0065b472b7900043,0x00ba7efd2ff1064b,0x000b67d6c4c3020f,0x0012d28469f4e46d,0x0031c32939703ec7,0x00b49f0bce133066,0x00f7e10416181d47,0x005c90f51867eecc)}, + }}, {{ + {FIELD_LITERAL(0x0051207abd179101,0x00fc2a5c20d9c5da,0x00fb9d5f2701b6df,0x002dd040fdea82b8,0x00f163b0738442ff,0x00d9736bd68855b8,0x00e0d8e93005e61c,0x00df5a40b3988570)}, + {FIELD_LITERAL(0x0006918f5dfce6dc,0x00d4bf1c793c57fb,0x0069a3f649435364,0x00e89a50e5b0cd6e,0x00b9f6a237e973af,0x006d4ed8b104e41d,0x00498946a3924cd2,0x00c136ec5ac9d4f7)}, + {FIELD_LITERAL(0x0011a9c290ac5336,0x002b9a2d4a6a6533,0x009a8a68c445d937,0x00361b27b07e5e5c,0x003c043b1755b974,0x00b7eb66cf1155ee,0x0077af5909eefff2,0x0098f609877cc806)}, + }}, {{ + {FIELD_LITERAL(0x00ab13af436bf8f4,0x000bcf0a0dac8574,0x00d50c864f705045,0x00c40e611debc842,0x0085010489bd5caa,0x007c5050acec026f,0x00f67d943c8da6d1,0x00de1da0278074c6)}, + {FIELD_LITERAL(0x00b373076597455f,0x00e83f1af53ac0f5,0x0041f63c01dc6840,0x0097dea19b0c6f4b,0x007f9d63b4c1572c,0x00e692d492d0f5f0,0x00cbcb392e83b4ad,0x0069c0f39ed9b1a8)}, + {FIELD_LITERAL(0x00861030012707c9,0x009fbbdc7fd4aafb,0x008f591d6b554822,0x00df08a41ea18ade,0x009d7d83e642abea,0x0098c71bda3b78ff,0x0022c89e7021f005,0x0044d29a3fe1e3c4)}, + }}, {{ + {FIELD_LITERAL(0x00e748cd7b5c52f2,0x00ea9df883f89cc3,0x0018970df156b6c7,0x00c5a46c2a33a847,0x00cbde395e32aa09,0x0072474ebb423140,0x00fb00053086a23d,0x001dafcfe22d4e1f)}, + {FIELD_LITERAL(0x00c903ee6d825540,0x00add6c4cf98473e,0x007636efed4227f1,0x00905124ae55e772,0x00e6b38fab12ed53,0x0045e132b863fe55,0x003974662edb366a,0x00b1787052be8208)}, + {FIELD_LITERAL(0x00a614b00d775c7c,0x00d7c78941cc7754,0x00422dd68b5dabc4,0x00a6110f0167d28b,0x00685a309c252886,0x00b439ffd5143660,0x003656e29ee7396f,0x00c7c9b9ed5ad854)}, + }}, {{ + {FIELD_LITERAL(0x0040f7e7c5b37bf2,0x0064e4dc81181bba,0x00a8767ae2a366b6,0x001496b4f90546f2,0x002a28493f860441,0x0021f59513049a3a,0x00852d369a8b7ee3,0x00dd2e7d8b7d30a9)}, + {FIELD_LITERAL(0x00006e34a35d9fbc,0x00eee4e48b2f019a,0x006b344743003a5f,0x00541d514f04a7e3,0x00e81f9ee7647455,0x005e2b916c438f81,0x00116f8137b7eff0,0x009bd3decc7039d1)}, + {FIELD_LITERAL(0x0005d226f434110d,0x00af8288b8ef21d5,0x004a7a52ef181c8c,0x00be0b781b4b06de,0x00e6e3627ded07e1,0x00e43aa342272b8b,0x00e86ab424577d84,0x00fb292c566e35bb)}, + }}, {{ + {FIELD_LITERAL(0x00334f5303ea1222,0x00dfb3dbeb0a5d3e,0x002940d9592335c1,0x00706a7a63e8938a,0x005a533558bc4caf,0x00558e33192022a9,0x00970d9faf74c133,0x002979fcb63493ca)}, + {FIELD_LITERAL(0x00e38abece3c82ab,0x005a51f18a2c7a86,0x009dafa2e86d592e,0x00495a62eb688678,0x00b79df74c0eb212,0x0023e8cc78b75982,0x005998cb91075e13,0x00735aa9ba61bc76)}, + {FIELD_LITERAL(0x00d9f7a82ddbe628,0x00a1fc782889ae0f,0x0071ffda12d14b66,0x0037cf4eca7fb3d5,0x00c80bc242c58808,0x0075bf8c2d08c863,0x008d41f31afc52a7,0x00197962ecf38741)}, + }}, {{ + {FIELD_LITERAL(0x006e9f475cccf2ee,0x00454b9cd506430c,0x00224a4fb79ee479,0x0062e3347ef0b5e2,0x0034fd2a3512232a,0x00b8b3cb0f457046,0x00eb20165daa38ec,0x00128eebc2d9c0f7)}, + {FIELD_LITERAL(0x00bfc5fa1e4ea21f,0x00c21d7b6bb892e6,0x00cf043f3acf0291,0x00c13f2f849b3c90,0x00d1a97ebef10891,0x0061e130a445e7fe,0x0019513fdedbf22b,0x001d60c813bff841)}, + {FIELD_LITERAL(0x0019561c7fcf0213,0x00e3dca6843ebd77,0x0068ea95b9ca920e,0x009bdfb70f253595,0x00c68f59186aa02a,0x005aee1cca1c3039,0x00ab79a8a937a1ce,0x00b9a0e549959e6f)}, + }}, {{ + {FIELD_LITERAL(0x00c79e0b6d97dfbd,0x00917c71fd2bc6e8,0x00db7529ccfb63d8,0x00be5be957f17866,0x00a9e11fdc2cdac1,0x007b91a8e1f44443,0x00a3065e4057d80f,0x004825f5b8d5f6d4)}, + {FIELD_LITERAL(0x003e4964fa8a8fc8,0x00f6a1cdbcf41689,0x00943cb18fe7fda7,0x00606dafbf34440a,0x005d37a86399c789,0x00e79a2a69417403,0x00fe34f7e68b8866,0x0011f448ed2df10e)}, + {FIELD_LITERAL(0x00f1f57efcc1fcc4,0x00513679117de154,0x002e5b5b7c86d8c3,0x009f6486561f9cfb,0x00169e74b0170cf7,0x00900205af4af696,0x006acfddb77853f3,0x00df184c90f31068)}, + }}, {{ + {FIELD_LITERAL(0x00b37396c3320791,0x00fc7b67175c5783,0x00c36d2cd73ecc38,0x0080ebcc0b328fc5,0x0043a5b22b35d35d,0x00466c9f1713c9da,0x0026ad346dcaa8da,0x007c684e701183a6)}, + {FIELD_LITERAL(0x00fd579ffb691713,0x00b76af4f81c412d,0x00f239de96110f82,0x00e965fb437f0306,0x00ca7e9436900921,0x00e487f1325fa24a,0x00633907de476380,0x00721c62ac5b8ea0)}, + {FIELD_LITERAL(0x00c0d54e542eb4f9,0x004ed657171c8dcf,0x00b743a4f7c2a39b,0x00fd9f93ed6cc567,0x00307fae3113e58b,0x0058aa577c93c319,0x00d254556f35b346,0x00491aada2203f0d)}, + }}, {{ + {FIELD_LITERAL(0x00dff3103786ff34,0x000144553b1f20c3,0x0095613baeb930e4,0x00098058275ea5d4,0x007cd1402b046756,0x0074d74e4d58aee3,0x005f93fc343ff69b,0x00873df17296b3b0)}, + {FIELD_LITERAL(0x00c4a1fb48635413,0x00b5dd54423ad59f,0x009ff5d53fd24a88,0x003c98d267fc06a7,0x002db7cb20013641,0x00bd1d6716e191f2,0x006dbc8b29094241,0x0044bbf233dafa2c)}, + {FIELD_LITERAL(0x0055838d41f531e6,0x00bf6a2dd03c81b2,0x005827a061c4839e,0x0000de2cbb36aac3,0x002efa29d9717478,0x00f9e928cc8a77ba,0x00c134b458def9ef,0x00958a182223fc48)}, + }}, {{ + {FIELD_LITERAL(0x000a9ee23c06881f,0x002c727d3d871945,0x00f47d971512d24a,0x00671e816f9ef31a,0x00883af2cfaad673,0x00601f98583d6c9a,0x00b435f5adc79655,0x00ad87b71c04bff2)}, + {FIELD_LITERAL(0x007860d99db787cf,0x00fda8983018f4a8,0x008c8866bac4743c,0x00ef471f84c82a3f,0x00abea5976d3b8e7,0x00714882896cd015,0x00b49fae584ddac5,0x008e33a1a0b69c81)}, + {FIELD_LITERAL(0x007b6ee2c9e8a9ec,0x002455dbbd89d622,0x006490cf4eaab038,0x00d925f6c3081561,0x00153b3047de7382,0x003b421f8bdceb6f,0x00761a4a5049da78,0x00980348c5202433)}, + }}, {{ + {FIELD_LITERAL(0x007f8a43da97dd5c,0x00058539c800fc7b,0x0040f3cf5a28414a,0x00d68dd0d95283d6,0x004adce9da90146e,0x00befa41c7d4f908,0x007603bc2e3c3060,0x00bdf360ab3545db)}, + {FIELD_LITERAL(0x00eebfd4e2312cc3,0x00474b2564e4fc8c,0x003303ef14b1da9b,0x003c93e0e66beb1d,0x0013619b0566925a,0x008817c24d901bf3,0x00b62bd8898d218b,0x0075a7716f1e88a2)}, + {FIELD_LITERAL(0x0009218da1e6890f,0x0026907f5fd02575,0x004dabed5f19d605,0x003abf181870249d,0x00b52fd048cc92c4,0x00b6dd51e415a5c5,0x00d9eb82bd2b4014,0x002c865a43b46b43)}, + }}, {{ + {FIELD_LITERAL(0x0070047189452f4c,0x00f7ad12e1ce78d5,0x00af1ba51ec44a8b,0x005f39f63e667cd6,0x00058eac4648425e,0x00d7fdab42bea03b,0x0028576a5688de15,0x00af973209e77c10)}, + {FIELD_LITERAL(0x00c338b915d8fef0,0x00a893292045c39a,0x0028ab4f2eba6887,0x0060743cb519fd61,0x0006213964093ac0,0x007c0b7a43f6266d,0x008e3557c4fa5bda,0x002da976de7b8d9d)}, + {FIELD_LITERAL(0x0048729f8a8b6dcd,0x00fe23b85cc4d323,0x00e7384d16e4db0e,0x004a423970678942,0x00ec0b763345d4ba,0x00c477b9f99ed721,0x00c29dad3777b230,0x001c517b466f7df6)}, + }}, {{ + {FIELD_LITERAL(0x006366c380f7b574,0x001c7d1f09ff0438,0x003e20a7301f5b22,0x00d3efb1916d28f6,0x0049f4f81060ce83,0x00c69d91ea43ced1,0x002b6f3e5cd269ed,0x005b0fb22ce9ec65)}, + {FIELD_LITERAL(0x00aa2261022d883f,0x00ebcca4548010ac,0x002528512e28a437,0x0070ca7676b66082,0x0084bda170f7c6d3,0x00581b4747c9b8bb,0x005c96a01061c7e2,0x00fb7c4a362b5273)}, + {FIELD_LITERAL(0x00c30020eb512d02,0x0060f288283a4d26,0x00b7ed13becde260,0x0075ebb74220f6e9,0x00701079fcfe8a1f,0x001c28fcdff58938,0x002e4544b8f4df6b,0x0060c5bc4f1a7d73)}, + }}, {{ + {FIELD_LITERAL(0x00ae307cf069f701,0x005859f222dd618b,0x00212d6c46ec0b0d,0x00a0fe4642afb62d,0x00420d8e4a0a8903,0x00a80ff639bdf7b0,0x0019bee1490b5d8e,0x007439e4b9c27a86)}, + {FIELD_LITERAL(0x00a94700032a093f,0x0076e96c225216e7,0x00a63a4316e45f91,0x007d8bbb4645d3b2,0x00340a6ff22793eb,0x006f935d4572aeb7,0x00b1fb69f00afa28,0x009e8f3423161ed3)}, + {FIELD_LITERAL(0x009ef49c6b5ced17,0x00a555e6269e9f0a,0x007e6f1d79ec73b5,0x009ac78695a32ac4,0x0001d77fbbcd5682,0x008cea1fee0aaeed,0x00f42bea82a53462,0x002e46ab96cafcc9)}, + }}, {{ + {FIELD_LITERAL(0x0051cfcc5885377a,0x00dce566cb1803ca,0x00430c7643f2c7d4,0x00dce1a1337bdcc0,0x0010d5bd7283c128,0x003b1b547f9b46fe,0x000f245e37e770ab,0x007b72511f022b37)}, + {FIELD_LITERAL(0x0060db815bc4786c,0x006fab25beedc434,0x00c610d06084797c,0x000c48f08537bec0,0x0031aba51c5b93da,0x007968fa6e01f347,0x0030070da52840c6,0x00c043c225a4837f)}, + {FIELD_LITERAL(0x001bcfd00649ee93,0x006dceb47e2a0fd5,0x00f2cebda0cf8fd0,0x00b6b9d9d1fbdec3,0x00815262e6490611,0x00ef7f5ce3176760,0x00e49cd0c998d58b,0x005fc6cc269ba57c)}, + }}, {{ + {FIELD_LITERAL(0x008940211aa0d633,0x00addae28136571d,0x00d68fdbba20d673,0x003bc6129bc9e21a,0x000346cf184ebe9a,0x0068774d741ebc7f,0x0019d5e9e6966557,0x0003cbd7f981b651)}, + {FIELD_LITERAL(0x004a2902926f8d3f,0x00ad79b42637ab75,0x0088f60b90f2d4e8,0x0030f54ef0e398c4,0x00021dc9bf99681e,0x007ebf66fde74ee3,0x004ade654386e9a4,0x00e7485066be4c27)}, + {FIELD_LITERAL(0x00445f1263983be0,0x004cf371dda45e6a,0x00744a89d5a310e7,0x001f20ce4f904833,0x00e746edebe66e29,0x000912ab1f6c153d,0x00f61d77d9b2444c,0x0001499cd6647610)}, + }} + } +}; +const struct curve448_precomputed_s *curve448_precomputed_base + = &curve448_precomputed_base_table; + +static const niels_t curve448_wnaf_base_table[32] = { + {{ + {FIELD_LITERAL(0x00303cda6feea532,0x00860f1d5a3850e4,0x00226b9fa4728ccd,0x00e822938a0a0c0c,0x00263a61c9ea9216,0x001204029321b828,0x006a468360983c65,0x0002846f0a782143)}, + {FIELD_LITERAL(0x00303cda6feea532,0x00860f1d5a3850e4,0x00226b9fa4728ccd,0x006822938a0a0c0c,0x00263a61c9ea9215,0x001204029321b828,0x006a468360983c65,0x0082846f0a782143)}, + {FIELD_LITERAL(0x00ef8e22b275198d,0x00b0eb141a0b0e8b,0x001f6789da3cb38c,0x006d2ff8ed39073e,0x00610bdb69a167f3,0x00571f306c9689b4,0x00f557e6f84b2df8,0x002affd38b2c86db)}, + }}, {{ + {FIELD_LITERAL(0x00cea0fc8d2e88b5,0x00821612d69f1862,0x0074c283b3e67522,0x005a195ba05a876d,0x000cddfe557feea4,0x008046c795bcc5e5,0x00540969f4d6e119,0x00d27f96d6b143d5)}, + {FIELD_LITERAL(0x000c3b1019d474e8,0x00e19533e4952284,0x00cc9810ba7c920a,0x00f103d2785945ac,0x00bfa5696cc69b34,0x00a8d3d51e9ca839,0x005623cb459586b9,0x00eae7ce1cd52e9e)}, + {FIELD_LITERAL(0x0005a178751dd7d8,0x002cc3844c69c42f,0x00acbfe5efe10539,0x009c20f43431a65a,0x008435d96374a7b3,0x009ee57566877bd3,0x0044691725ed4757,0x001e87bb2fe2c6b2)}, + }}, {{ + {FIELD_LITERAL(0x000cedc4debf7a04,0x002ffa45000470ac,0x002e9f9678201915,0x0017da1208c4fe72,0x007d558cc7d656cb,0x0037a827287cf289,0x00142472d3441819,0x009c21f166cf8dd1)}, + {FIELD_LITERAL(0x003ef83af164b2f2,0x000949a5a0525d0d,0x00f4498186cac051,0x00e77ac09ef126d2,0x0073ae0b2c9296e9,0x001c163f6922e3ed,0x0062946159321bea,0x00cfb79b22990b39)}, + {FIELD_LITERAL(0x00b001431ca9e654,0x002d7e5eabcc9a3a,0x0052e8114c2f6747,0x0079ac4f94487f92,0x00bffd919b5d749c,0x00261f92ad15e620,0x00718397b7a97895,0x00c1443e6ebbc0c4)}, + }}, {{ + {FIELD_LITERAL(0x00eacd90c1e0a049,0x008977935b149fbe,0x0004cb9ba11c93dc,0x009fbd5b3470844d,0x004bc18c9bfc22cf,0x0057679a991839f3,0x00ef15b76fb4092e,0x0074a5173a225041)}, + {FIELD_LITERAL(0x003f5f9d7ec4777b,0x00ab2e733c919c94,0x001bb6c035245ae5,0x00a325a49a883630,0x0033e9a9ea3cea2f,0x00e442a1eaa0e844,0x00b2116d5b0e71b8,0x00c16abed6d64047)}, + {FIELD_LITERAL(0x00c560b5ed051165,0x001945adc5d65094,0x00e221865710f910,0x00cc12bc9e9b8ceb,0x004faa9518914e35,0x0017476d89d42f6d,0x00b8f637c8fa1c8b,0x0088c7d2790864b8)}, + }}, {{ + {FIELD_LITERAL(0x00ef7eafc1c69be6,0x0085d3855778fbea,0x002c8d5b450cb6f5,0x004e77de5e1e7fec,0x0047c057893abded,0x001b430b85d51e16,0x00965c7b45640c3c,0x00487b2bb1162b97)}, + {FIELD_LITERAL(0x0099c73a311beec2,0x00a3eff38d8912ad,0x002efa9d1d7e8972,0x00f717ae1e14d126,0x002833f795850c8b,0x0066c12ad71486bd,0x00ae9889da4820eb,0x00d6044309555c08)}, + {FIELD_LITERAL(0x004b1c5283d15e41,0x00669d8ea308ff75,0x0004390233f762a1,0x00e1d67b83cb6cec,0x003eebaa964c78b1,0x006b0aff965eb664,0x00b313d4470bdc37,0x008814ffcb3cb9d8)}, + }}, {{ + {FIELD_LITERAL(0x009724b8ce68db70,0x007678b5ed006f3d,0x00bdf4b89c0abd73,0x00299748e04c7c6d,0x00ddd86492c3c977,0x00c5a7febfa30a99,0x00ed84715b4b02bb,0x00319568adf70486)}, + {FIELD_LITERAL(0x0070ff2d864de5bb,0x005a37eeb637ee95,0x0033741c258de160,0x00e6ca5cb1988f46,0x001ceabd92a24661,0x0030957bd500fe40,0x001c3362afe912c5,0x005187889f678bd2)}, + {FIELD_LITERAL(0x0086835fc62bbdc7,0x009c3516ca4910a1,0x00956c71f8d00783,0x0095c78fcf63235f,0x00fc7ff6ba05c222,0x00cdd8b3f8d74a52,0x00ac5ae16de8256e,0x00e9d4be8ed48624)}, + }}, {{ + {FIELD_LITERAL(0x00c0ce11405df2d8,0x004e3f37b293d7b6,0x002410172e1ac6db,0x00b8dbff4bf8143d,0x003a7b409d56eb66,0x003e0f6a0dfef9af,0x0081c4e4d3645be1,0x00ce76076b127623)}, + {FIELD_LITERAL(0x00f6ee0f98974239,0x0042d89af07d3a4f,0x00846b7fe84346b5,0x006a21fc6a8d39a1,0x00ac8bc2541ff2d9,0x006d4e2a77732732,0x009a39b694cc3f2f,0x0085c0aa2a404c8f)}, + {FIELD_LITERAL(0x00b261101a218548,0x00c1cae96424277b,0x00869da0a77dd268,0x00bc0b09f8ec83ea,0x00d61027f8e82ba9,0x00aa4c85999dce67,0x00eac3132b9f3fe1,0x00fb9b0cf1c695d2)}, + }}, {{ + {FIELD_LITERAL(0x0043079295512f0d,0x0046a009861758e0,0x003ee2842a807378,0x0034cc9d1298e4fa,0x009744eb4d31b3ee,0x00afacec96650cd0,0x00ac891b313761ae,0x00e864d6d26e708a)}, + {FIELD_LITERAL(0x00a84d7c8a23b491,0x0088e19aa868b27f,0x0005986d43e78ce9,0x00f28012f0606d28,0x0017ded7e10249b3,0x005ed4084b23af9b,0x00b9b0a940564472,0x00ad9056cceeb1f4)}, + {FIELD_LITERAL(0x00db91b357fe755e,0x00a1aa544b15359c,0x00af4931a0195574,0x007686124fe11aef,0x00d1ead3c7b9ef7e,0x00aaf5fc580f8c15,0x00e727be147ee1ec,0x003c61c1e1577b86)}, + }}, {{ + {FIELD_LITERAL(0x009d3fca983220cf,0x00cd11acbc853dc4,0x0017590409d27f1d,0x00d2176698082802,0x00fa01251b2838c8,0x00dd297a0d9b51c6,0x00d76c92c045820a,0x00534bc7c46c9033)}, + {FIELD_LITERAL(0x0080ed9bc9b07338,0x00fceac7745d2652,0x008a9d55f5f2cc69,0x0096ce72df301ac5,0x00f53232e7974d87,0x0071728c7ae73947,0x0090507602570778,0x00cb81cfd883b1b2)}, + {FIELD_LITERAL(0x005011aadea373da,0x003a8578ec896034,0x00f20a6535fa6d71,0x005152d31e5a87cf,0x002bac1c8e68ca31,0x00b0e323db4c1381,0x00f1d596b7d5ae25,0x00eae458097cb4e0)}, + }}, {{ + {FIELD_LITERAL(0x00920ac80f9b0d21,0x00f80f7f73401246,0x0086d37849b557d6,0x0002bd4b317b752e,0x00b26463993a42bb,0x002070422a73b129,0x00341acaa0380cb3,0x00541914dd66a1b2)}, + {FIELD_LITERAL(0x00c1513cd66abe8c,0x000139e01118944d,0x0064abbcb8080bbb,0x00b3b08202473142,0x00c629ef25da2403,0x00f0aec3310d9b7f,0x0050b2227472d8cd,0x00f6c8a922d41fb4)}, + {FIELD_LITERAL(0x001075ccf26b7b1f,0x00bb6bb213170433,0x00e9491ad262da79,0x009ef4f48d2d384c,0x008992770766f09d,0x001584396b6b1101,0x00af3f8676c9feef,0x0024603c40269118)}, + }}, {{ + {FIELD_LITERAL(0x009dd7b31319527c,0x001e7ac948d873a9,0x00fa54b46ef9673a,0x0066efb8d5b02fe6,0x00754b1d3928aeae,0x0004262ac72a6f6b,0x0079b7d49a6eb026,0x003126a753540102)}, + {FIELD_LITERAL(0x009666e24f693947,0x00f714311269d45f,0x0010ffac1d0c851c,0x0066e80c37363497,0x00f1f4ad010c60b0,0x0015c87408470ff7,0x00651d5e9c7766a4,0x008138819d7116de)}, + {FIELD_LITERAL(0x003934b11c57253b,0x00ef308edf21f46e,0x00e54e99c7a16198,0x0080d57135764e63,0x00751c27b946bc24,0x00dd389ce4e9e129,0x00a1a2bfd1cd84dc,0x002fae73e5149b32)}, + }}, {{ + {FIELD_LITERAL(0x00911657dffb4cdd,0x00c100b7cc553d06,0x00449d075ec467cc,0x007062100bc64e70,0x0043cf86f7bd21e7,0x00f401dc4b797dea,0x005224afb2f62e65,0x00d1ede3fb5a42be)}, + {FIELD_LITERAL(0x00f2ba36a41aa144,0x00a0c22d946ee18f,0x008aae8ef9a14f99,0x00eef4d79b19bb36,0x008e75ce3d27b1fc,0x00a65daa03b29a27,0x00d9cc83684eb145,0x009e1ed80cc2ed74)}, + {FIELD_LITERAL(0x00bed953d1997988,0x00b93ed175a24128,0x00871c5963fb6365,0x00ca2df20014a787,0x00f5d9c1d0b34322,0x00f6f5942818db0a,0x004cc091f49c9906,0x00e8a188a60bff9f)}, + }}, {{ + {FIELD_LITERAL(0x0032c7762032fae8,0x00e4087232e0bc21,0x00f767344b6e8d85,0x00bbf369b76c2aa2,0x008a1f46c6e1570c,0x001368cd9780369f,0x007359a39d079430,0x0003646512921434)}, + {FIELD_LITERAL(0x007c4b47ca7c73e7,0x005396221039734b,0x008b64ddf0e45d7e,0x00bfad5af285e6c2,0x008ec711c5b1a1a8,0x00cf663301237f98,0x00917ee3f1655126,0x004152f337efedd8)}, + {FIELD_LITERAL(0x0007c7edc9305daa,0x000a6664f273701c,0x00f6e78795e200b1,0x005d05b9ecd2473e,0x0014f5f17c865786,0x00c7fd2d166fa995,0x004939a2d8eb80e0,0x002244ba0942c199)}, + }}, {{ + {FIELD_LITERAL(0x00321e767f0262cf,0x002e57d776caf68e,0x00bf2c94814f0437,0x00c339196acd622f,0x001db4cce71e2770,0x001ded5ddba6eee2,0x0078608ab1554c8d,0x00067fe0ab76365b)}, + {FIELD_LITERAL(0x00f09758e11e3985,0x00169efdbd64fad3,0x00e8889b7d6dacd6,0x0035cdd58ea88209,0x00bcda47586d7f49,0x003cdddcb2879088,0x0016da70187e954b,0x009556ea2e92aacd)}, + {FIELD_LITERAL(0x008cab16bd1ff897,0x00b389972cdf753f,0x00ea8ed1e46dfdc0,0x004fe7ef94c589f4,0x002b8ae9b805ecf3,0x0025c08d892874a5,0x0023938e98d44c4c,0x00f759134cabf69c)}, + }}, {{ + {FIELD_LITERAL(0x006c2a84678e4b3b,0x007a194aacd1868f,0x00ed0225af424761,0x00da0a6f293c64b8,0x001062ac5c6a7a18,0x0030f5775a8aeef4,0x0002acaad76b7af0,0x00410b8fd63a579f)}, + {FIELD_LITERAL(0x001ec59db3d9590e,0x001e9e3f1c3f182d,0x0045a9c3ec2cab14,0x0008198572aeb673,0x00773b74068bd167,0x0012535eaa395434,0x0044dba9e3bbb74a,0x002fba4d3c74bd0e)}, + {FIELD_LITERAL(0x0042bf08fe66922c,0x003318b8fbb49e8c,0x00d75946004aa14c,0x00f601586b42bf1c,0x00c74cf1d912fe66,0x00abcb36974b30ad,0x007eb78720c9d2b8,0x009f54ab7bd4df85)}, + }}, {{ + {FIELD_LITERAL(0x00db9fc948f73826,0x00fa8b3746ed8ee9,0x00132cb65aafbeb2,0x00c36ff3fe7925b8,0x00837daed353d2fe,0x00ec661be0667cf4,0x005beb8ed2e90204,0x00d77dd69e564967)}, + {FIELD_LITERAL(0x0042e6268b861751,0x0008dd0469500c16,0x00b51b57c338a3fd,0x00cc4497d85cff6b,0x002f13d6b57c34a4,0x0083652eaf301105,0x00cc344294cc93a8,0x0060f4d02810e270)}, + {FIELD_LITERAL(0x00a8954363cd518b,0x00ad171124bccb7b,0x0065f46a4adaae00,0x001b1a5b2a96e500,0x0043fe24f8233285,0x0066996d8ae1f2c3,0x00c530f3264169f9,0x00c0f92d07cf6a57)}, + }}, {{ + {FIELD_LITERAL(0x0036a55c6815d943,0x008c8d1def993db3,0x002e0e1e8ff7318f,0x00d883a4b92db00a,0x002f5e781ae33906,0x001a72adb235c06d,0x00f2e59e736e9caa,0x001a4b58e3031914)}, + {FIELD_LITERAL(0x00d73bfae5e00844,0x00bf459766fb5f52,0x0061b4f5a5313cde,0x004392d4c3b95514,0x000d3551b1077523,0x0000998840ee5d71,0x006de6e340448b7b,0x00251aa504875d6e)}, + {FIELD_LITERAL(0x003bf343427ac342,0x00adc0a78642b8c5,0x0003b893175a8314,0x0061a34ade5703bc,0x00ea3ea8bb71d632,0x00be0df9a1f198c2,0x0046dd8e7c1635fb,0x00f1523fdd25d5e5)}, + }}, {{ + {FIELD_LITERAL(0x00633f63fc9dd406,0x00e713ff80e04a43,0x0060c6e970f2d621,0x00a57cd7f0df1891,0x00f2406a550650bb,0x00b064290efdc684,0x001eab0144d17916,0x00cd15f863c293ab)}, + {FIELD_LITERAL(0x0029cec55273f70d,0x007044ee275c6340,0x0040f637a93015e2,0x00338bb78db5aae9,0x001491b2a6132147,0x00a125d6cfe6bde3,0x005f7ac561ba8669,0x001d5eaea3fbaacf)}, + {FIELD_LITERAL(0x00054e9635e3be31,0x000e43f31e2872be,0x00d05b1c9e339841,0x006fac50bd81fd98,0x00cdc7852eaebb09,0x004ff519b061991b,0x009099e8107d4c85,0x00273e24c36a4a61)}, + }}, {{ + {FIELD_LITERAL(0x00070b4441ef2c46,0x00efa5b02801a109,0x00bf0b8c3ee64adf,0x008a67e0b3452e98,0x001916b1f2fa7a74,0x00d781a78ff6cdc3,0x008682ce57e5c919,0x00cc1109dd210da3)}, + {FIELD_LITERAL(0x00cae8aaff388663,0x005e983a35dda1c7,0x007ab1030d8e37f4,0x00e48940f5d032fe,0x006a36f9ef30b331,0x009be6f03958c757,0x0086231ceba91400,0x008bd0f7b823e7aa)}, + {FIELD_LITERAL(0x00cf881ebef5a45a,0x004ebea78e7c6f2c,0x0090da9209cf26a0,0x00de2b2e4c775b84,0x0071d6031c3c15ae,0x00d9e927ef177d70,0x00894ee8c23896fd,0x00e3b3b401e41aad)}, + }}, {{ + {FIELD_LITERAL(0x00204fef26864170,0x00819269c5dee0f8,0x00bfb4713ec97966,0x0026339a6f34df78,0x001f26e64c761dc2,0x00effe3af313cb60,0x00e17b70138f601b,0x00f16e1ccd9ede5e)}, + {FIELD_LITERAL(0x005d9a8353fdb2db,0x0055cc2048c698f0,0x00f6c4ac89657218,0x00525034d73faeb2,0x00435776fbda3c7d,0x0070ea5312323cbc,0x007a105d44d069fb,0x006dbc8d6dc786aa)}, + {FIELD_LITERAL(0x0017cff19cd394ec,0x00fef7b810922587,0x00e6483970dff548,0x00ddf36ad6874264,0x00e61778523fcce2,0x0093a66c0c93b24a,0x00fd367114db7f86,0x007652d7ddce26dd)}, + }}, {{ + {FIELD_LITERAL(0x00d92ced7ba12843,0x00aea9c7771e86e7,0x0046639693354f7b,0x00a628dbb6a80c47,0x003a0b0507372953,0x00421113ab45c0d9,0x00e545f08362ab7a,0x0028ce087b4d6d96)}, + {FIELD_LITERAL(0x00a67ee7cf9f99eb,0x005713b275f2ff68,0x00f1d536a841513d,0x00823b59b024712e,0x009c46b9d0d38cec,0x00cdb1595aa2d7d4,0x008375b3423d9af8,0x000ab0b516d978f7)}, + {FIELD_LITERAL(0x00428dcb3c510b0f,0x00585607ea24bb4e,0x003736bf1603687a,0x00c47e568c4fe3c7,0x003cd00282848605,0x0043a487c3b91939,0x004ffc04e1095a06,0x00a4c989a3d4b918)}, + }}, {{ + {FIELD_LITERAL(0x00a8778d0e429f7a,0x004c02b059105a68,0x0016653b609da3ff,0x00d5107bd1a12d27,0x00b4708f9a771cab,0x00bb63b662033f69,0x0072f322240e7215,0x0019445b59c69222)}, + {FIELD_LITERAL(0x00cf4f6069a658e6,0x0053ca52859436a6,0x0064b994d7e3e117,0x00cb469b9a07f534,0x00cfb68f399e9d47,0x00f0dcb8dac1c6e7,0x00f2ab67f538b3a5,0x0055544f178ab975)}, + {FIELD_LITERAL(0x0099b7a2685d538c,0x00e2f1897b7c0018,0x003adac8ce48dae3,0x00089276d5c50c0c,0x00172fca07ad6717,0x00cb1a72f54069e5,0x004ee42f133545b3,0x00785f8651362f16)}, + }}, {{ + {FIELD_LITERAL(0x0049cbac38509e11,0x0015234505d42cdf,0x00794fb0b5840f1c,0x00496437344045a5,0x0031b6d944e4f9b0,0x00b207318ac1f5d8,0x0000c840da7f5c5d,0x00526f373a5c8814)}, + {FIELD_LITERAL(0x002c7b7742d1dfd9,0x002cabeb18623c01,0x00055f5e3e044446,0x006c20f3b4ef54ba,0x00c600141ec6b35f,0x00354f437f1a32a3,0x00bac4624a3520f9,0x00c483f734a90691)}, + {FIELD_LITERAL(0x0053a737d422918d,0x00f7fca1d8758625,0x00c360336dadb04c,0x00f38e3d9158a1b8,0x0069ce3b418e84c6,0x005d1697eca16ead,0x00f8bd6a35ece13d,0x007885dfc2b5afea)}, + }}, {{ + {FIELD_LITERAL(0x00c3617ae260776c,0x00b20dc3e96922d7,0x00a1a7802246706a,0x00ca6505a5240244,0x002246b62d919782,0x001439102d7aa9b3,0x00e8af1139e6422c,0x00c888d1b52f2b05)}, + {FIELD_LITERAL(0x005b67690ffd41d9,0x005294f28df516f9,0x00a879272412fcb9,0x00098b629a6d1c8d,0x00fabd3c8050865a,0x00cd7e5b0a3879c5,0x00153238210f3423,0x00357cac101e9f42)}, + {FIELD_LITERAL(0x008917b454444fb7,0x00f59247c97e441b,0x00a6200a6815152d,0x0009a4228601d254,0x001c0360559bd374,0x007563362039cb36,0x00bd75b48d74e32b,0x0017f515ac3499e8)}, + }}, {{ + {FIELD_LITERAL(0x001532a7ffe41c5a,0x00eb1edce358d6bf,0x00ddbacc7b678a7b,0x008a7b70f3c841a3,0x00f1923bf27d3f4c,0x000b2713ed8f7873,0x00aaf67e29047902,0x0044994a70b3976d)}, + {FIELD_LITERAL(0x00d54e802082d42c,0x00a55aa0dce7cc6c,0x006477b96073f146,0x0082efe4ceb43594,0x00a922bcba026845,0x0077f19d1ab75182,0x00c2bb2737846e59,0x0004d7eec791dd33)}, + {FIELD_LITERAL(0x0044588d1a81d680,0x00b0a9097208e4f8,0x00212605350dc57e,0x0028717cd2871123,0x00fb083c100fd979,0x0045a056ce063fdf,0x00a5d604b4dd6a41,0x001dabc08ba4e236)}, + }}, {{ + {FIELD_LITERAL(0x00c4887198d7a7fa,0x00244f98fb45784a,0x0045911e15a15d01,0x001d323d374c0966,0x00967c3915196562,0x0039373abd2f3c67,0x000d2c5614312423,0x0041cf2215442ce3)}, + {FIELD_LITERAL(0x008ede889ada7f06,0x001611e91de2e135,0x00fdb9a458a471b9,0x00563484e03710d1,0x0031cc81925e3070,0x0062c97b3af80005,0x00fa733eea28edeb,0x00e82457e1ebbc88)}, + {FIELD_LITERAL(0x006a0df5fe9b6f59,0x00a0d4ff46040d92,0x004a7cedb6f93250,0x00d1df8855b8c357,0x00e73a46086fd058,0x0048fb0add6dfe59,0x001e03a28f1b4e3d,0x00a871c993308d76)}, + }}, {{ + {FIELD_LITERAL(0x0030dbb2d1766ec8,0x00586c0ad138555e,0x00d1a34f9e91c77c,0x0063408ad0e89014,0x00d61231b05f6f5b,0x0009abf569f5fd8a,0x00aec67a110f1c43,0x0031d1a790938dd7)}, + {FIELD_LITERAL(0x006cded841e2a862,0x00198d60af0ab6fb,0x0018f09db809e750,0x004e6ac676016263,0x00eafcd1620969cb,0x002c9784ca34917d,0x0054f00079796de7,0x00d9fab5c5972204)}, + {FIELD_LITERAL(0x004bd0fee2438a83,0x00b571e62b0f83bd,0x0059287d7ce74800,0x00fb3631b645c3f0,0x00a018e977f78494,0x0091e27065c27b12,0x007696c1817165e0,0x008c40be7c45ba3a)}, + }}, {{ + {FIELD_LITERAL(0x00a0f326327cb684,0x001c7d0f672680ff,0x008c1c81ffb112d1,0x00f8f801674eddc8,0x00e926d5d48c2a9d,0x005bd6d954c6fe9a,0x004c6b24b4e33703,0x00d05eb5c09105cc)}, + {FIELD_LITERAL(0x00d61731caacf2cf,0x002df0c7609e01c5,0x00306172208b1e2b,0x00b413fe4fb2b686,0x00826d360902a221,0x003f8d056e67e7f7,0x0065025b0175e989,0x00369add117865eb)}, + {FIELD_LITERAL(0x00aaf895aec2fa11,0x000f892bc313eb52,0x005b1c794dad050b,0x003f8ec4864cec14,0x00af81058d0b90e5,0x00ebe43e183997bb,0x00a9d610f9f3e615,0x007acd8eec2e88d3)}, + }}, {{ + {FIELD_LITERAL(0x0049b2fab13812a3,0x00846db32cd60431,0x000177fa578c8d6c,0x00047d0e2ad4bc51,0x00b158ba38d1e588,0x006a45daad79e3f3,0x000997b93cab887b,0x00c47ea42fa23dc3)}, + {FIELD_LITERAL(0x0012b6fef7aeb1ca,0x009412768194b6a7,0x00ff0d351f23ab93,0x007e8a14c1aff71b,0x006c1c0170c512bc,0x0016243ea02ab2e5,0x007bb6865b303f3e,0x0015ce6b29b159f4)}, + {FIELD_LITERAL(0x009961cd02e68108,0x00e2035d3a1d0836,0x005d51f69b5e1a1d,0x004bccb4ea36edcd,0x0069be6a7aeef268,0x0063f4dd9de8d5a7,0x006283783092ca35,0x0075a31af2c35409)}, + }}, {{ + {FIELD_LITERAL(0x00c412365162e8cf,0x00012283fb34388a,0x003e6543babf39e2,0x00eead6b3a804978,0x0099c0314e8b326f,0x00e98e0a8d477a4f,0x00d2eb96b127a687,0x00ed8d7df87571bb)}, + {FIELD_LITERAL(0x00777463e308cacf,0x00c8acb93950132d,0x00ebddbf4ca48b2c,0x0026ad7ca0795a0a,0x00f99a3d9a715064,0x000d60bcf9d4dfcc,0x005e65a73a437a06,0x0019d536a8db56c8)}, + {FIELD_LITERAL(0x00192d7dd558d135,0x0027cd6a8323ffa7,0x00239f1a412dc1e7,0x0046b4b3be74fc5c,0x0020c47a2bef5bce,0x00aa17e48f43862b,0x00f7e26c96342e5f,0x0008011c530f39a9)}, + }}, {{ + {FIELD_LITERAL(0x00aad4ac569bf0f1,0x00a67adc90b27740,0x0048551369a5751a,0x0031252584a3306a,0x0084e15df770e6fc,0x00d7bba1c74b5805,0x00a80ef223af1012,0x0089c85ceb843a34)}, + {FIELD_LITERAL(0x00c4545be4a54004,0x0099e11f60357e6c,0x001f3936d19515a6,0x007793df84341a6e,0x0051061886717ffa,0x00e9b0a660b28f85,0x0044ea685892de0d,0x000257d2a1fda9d9)}, + {FIELD_LITERAL(0x007e8b01b24ac8a8,0x006cf3b0b5ca1337,0x00f1607d3e36a570,0x0039b7fab82991a1,0x00231777065840c5,0x00998e5afdd346f9,0x00b7dc3e64acc85f,0x00baacc748013ad6)}, + }}, {{ + {FIELD_LITERAL(0x008ea6a4177580bf,0x005fa1953e3f0378,0x005fe409ac74d614,0x00452327f477e047,0x00a4018507fb6073,0x007b6e71951caac8,0x0012b42ab8a6ce91,0x0080eca677294ab7)}, + {FIELD_LITERAL(0x00a53edc023ba69b,0x00c6afa83ddde2e8,0x00c3f638b307b14e,0x004a357a64414062,0x00e4d94d8b582dc9,0x001739caf71695b7,0x0012431b2ae28de1,0x003b6bc98682907c)}, + {FIELD_LITERAL(0x008a9a93be1f99d6,0x0079fa627cc699c8,0x00b0cfb134ba84c8,0x001c4b778249419a,0x00df4ab3d9c44f40,0x009f596e6c1a9e3c,0x001979c0df237316,0x00501e953a919b87)}, + }} +}; +const niels_t *curve448_wnaf_base = curve448_wnaf_base_table; diff --git a/crypto/ec/curve448/curve448utils.h b/crypto/ec/curve448/curve448utils.h new file mode 100644 index 00000000..9bf83799 --- /dev/null +++ b/crypto/ec/curve448/curve448utils.h @@ -0,0 +1,78 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ + +#ifndef HEADER_CURVE448UTILS_H +# define HEADER_CURVE448UTILS_H + +# include + +/* + * Internal word types. Somewhat tricky. This could be decided separately per + * platform. However, the structs do need to be all the same size and + * alignment on a given platform to support dynamic linking, since even if you + * header was built with eg arch_neon, you might end up linking a library built + * with arch_arm32. + */ +# ifndef C448_WORD_BITS +# if (defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16)) \ + && !defined(__sparc__) +# define C448_WORD_BITS 64 /* The number of bits in a word */ +# else +# define C448_WORD_BITS 32 /* The number of bits in a word */ +# endif +# endif + +# if C448_WORD_BITS == 64 +/* Word size for internal computations */ +typedef uint64_t c448_word_t; +/* Signed word size for internal computations */ +typedef int64_t c448_sword_t; +/* "Boolean" type, will be set to all-zero or all-one (i.e. -1u) */ +typedef uint64_t c448_bool_t; +/* Double-word size for internal computations */ +typedef __uint128_t c448_dword_t; +/* Signed double-word size for internal computations */ +typedef __int128_t c448_dsword_t; +# elif C448_WORD_BITS == 32 +/* Word size for internal computations */ +typedef uint32_t c448_word_t; +/* Signed word size for internal computations */ +typedef int32_t c448_sword_t; +/* "Boolean" type, will be set to all-zero or all-one (i.e. -1u) */ +typedef uint32_t c448_bool_t; +/* Double-word size for internal computations */ +typedef uint64_t c448_dword_t; +/* Signed double-word size for internal computations */ +typedef int64_t c448_dsword_t; +# else +# error "Only supporting C448_WORD_BITS = 32 or 64 for now" +# endif + +/* C448_TRUE = -1 so that C448_TRUE & x = x */ +# define C448_TRUE (0 - (c448_bool_t)1) + +/* C448_FALSE = 0 so that C448_FALSE & x = 0 */ +# define C448_FALSE 0 + +/* Another boolean type used to indicate success or failure. */ +typedef enum { + C448_SUCCESS = -1, /**< The operation succeeded. */ + C448_FAILURE = 0 /**< The operation failed. */ +} c448_error_t; + +/* Return success if x is true */ +static ossl_inline c448_error_t c448_succeed_if(c448_bool_t x) +{ + return (c448_error_t) x; +} + +#endif /* __C448_COMMON_H__ */ diff --git a/crypto/ec/curve448/ed448.h b/crypto/ec/curve448/ed448.h new file mode 100644 index 00000000..5fe939e8 --- /dev/null +++ b/crypto/ec/curve448/ed448.h @@ -0,0 +1,195 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2016 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ + +#ifndef HEADER_ED448_H +# define HEADER_ED448_H + +# include "point_448.h" + +/* Number of bytes in an EdDSA public key. */ +# define EDDSA_448_PUBLIC_BYTES 57 + +/* Number of bytes in an EdDSA private key. */ +# define EDDSA_448_PRIVATE_BYTES EDDSA_448_PUBLIC_BYTES + +/* Number of bytes in an EdDSA private key. */ +# define EDDSA_448_SIGNATURE_BYTES (EDDSA_448_PUBLIC_BYTES + \ + EDDSA_448_PRIVATE_BYTES) + +/* EdDSA encoding ratio. */ +# define C448_EDDSA_ENCODE_RATIO 4 + +/* EdDSA decoding ratio. */ +# define C448_EDDSA_DECODE_RATIO (4 / 4) + +/* + * EdDSA key generation. This function uses a different (non-Decaf) encoding. + * + * pubkey (out): The public key. + * privkey (in): The private key. + */ +c448_error_t c448_ed448_derive_public_key( + uint8_t pubkey [EDDSA_448_PUBLIC_BYTES], + const uint8_t privkey [EDDSA_448_PRIVATE_BYTES]); + +/* + * EdDSA signing. + * + * signature (out): The signature. + * privkey (in): The private key. + * pubkey (in): The public key. + * message (in): The message to sign. + * message_len (in): The length of the message. + * prehashed (in): Nonzero if the message is actually the hash of something + * you want to sign. + * context (in): A "context" for this signature of up to 255 bytes. + * context_len (in): Length of the context. + * + * For Ed25519, it is unsafe to use the same key for both prehashed and + * non-prehashed messages, at least without some very careful protocol-level + * disambiguation. For Ed448 it is safe. + */ +c448_error_t c448_ed448_sign( + uint8_t signature[EDDSA_448_SIGNATURE_BYTES], + const uint8_t privkey[EDDSA_448_PRIVATE_BYTES], + const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], + const uint8_t *message, size_t message_len, + uint8_t prehashed, const uint8_t *context, + size_t context_len); + +/* + * EdDSA signing with prehash. + * + * signature (out): The signature. + * privkey (in): The private key. + * pubkey (in): The public key. + * hash (in): The hash of the message. This object will not be modified by the + * call. + * context (in): A "context" for this signature of up to 255 bytes. Must be the + * same as what was used for the prehash. + * context_len (in): Length of the context. + * + * For Ed25519, it is unsafe to use the same key for both prehashed and + * non-prehashed messages, at least without some very careful protocol-level + * disambiguation. For Ed448 it is safe. + */ +c448_error_t c448_ed448_sign_prehash( + uint8_t signature[EDDSA_448_SIGNATURE_BYTES], + const uint8_t privkey[EDDSA_448_PRIVATE_BYTES], + const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], + const uint8_t hash[64], + const uint8_t *context, + size_t context_len); + +/* + * EdDSA signature verification. + * + * Uses the standard (i.e. less-strict) verification formula. + * + * signature (in): The signature. + * pubkey (in): The public key. + * message (in): The message to verify. + * message_len (in): The length of the message. + * prehashed (in): Nonzero if the message is actually the hash of something you + * want to verify. + * context (in): A "context" for this signature of up to 255 bytes. + * context_len (in): Length of the context. + * + * For Ed25519, it is unsafe to use the same key for both prehashed and + * non-prehashed messages, at least without some very careful protocol-level + * disambiguation. For Ed448 it is safe. + */ +c448_error_t c448_ed448_verify(const uint8_t + signature[EDDSA_448_SIGNATURE_BYTES], + const uint8_t + pubkey[EDDSA_448_PUBLIC_BYTES], + const uint8_t *message, size_t message_len, + uint8_t prehashed, const uint8_t *context, + uint8_t context_len); + +/* + * EdDSA signature verification. + * + * Uses the standard (i.e. less-strict) verification formula. + * + * signature (in): The signature. + * pubkey (in): The public key. + * hash (in): The hash of the message. This object will not be modified by the + * call. + * context (in): A "context" for this signature of up to 255 bytes. Must be the + * same as what was used for the prehash. + * context_len (in): Length of the context. + * + * For Ed25519, it is unsafe to use the same key for both prehashed and + * non-prehashed messages, at least without some very careful protocol-level + * disambiguation. For Ed448 it is safe. + */ +c448_error_t c448_ed448_verify_prehash( + const uint8_t signature[EDDSA_448_SIGNATURE_BYTES], + const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], + const uint8_t hash[64], + const uint8_t *context, + uint8_t context_len); + +/* + * EdDSA point encoding. Used internally, exposed externally. + * Multiplies by C448_EDDSA_ENCODE_RATIO first. + * + * The multiplication is required because the EdDSA encoding represents + * the cofactor information, but the Decaf encoding ignores it (which + * is the whole point). So if you decode from EdDSA and re-encode to + * EdDSA, the cofactor info must get cleared, because the intermediate + * representation doesn't track it. + * + * The way we handle this is to multiply by C448_EDDSA_DECODE_RATIO when + * decoding, and by C448_EDDSA_ENCODE_RATIO when encoding. The product of + * these ratios is always exactly the cofactor 4, so the cofactor ends up + * cleared one way or another. But exactly how that shakes out depends on the + * base points specified in RFC 8032. + * + * The upshot is that if you pass the Decaf/Ristretto base point to + * this function, you will get C448_EDDSA_ENCODE_RATIO times the + * EdDSA base point. + * + * enc (out): The encoded point. + * p (in): The point. + */ +void curve448_point_mul_by_ratio_and_encode_like_eddsa( + uint8_t enc [EDDSA_448_PUBLIC_BYTES], + const curve448_point_t p); + +/* + * EdDSA point decoding. Multiplies by C448_EDDSA_DECODE_RATIO, and + * ignores cofactor information. + * + * See notes on curve448_point_mul_by_ratio_and_encode_like_eddsa + * + * enc (out): The encoded point. + * p (in): The point. + */ +c448_error_t curve448_point_decode_like_eddsa_and_mul_by_ratio( + curve448_point_t p, + const uint8_t enc[EDDSA_448_PUBLIC_BYTES]); + +/* + * EdDSA to ECDH private key conversion + * Using the appropriate hash function, hash the EdDSA private key + * and keep only the lower bytes to get the ECDH private key + * + * x (out): The ECDH private key as in RFC7748 + * ed (in): The EdDSA private key + */ +c448_error_t c448_ed448_convert_private_key_to_x448( + uint8_t x[X448_PRIVATE_BYTES], + const uint8_t ed[EDDSA_448_PRIVATE_BYTES]); + +#endif /* HEADER_ED448_H */ diff --git a/crypto/ec/curve448/eddsa.c b/crypto/ec/curve448/eddsa.c new file mode 100644 index 00000000..d3188763 --- /dev/null +++ b/crypto/ec/curve448/eddsa.c @@ -0,0 +1,353 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2016 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ +#include +#include +#include +#include "curve448_lcl.h" +#include "word.h" +#include "ed448.h" +#include "internal/numbers.h" + +#define COFACTOR 4 + +static c448_error_t oneshot_hash(uint8_t *out, size_t outlen, + const uint8_t *in, size_t inlen) +{ + EVP_MD_CTX *hashctx = EVP_MD_CTX_new(); + + if (hashctx == NULL) + return C448_FAILURE; + + if (!EVP_DigestInit_ex(hashctx, EVP_shake256(), NULL) + || !EVP_DigestUpdate(hashctx, in, inlen) + || !EVP_DigestFinalXOF(hashctx, out, outlen)) { + EVP_MD_CTX_free(hashctx); + return C448_FAILURE; + } + + EVP_MD_CTX_free(hashctx); + return C448_SUCCESS; +} + +static void clamp(uint8_t secret_scalar_ser[EDDSA_448_PRIVATE_BYTES]) +{ + secret_scalar_ser[0] &= -COFACTOR; + secret_scalar_ser[EDDSA_448_PRIVATE_BYTES - 1] = 0; + secret_scalar_ser[EDDSA_448_PRIVATE_BYTES - 2] |= 0x80; +} + +static c448_error_t hash_init_with_dom(EVP_MD_CTX *hashctx, uint8_t prehashed, + uint8_t for_prehash, + const uint8_t *context, + size_t context_len) +{ + const char *dom_s = "SigEd448"; + uint8_t dom[2]; + + if (context_len > UINT8_MAX) + return C448_FAILURE; + + dom[0] = (uint8_t)(2 - (prehashed == 0 ? 1 : 0) + - (for_prehash == 0 ? 1 : 0)); + dom[1] = (uint8_t)context_len; + + if (!EVP_DigestInit_ex(hashctx, EVP_shake256(), NULL) + || !EVP_DigestUpdate(hashctx, dom_s, strlen(dom_s)) + || !EVP_DigestUpdate(hashctx, dom, sizeof(dom)) + || (context_len > 0 + && !EVP_DigestUpdate(hashctx, context, context_len))) + return C448_FAILURE; + + return C448_SUCCESS; +} + +/* In this file because it uses the hash */ +c448_error_t c448_ed448_convert_private_key_to_x448( + uint8_t x[X448_PRIVATE_BYTES], + const uint8_t ed [EDDSA_448_PRIVATE_BYTES]) +{ + /* pass the private key through oneshot_hash function */ + /* and keep the first X448_PRIVATE_BYTES bytes */ + return oneshot_hash(x, X448_PRIVATE_BYTES, ed, + EDDSA_448_PRIVATE_BYTES); +} + +c448_error_t c448_ed448_derive_public_key( + uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], + const uint8_t privkey[EDDSA_448_PRIVATE_BYTES]) +{ + /* only this much used for keygen */ + uint8_t secret_scalar_ser[EDDSA_448_PRIVATE_BYTES]; + curve448_scalar_t secret_scalar; + unsigned int c; + curve448_point_t p; + + if (!oneshot_hash(secret_scalar_ser, sizeof(secret_scalar_ser), privkey, + EDDSA_448_PRIVATE_BYTES)) + return C448_FAILURE; + + clamp(secret_scalar_ser); + + curve448_scalar_decode_long(secret_scalar, secret_scalar_ser, + sizeof(secret_scalar_ser)); + + /* + * Since we are going to mul_by_cofactor during encoding, divide by it + * here. However, the EdDSA base point is not the same as the decaf base + * point if the sigma isogeny is in use: the EdDSA base point is on + * Etwist_d/(1-d) and the decaf base point is on Etwist_d, and when + * converted it effectively picks up a factor of 2 from the isogenies. So + * we might start at 2 instead of 1. + */ + for (c = 1; c < C448_EDDSA_ENCODE_RATIO; c <<= 1) + curve448_scalar_halve(secret_scalar, secret_scalar); + + curve448_precomputed_scalarmul(p, curve448_precomputed_base, secret_scalar); + + curve448_point_mul_by_ratio_and_encode_like_eddsa(pubkey, p); + + /* Cleanup */ + curve448_scalar_destroy(secret_scalar); + curve448_point_destroy(p); + OPENSSL_cleanse(secret_scalar_ser, sizeof(secret_scalar_ser)); + + return C448_SUCCESS; +} + +c448_error_t c448_ed448_sign( + uint8_t signature[EDDSA_448_SIGNATURE_BYTES], + const uint8_t privkey[EDDSA_448_PRIVATE_BYTES], + const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], + const uint8_t *message, size_t message_len, + uint8_t prehashed, const uint8_t *context, + size_t context_len) +{ + curve448_scalar_t secret_scalar; + EVP_MD_CTX *hashctx = EVP_MD_CTX_new(); + c448_error_t ret = C448_FAILURE; + curve448_scalar_t nonce_scalar; + uint8_t nonce_point[EDDSA_448_PUBLIC_BYTES] = { 0 }; + unsigned int c; + curve448_scalar_t challenge_scalar; + + if (hashctx == NULL) + return C448_FAILURE; + + { + /* + * Schedule the secret key, First EDDSA_448_PRIVATE_BYTES is serialised + * secret scalar,next EDDSA_448_PRIVATE_BYTES bytes is the seed. + */ + uint8_t expanded[EDDSA_448_PRIVATE_BYTES * 2]; + + if (!oneshot_hash(expanded, sizeof(expanded), privkey, + EDDSA_448_PRIVATE_BYTES)) + goto err; + clamp(expanded); + curve448_scalar_decode_long(secret_scalar, expanded, + EDDSA_448_PRIVATE_BYTES); + + /* Hash to create the nonce */ + if (!hash_init_with_dom(hashctx, prehashed, 0, context, context_len) + || !EVP_DigestUpdate(hashctx, + expanded + EDDSA_448_PRIVATE_BYTES, + EDDSA_448_PRIVATE_BYTES) + || (message_len > 0 + && !EVP_DigestUpdate(hashctx, message, message_len))) { + OPENSSL_cleanse(expanded, sizeof(expanded)); + goto err; + } + OPENSSL_cleanse(expanded, sizeof(expanded)); + } + + /* Decode the nonce */ + { + uint8_t nonce[2 * EDDSA_448_PRIVATE_BYTES]; + + if (!EVP_DigestFinalXOF(hashctx, nonce, sizeof(nonce))) + goto err; + curve448_scalar_decode_long(nonce_scalar, nonce, sizeof(nonce)); + OPENSSL_cleanse(nonce, sizeof(nonce)); + } + + { + /* Scalarmul to create the nonce-point */ + curve448_scalar_t nonce_scalar_2; + curve448_point_t p; + + curve448_scalar_halve(nonce_scalar_2, nonce_scalar); + for (c = 2; c < C448_EDDSA_ENCODE_RATIO; c <<= 1) + curve448_scalar_halve(nonce_scalar_2, nonce_scalar_2); + + curve448_precomputed_scalarmul(p, curve448_precomputed_base, + nonce_scalar_2); + curve448_point_mul_by_ratio_and_encode_like_eddsa(nonce_point, p); + curve448_point_destroy(p); + curve448_scalar_destroy(nonce_scalar_2); + } + + { + uint8_t challenge[2 * EDDSA_448_PRIVATE_BYTES]; + + /* Compute the challenge */ + if (!hash_init_with_dom(hashctx, prehashed, 0, context, context_len) + || !EVP_DigestUpdate(hashctx, nonce_point, sizeof(nonce_point)) + || !EVP_DigestUpdate(hashctx, pubkey, EDDSA_448_PUBLIC_BYTES) + || (message_len > 0 + && !EVP_DigestUpdate(hashctx, message, message_len)) + || !EVP_DigestFinalXOF(hashctx, challenge, sizeof(challenge))) + goto err; + + curve448_scalar_decode_long(challenge_scalar, challenge, + sizeof(challenge)); + OPENSSL_cleanse(challenge, sizeof(challenge)); + } + + curve448_scalar_mul(challenge_scalar, challenge_scalar, secret_scalar); + curve448_scalar_add(challenge_scalar, challenge_scalar, nonce_scalar); + + OPENSSL_cleanse(signature, EDDSA_448_SIGNATURE_BYTES); + memcpy(signature, nonce_point, sizeof(nonce_point)); + curve448_scalar_encode(&signature[EDDSA_448_PUBLIC_BYTES], + challenge_scalar); + + curve448_scalar_destroy(secret_scalar); + curve448_scalar_destroy(nonce_scalar); + curve448_scalar_destroy(challenge_scalar); + + ret = C448_SUCCESS; + err: + EVP_MD_CTX_free(hashctx); + return ret; +} + +c448_error_t c448_ed448_sign_prehash( + uint8_t signature[EDDSA_448_SIGNATURE_BYTES], + const uint8_t privkey[EDDSA_448_PRIVATE_BYTES], + const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], + const uint8_t hash[64], const uint8_t *context, + size_t context_len) +{ + return c448_ed448_sign(signature, privkey, pubkey, hash, 64, 1, context, + context_len); +} + +c448_error_t c448_ed448_verify( + const uint8_t signature[EDDSA_448_SIGNATURE_BYTES], + const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], + const uint8_t *message, size_t message_len, + uint8_t prehashed, const uint8_t *context, + uint8_t context_len) +{ + curve448_point_t pk_point, r_point; + c448_error_t error = + curve448_point_decode_like_eddsa_and_mul_by_ratio(pk_point, pubkey); + curve448_scalar_t challenge_scalar; + curve448_scalar_t response_scalar; + unsigned int c; + + if (C448_SUCCESS != error) + return error; + + error = + curve448_point_decode_like_eddsa_and_mul_by_ratio(r_point, signature); + if (C448_SUCCESS != error) + return error; + + { + /* Compute the challenge */ + EVP_MD_CTX *hashctx = EVP_MD_CTX_new(); + uint8_t challenge[2 * EDDSA_448_PRIVATE_BYTES]; + + if (hashctx == NULL + || !hash_init_with_dom(hashctx, prehashed, 0, context, + context_len) + || !EVP_DigestUpdate(hashctx, signature, EDDSA_448_PUBLIC_BYTES) + || !EVP_DigestUpdate(hashctx, pubkey, EDDSA_448_PUBLIC_BYTES) + || !EVP_DigestUpdate(hashctx, message, message_len) + || !EVP_DigestFinalXOF(hashctx, challenge, sizeof(challenge))) { + EVP_MD_CTX_free(hashctx); + return C448_FAILURE; + } + + EVP_MD_CTX_free(hashctx); + curve448_scalar_decode_long(challenge_scalar, challenge, + sizeof(challenge)); + OPENSSL_cleanse(challenge, sizeof(challenge)); + } + curve448_scalar_sub(challenge_scalar, curve448_scalar_zero, + challenge_scalar); + + curve448_scalar_decode_long(response_scalar, + &signature[EDDSA_448_PUBLIC_BYTES], + EDDSA_448_PRIVATE_BYTES); + + for (c = 1; c < C448_EDDSA_DECODE_RATIO; c <<= 1) + curve448_scalar_add(response_scalar, response_scalar, response_scalar); + + /* pk_point = -c(x(P)) + (cx + k)G = kG */ + curve448_base_double_scalarmul_non_secret(pk_point, + response_scalar, + pk_point, challenge_scalar); + return c448_succeed_if(curve448_point_eq(pk_point, r_point)); +} + +c448_error_t c448_ed448_verify_prehash( + const uint8_t signature[EDDSA_448_SIGNATURE_BYTES], + const uint8_t pubkey[EDDSA_448_PUBLIC_BYTES], + const uint8_t hash[64], const uint8_t *context, + uint8_t context_len) +{ + return c448_ed448_verify(signature, pubkey, hash, 64, 1, context, + context_len); +} + +int ED448_sign(uint8_t *out_sig, const uint8_t *message, size_t message_len, + const uint8_t public_key[57], const uint8_t private_key[57], + const uint8_t *context, size_t context_len) +{ + return c448_ed448_sign(out_sig, private_key, public_key, message, + message_len, 0, context, context_len) + == C448_SUCCESS; +} + +int ED448_verify(const uint8_t *message, size_t message_len, + const uint8_t signature[114], const uint8_t public_key[57], + const uint8_t *context, size_t context_len) +{ + return c448_ed448_verify(signature, public_key, message, message_len, 0, + context, (uint8_t)context_len) == C448_SUCCESS; +} + +int ED448ph_sign(uint8_t *out_sig, const uint8_t hash[64], + const uint8_t public_key[57], const uint8_t private_key[57], + const uint8_t *context, size_t context_len) +{ + return c448_ed448_sign_prehash(out_sig, private_key, public_key, hash, + context, context_len) == C448_SUCCESS; + +} + +int ED448ph_verify(const uint8_t hash[64], const uint8_t signature[114], + const uint8_t public_key[57], const uint8_t *context, + size_t context_len) +{ + return c448_ed448_verify_prehash(signature, public_key, hash, context, + (uint8_t)context_len) == C448_SUCCESS; +} + +int ED448_public_from_private(uint8_t out_public_key[57], + const uint8_t private_key[57]) +{ + return c448_ed448_derive_public_key(out_public_key, private_key) + == C448_SUCCESS; +} diff --git a/crypto/ec/curve448/f_generic.c b/crypto/ec/curve448/f_generic.c new file mode 100644 index 00000000..6babea6e --- /dev/null +++ b/crypto/ec/curve448/f_generic.c @@ -0,0 +1,204 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2016 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ +#include "field.h" + +static const gf MODULUS = { + FIELD_LITERAL(0xffffffffffffff, 0xffffffffffffff, 0xffffffffffffff, + 0xffffffffffffff, 0xfffffffffffffe, 0xffffffffffffff, + 0xffffffffffffff, 0xffffffffffffff) +}; + +/* Serialize to wire format. */ +void gf_serialize(uint8_t serial[SER_BYTES], const gf x, int with_hibit) +{ + unsigned int j = 0, fill = 0; + dword_t buffer = 0; + int i; + gf red; + + gf_copy(red, x); + gf_strong_reduce(red); + if (!with_hibit) + assert(gf_hibit(red) == 0); + + for (i = 0; i < (with_hibit ? X_SER_BYTES : SER_BYTES); i++) { + if (fill < 8 && j < NLIMBS) { + buffer |= ((dword_t) red->limb[LIMBPERM(j)]) << fill; + fill += LIMB_PLACE_VALUE(LIMBPERM(j)); + j++; + } + serial[i] = (uint8_t)buffer; + fill -= 8; + buffer >>= 8; + } +} + +/* Return high bit of x = low bit of 2x mod p */ +mask_t gf_hibit(const gf x) +{ + gf y; + + gf_add(y, x, x); + gf_strong_reduce(y); + return 0 - (y->limb[0] & 1); +} + +/* Return high bit of x = low bit of 2x mod p */ +mask_t gf_lobit(const gf x) +{ + gf y; + + gf_copy(y, x); + gf_strong_reduce(y); + return 0 - (y->limb[0] & 1); +} + +/* Deserialize from wire format; return -1 on success and 0 on failure. */ +mask_t gf_deserialize(gf x, const uint8_t serial[SER_BYTES], int with_hibit, + uint8_t hi_nmask) +{ + unsigned int j = 0, fill = 0; + dword_t buffer = 0; + dsword_t scarry = 0; + const unsigned nbytes = with_hibit ? X_SER_BYTES : SER_BYTES; + unsigned int i; + mask_t succ; + + for (i = 0; i < NLIMBS; i++) { + while (fill < LIMB_PLACE_VALUE(LIMBPERM(i)) && j < nbytes) { + uint8_t sj; + + sj = serial[j]; + if (j == nbytes - 1) + sj &= ~hi_nmask; + buffer |= ((dword_t) sj) << fill; + fill += 8; + j++; + } + x->limb[LIMBPERM(i)] = (word_t) + ((i < NLIMBS - 1) ? buffer & LIMB_MASK(LIMBPERM(i)) : buffer); + fill -= LIMB_PLACE_VALUE(LIMBPERM(i)); + buffer >>= LIMB_PLACE_VALUE(LIMBPERM(i)); + scarry = + (scarry + x->limb[LIMBPERM(i)] - + MODULUS->limb[LIMBPERM(i)]) >> (8 * sizeof(word_t)); + } + succ = with_hibit ? 0 - (mask_t) 1 : ~gf_hibit(x); + return succ & word_is_zero((word_t)buffer) & ~word_is_zero((word_t)scarry); +} + +/* Reduce to canonical form. */ +void gf_strong_reduce(gf a) +{ + dsword_t scarry; + word_t scarry_0; + dword_t carry = 0; + unsigned int i; + + /* first, clear high */ + gf_weak_reduce(a); /* Determined to have negligible perf impact. */ + + /* now the total is less than 2p */ + + /* compute total_value - p. No need to reduce mod p. */ + scarry = 0; + for (i = 0; i < NLIMBS; i++) { + scarry = scarry + a->limb[LIMBPERM(i)] - MODULUS->limb[LIMBPERM(i)]; + a->limb[LIMBPERM(i)] = scarry & LIMB_MASK(LIMBPERM(i)); + scarry >>= LIMB_PLACE_VALUE(LIMBPERM(i)); + } + + /* + * uncommon case: it was >= p, so now scarry = 0 and this = x common case: + * it was < p, so now scarry = -1 and this = x - p + 2^255 so let's add + * back in p. will carry back off the top for 2^255. + */ + assert(word_is_zero(scarry) | word_is_zero(scarry + 1)); + + scarry_0 = (word_t)scarry; + + /* add it back */ + for (i = 0; i < NLIMBS; i++) { + carry = + carry + a->limb[LIMBPERM(i)] + + (scarry_0 & MODULUS->limb[LIMBPERM(i)]); + a->limb[LIMBPERM(i)] = carry & LIMB_MASK(LIMBPERM(i)); + carry >>= LIMB_PLACE_VALUE(LIMBPERM(i)); + } + + assert(word_is_zero(carry + scarry_0)); +} + +/* Subtract two gf elements d=a-b */ +void gf_sub(gf d, const gf a, const gf b) +{ + gf_sub_RAW(d, a, b); + gf_bias(d, 2); + gf_weak_reduce(d); +} + +/* Add two field elements d = a+b */ +void gf_add(gf d, const gf a, const gf b) +{ + gf_add_RAW(d, a, b); + gf_weak_reduce(d); +} + +/* Compare a==b */ +mask_t gf_eq(const gf a, const gf b) +{ + gf c; + mask_t ret = 0; + unsigned int i; + + gf_sub(c, a, b); + gf_strong_reduce(c); + + for (i = 0; i < NLIMBS; i++) + ret |= c->limb[LIMBPERM(i)]; + + return word_is_zero(ret); +} + +mask_t gf_isr(gf a, const gf x) +{ + gf L0, L1, L2; + + gf_sqr(L1, x); + gf_mul(L2, x, L1); + gf_sqr(L1, L2); + gf_mul(L2, x, L1); + gf_sqrn(L1, L2, 3); + gf_mul(L0, L2, L1); + gf_sqrn(L1, L0, 3); + gf_mul(L0, L2, L1); + gf_sqrn(L2, L0, 9); + gf_mul(L1, L0, L2); + gf_sqr(L0, L1); + gf_mul(L2, x, L0); + gf_sqrn(L0, L2, 18); + gf_mul(L2, L1, L0); + gf_sqrn(L0, L2, 37); + gf_mul(L1, L2, L0); + gf_sqrn(L0, L1, 37); + gf_mul(L1, L2, L0); + gf_sqrn(L0, L1, 111); + gf_mul(L2, L1, L0); + gf_sqr(L0, L2); + gf_mul(L1, x, L0); + gf_sqrn(L0, L1, 223); + gf_mul(L1, L2, L0); + gf_sqr(L2, L1); + gf_mul(L0, L2, x); + gf_copy(a, L1); + return gf_eq(L0, ONE); +} diff --git a/crypto/ec/curve448/field.h b/crypto/ec/curve448/field.h new file mode 100644 index 00000000..c3bad40e --- /dev/null +++ b/crypto/ec/curve448/field.h @@ -0,0 +1,168 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2014 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ + +#ifndef HEADER_FIELD_H +# define HEADER_FIELD_H + +# include "internal/constant_time_locl.h" +# include +# include +# include "word.h" + +# define NLIMBS (64/sizeof(word_t)) +# define X_SER_BYTES 56 +# define SER_BYTES 56 + +# if defined(__GNUC__) || defined(__clang__) +# define INLINE_UNUSED __inline__ __attribute__((__unused__,__always_inline__)) +# define RESTRICT __restrict__ +# define ALIGNED __attribute__((__aligned__(32))) +# else +# define INLINE_UNUSED ossl_inline +# define RESTRICT +# define ALIGNED +# endif + +typedef struct gf_s { + word_t limb[NLIMBS]; +} ALIGNED gf_s, gf[1]; + +/* RFC 7748 support */ +# define X_PUBLIC_BYTES X_SER_BYTES +# define X_PRIVATE_BYTES X_PUBLIC_BYTES +# define X_PRIVATE_BITS 448 + +static INLINE_UNUSED void gf_copy(gf out, const gf a) +{ + *out = *a; +} + +static INLINE_UNUSED void gf_add_RAW(gf out, const gf a, const gf b); +static INLINE_UNUSED void gf_sub_RAW(gf out, const gf a, const gf b); +static INLINE_UNUSED void gf_bias(gf inout, int amount); +static INLINE_UNUSED void gf_weak_reduce(gf inout); + +void gf_strong_reduce(gf inout); +void gf_add(gf out, const gf a, const gf b); +void gf_sub(gf out, const gf a, const gf b); +void gf_mul(gf_s * RESTRICT out, const gf a, const gf b); +void gf_mulw_unsigned(gf_s * RESTRICT out, const gf a, uint32_t b); +void gf_sqr(gf_s * RESTRICT out, const gf a); +mask_t gf_isr(gf a, const gf x); /** a^2 x = 1, QNR, or 0 if x=0. Return true if successful */ +mask_t gf_eq(const gf x, const gf y); +mask_t gf_lobit(const gf x); +mask_t gf_hibit(const gf x); + +void gf_serialize(uint8_t *serial, const gf x, int with_highbit); +mask_t gf_deserialize(gf x, const uint8_t serial[SER_BYTES], int with_hibit, + uint8_t hi_nmask); + +# include "f_impl.h" /* Bring in the inline implementations */ + +# define LIMBPERM(i) (i) +# define LIMB_MASK(i) (((1)< 0); + if (n & 1) { + gf_sqr(y, x); + n--; + } else { + gf_sqr(tmp, x); + gf_sqr(y, tmp); + n -= 2; + } + for (; n; n -= 2) { + gf_sqr(tmp, y); + gf_sqr(y, tmp); + } +} + +# define gf_add_nr gf_add_RAW + +/* Subtract mod p. Bias by 2 and don't reduce */ +static ossl_inline void gf_sub_nr(gf c, const gf a, const gf b) +{ + gf_sub_RAW(c, a, b); + gf_bias(c, 2); + if (GF_HEADROOM < 3) + gf_weak_reduce(c); +} + +/* Subtract mod p. Bias by amt but don't reduce. */ +static ossl_inline void gf_subx_nr(gf c, const gf a, const gf b, int amt) +{ + gf_sub_RAW(c, a, b); + gf_bias(c, amt); + if (GF_HEADROOM < amt + 1) + gf_weak_reduce(c); +} + +/* Mul by signed int. Not constant-time WRT the sign of that int. */ +static ossl_inline void gf_mulw(gf c, const gf a, int32_t w) +{ + if (w > 0) { + gf_mulw_unsigned(c, a, w); + } else { + gf_mulw_unsigned(c, a, -w); + gf_sub(c, ZERO, c); + } +} + +/* Constant time, x = is_z ? z : y */ +static ossl_inline void gf_cond_sel(gf x, const gf y, const gf z, mask_t is_z) +{ + size_t i; + + for (i = 0; i < NLIMBS; i++) { +#if ARCH_WORD_BITS == 32 + x[0].limb[i] = constant_time_select_32(is_z, z[0].limb[i], + y[0].limb[i]); +#else + /* Must be 64 bit */ + x[0].limb[i] = constant_time_select_64(is_z, z[0].limb[i], + y[0].limb[i]); +#endif + } +} + +/* Constant time, if (neg) x=-x; */ +static ossl_inline void gf_cond_neg(gf x, mask_t neg) +{ + gf y; + + gf_sub(y, ZERO, x); + gf_cond_sel(x, x, y, neg); +} + +/* Constant time, if (swap) (x,y) = (y,x); */ +static ossl_inline void gf_cond_swap(gf x, gf_s * RESTRICT y, mask_t swap) +{ + size_t i; + + for (i = 0; i < NLIMBS; i++) { +#if ARCH_WORD_BITS == 32 + constant_time_cond_swap_32(swap, &(x[0].limb[i]), &(y->limb[i])); +#else + /* Must be 64 bit */ + constant_time_cond_swap_64(swap, &(x[0].limb[i]), &(y->limb[i])); +#endif + } +} + +#endif /* HEADER_FIELD_H */ diff --git a/crypto/ec/curve448/point_448.h b/crypto/ec/curve448/point_448.h new file mode 100644 index 00000000..0ef3b871 --- /dev/null +++ b/crypto/ec/curve448/point_448.h @@ -0,0 +1,301 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2016 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ + +#ifndef HEADER_POINT_448_H +# define HEADER_POINT_448_H + +# include "curve448utils.h" +# include "field.h" + +/* Comb config: number of combs, n, t, s. */ +#define COMBS_N 5 +#define COMBS_T 5 +#define COMBS_S 18 + +/* Projective Niels coordinates */ +typedef struct { + gf a, b, c; +} niels_s, niels_t[1]; +typedef struct { + niels_t n; + gf z; +} pniels_t[1]; + +/* Precomputed base */ +struct curve448_precomputed_s { + niels_t table[COMBS_N << (COMBS_T - 1)]; +}; + +# define C448_SCALAR_LIMBS ((446-1)/C448_WORD_BITS+1) + +/* The number of bits in a scalar */ +# define C448_SCALAR_BITS 446 + +/* Number of bytes in a serialized scalar. */ +# define C448_SCALAR_BYTES 56 + +/* X448 encoding ratio. */ +# define X448_ENCODE_RATIO 2 + +/* Number of bytes in an x448 public key */ +# define X448_PUBLIC_BYTES 56 + +/* Number of bytes in an x448 private key */ +# define X448_PRIVATE_BYTES 56 + +/* Twisted Edwards extended homogeneous coordinates */ +typedef struct curve448_point_s { + gf x, y, z, t; +} curve448_point_t[1]; + +/* Precomputed table based on a point. Can be trivial implementation. */ +struct curve448_precomputed_s; + +/* Precomputed table based on a point. Can be trivial implementation. */ +typedef struct curve448_precomputed_s curve448_precomputed_s; + +/* Scalar is stored packed, because we don't need the speed. */ +typedef struct curve448_scalar_s { + c448_word_t limb[C448_SCALAR_LIMBS]; +} curve448_scalar_t[1]; + +/* A scalar equal to 1. */ +extern const curve448_scalar_t curve448_scalar_one; + +/* A scalar equal to 0. */ +extern const curve448_scalar_t curve448_scalar_zero; + +/* The identity point on the curve. */ +extern const curve448_point_t curve448_point_identity; + +/* Precomputed table for the base point on the curve. */ +extern const struct curve448_precomputed_s *curve448_precomputed_base; +extern const niels_t *curve448_wnaf_base; + +/* + * Read a scalar from wire format or from bytes. + * + * ser (in): Serialized form of a scalar. + * out (out): Deserialized form. + * + * Returns: + * C448_SUCCESS: The scalar was correctly encoded. + * C448_FAILURE: The scalar was greater than the modulus, and has been reduced + * modulo that modulus. + */ +c448_error_t curve448_scalar_decode(curve448_scalar_t out, + const unsigned char ser[C448_SCALAR_BYTES]); + +/* + * Read a scalar from wire format or from bytes. Reduces mod scalar prime. + * + * ser (in): Serialized form of a scalar. + * ser_len (in): Length of serialized form. + * out (out): Deserialized form. + */ +void curve448_scalar_decode_long(curve448_scalar_t out, + const unsigned char *ser, size_t ser_len); + +/* + * Serialize a scalar to wire format. + * + * ser (out): Serialized form of a scalar. + * s (in): Deserialized scalar. + */ +void curve448_scalar_encode(unsigned char ser[C448_SCALAR_BYTES], + const curve448_scalar_t s); + +/* + * Add two scalars. |a|, |b| and |out| may alias each other. + * + * a (in): One scalar. + * b (in): Another scalar. + * out (out): a+b. + */ +void curve448_scalar_add(curve448_scalar_t out, + const curve448_scalar_t a, const curve448_scalar_t b); + +/* + * Subtract two scalars. |a|, |b| and |out| may alias each other. + * a (in): One scalar. + * b (in): Another scalar. + * out (out): a-b. + */ +void curve448_scalar_sub(curve448_scalar_t out, + const curve448_scalar_t a, const curve448_scalar_t b); + +/* + * Multiply two scalars. |a|, |b| and |out| may alias each other. + * + * a (in): One scalar. + * b (in): Another scalar. + * out (out): a*b. + */ +void curve448_scalar_mul(curve448_scalar_t out, + const curve448_scalar_t a, const curve448_scalar_t b); + +/* +* Halve a scalar. |a| and |out| may alias each other. +* +* a (in): A scalar. +* out (out): a/2. +*/ +void curve448_scalar_halve(curve448_scalar_t out, const curve448_scalar_t a); + +/* + * Copy a scalar. The scalars may alias each other, in which case this + * function does nothing. + * + * a (in): A scalar. + * out (out): Will become a copy of a. + */ +static ossl_inline void curve448_scalar_copy(curve448_scalar_t out, + const curve448_scalar_t a) +{ + *out = *a; +} + +/* + * Copy a point. The input and output may alias, in which case this function + * does nothing. + * + * a (out): A copy of the point. + * b (in): Any point. + */ +static ossl_inline void curve448_point_copy(curve448_point_t a, + const curve448_point_t b) +{ + *a = *b; +} + +/* + * Test whether two points are equal. If yes, return C448_TRUE, else return + * C448_FALSE. + * + * a (in): A point. + * b (in): Another point. + * + * Returns: + * C448_TRUE: The points are equal. + * C448_FALSE: The points are not equal. + */ +__owur c448_bool_t curve448_point_eq(const curve448_point_t a, + const curve448_point_t b); + +/* + * Double a point. Equivalent to curve448_point_add(two_a,a,a), but potentially + * faster. + * + * two_a (out): The sum a+a. + * a (in): A point. + */ +void curve448_point_double(curve448_point_t two_a, const curve448_point_t a); + +/* + * RFC 7748 Diffie-Hellman scalarmul. This function uses a different + * (non-Decaf) encoding. + * + * out (out): The scaled point base*scalar + * base (in): The point to be scaled. + * scalar (in): The scalar to multiply by. + * + * Returns: + * C448_SUCCESS: The scalarmul succeeded. + * C448_FAILURE: The scalarmul didn't succeed, because the base point is in a + * small subgroup. + */ +__owur c448_error_t x448_int(uint8_t out[X448_PUBLIC_BYTES], + const uint8_t base[X448_PUBLIC_BYTES], + const uint8_t scalar[X448_PRIVATE_BYTES]); + +/* + * Multiply a point by X448_ENCODE_RATIO, then encode it like RFC 7748. + * + * This function is mainly used internally, but is exported in case + * it will be useful. + * + * The ratio is necessary because the internal representation doesn't + * track the cofactor information, so on output we must clear the cofactor. + * This would multiply by the cofactor, but in fact internally points are always + * even, so it multiplies by half the cofactor instead. + * + * As it happens, this aligns with the base point definitions; that is, + * if you pass the Decaf/Ristretto base point to this function, the result + * will be X448_ENCODE_RATIO times the X448 + * base point. + * + * out (out): The scaled and encoded point. + * p (in): The point to be scaled and encoded. + */ +void curve448_point_mul_by_ratio_and_encode_like_x448( + uint8_t out[X448_PUBLIC_BYTES], + const curve448_point_t p); + +/* + * RFC 7748 Diffie-Hellman base point scalarmul. This function uses a different + * (non-Decaf) encoding. + * + * out (out): The scaled point base*scalar + * scalar (in): The scalar to multiply by. + */ +void x448_derive_public_key(uint8_t out[X448_PUBLIC_BYTES], + const uint8_t scalar[X448_PRIVATE_BYTES]); + +/* + * Multiply a precomputed base point by a scalar: out = scalar*base. + * + * scaled (out): The scaled point base*scalar + * base (in): The point to be scaled. + * scalar (in): The scalar to multiply by. + */ +void curve448_precomputed_scalarmul(curve448_point_t scaled, + const curve448_precomputed_s * base, + const curve448_scalar_t scalar); + +/* + * Multiply two base points by two scalars: + * combo = scalar1*curve448_point_base + scalar2*base2. + * + * Otherwise equivalent to curve448_point_double_scalarmul, but may be + * faster at the expense of being variable time. + * + * combo (out): The linear combination scalar1*base + scalar2*base2. + * scalar1 (in): A first scalar to multiply by. + * base2 (in): A second point to be scaled. + * scalar2 (in) A second scalar to multiply by. + * + * Warning: This function takes variable time, and may leak the scalars used. + * It is designed for signature verification. + */ +void curve448_base_double_scalarmul_non_secret(curve448_point_t combo, + const curve448_scalar_t scalar1, + const curve448_point_t base2, + const curve448_scalar_t scalar2); + +/* + * Test that a point is valid, for debugging purposes. + * + * to_test (in): The point to test. + * + * Returns: + * C448_TRUE The point is valid. + * C448_FALSE The point is invalid. + */ +__owur c448_bool_t curve448_point_valid(const curve448_point_t to_test); + +/* Overwrite scalar with zeros. */ +void curve448_scalar_destroy(curve448_scalar_t scalar); + +/* Overwrite point with zeros. */ +void curve448_point_destroy(curve448_point_t point); + +#endif /* HEADER_POINT_448_H */ diff --git a/crypto/ec/curve448/scalar.c b/crypto/ec/curve448/scalar.c new file mode 100644 index 00000000..0f14bc4b --- /dev/null +++ b/crypto/ec/curve448/scalar.c @@ -0,0 +1,235 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2016 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ +#include + +#include "word.h" +#include "point_448.h" + +static const c448_word_t MONTGOMERY_FACTOR = (c448_word_t) 0x3bd440fae918bc5; +static const curve448_scalar_t sc_p = { + { + { + SC_LIMB(0x2378c292ab5844f3), SC_LIMB(0x216cc2728dc58f55), + SC_LIMB(0xc44edb49aed63690), SC_LIMB(0xffffffff7cca23e9), + SC_LIMB(0xffffffffffffffff), SC_LIMB(0xffffffffffffffff), + SC_LIMB(0x3fffffffffffffff) + } + } +}, sc_r2 = { + { + { + + SC_LIMB(0xe3539257049b9b60), SC_LIMB(0x7af32c4bc1b195d9), + SC_LIMB(0x0d66de2388ea1859), SC_LIMB(0xae17cf725ee4d838), + SC_LIMB(0x1a9cc14ba3c47c44), SC_LIMB(0x2052bcb7e4d070af), + SC_LIMB(0x3402a939f823b729) + } + } +}; + +#define WBITS C448_WORD_BITS /* NB this may be different from ARCH_WORD_BITS */ + +const curve448_scalar_t curve448_scalar_one = {{{1}}}; +const curve448_scalar_t curve448_scalar_zero = {{{0}}}; + +/* + * {extra,accum} - sub +? p + * Must have extra <= 1 + */ +static void sc_subx(curve448_scalar_t out, + const c448_word_t accum[C448_SCALAR_LIMBS], + const curve448_scalar_t sub, + const curve448_scalar_t p, c448_word_t extra) +{ + c448_dsword_t chain = 0; + unsigned int i; + c448_word_t borrow; + + for (i = 0; i < C448_SCALAR_LIMBS; i++) { + chain = (chain + accum[i]) - sub->limb[i]; + out->limb[i] = (c448_word_t)chain; + chain >>= WBITS; + } + borrow = (c448_word_t)chain + extra; /* = 0 or -1 */ + + chain = 0; + for (i = 0; i < C448_SCALAR_LIMBS; i++) { + chain = (chain + out->limb[i]) + (p->limb[i] & borrow); + out->limb[i] = (c448_word_t)chain; + chain >>= WBITS; + } +} + +static void sc_montmul(curve448_scalar_t out, const curve448_scalar_t a, + const curve448_scalar_t b) +{ + unsigned int i, j; + c448_word_t accum[C448_SCALAR_LIMBS + 1] = { 0 }; + c448_word_t hi_carry = 0; + + for (i = 0; i < C448_SCALAR_LIMBS; i++) { + c448_word_t mand = a->limb[i]; + const c448_word_t *mier = b->limb; + + c448_dword_t chain = 0; + for (j = 0; j < C448_SCALAR_LIMBS; j++) { + chain += ((c448_dword_t) mand) * mier[j] + accum[j]; + accum[j] = (c448_word_t)chain; + chain >>= WBITS; + } + accum[j] = (c448_word_t)chain; + + mand = accum[0] * MONTGOMERY_FACTOR; + chain = 0; + mier = sc_p->limb; + for (j = 0; j < C448_SCALAR_LIMBS; j++) { + chain += (c448_dword_t) mand *mier[j] + accum[j]; + if (j) + accum[j - 1] = (c448_word_t)chain; + chain >>= WBITS; + } + chain += accum[j]; + chain += hi_carry; + accum[j - 1] = (c448_word_t)chain; + hi_carry = chain >> WBITS; + } + + sc_subx(out, accum, sc_p, sc_p, hi_carry); +} + +void curve448_scalar_mul(curve448_scalar_t out, const curve448_scalar_t a, + const curve448_scalar_t b) +{ + sc_montmul(out, a, b); + sc_montmul(out, out, sc_r2); +} + +void curve448_scalar_sub(curve448_scalar_t out, const curve448_scalar_t a, + const curve448_scalar_t b) +{ + sc_subx(out, a->limb, b, sc_p, 0); +} + +void curve448_scalar_add(curve448_scalar_t out, const curve448_scalar_t a, + const curve448_scalar_t b) +{ + c448_dword_t chain = 0; + unsigned int i; + + for (i = 0; i < C448_SCALAR_LIMBS; i++) { + chain = (chain + a->limb[i]) + b->limb[i]; + out->limb[i] = (c448_word_t)chain; + chain >>= WBITS; + } + sc_subx(out, out->limb, sc_p, sc_p, (c448_word_t)chain); +} + +static ossl_inline void scalar_decode_short(curve448_scalar_t s, + const unsigned char *ser, + unsigned int nbytes) +{ + unsigned int i, j, k = 0; + + for (i = 0; i < C448_SCALAR_LIMBS; i++) { + c448_word_t out = 0; + + for (j = 0; j < sizeof(c448_word_t) && k < nbytes; j++, k++) + out |= ((c448_word_t) ser[k]) << (8 * j); + s->limb[i] = out; + } +} + +c448_error_t curve448_scalar_decode( + curve448_scalar_t s, + const unsigned char ser[C448_SCALAR_BYTES]) +{ + unsigned int i; + c448_dsword_t accum = 0; + + scalar_decode_short(s, ser, C448_SCALAR_BYTES); + for (i = 0; i < C448_SCALAR_LIMBS; i++) + accum = (accum + s->limb[i] - sc_p->limb[i]) >> WBITS; + /* Here accum == 0 or -1 */ + + curve448_scalar_mul(s, s, curve448_scalar_one); /* ham-handed reduce */ + + return c448_succeed_if(~word_is_zero((uint32_t)accum)); +} + +void curve448_scalar_destroy(curve448_scalar_t scalar) +{ + OPENSSL_cleanse(scalar, sizeof(curve448_scalar_t)); +} + +void curve448_scalar_decode_long(curve448_scalar_t s, + const unsigned char *ser, size_t ser_len) +{ + size_t i; + curve448_scalar_t t1, t2; + + if (ser_len == 0) { + curve448_scalar_copy(s, curve448_scalar_zero); + return; + } + + i = ser_len - (ser_len % C448_SCALAR_BYTES); + if (i == ser_len) + i -= C448_SCALAR_BYTES; + + scalar_decode_short(t1, &ser[i], ser_len - i); + + if (ser_len == sizeof(curve448_scalar_t)) { + assert(i == 0); + /* ham-handed reduce */ + curve448_scalar_mul(s, t1, curve448_scalar_one); + curve448_scalar_destroy(t1); + return; + } + + while (i) { + i -= C448_SCALAR_BYTES; + sc_montmul(t1, t1, sc_r2); + (void)curve448_scalar_decode(t2, ser + i); + curve448_scalar_add(t1, t1, t2); + } + + curve448_scalar_copy(s, t1); + curve448_scalar_destroy(t1); + curve448_scalar_destroy(t2); +} + +void curve448_scalar_encode(unsigned char ser[C448_SCALAR_BYTES], + const curve448_scalar_t s) +{ + unsigned int i, j, k = 0; + + for (i = 0; i < C448_SCALAR_LIMBS; i++) { + for (j = 0; j < sizeof(c448_word_t); j++, k++) + ser[k] = s->limb[i] >> (8 * j); + } +} + +void curve448_scalar_halve(curve448_scalar_t out, const curve448_scalar_t a) +{ + c448_word_t mask = 0 - (a->limb[0] & 1); + c448_dword_t chain = 0; + unsigned int i; + + for (i = 0; i < C448_SCALAR_LIMBS; i++) { + chain = (chain + a->limb[i]) + (sc_p->limb[i] & mask); + out->limb[i] = (c448_word_t)chain; + chain >>= C448_WORD_BITS; + } + for (i = 0; i < C448_SCALAR_LIMBS - 1; i++) + out->limb[i] = out->limb[i] >> 1 | out->limb[i + 1] << (WBITS - 1); + out->limb[i] = out->limb[i] >> 1 | (c448_word_t)(chain << (WBITS - 1)); +} diff --git a/crypto/ec/curve448/word.h b/crypto/ec/curve448/word.h new file mode 100644 index 00000000..a48b9e05 --- /dev/null +++ b/crypto/ec/curve448/word.h @@ -0,0 +1,81 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2014 Cryptography Research, Inc. + * + * 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 + * + * Originally written by Mike Hamburg + */ + +#ifndef HEADER_WORD_H +# define HEADER_WORD_H + +# include +# include +# include +# include +# include "arch_intrinsics.h" +# include "curve448utils.h" + +# if (ARCH_WORD_BITS == 64) +typedef uint64_t word_t, mask_t; +typedef __uint128_t dword_t; +typedef int32_t hsword_t; +typedef int64_t sword_t; +typedef __int128_t dsword_t; +# elif (ARCH_WORD_BITS == 32) +typedef uint32_t word_t, mask_t; +typedef uint64_t dword_t; +typedef int16_t hsword_t; +typedef int32_t sword_t; +typedef int64_t dsword_t; +# else +# error "For now, we only support 32- and 64-bit architectures." +# endif + +/* + * Scalar limbs are keyed off of the API word size instead of the arch word + * size. + */ +# if C448_WORD_BITS == 64 +# define SC_LIMB(x) (x) +# elif C448_WORD_BITS == 32 +# define SC_LIMB(x) ((uint32_t)(x)),((x) >> 32) +# else +# error "For now we only support 32- and 64-bit architectures." +# endif + +/* + * The plan on booleans: The external interface uses c448_bool_t, but this + * might be a different size than our particular arch's word_t (and thus + * mask_t). Also, the caller isn't guaranteed to pass it as nonzero. So + * bool_to_mask converts word sizes and checks nonzero. On the flip side, + * mask_t is always -1 or 0, but it might be a different size than + * c448_bool_t. On the third hand, we have success vs boolean types, but + * that's handled in common.h: it converts between c448_bool_t and + * c448_error_t. + */ +static ossl_inline c448_bool_t mask_to_bool(mask_t m) +{ + return (c448_sword_t)(sword_t)m; +} + +static ossl_inline mask_t bool_to_mask(c448_bool_t m) +{ + /* On most arches this will be optimized to a simple cast. */ + mask_t ret = 0; + unsigned int i; + unsigned int limit = sizeof(c448_bool_t) / sizeof(mask_t); + + if (limit < 1) + limit = 1; + for (i = 0; i < limit; i++) + ret |= ~word_is_zero(m >> (i * 8 * sizeof(word_t))); + + return ret; +} + +#endif /* HEADER_WORD_H */ diff --git a/crypto/ec/ec2_mult.c b/crypto/ec/ec2_mult.c index e4a1ec57..891e8102 100644 --- a/crypto/ec/ec2_mult.c +++ b/crypto/ec/ec2_mult.c @@ -1,5 +1,6 @@ /* * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,21 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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 software is originally written by Sheueling Chang Shantz and - * Douglas Stebila of Sun Microsystems Laboratories. - * - */ - #include #include "internal/bn_int.h" diff --git a/crypto/ec/ec2_oct.c b/crypto/ec/ec2_oct.c index ea88ce86..24c32ae6 100644 --- a/crypto/ec/ec2_oct.c +++ b/crypto/ec/ec2_oct.c @@ -1,5 +1,6 @@ /* * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,21 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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 software is originally written by Sheueling Chang Shantz and - * Douglas Stebila of Sun Microsystems Laboratories. - * - */ - #include #include "ec_lcl.h" diff --git a/crypto/ec/ec2_smpl.c b/crypto/ec/ec2_smpl.c index cfeef5fc..6bd5f9d8 100644 --- a/crypto/ec/ec2_smpl.c +++ b/crypto/ec/ec2_smpl.c @@ -1,5 +1,6 @@ /* * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,21 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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 software is originally written by Sheueling Chang Shantz and - * Douglas Stebila of Sun Microsystems Laboratories. - * - */ - #include #include "internal/bn_int.h" @@ -617,9 +603,9 @@ int ec_GF2m_simple_is_on_curve(const EC_GROUP *group, const EC_POINT *point, if (!BN_GF2m_add(lh, lh, y2)) goto err; ret = BN_is_zero(lh); + err: - if (ctx) - BN_CTX_end(ctx); + BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; } @@ -670,8 +656,7 @@ int ec_GF2m_simple_cmp(const EC_GROUP *group, const EC_POINT *a, ret = ((BN_cmp(aX, bX) == 0) && BN_cmp(aY, bY) == 0) ? 0 : 1; err: - if (ctx) - BN_CTX_end(ctx); + BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; } @@ -712,8 +697,7 @@ int ec_GF2m_simple_make_affine(const EC_GROUP *group, EC_POINT *point, ret = 1; err: - if (ctx) - BN_CTX_end(ctx); + BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; } diff --git a/crypto/ec/ec_ameth.c b/crypto/ec/ec_ameth.c index b66adf2b..0682bc3d 100644 --- a/crypto/ec/ec_ameth.c +++ b/crypto/ec/ec_ameth.c @@ -520,6 +520,48 @@ static int ec_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) } +static int ec_pkey_check(const EVP_PKEY *pkey) +{ + EC_KEY *eckey = pkey->pkey.ec; + + /* stay consistent to what EVP_PKEY_check demands */ + if (eckey->priv_key == NULL) { + ECerr(EC_F_EC_PKEY_CHECK, EC_R_MISSING_PRIVATE_KEY); + return 0; + } + + return EC_KEY_check_key(eckey); +} + +static int ec_pkey_public_check(const EVP_PKEY *pkey) +{ + EC_KEY *eckey = pkey->pkey.ec; + + /* + * Note: it unnecessary to check eckey->pub_key here since + * it will be checked in EC_KEY_check_key(). In fact, the + * EC_KEY_check_key() mainly checks the public key, and checks + * the private key optionally (only if there is one). So if + * someone passes a whole EC key (public + private), this + * will also work... + */ + + return EC_KEY_check_key(eckey); +} + +static int ec_pkey_param_check(const EVP_PKEY *pkey) +{ + EC_KEY *eckey = pkey->pkey.ec; + + /* stay consistent to what EVP_PKEY_check demands */ + if (eckey->group == NULL) { + ECerr(EC_F_EC_PKEY_PARAM_CHECK, EC_R_MISSING_PARAMETERS); + return 0; + } + + return EC_GROUP_check(eckey->group, NULL); +} + const EVP_PKEY_ASN1_METHOD eckey_asn1_meth = { EVP_PKEY_EC, EVP_PKEY_EC, @@ -551,7 +593,13 @@ const EVP_PKEY_ASN1_METHOD eckey_asn1_meth = { int_ec_free, ec_pkey_ctrl, old_ec_priv_decode, - old_ec_priv_encode + old_ec_priv_encode, + + 0, 0, 0, + + ec_pkey_check, + ec_pkey_public_check, + ec_pkey_param_check }; int EC_KEY_print(BIO *bp, const EC_KEY *x, int off) diff --git a/crypto/ec/ec_asn1.c b/crypto/ec/ec_asn1.c index 271178f8..c7ed01ef 100644 --- a/crypto/ec/ec_asn1.c +++ b/crypto/ec/ec_asn1.c @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2002-2018 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 @@ -12,6 +12,7 @@ #include #include #include +#include "internal/nelem.h" int EC_GROUP_get_basis_type(const EC_GROUP *group) { @@ -87,13 +88,13 @@ int EC_GROUP_get_pentanomial_basis(const EC_GROUP *group, unsigned int *k1, /* some structures needed for the asn1 encoding */ typedef struct x9_62_pentanomial_st { - long k1; - long k2; - long k3; + int32_t k1; + int32_t k2; + int32_t k3; } X9_62_PENTANOMIAL; typedef struct x9_62_characteristic_two_st { - long m; + int32_t m; ASN1_OBJECT *type; union { char *ptr; @@ -128,7 +129,7 @@ typedef struct x9_62_curve_st { } X9_62_CURVE; struct ec_parameters_st { - long version; + int32_t version; X9_62_FIELDID *fieldID; X9_62_CURVE *curve; ASN1_OCTET_STRING *base; @@ -147,7 +148,7 @@ struct ecpk_parameters_st { /* SEC1 ECPrivateKey */ typedef struct ec_privatekey_st { - long version; + int32_t version; ASN1_OCTET_STRING *privateKey; ECPKPARAMETERS *parameters; ASN1_BIT_STRING *publicKey; @@ -155,9 +156,9 @@ typedef struct ec_privatekey_st { /* the OpenSSL ASN.1 definitions */ ASN1_SEQUENCE(X9_62_PENTANOMIAL) = { - ASN1_SIMPLE(X9_62_PENTANOMIAL, k1, LONG), - ASN1_SIMPLE(X9_62_PENTANOMIAL, k2, LONG), - ASN1_SIMPLE(X9_62_PENTANOMIAL, k3, LONG) + ASN1_EMBED(X9_62_PENTANOMIAL, k1, INT32), + ASN1_EMBED(X9_62_PENTANOMIAL, k2, INT32), + ASN1_EMBED(X9_62_PENTANOMIAL, k3, INT32) } static_ASN1_SEQUENCE_END(X9_62_PENTANOMIAL) DECLARE_ASN1_ALLOC_FUNCTIONS(X9_62_PENTANOMIAL) @@ -172,7 +173,7 @@ ASN1_ADB(X9_62_CHARACTERISTIC_TWO) = { } ASN1_ADB_END(X9_62_CHARACTERISTIC_TWO, 0, type, 0, &char_two_def_tt, NULL); ASN1_SEQUENCE(X9_62_CHARACTERISTIC_TWO) = { - ASN1_SIMPLE(X9_62_CHARACTERISTIC_TWO, m, LONG), + ASN1_EMBED(X9_62_CHARACTERISTIC_TWO, m, INT32), ASN1_SIMPLE(X9_62_CHARACTERISTIC_TWO, type, ASN1_OBJECT), ASN1_ADB_OBJECT(X9_62_CHARACTERISTIC_TWO) } static_ASN1_SEQUENCE_END(X9_62_CHARACTERISTIC_TWO) @@ -199,7 +200,7 @@ ASN1_SEQUENCE(X9_62_CURVE) = { } static_ASN1_SEQUENCE_END(X9_62_CURVE) ASN1_SEQUENCE(ECPARAMETERS) = { - ASN1_SIMPLE(ECPARAMETERS, version, LONG), + ASN1_EMBED(ECPARAMETERS, version, INT32), ASN1_SIMPLE(ECPARAMETERS, fieldID, X9_62_FIELDID), ASN1_SIMPLE(ECPARAMETERS, curve, X9_62_CURVE), ASN1_SIMPLE(ECPARAMETERS, base, ASN1_OCTET_STRING), @@ -221,7 +222,7 @@ DECLARE_ASN1_ENCODE_FUNCTIONS_const(ECPKPARAMETERS, ECPKPARAMETERS) IMPLEMENT_ASN1_FUNCTIONS_const(ECPKPARAMETERS) ASN1_SEQUENCE(EC_PRIVATEKEY) = { - ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG), + ASN1_EMBED(EC_PRIVATEKEY, version, INT32), ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING), ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0), ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1) @@ -359,7 +360,7 @@ static int ec_asn1_group2fieldid(const EC_GROUP *group, X9_62_FIELDID *field) err: BN_free(tmp); - return (ok); + return ok; } static int ec_asn1_group2curve(const EC_GROUP *group, X9_62_CURVE *curve) @@ -465,7 +466,7 @@ static int ec_asn1_group2curve(const EC_GROUP *group, X9_62_CURVE *curve) OPENSSL_free(buffer_2); BN_free(tmp_1); BN_free(tmp_2); - return (ok); + return ok; } ECPARAMETERS *EC_GROUP_get_ecparameters(const EC_GROUP *group, @@ -571,7 +572,7 @@ ECPKPARAMETERS *EC_GROUP_get_ecpkparameters(const EC_GROUP *group, if (EC_GROUP_get_asn1_flag(group)) { /* - * use the asn1 OID to describe the the elliptic curve parameters + * use the asn1 OID to describe the elliptic curve parameters */ tmp = EC_GROUP_get_curve_name(group); if (tmp) { @@ -827,7 +828,7 @@ EC_GROUP *EC_GROUP_new_from_ecparameters(const ECPARAMETERS *params) BN_free(a); BN_free(b); EC_POINT_free(point); - return (ret); + return ret; } EC_GROUP *EC_GROUP_new_from_ecpkparameters(const ECPKPARAMETERS *params) @@ -893,7 +894,7 @@ EC_GROUP *d2i_ECPKParameters(EC_GROUP **a, const unsigned char **in, long len) ECPKPARAMETERS_free(params); *in = p; - return (group); + return group; } int i2d_ECPKParameters(const EC_GROUP *a, unsigned char **out) @@ -910,7 +911,7 @@ int i2d_ECPKParameters(const EC_GROUP *a, unsigned char **out) return 0; } ECPKPARAMETERS_free(tmp); - return (ret); + return ret; } /* some EC_KEY functions */ @@ -985,7 +986,7 @@ EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigned char **in, long len) *a = ret; EC_PRIVATEKEY_free(priv_key); *in = p; - return (ret); + return ret; err: if (a == NULL || *a != ret) @@ -1233,5 +1234,5 @@ int ECDSA_size(const EC_KEY *r) i = i2d_ASN1_INTEGER(&bs, NULL); i += i; /* r and s */ ret = ASN1_object_size(1, i, V_ASN1_SEQUENCE); - return (ret); + return ret; } diff --git a/crypto/ec/ec_curve.c b/crypto/ec/ec_curve.c index f8a3846f..75fc5411 100644 --- a/crypto/ec/ec_curve.c +++ b/crypto/ec/ec_curve.c @@ -1,5 +1,6 @@ /* * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,26 +8,12 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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 #include "ec_lcl.h" #include #include #include -#include "e_os.h" +#include "internal/nelem.h" typedef struct { int field_type, /* either NID_X9_62_prime_field or @@ -2217,7 +2204,7 @@ static const struct { #endif /* - * These curves were added by Annie Yousar + * These curves were added by Annie Yousar. * For the definition of RFC 5639 curves see * http://www.ietf.org/rfc/rfc5639.txt These curves are generated verifiable * at random, nevertheless the seed is omitted as parameter because the diff --git a/crypto/ec/ec_cvt.c b/crypto/ec/ec_cvt.c index bfff6d65..13218237 100644 --- a/crypto/ec/ec_cvt.c +++ b/crypto/ec/ec_cvt.c @@ -1,5 +1,6 @@ /* * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,20 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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 #include "ec_lcl.h" diff --git a/crypto/ec/ec_err.c b/crypto/ec/ec_err.c index cb78bd5c..588e95c1 100644 --- a/crypto/ec/ec_err.c +++ b/crypto/ec/ec_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -8,272 +8,332 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_EC,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_EC,0,reason) - -static ERR_STRING_DATA EC_str_functs[] = { - {ERR_FUNC(EC_F_BN_TO_FELEM), "BN_to_felem"}, - {ERR_FUNC(EC_F_D2I_ECPARAMETERS), "d2i_ECParameters"}, - {ERR_FUNC(EC_F_D2I_ECPKPARAMETERS), "d2i_ECPKParameters"}, - {ERR_FUNC(EC_F_D2I_ECPRIVATEKEY), "d2i_ECPrivateKey"}, - {ERR_FUNC(EC_F_DO_EC_KEY_PRINT), "do_EC_KEY_print"}, - {ERR_FUNC(EC_F_ECDH_CMS_DECRYPT), "ecdh_cms_decrypt"}, - {ERR_FUNC(EC_F_ECDH_CMS_SET_SHARED_INFO), "ecdh_cms_set_shared_info"}, - {ERR_FUNC(EC_F_ECDH_COMPUTE_KEY), "ECDH_compute_key"}, - {ERR_FUNC(EC_F_ECDH_SIMPLE_COMPUTE_KEY), "ecdh_simple_compute_key"}, - {ERR_FUNC(EC_F_ECDSA_DO_SIGN_EX), "ECDSA_do_sign_ex"}, - {ERR_FUNC(EC_F_ECDSA_DO_VERIFY), "ECDSA_do_verify"}, - {ERR_FUNC(EC_F_ECDSA_SIGN_EX), "ECDSA_sign_ex"}, - {ERR_FUNC(EC_F_ECDSA_SIGN_SETUP), "ECDSA_sign_setup"}, - {ERR_FUNC(EC_F_ECDSA_SIG_NEW), "ECDSA_SIG_new"}, - {ERR_FUNC(EC_F_ECDSA_VERIFY), "ECDSA_verify"}, - {ERR_FUNC(EC_F_ECKEY_PARAM2TYPE), "eckey_param2type"}, - {ERR_FUNC(EC_F_ECKEY_PARAM_DECODE), "eckey_param_decode"}, - {ERR_FUNC(EC_F_ECKEY_PRIV_DECODE), "eckey_priv_decode"}, - {ERR_FUNC(EC_F_ECKEY_PRIV_ENCODE), "eckey_priv_encode"}, - {ERR_FUNC(EC_F_ECKEY_PUB_DECODE), "eckey_pub_decode"}, - {ERR_FUNC(EC_F_ECKEY_PUB_ENCODE), "eckey_pub_encode"}, - {ERR_FUNC(EC_F_ECKEY_TYPE2PARAM), "eckey_type2param"}, - {ERR_FUNC(EC_F_ECPARAMETERS_PRINT), "ECParameters_print"}, - {ERR_FUNC(EC_F_ECPARAMETERS_PRINT_FP), "ECParameters_print_fp"}, - {ERR_FUNC(EC_F_ECPKPARAMETERS_PRINT), "ECPKParameters_print"}, - {ERR_FUNC(EC_F_ECPKPARAMETERS_PRINT_FP), "ECPKParameters_print_fp"}, - {ERR_FUNC(EC_F_ECP_NISTZ256_GET_AFFINE), "ecp_nistz256_get_affine"}, +static const ERR_STRING_DATA EC_str_functs[] = { + {ERR_PACK(ERR_LIB_EC, EC_F_BN_TO_FELEM, 0), "BN_to_felem"}, + {ERR_PACK(ERR_LIB_EC, EC_F_D2I_ECPARAMETERS, 0), "d2i_ECParameters"}, + {ERR_PACK(ERR_LIB_EC, EC_F_D2I_ECPKPARAMETERS, 0), "d2i_ECPKParameters"}, + {ERR_PACK(ERR_LIB_EC, EC_F_D2I_ECPRIVATEKEY, 0), "d2i_ECPrivateKey"}, + {ERR_PACK(ERR_LIB_EC, EC_F_DO_EC_KEY_PRINT, 0), "do_EC_KEY_print"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECDH_CMS_DECRYPT, 0), "ecdh_cms_decrypt"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECDH_CMS_SET_SHARED_INFO, 0), + "ecdh_cms_set_shared_info"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECDH_COMPUTE_KEY, 0), "ECDH_compute_key"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECDH_SIMPLE_COMPUTE_KEY, 0), + "ecdh_simple_compute_key"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECDSA_DO_SIGN_EX, 0), "ECDSA_do_sign_ex"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECDSA_DO_VERIFY, 0), "ECDSA_do_verify"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECDSA_SIGN_EX, 0), "ECDSA_sign_ex"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECDSA_SIGN_SETUP, 0), "ECDSA_sign_setup"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECDSA_SIG_NEW, 0), "ECDSA_SIG_new"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECDSA_VERIFY, 0), "ECDSA_verify"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECD_ITEM_VERIFY, 0), "ecd_item_verify"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECKEY_PARAM2TYPE, 0), "eckey_param2type"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECKEY_PARAM_DECODE, 0), "eckey_param_decode"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECKEY_PRIV_DECODE, 0), "eckey_priv_decode"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECKEY_PRIV_ENCODE, 0), "eckey_priv_encode"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECKEY_PUB_DECODE, 0), "eckey_pub_decode"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECKEY_PUB_ENCODE, 0), "eckey_pub_encode"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECKEY_TYPE2PARAM, 0), "eckey_type2param"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECPARAMETERS_PRINT, 0), "ECParameters_print"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECPARAMETERS_PRINT_FP, 0), + "ECParameters_print_fp"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECPKPARAMETERS_PRINT, 0), + "ECPKParameters_print"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECPKPARAMETERS_PRINT_FP, 0), + "ECPKParameters_print_fp"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECP_NISTZ256_GET_AFFINE, 0), + "ecp_nistz256_get_affine"}, {ERR_PACK(ERR_LIB_EC, EC_F_ECP_NISTZ256_INV_MOD_ORD, 0), "ecp_nistz256_inv_mod_ord"}, - {ERR_FUNC(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE), + {ERR_PACK(ERR_LIB_EC, EC_F_ECP_NISTZ256_MULT_PRECOMPUTE, 0), "ecp_nistz256_mult_precompute"}, - {ERR_FUNC(EC_F_ECP_NISTZ256_POINTS_MUL), "ecp_nistz256_points_mul"}, - {ERR_FUNC(EC_F_ECP_NISTZ256_PRE_COMP_NEW), "ecp_nistz256_pre_comp_new"}, - {ERR_FUNC(EC_F_ECP_NISTZ256_WINDOWED_MUL), "ecp_nistz256_windowed_mul"}, - {ERR_FUNC(EC_F_ECX_KEY_OP), "ecx_key_op"}, - {ERR_FUNC(EC_F_ECX_PRIV_ENCODE), "ecx_priv_encode"}, - {ERR_FUNC(EC_F_ECX_PUB_ENCODE), "ecx_pub_encode"}, - {ERR_FUNC(EC_F_EC_ASN1_GROUP2CURVE), "ec_asn1_group2curve"}, - {ERR_FUNC(EC_F_EC_ASN1_GROUP2FIELDID), "ec_asn1_group2fieldid"}, - {ERR_FUNC(EC_F_EC_GF2M_MONTGOMERY_POINT_MULTIPLY), + {ERR_PACK(ERR_LIB_EC, EC_F_ECP_NISTZ256_POINTS_MUL, 0), + "ecp_nistz256_points_mul"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECP_NISTZ256_PRE_COMP_NEW, 0), + "ecp_nistz256_pre_comp_new"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECP_NISTZ256_WINDOWED_MUL, 0), + "ecp_nistz256_windowed_mul"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECX_KEY_OP, 0), "ecx_key_op"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECX_PRIV_ENCODE, 0), "ecx_priv_encode"}, + {ERR_PACK(ERR_LIB_EC, EC_F_ECX_PUB_ENCODE, 0), "ecx_pub_encode"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_ASN1_GROUP2CURVE, 0), "ec_asn1_group2curve"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_ASN1_GROUP2FIELDID, 0), + "ec_asn1_group2fieldid"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GF2M_MONTGOMERY_POINT_MULTIPLY, 0), "ec_GF2m_montgomery_point_multiply"}, - {ERR_FUNC(EC_F_EC_GF2M_SIMPLE_GROUP_CHECK_DISCRIMINANT), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GF2M_SIMPLE_GROUP_CHECK_DISCRIMINANT, 0), "ec_GF2m_simple_group_check_discriminant"}, - {ERR_FUNC(EC_F_EC_GF2M_SIMPLE_GROUP_SET_CURVE), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GF2M_SIMPLE_GROUP_SET_CURVE, 0), "ec_GF2m_simple_group_set_curve"}, - {ERR_FUNC(EC_F_EC_GF2M_SIMPLE_OCT2POINT), "ec_GF2m_simple_oct2point"}, - {ERR_FUNC(EC_F_EC_GF2M_SIMPLE_POINT2OCT), "ec_GF2m_simple_point2oct"}, - {ERR_FUNC(EC_F_EC_GF2M_SIMPLE_POINT_GET_AFFINE_COORDINATES), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GF2M_SIMPLE_OCT2POINT, 0), + "ec_GF2m_simple_oct2point"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GF2M_SIMPLE_POINT2OCT, 0), + "ec_GF2m_simple_point2oct"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GF2M_SIMPLE_POINT_GET_AFFINE_COORDINATES, 0), "ec_GF2m_simple_point_get_affine_coordinates"}, - {ERR_FUNC(EC_F_EC_GF2M_SIMPLE_POINT_SET_AFFINE_COORDINATES), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GF2M_SIMPLE_POINT_SET_AFFINE_COORDINATES, 0), "ec_GF2m_simple_point_set_affine_coordinates"}, - {ERR_FUNC(EC_F_EC_GF2M_SIMPLE_SET_COMPRESSED_COORDINATES), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GF2M_SIMPLE_SET_COMPRESSED_COORDINATES, 0), "ec_GF2m_simple_set_compressed_coordinates"}, - {ERR_FUNC(EC_F_EC_GFP_MONT_FIELD_DECODE), "ec_GFp_mont_field_decode"}, - {ERR_FUNC(EC_F_EC_GFP_MONT_FIELD_ENCODE), "ec_GFp_mont_field_encode"}, - {ERR_FUNC(EC_F_EC_GFP_MONT_FIELD_MUL), "ec_GFp_mont_field_mul"}, - {ERR_FUNC(EC_F_EC_GFP_MONT_FIELD_SET_TO_ONE), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_MONT_FIELD_DECODE, 0), + "ec_GFp_mont_field_decode"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_MONT_FIELD_ENCODE, 0), + "ec_GFp_mont_field_encode"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_MONT_FIELD_MUL, 0), + "ec_GFp_mont_field_mul"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_MONT_FIELD_SET_TO_ONE, 0), "ec_GFp_mont_field_set_to_one"}, - {ERR_FUNC(EC_F_EC_GFP_MONT_FIELD_SQR), "ec_GFp_mont_field_sqr"}, - {ERR_FUNC(EC_F_EC_GFP_MONT_GROUP_SET_CURVE), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_MONT_FIELD_SQR, 0), + "ec_GFp_mont_field_sqr"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_MONT_GROUP_SET_CURVE, 0), "ec_GFp_mont_group_set_curve"}, - {ERR_FUNC(EC_F_EC_GFP_NISTP224_GROUP_SET_CURVE), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NISTP224_GROUP_SET_CURVE, 0), "ec_GFp_nistp224_group_set_curve"}, - {ERR_FUNC(EC_F_EC_GFP_NISTP224_POINTS_MUL), "ec_GFp_nistp224_points_mul"}, - {ERR_FUNC(EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NISTP224_POINTS_MUL, 0), + "ec_GFp_nistp224_points_mul"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES, 0), "ec_GFp_nistp224_point_get_affine_coordinates"}, - {ERR_FUNC(EC_F_EC_GFP_NISTP256_GROUP_SET_CURVE), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NISTP256_GROUP_SET_CURVE, 0), "ec_GFp_nistp256_group_set_curve"}, - {ERR_FUNC(EC_F_EC_GFP_NISTP256_POINTS_MUL), "ec_GFp_nistp256_points_mul"}, - {ERR_FUNC(EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NISTP256_POINTS_MUL, 0), + "ec_GFp_nistp256_points_mul"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES, 0), "ec_GFp_nistp256_point_get_affine_coordinates"}, - {ERR_FUNC(EC_F_EC_GFP_NISTP521_GROUP_SET_CURVE), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NISTP521_GROUP_SET_CURVE, 0), "ec_GFp_nistp521_group_set_curve"}, - {ERR_FUNC(EC_F_EC_GFP_NISTP521_POINTS_MUL), "ec_GFp_nistp521_points_mul"}, - {ERR_FUNC(EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NISTP521_POINTS_MUL, 0), + "ec_GFp_nistp521_points_mul"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES, 0), "ec_GFp_nistp521_point_get_affine_coordinates"}, - {ERR_FUNC(EC_F_EC_GFP_NIST_FIELD_MUL), "ec_GFp_nist_field_mul"}, - {ERR_FUNC(EC_F_EC_GFP_NIST_FIELD_SQR), "ec_GFp_nist_field_sqr"}, - {ERR_FUNC(EC_F_EC_GFP_NIST_GROUP_SET_CURVE), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NIST_FIELD_MUL, 0), + "ec_GFp_nist_field_mul"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NIST_FIELD_SQR, 0), + "ec_GFp_nist_field_sqr"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_NIST_GROUP_SET_CURVE, 0), "ec_GFp_nist_group_set_curve"}, - {ERR_FUNC(EC_F_EC_GFP_SIMPLE_GROUP_CHECK_DISCRIMINANT), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_SIMPLE_GROUP_CHECK_DISCRIMINANT, 0), "ec_GFp_simple_group_check_discriminant"}, - {ERR_FUNC(EC_F_EC_GFP_SIMPLE_GROUP_SET_CURVE), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_SIMPLE_GROUP_SET_CURVE, 0), "ec_GFp_simple_group_set_curve"}, - {ERR_FUNC(EC_F_EC_GFP_SIMPLE_MAKE_AFFINE), "ec_GFp_simple_make_affine"}, - {ERR_FUNC(EC_F_EC_GFP_SIMPLE_OCT2POINT), "ec_GFp_simple_oct2point"}, - {ERR_FUNC(EC_F_EC_GFP_SIMPLE_POINT2OCT), "ec_GFp_simple_point2oct"}, - {ERR_FUNC(EC_F_EC_GFP_SIMPLE_POINTS_MAKE_AFFINE), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_SIMPLE_MAKE_AFFINE, 0), + "ec_GFp_simple_make_affine"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_SIMPLE_OCT2POINT, 0), + "ec_GFp_simple_oct2point"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_SIMPLE_POINT2OCT, 0), + "ec_GFp_simple_point2oct"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_SIMPLE_POINTS_MAKE_AFFINE, 0), "ec_GFp_simple_points_make_affine"}, - {ERR_FUNC(EC_F_EC_GFP_SIMPLE_POINT_GET_AFFINE_COORDINATES), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_SIMPLE_POINT_GET_AFFINE_COORDINATES, 0), "ec_GFp_simple_point_get_affine_coordinates"}, - {ERR_FUNC(EC_F_EC_GFP_SIMPLE_POINT_SET_AFFINE_COORDINATES), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_SIMPLE_POINT_SET_AFFINE_COORDINATES, 0), "ec_GFp_simple_point_set_affine_coordinates"}, - {ERR_FUNC(EC_F_EC_GFP_SIMPLE_SET_COMPRESSED_COORDINATES), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GFP_SIMPLE_SET_COMPRESSED_COORDINATES, 0), "ec_GFp_simple_set_compressed_coordinates"}, - {ERR_FUNC(EC_F_EC_GROUP_CHECK), "EC_GROUP_check"}, - {ERR_FUNC(EC_F_EC_GROUP_CHECK_DISCRIMINANT), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_CHECK, 0), "EC_GROUP_check"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_CHECK_DISCRIMINANT, 0), "EC_GROUP_check_discriminant"}, - {ERR_FUNC(EC_F_EC_GROUP_COPY), "EC_GROUP_copy"}, - {ERR_FUNC(EC_F_EC_GROUP_GET_CURVE_GF2M), "EC_GROUP_get_curve_GF2m"}, - {ERR_FUNC(EC_F_EC_GROUP_GET_CURVE_GFP), "EC_GROUP_get_curve_GFp"}, - {ERR_FUNC(EC_F_EC_GROUP_GET_DEGREE), "EC_GROUP_get_degree"}, - {ERR_FUNC(EC_F_EC_GROUP_GET_ECPARAMETERS), "EC_GROUP_get_ecparameters"}, - {ERR_FUNC(EC_F_EC_GROUP_GET_ECPKPARAMETERS), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_COPY, 0), "EC_GROUP_copy"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_GET_CURVE_GF2M, 0), + "EC_GROUP_get_curve_GF2m"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_GET_CURVE_GFP, 0), + "EC_GROUP_get_curve_GFp"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_GET_DEGREE, 0), "EC_GROUP_get_degree"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_GET_ECPARAMETERS, 0), + "EC_GROUP_get_ecparameters"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_GET_ECPKPARAMETERS, 0), "EC_GROUP_get_ecpkparameters"}, - {ERR_FUNC(EC_F_EC_GROUP_GET_PENTANOMIAL_BASIS), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_GET_PENTANOMIAL_BASIS, 0), "EC_GROUP_get_pentanomial_basis"}, - {ERR_FUNC(EC_F_EC_GROUP_GET_TRINOMIAL_BASIS), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_GET_TRINOMIAL_BASIS, 0), "EC_GROUP_get_trinomial_basis"}, - {ERR_FUNC(EC_F_EC_GROUP_NEW), "EC_GROUP_new"}, - {ERR_FUNC(EC_F_EC_GROUP_NEW_BY_CURVE_NAME), "EC_GROUP_new_by_curve_name"}, - {ERR_FUNC(EC_F_EC_GROUP_NEW_FROM_DATA), "ec_group_new_from_data"}, - {ERR_FUNC(EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_NEW, 0), "EC_GROUP_new"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_NEW_BY_CURVE_NAME, 0), + "EC_GROUP_new_by_curve_name"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_NEW_FROM_DATA, 0), + "ec_group_new_from_data"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS, 0), "EC_GROUP_new_from_ecparameters"}, - {ERR_FUNC(EC_F_EC_GROUP_NEW_FROM_ECPKPARAMETERS), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_NEW_FROM_ECPKPARAMETERS, 0), "EC_GROUP_new_from_ecpkparameters"}, - {ERR_FUNC(EC_F_EC_GROUP_SET_CURVE_GF2M), "EC_GROUP_set_curve_GF2m"}, - {ERR_FUNC(EC_F_EC_GROUP_SET_CURVE_GFP), "EC_GROUP_set_curve_GFp"}, - {ERR_FUNC(EC_F_EC_GROUP_SET_GENERATOR), "EC_GROUP_set_generator"}, - {ERR_FUNC(EC_F_EC_KEY_CHECK_KEY), "EC_KEY_check_key"}, - {ERR_FUNC(EC_F_EC_KEY_COPY), "EC_KEY_copy"}, - {ERR_FUNC(EC_F_EC_KEY_GENERATE_KEY), "EC_KEY_generate_key"}, - {ERR_FUNC(EC_F_EC_KEY_NEW), "EC_KEY_new"}, - {ERR_FUNC(EC_F_EC_KEY_NEW_METHOD), "EC_KEY_new_method"}, - {ERR_FUNC(EC_F_EC_KEY_OCT2PRIV), "EC_KEY_oct2priv"}, - {ERR_FUNC(EC_F_EC_KEY_PRINT), "EC_KEY_print"}, - {ERR_FUNC(EC_F_EC_KEY_PRINT_FP), "EC_KEY_print_fp"}, - {ERR_FUNC(EC_F_EC_KEY_PRIV2OCT), "EC_KEY_priv2oct"}, - {ERR_FUNC(EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_SET_CURVE_GF2M, 0), + "EC_GROUP_set_curve_GF2m"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_SET_CURVE_GFP, 0), + "EC_GROUP_set_curve_GFp"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_GROUP_SET_GENERATOR, 0), + "EC_GROUP_set_generator"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_CHECK_KEY, 0), "EC_KEY_check_key"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_COPY, 0), "EC_KEY_copy"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_GENERATE_KEY, 0), "EC_KEY_generate_key"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_NEW, 0), "EC_KEY_new"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_NEW_METHOD, 0), "EC_KEY_new_method"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_OCT2PRIV, 0), "EC_KEY_oct2priv"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_PRINT, 0), "EC_KEY_print"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_PRINT_FP, 0), "EC_KEY_print_fp"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_PRIV2OCT, 0), "EC_KEY_priv2oct"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES, 0), "EC_KEY_set_public_key_affine_coordinates"}, - {ERR_FUNC(EC_F_EC_KEY_SIMPLE_CHECK_KEY), "ec_key_simple_check_key"}, - {ERR_FUNC(EC_F_EC_KEY_SIMPLE_OCT2PRIV), "ec_key_simple_oct2priv"}, - {ERR_FUNC(EC_F_EC_KEY_SIMPLE_PRIV2OCT), "ec_key_simple_priv2oct"}, - {ERR_FUNC(EC_F_EC_POINTS_MAKE_AFFINE), "EC_POINTs_make_affine"}, - {ERR_FUNC(EC_F_EC_POINT_ADD), "EC_POINT_add"}, - {ERR_FUNC(EC_F_EC_POINT_CMP), "EC_POINT_cmp"}, - {ERR_FUNC(EC_F_EC_POINT_COPY), "EC_POINT_copy"}, - {ERR_FUNC(EC_F_EC_POINT_DBL), "EC_POINT_dbl"}, - {ERR_FUNC(EC_F_EC_POINT_GET_AFFINE_COORDINATES_GF2M), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_SIMPLE_CHECK_KEY, 0), + "ec_key_simple_check_key"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_SIMPLE_OCT2PRIV, 0), + "ec_key_simple_oct2priv"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_KEY_SIMPLE_PRIV2OCT, 0), + "ec_key_simple_priv2oct"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_PKEY_CHECK, 0), "ec_pkey_check"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_PKEY_PARAM_CHECK, 0), "ec_pkey_param_check"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINTS_MAKE_AFFINE, 0), + "EC_POINTs_make_affine"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_ADD, 0), "EC_POINT_add"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_CMP, 0), "EC_POINT_cmp"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_COPY, 0), "EC_POINT_copy"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_DBL, 0), "EC_POINT_dbl"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_GET_AFFINE_COORDINATES_GF2M, 0), "EC_POINT_get_affine_coordinates_GF2m"}, - {ERR_FUNC(EC_F_EC_POINT_GET_AFFINE_COORDINATES_GFP), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_GET_AFFINE_COORDINATES_GFP, 0), "EC_POINT_get_affine_coordinates_GFp"}, - {ERR_FUNC(EC_F_EC_POINT_GET_JPROJECTIVE_COORDINATES_GFP), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_GET_JPROJECTIVE_COORDINATES_GFP, 0), "EC_POINT_get_Jprojective_coordinates_GFp"}, - {ERR_FUNC(EC_F_EC_POINT_INVERT), "EC_POINT_invert"}, - {ERR_FUNC(EC_F_EC_POINT_IS_AT_INFINITY), "EC_POINT_is_at_infinity"}, - {ERR_FUNC(EC_F_EC_POINT_IS_ON_CURVE), "EC_POINT_is_on_curve"}, - {ERR_FUNC(EC_F_EC_POINT_MAKE_AFFINE), "EC_POINT_make_affine"}, - {ERR_FUNC(EC_F_EC_POINT_NEW), "EC_POINT_new"}, - {ERR_FUNC(EC_F_EC_POINT_OCT2POINT), "EC_POINT_oct2point"}, - {ERR_FUNC(EC_F_EC_POINT_POINT2OCT), "EC_POINT_point2oct"}, - {ERR_FUNC(EC_F_EC_POINT_SET_AFFINE_COORDINATES_GF2M), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_INVERT, 0), "EC_POINT_invert"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_IS_AT_INFINITY, 0), + "EC_POINT_is_at_infinity"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_IS_ON_CURVE, 0), + "EC_POINT_is_on_curve"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_MAKE_AFFINE, 0), + "EC_POINT_make_affine"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_NEW, 0), "EC_POINT_new"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_OCT2POINT, 0), "EC_POINT_oct2point"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_POINT2OCT, 0), "EC_POINT_point2oct"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_SET_AFFINE_COORDINATES_GF2M, 0), "EC_POINT_set_affine_coordinates_GF2m"}, - {ERR_FUNC(EC_F_EC_POINT_SET_AFFINE_COORDINATES_GFP), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_SET_AFFINE_COORDINATES_GFP, 0), "EC_POINT_set_affine_coordinates_GFp"}, - {ERR_FUNC(EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GF2M), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GF2M, 0), "EC_POINT_set_compressed_coordinates_GF2m"}, - {ERR_FUNC(EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GFP), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GFP, 0), "EC_POINT_set_compressed_coordinates_GFp"}, - {ERR_FUNC(EC_F_EC_POINT_SET_JPROJECTIVE_COORDINATES_GFP), + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_SET_JPROJECTIVE_COORDINATES_GFP, 0), "EC_POINT_set_Jprojective_coordinates_GFp"}, - {ERR_FUNC(EC_F_EC_POINT_SET_TO_INFINITY), "EC_POINT_set_to_infinity"}, - {ERR_FUNC(EC_F_EC_PRE_COMP_NEW), "ec_pre_comp_new"}, - {ERR_FUNC(EC_F_EC_WNAF_MUL), "ec_wNAF_mul"}, - {ERR_FUNC(EC_F_EC_WNAF_PRECOMPUTE_MULT), "ec_wNAF_precompute_mult"}, - {ERR_FUNC(EC_F_I2D_ECPARAMETERS), "i2d_ECParameters"}, - {ERR_FUNC(EC_F_I2D_ECPKPARAMETERS), "i2d_ECPKParameters"}, - {ERR_FUNC(EC_F_I2D_ECPRIVATEKEY), "i2d_ECPrivateKey"}, - {ERR_FUNC(EC_F_I2O_ECPUBLICKEY), "i2o_ECPublicKey"}, - {ERR_FUNC(EC_F_NISTP224_PRE_COMP_NEW), "nistp224_pre_comp_new"}, - {ERR_FUNC(EC_F_NISTP256_PRE_COMP_NEW), "nistp256_pre_comp_new"}, - {ERR_FUNC(EC_F_NISTP521_PRE_COMP_NEW), "nistp521_pre_comp_new"}, - {ERR_FUNC(EC_F_O2I_ECPUBLICKEY), "o2i_ECPublicKey"}, - {ERR_FUNC(EC_F_OLD_EC_PRIV_DECODE), "old_ec_priv_decode"}, - {ERR_FUNC(EC_F_OSSL_ECDH_COMPUTE_KEY), "ossl_ecdh_compute_key"}, - {ERR_FUNC(EC_F_OSSL_ECDSA_SIGN_SIG), "ossl_ecdsa_sign_sig"}, - {ERR_FUNC(EC_F_OSSL_ECDSA_VERIFY_SIG), "ossl_ecdsa_verify_sig"}, - {ERR_FUNC(EC_F_PKEY_ECX_DERIVE), "pkey_ecx_derive"}, - {ERR_FUNC(EC_F_PKEY_EC_CTRL), "pkey_ec_ctrl"}, - {ERR_FUNC(EC_F_PKEY_EC_CTRL_STR), "pkey_ec_ctrl_str"}, - {ERR_FUNC(EC_F_PKEY_EC_DERIVE), "pkey_ec_derive"}, - {ERR_FUNC(EC_F_PKEY_EC_KEYGEN), "pkey_ec_keygen"}, - {ERR_FUNC(EC_F_PKEY_EC_PARAMGEN), "pkey_ec_paramgen"}, - {ERR_FUNC(EC_F_PKEY_EC_SIGN), "pkey_ec_sign"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_POINT_SET_TO_INFINITY, 0), + "EC_POINT_set_to_infinity"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_PRE_COMP_NEW, 0), "ec_pre_comp_new"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_WNAF_MUL, 0), "ec_wNAF_mul"}, + {ERR_PACK(ERR_LIB_EC, EC_F_EC_WNAF_PRECOMPUTE_MULT, 0), + "ec_wNAF_precompute_mult"}, + {ERR_PACK(ERR_LIB_EC, EC_F_I2D_ECPARAMETERS, 0), "i2d_ECParameters"}, + {ERR_PACK(ERR_LIB_EC, EC_F_I2D_ECPKPARAMETERS, 0), "i2d_ECPKParameters"}, + {ERR_PACK(ERR_LIB_EC, EC_F_I2D_ECPRIVATEKEY, 0), "i2d_ECPrivateKey"}, + {ERR_PACK(ERR_LIB_EC, EC_F_I2O_ECPUBLICKEY, 0), "i2o_ECPublicKey"}, + {ERR_PACK(ERR_LIB_EC, EC_F_NISTP224_PRE_COMP_NEW, 0), + "nistp224_pre_comp_new"}, + {ERR_PACK(ERR_LIB_EC, EC_F_NISTP256_PRE_COMP_NEW, 0), + "nistp256_pre_comp_new"}, + {ERR_PACK(ERR_LIB_EC, EC_F_NISTP521_PRE_COMP_NEW, 0), + "nistp521_pre_comp_new"}, + {ERR_PACK(ERR_LIB_EC, EC_F_O2I_ECPUBLICKEY, 0), "o2i_ECPublicKey"}, + {ERR_PACK(ERR_LIB_EC, EC_F_OLD_EC_PRIV_DECODE, 0), "old_ec_priv_decode"}, + {ERR_PACK(ERR_LIB_EC, EC_F_OSSL_ECDH_COMPUTE_KEY, 0), + "ossl_ecdh_compute_key"}, + {ERR_PACK(ERR_LIB_EC, EC_F_OSSL_ECDSA_SIGN_SIG, 0), "ossl_ecdsa_sign_sig"}, + {ERR_PACK(ERR_LIB_EC, EC_F_OSSL_ECDSA_VERIFY_SIG, 0), + "ossl_ecdsa_verify_sig"}, + {ERR_PACK(ERR_LIB_EC, EC_F_PKEY_ECD_CTRL, 0), "pkey_ecd_ctrl"}, + {ERR_PACK(ERR_LIB_EC, EC_F_PKEY_ECD_DIGESTSIGN, 0), "pkey_ecd_digestsign"}, + {ERR_PACK(ERR_LIB_EC, EC_F_PKEY_ECX_DERIVE, 0), "pkey_ecx_derive"}, + {ERR_PACK(ERR_LIB_EC, EC_F_PKEY_EC_CTRL, 0), "pkey_ec_ctrl"}, + {ERR_PACK(ERR_LIB_EC, EC_F_PKEY_EC_CTRL_STR, 0), "pkey_ec_ctrl_str"}, + {ERR_PACK(ERR_LIB_EC, EC_F_PKEY_EC_DERIVE, 0), "pkey_ec_derive"}, + {ERR_PACK(ERR_LIB_EC, EC_F_PKEY_EC_KEYGEN, 0), "pkey_ec_keygen"}, + {ERR_PACK(ERR_LIB_EC, EC_F_PKEY_EC_PARAMGEN, 0), "pkey_ec_paramgen"}, + {ERR_PACK(ERR_LIB_EC, EC_F_PKEY_EC_SIGN, 0), "pkey_ec_sign"}, {0, NULL} }; -static ERR_STRING_DATA EC_str_reasons[] = { - {ERR_REASON(EC_R_ASN1_ERROR), "asn1 error"}, - {ERR_REASON(EC_R_BAD_SIGNATURE), "bad signature"}, - {ERR_REASON(EC_R_BIGNUM_OUT_OF_RANGE), "bignum out of range"}, - {ERR_REASON(EC_R_BUFFER_TOO_SMALL), "buffer too small"}, - {ERR_REASON(EC_R_COORDINATES_OUT_OF_RANGE), "coordinates out of range"}, - {ERR_REASON(EC_R_CURVE_DOES_NOT_SUPPORT_ECDH), - "curve does not support ecdh"}, - {ERR_REASON(EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING), - "curve does not support signing"}, - {ERR_REASON(EC_R_D2I_ECPKPARAMETERS_FAILURE), - "d2i ecpkparameters failure"}, - {ERR_REASON(EC_R_DECODE_ERROR), "decode error"}, - {ERR_REASON(EC_R_DISCRIMINANT_IS_ZERO), "discriminant is zero"}, - {ERR_REASON(EC_R_EC_GROUP_NEW_BY_NAME_FAILURE), - "ec group new by name failure"}, - {ERR_REASON(EC_R_FIELD_TOO_LARGE), "field too large"}, - {ERR_REASON(EC_R_GF2M_NOT_SUPPORTED), "gf2m not supported"}, - {ERR_REASON(EC_R_GROUP2PKPARAMETERS_FAILURE), - "group2pkparameters failure"}, - {ERR_REASON(EC_R_I2D_ECPKPARAMETERS_FAILURE), - "i2d ecpkparameters failure"}, - {ERR_REASON(EC_R_INCOMPATIBLE_OBJECTS), "incompatible objects"}, - {ERR_REASON(EC_R_INVALID_ARGUMENT), "invalid argument"}, - {ERR_REASON(EC_R_INVALID_COMPRESSED_POINT), "invalid compressed point"}, - {ERR_REASON(EC_R_INVALID_COMPRESSION_BIT), "invalid compression bit"}, - {ERR_REASON(EC_R_INVALID_CURVE), "invalid curve"}, - {ERR_REASON(EC_R_INVALID_DIGEST), "invalid digest"}, - {ERR_REASON(EC_R_INVALID_DIGEST_TYPE), "invalid digest type"}, - {ERR_REASON(EC_R_INVALID_ENCODING), "invalid encoding"}, - {ERR_REASON(EC_R_INVALID_FIELD), "invalid field"}, - {ERR_REASON(EC_R_INVALID_FORM), "invalid form"}, - {ERR_REASON(EC_R_INVALID_GROUP_ORDER), "invalid group order"}, - {ERR_REASON(EC_R_INVALID_KEY), "invalid key"}, - {ERR_REASON(EC_R_INVALID_OUTPUT_LENGTH), "invalid output length"}, - {ERR_REASON(EC_R_INVALID_PEER_KEY), "invalid peer key"}, - {ERR_REASON(EC_R_INVALID_PENTANOMIAL_BASIS), "invalid pentanomial basis"}, - {ERR_REASON(EC_R_INVALID_PRIVATE_KEY), "invalid private key"}, - {ERR_REASON(EC_R_INVALID_TRINOMIAL_BASIS), "invalid trinomial basis"}, - {ERR_REASON(EC_R_KDF_PARAMETER_ERROR), "kdf parameter error"}, - {ERR_REASON(EC_R_KEYS_NOT_SET), "keys not set"}, - {ERR_REASON(EC_R_MISSING_PARAMETERS), "missing parameters"}, - {ERR_REASON(EC_R_MISSING_PRIVATE_KEY), "missing private key"}, - {ERR_REASON(EC_R_NEED_NEW_SETUP_VALUES), "need new setup values"}, - {ERR_REASON(EC_R_NOT_A_NIST_PRIME), "not a NIST prime"}, - {ERR_REASON(EC_R_NOT_IMPLEMENTED), "not implemented"}, - {ERR_REASON(EC_R_NOT_INITIALIZED), "not initialized"}, - {ERR_REASON(EC_R_NO_PARAMETERS_SET), "no parameters set"}, - {ERR_REASON(EC_R_NO_PRIVATE_VALUE), "no private value"}, - {ERR_REASON(EC_R_OPERATION_NOT_SUPPORTED), "operation not supported"}, - {ERR_REASON(EC_R_PASSED_NULL_PARAMETER), "passed null parameter"}, - {ERR_REASON(EC_R_PEER_KEY_ERROR), "peer key error"}, - {ERR_REASON(EC_R_PKPARAMETERS2GROUP_FAILURE), - "pkparameters2group failure"}, - {ERR_REASON(EC_R_POINT_ARITHMETIC_FAILURE), "point arithmetic failure"}, - {ERR_REASON(EC_R_POINT_AT_INFINITY), "point at infinity"}, - {ERR_REASON(EC_R_POINT_IS_NOT_ON_CURVE), "point is not on curve"}, - {ERR_REASON(EC_R_RANDOM_NUMBER_GENERATION_FAILED), - "random number generation failed"}, - {ERR_REASON(EC_R_SHARED_INFO_ERROR), "shared info error"}, - {ERR_REASON(EC_R_SLOT_FULL), "slot full"}, - {ERR_REASON(EC_R_UNDEFINED_GENERATOR), "undefined generator"}, - {ERR_REASON(EC_R_UNDEFINED_ORDER), "undefined order"}, - {ERR_REASON(EC_R_UNKNOWN_GROUP), "unknown group"}, - {ERR_REASON(EC_R_UNKNOWN_ORDER), "unknown order"}, - {ERR_REASON(EC_R_UNSUPPORTED_FIELD), "unsupported field"}, - {ERR_REASON(EC_R_WRONG_CURVE_PARAMETERS), "wrong curve parameters"}, - {ERR_REASON(EC_R_WRONG_ORDER), "wrong order"}, +static const ERR_STRING_DATA EC_str_reasons[] = { + {ERR_PACK(ERR_LIB_EC, 0, EC_R_ASN1_ERROR), "asn1 error"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_BAD_SIGNATURE), "bad signature"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_BIGNUM_OUT_OF_RANGE), "bignum out of range"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_BUFFER_TOO_SMALL), "buffer too small"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_COORDINATES_OUT_OF_RANGE), + "coordinates out of range"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_CURVE_DOES_NOT_SUPPORT_ECDH), + "curve does not support ecdh"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING), + "curve does not support signing"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_D2I_ECPKPARAMETERS_FAILURE), + "d2i ecpkparameters failure"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_DECODE_ERROR), "decode error"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_DISCRIMINANT_IS_ZERO), + "discriminant is zero"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_EC_GROUP_NEW_BY_NAME_FAILURE), + "ec group new by name failure"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_FIELD_TOO_LARGE), "field too large"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_GF2M_NOT_SUPPORTED), "gf2m not supported"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_GROUP2PKPARAMETERS_FAILURE), + "group2pkparameters failure"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_I2D_ECPKPARAMETERS_FAILURE), + "i2d ecpkparameters failure"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INCOMPATIBLE_OBJECTS), + "incompatible objects"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_ARGUMENT), "invalid argument"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_COMPRESSED_POINT), + "invalid compressed point"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_COMPRESSION_BIT), + "invalid compression bit"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_CURVE), "invalid curve"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_DIGEST), "invalid digest"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_DIGEST_TYPE), "invalid digest type"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_ENCODING), "invalid encoding"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_FIELD), "invalid field"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_FORM), "invalid form"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_GROUP_ORDER), "invalid group order"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_KEY), "invalid key"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_OUTPUT_LENGTH), + "invalid output length"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_PEER_KEY), "invalid peer key"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_PENTANOMIAL_BASIS), + "invalid pentanomial basis"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_PRIVATE_KEY), "invalid private key"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_INVALID_TRINOMIAL_BASIS), + "invalid trinomial basis"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_KDF_PARAMETER_ERROR), "kdf parameter error"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_KEYS_NOT_SET), "keys not set"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_MISSING_PARAMETERS), "missing parameters"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_MISSING_PRIVATE_KEY), "missing private key"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_NEED_NEW_SETUP_VALUES), + "need new setup values"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_NOT_A_NIST_PRIME), "not a NIST prime"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_NOT_IMPLEMENTED), "not implemented"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_NOT_INITIALIZED), "not initialized"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_NO_PARAMETERS_SET), "no parameters set"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_NO_PRIVATE_VALUE), "no private value"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_OPERATION_NOT_SUPPORTED), + "operation not supported"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_PASSED_NULL_PARAMETER), + "passed null parameter"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_PEER_KEY_ERROR), "peer key error"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_PKPARAMETERS2GROUP_FAILURE), + "pkparameters2group failure"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_POINT_ARITHMETIC_FAILURE), + "point arithmetic failure"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_POINT_AT_INFINITY), "point at infinity"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_POINT_IS_NOT_ON_CURVE), + "point is not on curve"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_RANDOM_NUMBER_GENERATION_FAILED), + "random number generation failed"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_SHARED_INFO_ERROR), "shared info error"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_SLOT_FULL), "slot full"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNDEFINED_GENERATOR), "undefined generator"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNDEFINED_ORDER), "undefined order"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNKNOWN_GROUP), "unknown group"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNKNOWN_ORDER), "unknown order"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_UNSUPPORTED_FIELD), "unsupported field"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_WRONG_CURVE_PARAMETERS), + "wrong curve parameters"}, + {ERR_PACK(ERR_LIB_EC, 0, EC_R_WRONG_ORDER), "wrong order"}, {0, NULL} }; @@ -282,10 +342,9 @@ static ERR_STRING_DATA EC_str_reasons[] = { int ERR_load_EC_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(EC_str_functs[0].error) == NULL) { - ERR_load_strings(0, EC_str_functs); - ERR_load_strings(0, EC_str_reasons); + ERR_load_strings_const(EC_str_functs); + ERR_load_strings_const(EC_str_reasons); } #endif return 1; diff --git a/crypto/ec/ec_key.c b/crypto/ec/ec_key.c index f1f0afb4..38745531 100644 --- a/crypto/ec/ec_key.c +++ b/crypto/ec/ec_key.c @@ -1,5 +1,6 @@ /* - * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2002-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,15 +8,10 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * Portions originally developed by SUN MICROSYSTEMS, INC., and - * contributed to the OpenSSL project. - */ - -#include +#include "internal/cryptlib.h" #include #include "ec_lcl.h" +#include "internal/refcount.h" #include #include @@ -49,7 +45,7 @@ void EC_KEY_free(EC_KEY *r) if (r == NULL) return; - CRYPTO_atomic_add(&r->references, -1, &i, r->lock); + CRYPTO_DOWN_REF(&r->references, &i, r->lock); REF_PRINT_COUNT("EC_KEY", r); if (i > 0) return; @@ -169,7 +165,7 @@ int EC_KEY_up_ref(EC_KEY *r) { int i; - if (CRYPTO_atomic_add(&r->references, 1, &i, r->lock) <= 0) + if (CRYPTO_UP_REF(&r->references, &i, r->lock) <= 0) return 0; REF_PRINT_COUNT("EC_KEY", r); @@ -177,6 +173,11 @@ int EC_KEY_up_ref(EC_KEY *r) return ((i > 1) ? 1 : 0); } +ENGINE *EC_KEY_get0_engine(const EC_KEY *eckey) +{ + return eckey->engine; +} + int EC_KEY_generate_key(EC_KEY *eckey) { if (eckey == NULL || eckey->group == NULL) { @@ -191,7 +192,6 @@ int EC_KEY_generate_key(EC_KEY *eckey) int ossl_ec_key_gen(EC_KEY *eckey) { - OPENSSL_assert(eckey->group->meth->keygen != NULL); return eckey->group->meth->keygen(eckey); } @@ -218,7 +218,7 @@ int ec_key_simple_generate_key(EC_KEY *eckey) goto err; do - if (!BN_rand_range(priv_key, order)) + if (!BN_priv_rand_range(priv_key, order)) goto err; while (BN_is_zero(priv_key)) ; diff --git a/crypto/ec/ec_lcl.h b/crypto/ec/ec_lcl.h index 53db327f..421cd470 100644 --- a/crypto/ec/ec_lcl.h +++ b/crypto/ec/ec_lcl.h @@ -1,5 +1,6 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,27 +8,12 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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 #include #include #include - -#include "e_os.h" +#include "internal/refcount.h" #if defined(__SUNPRO_C) # if __SUNPRO_C >= 0x520 @@ -264,7 +250,7 @@ struct ec_key_st { BIGNUM *priv_key; unsigned int enc_flag; point_conversion_form_t conv_form; - int references; + CRYPTO_REF_COUNT references; int flags; CRYPTO_EX_DATA ex_data; CRYPTO_RWLOCK *lock; @@ -609,6 +595,13 @@ int ossl_ecdsa_verify(int type, const unsigned char *dgst, int dgst_len, int ossl_ecdsa_verify_sig(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey); +int ED25519_sign(uint8_t *out_sig, const uint8_t *message, size_t message_len, + const uint8_t public_key[32], const uint8_t private_key[32]); +int ED25519_verify(const uint8_t *message, size_t message_len, + const uint8_t signature[64], const uint8_t public_key[32]); +void ED25519_public_from_private(uint8_t out_public_key[32], + const uint8_t private_key[32]); + int X25519(uint8_t out_shared_key[32], const uint8_t private_key[32], const uint8_t peer_public_value[32]); void X25519_public_from_private(uint8_t out_public_value[32], diff --git a/crypto/ec/ec_lib.c b/crypto/ec/ec_lib.c index a74a96c6..d98ffae6 100644 --- a/crypto/ec/ec_lib.c +++ b/crypto/ec/ec_lib.c @@ -1,5 +1,6 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,12 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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 #include @@ -66,13 +61,13 @@ EC_GROUP *EC_GROUP_new(const EC_METHOD *meth) void EC_pre_comp_free(EC_GROUP *group) { switch (group->pre_comp_type) { - default: + case PCT_none: break; -#ifdef ECP_NISTZ256_REFERENCE_IMPLEMENTATION case PCT_nistz256: +#ifdef ECP_NISTZ256_ASM EC_nistz256_pre_comp_free(group->pre_comp.nistz256); - break; #endif + break; #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 case PCT_nistp224: EC_nistp224_pre_comp_free(group->pre_comp.nistp224); @@ -83,6 +78,11 @@ void EC_pre_comp_free(EC_GROUP *group) case PCT_nistp521: EC_nistp521_pre_comp_free(group->pre_comp.nistp521); break; +#else + case PCT_nistp224: + case PCT_nistp256: + case PCT_nistp521: + break; #endif case PCT_ec: EC_ec_pre_comp_free(group->pre_comp.ec); @@ -143,14 +143,14 @@ int EC_GROUP_copy(EC_GROUP *dest, const EC_GROUP *src) /* Copy precomputed */ dest->pre_comp_type = src->pre_comp_type; switch (src->pre_comp_type) { - default: + case PCT_none: dest->pre_comp.ec = NULL; break; -#ifdef ECP_NISTZ256_REFERENCE_IMPLEMENTATION case PCT_nistz256: +#ifdef ECP_NISTZ256_ASM dest->pre_comp.nistz256 = EC_nistz256_pre_comp_dup(src->pre_comp.nistz256); - break; #endif + break; #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 case PCT_nistp224: dest->pre_comp.nistp224 = EC_nistp224_pre_comp_dup(src->pre_comp.nistp224); @@ -161,6 +161,11 @@ int EC_GROUP_copy(EC_GROUP *dest, const EC_GROUP *src) case PCT_nistp521: dest->pre_comp.nistp521 = EC_nistp521_pre_comp_dup(src->pre_comp.nistp521); break; +#else + case PCT_nistp224: + case PCT_nistp256: + case PCT_nistp521: + break; #endif case PCT_ec: dest->pre_comp.ec = EC_ec_pre_comp_dup(src->pre_comp.ec); @@ -232,7 +237,7 @@ EC_GROUP *EC_GROUP_dup(const EC_GROUP *a) return NULL; if ((t = EC_GROUP_new(a->meth)) == NULL) - return (NULL); + return NULL; if (!EC_GROUP_copy(t, a)) goto err; @@ -327,7 +332,6 @@ const BIGNUM *EC_GROUP_get0_order(const EC_GROUP *group) int EC_GROUP_order_bits(const EC_GROUP *group) { - OPENSSL_assert(group->meth->group_order_bits != NULL); return group->meth->group_order_bits(group); } @@ -621,7 +625,7 @@ EC_POINT *EC_POINT_dup(const EC_POINT *a, const EC_GROUP *group) t = EC_POINT_new(group); if (t == NULL) - return (NULL); + return NULL; r = EC_POINT_copy(t, a); if (!r) { EC_POINT_free(t); diff --git a/crypto/ec/ec_mult.c b/crypto/ec/ec_mult.c index b39777fb..ed26b68c 100644 --- a/crypto/ec/ec_mult.c +++ b/crypto/ec/ec_mult.c @@ -1,5 +1,6 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,18 +8,13 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * Portions of this software developed by SUN MICROSYSTEMS, INC., - * and contributed to the OpenSSL project. - */ - #include #include #include "internal/cryptlib.h" #include "internal/bn_int.h" #include "ec_lcl.h" +#include "internal/refcount.h" /* * This file implements the wNAF-based interleaving multi-exponentiation method @@ -42,7 +38,7 @@ struct ec_pre_comp_st { * generator: 'num' pointers to EC_POINT * objects followed by a NULL */ size_t num; /* numblocks * 2^(w-1) */ - int references; + CRYPTO_REF_COUNT references; CRYPTO_RWLOCK *lock; }; @@ -77,7 +73,7 @@ EC_PRE_COMP *EC_ec_pre_comp_dup(EC_PRE_COMP *pre) { int i; if (pre != NULL) - CRYPTO_atomic_add(&pre->references, 1, &i, pre->lock); + CRYPTO_UP_REF(&pre->references, &i, pre->lock); return pre; } @@ -88,7 +84,7 @@ void EC_ec_pre_comp_free(EC_PRE_COMP *pre) if (pre == NULL) return; - CRYPTO_atomic_add(&pre->references, -1, &i, pre->lock); + CRYPTO_DOWN_REF(&pre->references, &i, pre->lock); REF_PRINT_COUNT("EC_ec", pre); if (i > 0) return; diff --git a/crypto/ec/ec_oct.c b/crypto/ec/ec_oct.c index effc42a3..4a3e54ae 100644 --- a/crypto/ec/ec_oct.c +++ b/crypto/ec/ec_oct.c @@ -1,5 +1,6 @@ /* * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,12 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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 #include diff --git a/crypto/ec/ecdh_ossl.c b/crypto/ec/ecdh_ossl.c index a8651459..3302050c 100644 --- a/crypto/ec/ecdh_ossl.c +++ b/crypto/ec/ecdh_ossl.c @@ -1,5 +1,6 @@ /* * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,21 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * 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. - * - */ - #include #include diff --git a/crypto/ec/ecdsa_ossl.c b/crypto/ec/ecdsa_ossl.c index 8f07b16f..2c9e5a88 100644 --- a/crypto/ec/ecdsa_ossl.c +++ b/crypto/ec/ecdsa_ossl.c @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2002-2018 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 @@ -20,7 +20,7 @@ int ossl_ecdsa_sign(int type, const unsigned char *dgst, int dlen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey) { ECDSA_SIG *s; - RAND_seed(dgst, dlen); + s = ECDSA_do_sign_ex(dgst, dlen, kinv, r, eckey); if (s == NULL) { *siglen = 0; @@ -97,7 +97,7 @@ static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, goto err; } } else { - if (!BN_rand_range(k, order)) { + if (!BN_priv_rand_range(k, order)) { ECerr(EC_F_ECDSA_SIGN_SETUP, EC_R_RANDOM_NUMBER_GENERATION_FAILED); goto err; @@ -199,7 +199,7 @@ static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BN_CTX_free(ctx); EC_POINT_free(tmp_point); BN_clear_free(X); - return (ret); + return ret; } int ossl_ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp, @@ -301,7 +301,7 @@ ECDSA_SIG *ossl_ecdsa_sign_sig(const unsigned char *dgst, int dgst_len, } if (BN_is_zero(s)) { /* - * if kinv and r have been supplied by the caller don't to + * if kinv and r have been supplied by the caller, don't * generate new kinv and r values */ if (in_kinv != NULL && in_r != NULL) { @@ -344,7 +344,7 @@ int ossl_ecdsa_verify(int type, const unsigned char *dgst, int dgst_len, s = ECDSA_SIG_new(); if (s == NULL) - return (ret); + return ret; if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL) goto err; /* Ensure signature uses DER and doesn't have trailing garbage */ @@ -355,7 +355,7 @@ int ossl_ecdsa_verify(int type, const unsigned char *dgst, int dgst_len, err: OPENSSL_clear_free(der, derlen); ECDSA_SIG_free(s); - return (ret); + return ret; } int ossl_ecdsa_verify_sig(const unsigned char *dgst, int dgst_len, diff --git a/crypto/ec/eck_prn.c b/crypto/ec/eck_prn.c index 3e826cb1..2e501b2d 100644 --- a/crypto/ec/eck_prn.c +++ b/crypto/ec/eck_prn.c @@ -1,5 +1,6 @@ /* * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,12 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * Portions originally developed by SUN MICROSYSTEMS, INC., and - * contributed to the OpenSSL project. - */ - #include #include "internal/cryptlib.h" #include @@ -27,12 +22,12 @@ int ECPKParameters_print_fp(FILE *fp, const EC_GROUP *x, int off) if ((b = BIO_new(BIO_s_file())) == NULL) { ECerr(EC_F_ECPKPARAMETERS_PRINT_FP, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = ECPKParameters_print(b, x, off); BIO_free(b); - return (ret); + return ret; } int EC_KEY_print_fp(FILE *fp, const EC_KEY *x, int off) @@ -42,12 +37,12 @@ int EC_KEY_print_fp(FILE *fp, const EC_KEY *x, int off) if ((b = BIO_new(BIO_s_file())) == NULL) { ECerr(EC_F_EC_KEY_PRINT_FP, ERR_R_BIO_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = EC_KEY_print(b, x, off); BIO_free(b); - return (ret); + return ret; } int ECParameters_print_fp(FILE *fp, const EC_KEY *x) @@ -57,12 +52,12 @@ int ECParameters_print_fp(FILE *fp, const EC_KEY *x) if ((b = BIO_new(BIO_s_file())) == NULL) { ECerr(EC_F_ECPARAMETERS_PRINT_FP, ERR_R_BIO_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = ECParameters_print(b, x); BIO_free(b); - return (ret); + return ret; } #endif @@ -231,7 +226,7 @@ int ECPKParameters_print(BIO *bp, const EC_GROUP *x, int off) BN_free(b); BN_free(gen); BN_CTX_free(ctx); - return (ret); + return ret; } static int print_bin(BIO *fp, const char *name, const unsigned char *buf, diff --git a/crypto/ec/ecp_mont.c b/crypto/ec/ecp_mont.c index 994cc1d0..1a760d12 100644 --- a/crypto/ec/ecp_mont.c +++ b/crypto/ec/ecp_mont.c @@ -1,5 +1,6 @@ /* * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,12 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * Portions of this software developed by SUN MICROSYSTEMS, INC., - * and contributed to the OpenSSL project. - */ - #include #include "ec_lcl.h" diff --git a/crypto/ec/ecp_nist.c b/crypto/ec/ecp_nist.c index 615563bc..16c4cce3 100644 --- a/crypto/ec/ecp_nist.c +++ b/crypto/ec/ecp_nist.c @@ -1,5 +1,6 @@ /* * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,12 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * Portions of this software developed by SUN MICROSYSTEMS, INC., - * and contributed to the OpenSSL project. - */ - #include #include diff --git a/crypto/ec/ecp_nistp224.c b/crypto/ec/ecp_nistp224.c index 0cd994fc..4ece15c9 100644 --- a/crypto/ec/ecp_nistp224.c +++ b/crypto/ec/ecp_nistp224.c @@ -1,5 +1,5 @@ /* - * Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2010-2018 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 @@ -40,12 +40,12 @@ NON_EMPTY_TRANSLATION_UNIT # include # include "ec_lcl.h" -# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +# if defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16 /* 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" +# error "Need GCC 4.0 or later to define type uint128_t" # endif typedef uint8_t u8; @@ -78,7 +78,7 @@ typedef limb felem[4]; typedef widelimb widefelem[7]; /* - * Field element represented as a byte arrary. 28*8 = 224 bits is also the + * Field element represented as a byte array. 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. */ @@ -235,7 +235,7 @@ static const felem gmul[2][16][3] = { /* Precomputation for the group generator. */ struct nistp224_pre_comp_st { felem g_pre_comp[2][16][3]; - int references; + CRYPTO_REF_COUNT references; CRYPTO_RWLOCK *lock; }; @@ -1238,7 +1238,7 @@ NISTP224_PRE_COMP *EC_nistp224_pre_comp_dup(NISTP224_PRE_COMP *p) { int i; if (p != NULL) - CRYPTO_atomic_add(&p->references, 1, &i, p->lock); + CRYPTO_UP_REF(&p->references, &i, p->lock); return p; } @@ -1249,7 +1249,7 @@ void EC_nistp224_pre_comp_free(NISTP224_PRE_COMP *p) if (p == NULL) return; - CRYPTO_atomic_add(&p->references, -1, &i, p->lock); + CRYPTO_DOWN_REF(&p->references, &i, p->lock); REF_PRINT_COUNT("EC_nistp224", x); if (i > 0) return; @@ -1284,9 +1284,10 @@ int ec_GFp_nistp224_group_set_curve(EC_GROUP *group, const BIGNUM *p, 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)) + curve_p = BN_CTX_get(ctx); + curve_a = BN_CTX_get(ctx); + curve_b = BN_CTX_get(ctx); + if (curve_b == 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); @@ -1415,10 +1416,11 @@ int ec_GFp_nistp224_points_mul(const EC_GROUP *group, EC_POINT *r, 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)) + x = BN_CTX_get(ctx); + y = BN_CTX_get(ctx); + z = BN_CTX_get(ctx); + tmp_scalar = BN_CTX_get(ctx); + if (tmp_scalar == NULL) goto err; if (scalar != NULL) { @@ -1598,7 +1600,9 @@ int ec_GFp_nistp224_precompute_mult(EC_GROUP *group, BN_CTX *ctx) 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)) + x = BN_CTX_get(ctx); + y = BN_CTX_get(ctx); + if (y == NULL) goto err; /* get the generator */ if (group->generator == NULL) diff --git a/crypto/ec/ecp_nistp256.c b/crypto/ec/ecp_nistp256.c index ffd2a7d9..5eee25cd 100644 --- a/crypto/ec/ecp_nistp256.c +++ b/crypto/ec/ecp_nistp256.c @@ -1,5 +1,5 @@ /* - * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2011-2018 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 @@ -41,13 +41,13 @@ NON_EMPTY_TRANSLATION_UNIT # include # include "ec_lcl.h" -# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +# if defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16 /* 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" +# error "Need GCC 4.0 or later to define type uint128_t" # endif typedef uint8_t u8; @@ -1766,7 +1766,7 @@ static void batch_mul(felem x_out, felem y_out, felem z_out, /* Precomputation for the group generator. */ struct nistp256_pre_comp_st { smallfelem g_pre_comp[2][16][3]; - int references; + CRYPTO_REF_COUNT references; CRYPTO_RWLOCK *lock; }; @@ -1856,7 +1856,7 @@ NISTP256_PRE_COMP *EC_nistp256_pre_comp_dup(NISTP256_PRE_COMP *p) { int i; if (p != NULL) - CRYPTO_atomic_add(&p->references, 1, &i, p->lock); + CRYPTO_UP_REF(&p->references, &i, p->lock); return p; } @@ -1867,7 +1867,7 @@ void EC_nistp256_pre_comp_free(NISTP256_PRE_COMP *pre) if (pre == NULL) return; - CRYPTO_atomic_add(&pre->references, -1, &i, pre->lock); + CRYPTO_DOWN_REF(&pre->references, &i, pre->lock); REF_PRINT_COUNT("EC_nistp256", x); if (i > 0) return; @@ -1902,9 +1902,10 @@ int ec_GFp_nistp256_group_set_curve(EC_GROUP *group, const BIGNUM *p, 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)) + curve_p = BN_CTX_get(ctx); + curve_a = BN_CTX_get(ctx); + curve_b = BN_CTX_get(ctx); + if (curve_b == 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); @@ -2034,10 +2035,11 @@ int ec_GFp_nistp256_points_mul(const EC_GROUP *group, EC_POINT *r, 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)) + x = BN_CTX_get(ctx); + y = BN_CTX_get(ctx); + z = BN_CTX_get(ctx); + tmp_scalar = BN_CTX_get(ctx); + if (tmp_scalar == NULL) goto err; if (scalar != NULL) { @@ -2224,7 +2226,9 @@ int ec_GFp_nistp256_precompute_mult(EC_GROUP *group, BN_CTX *ctx) 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)) + x = BN_CTX_get(ctx); + y = BN_CTX_get(ctx); + if (y == NULL) goto err; /* get the generator */ if (group->generator == NULL) diff --git a/crypto/ec/ecp_nistp521.c b/crypto/ec/ecp_nistp521.c index 133f089f..97846f85 100644 --- a/crypto/ec/ecp_nistp521.c +++ b/crypto/ec/ecp_nistp521.c @@ -1,5 +1,5 @@ /* - * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2011-2018 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 @@ -40,12 +40,12 @@ NON_EMPTY_TRANSLATION_UNIT # include # include "ec_lcl.h" -# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +# if defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16 /* 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" +# error "Need GCC 4.0 or later to define type uint128_t" # endif typedef uint8_t u8; @@ -1156,9 +1156,9 @@ static void copy_conditional(felem out, const felem in, limb mask) * 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. */ + * are equal (while not equal to the point at infinity). See comment below + * on constant-time. + */ 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, @@ -1252,6 +1252,22 @@ static void point_add(felem x3, felem y3, felem z3, /* ftmp5[i] < 2^61 */ if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) { + /* + * This is obviously not constant-time but it will almost-never happen + * for ECDH / ECDSA. The case where it can happen is during scalar-mult + * where the intermediate value gets very close to the group order. + * Since |ec_GFp_nistp_recode_scalar_bits| produces signed digits for + * the scalar, it's possible for the intermediate value to be a small + * negative multiple of the base point, and for the final signed digit + * to be the same value. We believe that this only occurs for the scalar + * 1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff + * ffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb + * 71e913863f7, in that case the penultimate intermediate is -9G and + * the final digit is also -9G. Since this only happens for a single + * scalar, the timing leak is irrelevent. (Any attacker who wanted to + * check whether a secret scalar was that exact value, can already do + * so.) + */ point_double(x3, y3, z3, x1, y1, z1); return; } @@ -1587,7 +1603,7 @@ static void batch_mul(felem x_out, felem y_out, felem z_out, /* Precomputation for the group generator. */ struct nistp521_pre_comp_st { felem g_pre_comp[16][3]; - int references; + CRYPTO_REF_COUNT references; CRYPTO_RWLOCK *lock; }; @@ -1677,7 +1693,7 @@ NISTP521_PRE_COMP *EC_nistp521_pre_comp_dup(NISTP521_PRE_COMP *p) { int i; if (p != NULL) - CRYPTO_atomic_add(&p->references, 1, &i, p->lock); + CRYPTO_UP_REF(&p->references, &i, p->lock); return p; } @@ -1688,7 +1704,7 @@ void EC_nistp521_pre_comp_free(NISTP521_PRE_COMP *p) if (p == NULL) return; - CRYPTO_atomic_add(&p->references, -1, &i, p->lock); + CRYPTO_DOWN_REF(&p->references, &i, p->lock); REF_PRINT_COUNT("EC_nistp521", x); if (i > 0) return; @@ -1723,9 +1739,10 @@ int ec_GFp_nistp521_group_set_curve(EC_GROUP *group, const BIGNUM *p, 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)) + curve_p = BN_CTX_get(ctx); + curve_a = BN_CTX_get(ctx); + curve_b = BN_CTX_get(ctx); + if (curve_b == 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); @@ -1854,10 +1871,11 @@ int ec_GFp_nistp521_points_mul(const EC_GROUP *group, EC_POINT *r, 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)) + x = BN_CTX_get(ctx); + y = BN_CTX_get(ctx); + z = BN_CTX_get(ctx); + tmp_scalar = BN_CTX_get(ctx); + if (tmp_scalar == NULL) goto err; if (scalar != NULL) { @@ -2041,7 +2059,9 @@ int ec_GFp_nistp521_precompute_mult(EC_GROUP *group, BN_CTX *ctx) 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)) + x = BN_CTX_get(ctx); + y = BN_CTX_get(ctx); + if (y == NULL) goto err; /* get the generator */ if (group->generator == NULL) diff --git a/crypto/ec/ecp_nistz256.c b/crypto/ec/ecp_nistz256.c index cecc6f02..4580f70b 100644 --- a/crypto/ec/ecp_nistz256.c +++ b/crypto/ec/ecp_nistz256.c @@ -1,47 +1,29 @@ /* - * Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2014-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2014, Intel Corporation. All Rights Reserved. * Copyright (c) 2015, CloudFlare, Inc. * * 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 + * + * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1, 3) + * (1) Intel Corporation, Israel Development Center, Haifa, Israel + * (2) University of Haifa, Israel + * (3) CloudFlare, Inc. + * + * Reference: + * S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with + * 256 Bit Primes" */ -/****************************************************************************** - * * - * 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 * - * (3) CloudFlare, Inc. * - * Reference: * - * S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with * - * 256 Bit Primes" * - * * - ******************************************************************************/ - #include #include "internal/cryptlib.h" #include "internal/bn_int.h" #include "ec_lcl.h" +#include "internal/refcount.h" #if BN_BITS2 != 64 # define TOBN(hi,lo) lo,hi @@ -86,7 +68,7 @@ struct nistz256_pre_comp_st { */ PRECOMP256_ROW *precomp; void *precomp_storage; - int references; + CRYPTO_REF_COUNT references; CRYPTO_RWLOCK *lock; }; @@ -256,6 +238,16 @@ static BN_ULONG is_one(const BIGNUM *z) return res; } +/* + * For reference, this macro is used only when new ecp_nistz256 assembly + * module is being developed. For example, configure with + * -DECP_NISTZ256_REFERENCE_IMPLEMENTATION and implement only functions + * performing simplest arithmetic operations on 256-bit vectors. Then + * work on implementation of higher-level functions performing point + * operations. Then remove ECP_NISTZ256_REFERENCE_IMPLEMENTATION + * and never define it again. (The correct macro denoting presence of + * ecp_nistz256 module is ECP_NISTZ256_ASM.) + */ #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, @@ -1469,7 +1461,7 @@ NISTZ256_PRE_COMP *EC_nistz256_pre_comp_dup(NISTZ256_PRE_COMP *p) { int i; if (p != NULL) - CRYPTO_atomic_add(&p->references, 1, &i, p->lock); + CRYPTO_UP_REF(&p->references, &i, p->lock); return p; } @@ -1480,7 +1472,7 @@ void EC_nistz256_pre_comp_free(NISTZ256_PRE_COMP *pre) if (pre == NULL) return; - CRYPTO_atomic_add(&pre->references, -1, &i, pre->lock); + CRYPTO_DOWN_REF(&pre->references, &i, pre->lock); REF_PRINT_COUNT("EC_nistz256", x); if (i > 0) return; @@ -1538,6 +1530,10 @@ static int ecp_nistz256_inv_mod_ord(const EC_GROUP *group, BIGNUM *r, BN_ULONG table[15][P256_LIMBS]; BN_ULONG out[P256_LIMBS], t[P256_LIMBS]; int i, ret = 0; + enum { + i_1 = 0, i_10, i_11, i_101, i_111, i_1010, i_1111, + i_10101, i_101010, i_101111, i_x6, i_x8, i_x16, i_x32 + }; /* * Catch allocation failure early. @@ -1615,10 +1611,6 @@ static int ecp_nistz256_inv_mod_ord(const EC_GROUP *group, BIGNUM *r, * multiplications, 25%, on grand scale sign operation is not that * much faster, not more that 2%... */ - enum { - i_1 = 0, i_10, i_11, i_101, i_111, i_1010, i_1111, - i_10101, i_101010, i_101111, i_x6, i_x8, i_x16, i_x32 - }; /* pre-calculate powers */ ecp_nistz256_ord_sqr_mont(table[i_10], table[i_1], 1); diff --git a/crypto/ec/ecp_oct.c b/crypto/ec/ecp_oct.c index 4d142a4a..a5010bcf 100644 --- a/crypto/ec/ecp_oct.c +++ b/crypto/ec/ecp_oct.c @@ -1,5 +1,6 @@ /* * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,12 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * Portions of this software developed by SUN MICROSYSTEMS, INC., - * and contributed to the OpenSSL project. - */ - #include #include @@ -130,7 +125,7 @@ int ec_GFp_simple_set_compressed_coordinates(const EC_GROUP *group, EC_R_INVALID_COMPRESSION_BIT); else /* - * BN_mod_sqrt() should have cought this error (not a square) + * BN_mod_sqrt() should have caught this error (not a square) */ ECerr(EC_F_EC_GFP_SIMPLE_SET_COMPRESSED_COORDINATES, EC_R_INVALID_COMPRESSED_POINT); diff --git a/crypto/ec/ecp_smpl.c b/crypto/ec/ecp_smpl.c index abd37950..7ff5489c 100644 --- a/crypto/ec/ecp_smpl.c +++ b/crypto/ec/ecp_smpl.c @@ -1,5 +1,6 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,12 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * Portions of this software developed by SUN MICROSYSTEMS, INC., - * and contributed to the OpenSSL project. - */ - #include #include @@ -1218,7 +1213,7 @@ int ec_GFp_simple_points_make_affine(const EC_GROUP *group, size_t num, BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); tmp_Z = BN_CTX_get(ctx); - if (tmp == NULL || tmp_Z == NULL) + if (tmp_Z == NULL) goto err; prod_Z = OPENSSL_malloc(num * sizeof(prod_Z[0])); diff --git a/crypto/ec/ecx_meth.c b/crypto/ec/ecx_meth.c index 018a9419..4f7cfec7 100644 --- a/crypto/ec/ecx_meth.c +++ b/crypto/ec/ecx_meth.c @@ -20,6 +20,8 @@ #define X25519_BITS 253 #define X25519_SECURITY_BITS 128 +#define ED25519_SIGSIZE 64 + typedef struct { unsigned char pubkey[X25519_KEYLEN]; unsigned char *privkey; @@ -32,7 +34,7 @@ typedef enum { } ecx_key_op_t; /* Setup EVP_PKEY using public, private or generation */ -static int ecx_key_op(EVP_PKEY *pkey, const X509_ALGOR *palg, +static int ecx_key_op(EVP_PKEY *pkey, int id, const X509_ALGOR *palg, const unsigned char *p, int plen, ecx_key_op_t op) { X25519_KEY *xkey; @@ -76,16 +78,21 @@ static int ecx_key_op(EVP_PKEY *pkey, const X509_ALGOR *palg, OPENSSL_free(xkey); return 0; } - xkey->privkey[0] &= 248; - xkey->privkey[31] &= 127; - xkey->privkey[31] |= 64; + if (id == EVP_PKEY_X25519) { + xkey->privkey[0] &= 248; + xkey->privkey[31] &= 127; + xkey->privkey[31] |= 64; + } } else { memcpy(xkey->privkey, p, X25519_KEYLEN); } - X25519_public_from_private(xkey->pubkey, xkey->privkey); + if (id == EVP_PKEY_X25519) + X25519_public_from_private(xkey->pubkey, xkey->privkey); + else + ED25519_public_from_private(xkey->pubkey, xkey->privkey); } - EVP_PKEY_assign(pkey, NID_X25519, xkey); + EVP_PKEY_assign(pkey, id, xkey); return 1; } @@ -105,8 +112,8 @@ static int ecx_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) return 0; } - if (!X509_PUBKEY_set0_param(pk, OBJ_nid2obj(NID_X25519), V_ASN1_UNDEF, - NULL, penc, X25519_KEYLEN)) { + if (!X509_PUBKEY_set0_param(pk, OBJ_nid2obj(pkey->ameth->pkey_id), + V_ASN1_UNDEF, NULL, penc, X25519_KEYLEN)) { OPENSSL_free(penc); ECerr(EC_F_ECX_PUB_ENCODE, ERR_R_MALLOC_FAILURE); return 0; @@ -122,7 +129,8 @@ static int ecx_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey) if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey)) return 0; - return ecx_key_op(pkey, palg, p, pklen, X25519_PUBLIC); + return ecx_key_op(pkey, pkey->ameth->pkey_id, palg, p, pklen, + X25519_PUBLIC); } static int ecx_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b) @@ -155,7 +163,7 @@ static int ecx_priv_decode(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8) plen = ASN1_STRING_length(oct); } - rv = ecx_key_op(pkey, palg, p, plen, X25519_PRIVATE); + rv = ecx_key_op(pkey, pkey->ameth->pkey_id, palg, p, plen, X25519_PRIVATE); ASN1_OCTET_STRING_free(oct); return rv; } @@ -182,7 +190,7 @@ static int ecx_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) return 0; } - if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_X25519), 0, + if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(pkey->ameth->pkey_id), 0, V_ASN1_UNDEF, NULL, penc, penclen)) { OPENSSL_clear_free(penc, penclen); ECerr(EC_F_ECX_PRIV_ENCODE, ERR_R_MALLOC_FAILURE); @@ -227,13 +235,15 @@ static int ecx_key_print(BIO *bp, const EVP_PKEY *pkey, int indent, { const X25519_KEY *xkey = pkey->pkey.ptr; + const char *nm = OBJ_nid2ln(pkey->ameth->pkey_id); + if (op == X25519_PRIVATE) { if (xkey == NULL || xkey->privkey == NULL) { if (BIO_printf(bp, "%*s\n", indent, "") <= 0) return 0; return 1; } - if (BIO_printf(bp, "%*sX25519 Private-Key:\n", indent, "") <= 0) + if (BIO_printf(bp, "%*s%s Private-Key:\n", indent, "", nm) <= 0) return 0; if (BIO_printf(bp, "%*spriv:\n", indent, "") <= 0) return 0; @@ -245,7 +255,7 @@ static int ecx_key_print(BIO *bp, const EVP_PKEY *pkey, int indent, return 0; return 1; } - if (BIO_printf(bp, "%*sX25519 Public-Key:\n", indent, "") <= 0) + if (BIO_printf(bp, "%*s%s Public-Key:\n", indent, "", nm) <= 0) return 0; } if (BIO_printf(bp, "%*spub:\n", indent, "") <= 0) @@ -272,7 +282,8 @@ static int ecx_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) switch (op) { case ASN1_PKEY_CTRL_SET1_TLS_ENCPT: - return ecx_key_op(pkey, NULL, arg2, arg1, X25519_PUBLIC); + return ecx_key_op(pkey, EVP_PKEY_X25519, NULL, arg2, arg1, + X25519_PUBLIC); case ASN1_PKEY_CTRL_GET1_TLS_ENCPT: if (pkey->pkey.ptr != NULL) { @@ -295,8 +306,8 @@ static int ecx_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) } const EVP_PKEY_ASN1_METHOD ecx25519_asn1_meth = { - NID_X25519, - NID_X25519, + EVP_PKEY_X25519, + EVP_PKEY_X25519, 0, "X25519", "OpenSSL X25519 algorithm", @@ -324,9 +335,87 @@ const EVP_PKEY_ASN1_METHOD ecx25519_asn1_meth = { NULL }; +static int ecd_size(const EVP_PKEY *pkey) +{ + return ED25519_SIGSIZE; +} + +static int ecd_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, + X509_ALGOR *sigalg, ASN1_BIT_STRING *str, + EVP_PKEY *pkey) +{ + const ASN1_OBJECT *obj; + int ptype; + + X509_ALGOR_get0(&obj, &ptype, NULL, sigalg); + /* Sanity check: make sure it is ED25519 with absent parameters */ + if (OBJ_obj2nid(obj) != NID_ED25519 || ptype != V_ASN1_UNDEF) { + ECerr(EC_F_ECD_ITEM_VERIFY, EC_R_INVALID_ENCODING); + return 0; + } + + if (!EVP_DigestVerifyInit(ctx, NULL, NULL, NULL, pkey)) + return 0; + + return 2; +} + +static int ecd_item_sign(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, + X509_ALGOR *alg1, X509_ALGOR *alg2, + ASN1_BIT_STRING *str) +{ + /* Set algorithms identifiers */ + X509_ALGOR_set0(alg1, OBJ_nid2obj(NID_ED25519), V_ASN1_UNDEF, NULL); + if (alg2) + X509_ALGOR_set0(alg2, OBJ_nid2obj(NID_ED25519), V_ASN1_UNDEF, NULL); + /* Algorithm idetifiers set: carry on as normal */ + return 3; +} + +static int ecd_sig_info_set(X509_SIG_INFO *siginf, const X509_ALGOR *alg, + const ASN1_STRING *sig) +{ + X509_SIG_INFO_set(siginf, NID_undef, NID_ED25519, X25519_SECURITY_BITS, + X509_SIG_INFO_TLS); + return 1; +} + +const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth = { + EVP_PKEY_ED25519, + EVP_PKEY_ED25519, + 0, + "ED25519", + "OpenSSL ED25519 algorithm", + + ecx_pub_decode, + ecx_pub_encode, + ecx_pub_cmp, + ecx_pub_print, + + ecx_priv_decode, + ecx_priv_encode, + ecx_priv_print, + + ecd_size, + ecx_bits, + ecx_security_bits, + + 0, 0, 0, 0, + ecx_cmp_parameters, + 0, 0, + + ecx_free, + 0, + NULL, + NULL, + ecd_item_verify, + ecd_item_sign, + ecd_sig_info_set +}; + static int pkey_ecx_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { - return ecx_key_op(pkey, NULL, NULL, 0, X25519_KEYGEN); + return ecx_key_op(pkey, ctx->pmeth->pkey_id, NULL, NULL, 0, X25519_KEYGEN); } static int pkey_ecx_derive(EVP_PKEY_CTX *ctx, unsigned char *key, @@ -363,7 +452,7 @@ static int pkey_ecx_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) } const EVP_PKEY_METHOD ecx25519_pkey_meth = { - NID_X25519, + EVP_PKEY_X25519, 0, 0, 0, 0, 0, 0, 0, pkey_ecx_keygen, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -371,3 +460,63 @@ const EVP_PKEY_METHOD ecx25519_pkey_meth = { pkey_ecx_ctrl, 0 }; + +static int pkey_ecd_digestsign(EVP_MD_CTX *ctx, unsigned char *sig, + size_t *siglen, const unsigned char *tbs, + size_t tbslen) +{ + const X25519_KEY *edkey = EVP_MD_CTX_pkey_ctx(ctx)->pkey->pkey.ptr; + + if (sig == NULL) { + *siglen = ED25519_SIGSIZE; + return 1; + } + if (*siglen < ED25519_SIGSIZE) { + ECerr(EC_F_PKEY_ECD_DIGESTSIGN, EC_R_BUFFER_TOO_SMALL); + return 0; + } + + if (ED25519_sign(sig, tbs, tbslen, edkey->pubkey, edkey->privkey) == 0) + return 0; + *siglen = ED25519_SIGSIZE; + return 1; +} + +static int pkey_ecd_digestverify(EVP_MD_CTX *ctx, const unsigned char *sig, + size_t siglen, const unsigned char *tbs, + size_t tbslen) +{ + const X25519_KEY *edkey = EVP_MD_CTX_pkey_ctx(ctx)->pkey->pkey.ptr; + + if (siglen != ED25519_SIGSIZE) + return 0; + + return ED25519_verify(tbs, tbslen, sig, edkey->pubkey); +} + +static int pkey_ecd_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) +{ + switch (type) { + case EVP_PKEY_CTRL_MD: + /* Only NULL allowed as digest */ + if (p2 == NULL) + return 1; + ECerr(EC_F_PKEY_ECD_CTRL, EC_R_INVALID_DIGEST_TYPE); + return 0; + + case EVP_PKEY_CTRL_DIGESTINIT: + return 1; + } + return -2; +} + +const EVP_PKEY_METHOD ed25519_pkey_meth = { + EVP_PKEY_ED25519, EVP_PKEY_FLAG_SIGCTX_CUSTOM, + 0, 0, 0, 0, 0, 0, + pkey_ecx_keygen, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + pkey_ecd_ctrl, + 0, + pkey_ecd_digestsign, + pkey_ecd_digestverify +}; diff --git a/crypto/engine/README b/crypto/engine/README index 41baa184..0050b9e5 100644 --- a/crypto/engine/README +++ b/crypto/engine/README @@ -161,7 +161,7 @@ actually qualitatively different depending on 'nid' (the "des_cbc" EVP_CIPHER is not an interoperable implementation of "aes_256_cbc"), RSA_METHODs are necessarily interoperable and don't have different flavours, only different implementations. In other words, the ENGINE_TABLE for RSA will either be empty, -or will have a single ENGING_PILE hashed to by the 'nid' 1 and that pile +or will have a single ENGINE_PILE hashed to by the 'nid' 1 and that pile represents ENGINEs that implement the single "type" of RSA there is. Cleanup - the registration and unregistration may pose questions about how @@ -188,7 +188,7 @@ state will be unchanged. Thus, no cleanup is required unless registration takes place. ENGINE_cleanup() will simply iterate across a list of registered cleanup callbacks calling each in turn, and will then internally delete its own storage (a STACK). When a cleanup callback is next registered (eg. if the cleanup() is -part of a gracefull restart and the application wants to cleanup all state then +part of a graceful restart and the application wants to cleanup all state then start again), the internal STACK storage will be freshly allocated. This is much the same as the situation in the ENGINE_TABLE instantiations ... NULL is the initialised state, so only modification operations (not queries) will cause that @@ -204,8 +204,8 @@ exists) - the idea of providing an ENGINE_cpy() function probably wasn't a good one and now certainly doesn't make sense in any generalised way. Some of the RSA, DSA, DH, and RAND functions that were fiddled during the original ENGINE changes have now, as a consequence, been reverted back. This is because the -hooking of ENGINE is now automatic (and passive, it can interally use a NULL +hooking of ENGINE is now automatic (and passive, it can internally use a NULL ENGINE pointer to simply ignore ENGINE from then on). -Hell, that should be enough for now ... comments welcome: geoff@openssl.org +Hell, that should be enough for now ... comments welcome. diff --git a/crypto/engine/build.info b/crypto/engine/build.info index 161dad4d..e00802a3 100644 --- a/crypto/engine/build.info +++ b/crypto/engine/build.info @@ -4,5 +4,8 @@ SOURCE[../../libcrypto]=\ eng_table.c eng_pkey.c eng_fat.c eng_all.c \ tb_rsa.c tb_dsa.c tb_dh.c tb_rand.c \ tb_cipher.c tb_digest.c tb_pkmeth.c tb_asnmth.c tb_eckey.c \ - eng_openssl.c eng_cnf.c eng_dyn.c eng_cryptodev.c \ + eng_openssl.c eng_cnf.c eng_dyn.c \ eng_rdrand.c +IF[{- !$disabled{devcryptoeng} -}] + SOURCE[../../libcrypto]=eng_devcrypto.c +ENDIF diff --git a/crypto/engine/eng_all.c b/crypto/engine/eng_all.c index ebe02773..c0d0b1cb 100644 --- a/crypto/engine/eng_all.c +++ b/crypto/engine/eng_all.c @@ -18,14 +18,8 @@ void ENGINE_load_builtin_engines(void) OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_ALL_BUILTIN, NULL); } -#if (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(HAVE_CRYPTODEV)) && !defined(OPENSSL_NO_DEPRECATED) +#if (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)) && !defined(OPENSSL_NO_DEPRECATED) void ENGINE_setup_bsd_cryptodev(void) { - static int bsd_cryptodev_default_loaded = 0; - if (!bsd_cryptodev_default_loaded) { - OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_CRYPTODEV, NULL); - ENGINE_register_all_complete(); - } - bsd_cryptodev_default_loaded = 1; } #endif diff --git a/crypto/engine/eng_cryptodev.c b/crypto/engine/eng_cryptodev.c deleted file mode 100644 index 55727350..00000000 --- a/crypto/engine/eng_cryptodev.c +++ /dev/null @@ -1,1757 +0,0 @@ -/* - * Copyright 2002-2018 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 - */ - -/* - * Copyright (c) 2002 Bob Beck - * 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 -#include -#include -#include -#include - -#if (defined(__unix__) || defined(unix)) && !defined(USG) && \ - (defined(OpenBSD) || defined(__FreeBSD__)) -# include -# if (defined(OpenBSD) && (OpenBSD >= 200112)) || \ - (defined(__FreeBSD_version) && \ - ((__FreeBSD_version >= 470101 && __FreeBSD_version < 500000) || \ - __FreeBSD_version >= 500041)) -# define HAVE_CRYPTODEV -# endif -# if defined(OpenBSD) && (OpenBSD >= 200110) -# define HAVE_SYSLOG_R -# endif -#endif - -#include -#ifdef HAVE_CRYPTODEV -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif -#include -#include -#include -#include - -#ifndef HAVE_CRYPTODEV - -void engine_load_cryptodev_int(void) -{ - /* This is a NOP on platforms without /dev/crypto */ - return; -} - -#else - -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 RSA_METHOD *cryptodev_rsa; -#ifndef OPENSSL_NO_DSA -static DSA_METHOD *cryptodev_dsa = NULL; -#endif -#ifndef OPENSSL_NO_DH -static DH_METHOD *cryptodev_dh; -#endif - -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); -#ifndef OPENSSL_NO_DSA -static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, const 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, const BIGNUM *g, - const BIGNUM *u1, const BIGNUM *pub_key, - const BIGNUM *u2, const 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); -#endif -#ifndef OPENSSL_NO_DH -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); -#endif -static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, - void (*f) (void)); -void engine_load_cryptodev_int(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, anything 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 initialization 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 algorithms 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 = EVP_CIPHER_CTX_get_cipher_data(ctx); - 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 % EVP_CIPHER_CTX_block_size(ctx)) != 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 = EVP_CIPHER_CTX_encrypting(ctx) ? COP_ENCRYPT : COP_DECRYPT; - - if (EVP_CIPHER_CTX_iv_length(ctx) > 0) { - cryp.iv = (caddr_t) EVP_CIPHER_CTX_iv(ctx); - if (!EVP_CIPHER_CTX_encrypting(ctx)) { - iiv = in + inl - EVP_CIPHER_CTX_iv_length(ctx); - memcpy(save_iv, iiv, EVP_CIPHER_CTX_iv_length(ctx)); - } - } else - cryp.iv = NULL; - - if (ioctl(state->d_fd, CIOCCRYPT, &cryp) == -1) { - /* - * XXX need better error handling this can fail for a number of - * different reasons. - */ - return (0); - } - - if (EVP_CIPHER_CTX_iv_length(ctx) > 0) { - if (EVP_CIPHER_CTX_encrypting(ctx)) - iiv = out + inl - EVP_CIPHER_CTX_iv_length(ctx); - else - iiv = save_iv; - memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iiv, - EVP_CIPHER_CTX_iv_length(ctx)); - } - 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 = EVP_CIPHER_CTX_get_cipher_data(ctx); - struct session_op *sess = &state->d_sess; - int cipher = -1, i; - - for (i = 0; ciphers[i].id; i++) - if (EVP_CIPHER_CTX_nid(ctx) == ciphers[i].nid && - EVP_CIPHER_CTX_iv_length(ctx) <= ciphers[i].ivmax && - EVP_CIPHER_CTX_key_length(ctx) == ciphers[i].keylen) { - cipher = ciphers[i].id; - break; - } - - if (!ciphers[i].id) { - state->d_fd = -1; - return (0); - } - - memset(sess, 0, sizeof(*sess)); - - if ((state->d_fd = get_dev_crypto()) < 0) - return (0); - - sess->key = (caddr_t) key; - sess->keylen = EVP_CIPHER_CTX_key_length(ctx); - 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 initing a - * session, and close the session. - */ -static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx) -{ - int ret = 0; - struct dev_crypto_state *state = EVP_CIPHER_CTX_get_cipher_data(ctx); - struct session_op *sess = &state->d_sess; - - if (state->d_fd < 0) - return (0); - - /* - * XXX if this ioctl fails, something'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 */ -static EVP_CIPHER *rc4_cipher = NULL; -static const EVP_CIPHER *cryptodev_rc4(void) -{ - if (rc4_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_rc4, 1, 16)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 0) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_VARIABLE_LENGTH) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state))) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - rc4_cipher = cipher; - } - return rc4_cipher; -} - -/* DES CBC EVP */ -static EVP_CIPHER *des_cbc_cipher = NULL; -static const EVP_CIPHER *cryptodev_des_cbc(void) -{ - if (des_cbc_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_des_cbc, 8, 8)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 8) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CBC_MODE) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state)) - || !EVP_CIPHER_meth_set_set_asn1_params(cipher, EVP_CIPHER_set_asn1_iv) - || !EVP_CIPHER_meth_set_get_asn1_params(cipher, EVP_CIPHER_get_asn1_iv)) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - des_cbc_cipher = cipher; - } - return des_cbc_cipher; -} - -/* 3DES CBC EVP */ -static EVP_CIPHER *des3_cbc_cipher = NULL; -static const EVP_CIPHER *cryptodev_3des_cbc(void) -{ - if (des3_cbc_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_des_ede3_cbc, 8, 24)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 8) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CBC_MODE) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state)) - || !EVP_CIPHER_meth_set_set_asn1_params(cipher, EVP_CIPHER_set_asn1_iv) - || !EVP_CIPHER_meth_set_get_asn1_params(cipher, EVP_CIPHER_get_asn1_iv)) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - des3_cbc_cipher = cipher; - } - return des3_cbc_cipher; -} - -static EVP_CIPHER *bf_cbc_cipher = NULL; -static const EVP_CIPHER *cryptodev_bf_cbc(void) -{ - if (bf_cbc_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_bf_cbc, 8, 16)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 8) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CBC_MODE) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state)) - || !EVP_CIPHER_meth_set_set_asn1_params(cipher, EVP_CIPHER_set_asn1_iv) - || !EVP_CIPHER_meth_set_get_asn1_params(cipher, EVP_CIPHER_get_asn1_iv)) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - bf_cbc_cipher = cipher; - } - return bf_cbc_cipher; -} - -static EVP_CIPHER *cast_cbc_cipher = NULL; -static const EVP_CIPHER *cryptodev_cast_cbc(void) -{ - if (cast_cbc_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_cast5_cbc, 8, 16)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 8) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CBC_MODE) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state)) - || !EVP_CIPHER_meth_set_set_asn1_params(cipher, EVP_CIPHER_set_asn1_iv) - || !EVP_CIPHER_meth_set_get_asn1_params(cipher, EVP_CIPHER_get_asn1_iv)) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - cast_cbc_cipher = cipher; - } - return cast_cbc_cipher; -} - -static EVP_CIPHER *aes_cbc_cipher = NULL; -static const EVP_CIPHER *cryptodev_aes_cbc(void) -{ - if (aes_cbc_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_aes_128_cbc, 16, 16)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 16) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CBC_MODE) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state)) - || !EVP_CIPHER_meth_set_set_asn1_params(cipher, EVP_CIPHER_set_asn1_iv) - || !EVP_CIPHER_meth_set_get_asn1_params(cipher, EVP_CIPHER_get_asn1_iv)) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - aes_cbc_cipher = cipher; - } - return aes_cbc_cipher; -} - -static EVP_CIPHER *aes_192_cbc_cipher = NULL; -static const EVP_CIPHER *cryptodev_aes_192_cbc(void) -{ - if (aes_192_cbc_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_aes_192_cbc, 16, 24)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 16) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CBC_MODE) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state)) - || !EVP_CIPHER_meth_set_set_asn1_params(cipher, EVP_CIPHER_set_asn1_iv) - || !EVP_CIPHER_meth_set_get_asn1_params(cipher, EVP_CIPHER_get_asn1_iv)) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - aes_192_cbc_cipher = cipher; - } - return aes_192_cbc_cipher; -} - -static EVP_CIPHER *aes_256_cbc_cipher = NULL; -static const EVP_CIPHER *cryptodev_aes_256_cbc(void) -{ - if (aes_256_cbc_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_aes_256_cbc, 16, 32)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 16) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CBC_MODE) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state)) - || !EVP_CIPHER_meth_set_set_asn1_params(cipher, EVP_CIPHER_set_asn1_iv) - || !EVP_CIPHER_meth_set_get_asn1_params(cipher, EVP_CIPHER_get_asn1_iv)) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - aes_256_cbc_cipher = cipher; - } - return aes_256_cbc_cipher; -} - -# ifdef CRYPTO_AES_CTR -static EVP_CIPHER *aes_ctr_cipher = NULL; -static const EVP_CIPHER *cryptodev_aes_ctr(void) -{ - if (aes_ctr_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_aes_128_ctr, 16, 16)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 14) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CTR_MODE) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state)) - || !EVP_CIPHER_meth_set_set_asn1_params(cipher, EVP_CIPHER_set_asn1_iv) - || !EVP_CIPHER_meth_set_get_asn1_params(cipher, EVP_CIPHER_get_asn1_iv)) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - aes_ctr_cipher = cipher; - } - return aes_ctr_cipher; -} - -static EVP_CIPHER *aes_192_ctr_cipher = NULL; -static const EVP_CIPHER *cryptodev_aes_192_ctr(void) -{ - if (aes_192_ctr_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_aes_192_ctr, 16, 24)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 14) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CTR_MODE) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state)) - || !EVP_CIPHER_meth_set_set_asn1_params(cipher, EVP_CIPHER_set_asn1_iv) - || !EVP_CIPHER_meth_set_get_asn1_params(cipher, EVP_CIPHER_get_asn1_iv)) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - aes_192_ctr_cipher = cipher; - } - return aes_192_ctr_cipher; -} - -static EVP_CIPHER *aes_256_ctr_cipher = NULL; -static const EVP_CIPHER *cryptodev_aes_256_ctr(void) -{ - if (aes_256_ctr_cipher == NULL) { - EVP_CIPHER *cipher; - - if ((cipher = EVP_CIPHER_meth_new(NID_aes_256_ctr, 16, 32)) == NULL - || !EVP_CIPHER_meth_set_iv_length(cipher, 14) - || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CTR_MODE) - || !EVP_CIPHER_meth_set_init(cipher, cryptodev_init_key) - || !EVP_CIPHER_meth_set_do_cipher(cipher, cryptodev_cipher) - || !EVP_CIPHER_meth_set_cleanup(cipher, cryptodev_cleanup) - || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(struct dev_crypto_state)) - || !EVP_CIPHER_meth_set_set_asn1_params(cipher, EVP_CIPHER_set_asn1_iv) - || !EVP_CIPHER_meth_set_get_asn1_params(cipher, EVP_CIPHER_get_asn1_iv)) { - EVP_CIPHER_meth_free(cipher); - cipher = NULL; - } - aes_256_ctr_cipher = cipher; - } - return aes_256_ctr_cipher; -} -# 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_192_ctr(); - break; - case NID_aes_256_ctr: - *cipher = cryptodev_aes_256_ctr(); - 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 = EVP_MD_CTX_md_data(ctx); - struct session_op *sess = &state->d_sess; - int digest; - - if ((digest = digest_nid_to_cryptodev(EVP_MD_CTX_type(ctx))) == NID_undef) { - printf("cryptodev_digest_init: Can't get digest \n"); - return (0); - } - - memset(state, 0, sizeof(*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(EVP_MD_CTX_type(ctx)); - 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 = EVP_MD_CTX_md_data(ctx); - struct session_op *sess = &state->d_sess; - char *new_mac_data; - - if (!data || state->d_fd < 0) { - printf("cryptodev_digest_update: illegal inputs \n"); - return (0); - } - - if (!count) { - return (0); - } - - if (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_ONESHOT)) { - /* if application doesn't support one buffer */ - new_mac_data = - OPENSSL_realloc(state->mac_data, state->mac_len + count); - - if (!new_mac_data) { - printf("cryptodev_digest_update: realloc failed\n"); - return (0); - } - state->mac_data = new_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 = EVP_MD_CTX_md_data(ctx); - 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 (!EVP_MD_CTX_test_flags(ctx, 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, EVP_MD_CTX_size(ctx)); - - return (ret); -} - -static int cryptodev_digest_cleanup(EVP_MD_CTX *ctx) -{ - int ret = 1; - struct dev_crypto_state *state = EVP_MD_CTX_md_data(ctx); - 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); - } - - 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 = EVP_MD_CTX_md_data(from); - struct dev_crypto_state *dstate = EVP_MD_CTX_md_data(to); - 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(EVP_MD_CTX_type(to)); - - sess->mackey = dstate->dummy_mac_key; - sess->mackeylen = digest_key_length(EVP_MD_CTX_type(to)); - 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_copy: Open session failed\n"); - return (0); - } - - 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_copy: mac_data allocation failed\n"); - return (0); - } - memcpy(dstate->mac_data, fstate->mac_data, fstate->mac_len); - dstate->mac_len = fstate->mac_len; - } - } - - return 1; -} - -static EVP_MD *sha1_md = NULL; -static const EVP_MD *cryptodev_sha1(void) -{ - if (sha1_md == NULL) { - EVP_MD *md; - - if ((md = EVP_MD_meth_new(NID_sha1, NID_undef)) == NULL - || !EVP_MD_meth_set_result_size(md, SHA_DIGEST_LENGTH) - || !EVP_MD_meth_set_flags(md, EVP_MD_FLAG_ONESHOT) - || !EVP_MD_meth_set_input_blocksize(md, SHA_CBLOCK) - || !EVP_MD_meth_set_app_datasize(md, - sizeof(struct dev_crypto_state)) - || !EVP_MD_meth_set_init(md, cryptodev_digest_init) - || !EVP_MD_meth_set_update(md, cryptodev_digest_update) - || !EVP_MD_meth_set_final(md, cryptodev_digest_final) - || !EVP_MD_meth_set_copy(md, cryptodev_digest_copy) - || !EVP_MD_meth_set_cleanup(md, cryptodev_digest_cleanup)) { - EVP_MD_meth_free(md); - md = NULL; - } - sha1_md = md; - } - return sha1_md; -} - -static EVP_MD *md5_md = NULL; -static const EVP_MD *cryptodev_md5(void) -{ - if (md5_md == NULL) { - EVP_MD *md; - - if ((md = EVP_MD_meth_new(NID_md5, NID_undef)) == NULL - || !EVP_MD_meth_set_result_size(md, 16 /* MD5_DIGEST_LENGTH */) - || !EVP_MD_meth_set_flags(md, EVP_MD_FLAG_ONESHOT) - || !EVP_MD_meth_set_input_blocksize(md, 64 /* MD5_CBLOCK */) - || !EVP_MD_meth_set_app_datasize(md, - sizeof(struct dev_crypto_state)) - || !EVP_MD_meth_set_init(md, cryptodev_digest_init) - || !EVP_MD_meth_set_update(md, cryptodev_digest_update) - || !EVP_MD_meth_set_final(md, cryptodev_digest_final) - || !EVP_MD_meth_set_copy(md, cryptodev_digest_copy) - || !EVP_MD_meth_set_cleanup(md, cryptodev_digest_cleanup)) { - EVP_MD_meth_free(md); - md = NULL; - } - md5_md = md; - } - return md5_md; -} - -# 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); -} - -static int cryptodev_engine_destroy(ENGINE *e) -{ - EVP_CIPHER_meth_free(rc4_cipher); - rc4_cipher = NULL; - EVP_CIPHER_meth_free(des_cbc_cipher); - des_cbc_cipher = NULL; - EVP_CIPHER_meth_free(des3_cbc_cipher); - des3_cbc_cipher = NULL; - EVP_CIPHER_meth_free(bf_cbc_cipher); - bf_cbc_cipher = NULL; - EVP_CIPHER_meth_free(cast_cbc_cipher); - cast_cbc_cipher = NULL; - EVP_CIPHER_meth_free(aes_cbc_cipher); - aes_cbc_cipher = NULL; - EVP_CIPHER_meth_free(aes_192_cbc_cipher); - aes_192_cbc_cipher = NULL; - EVP_CIPHER_meth_free(aes_256_cbc_cipher); - aes_256_cbc_cipher = NULL; -# ifdef CRYPTO_AES_CTR - EVP_CIPHER_meth_free(aes_ctr_cipher); - aes_ctr_cipher = NULL; - EVP_CIPHER_meth_free(aes_192_ctr_cipher); - aes_192_ctr_cipher = NULL; - EVP_CIPHER_meth_free(aes_256_ctr_cipher); - aes_256_ctr_cipher = NULL; -# endif -# ifdef USE_CRYPTODEV_DIGESTS - EVP_MD_meth_free(sha1_md); - sha1_md = NULL; - EVP_MD_meth_free(md5_md); - md5_md = NULL; -# endif - RSA_meth_free(cryptodev_rsa); - cryptodev_rsa = NULL; -#ifndef OPENSSL_NO_DSA - DSA_meth_free(cryptodev_dsa); - cryptodev_dsa = NULL; -#endif -#ifndef OPENSSL_NO_DH - DH_meth_free(cryptodev_dh); - cryptodev_dh = NULL; -#endif - return 1; -} - -/* - * 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) -{ - ssize_t bytes, bits; - u_char *b; - - crp->crp_p = NULL; - crp->crp_nbits = 0; - - bits = BN_num_bits(a); - bytes = BN_num_bytes(a); - - b = OPENSSL_zalloc(bytes); - if (b == NULL) - return (1); - - crp->crp_p = (caddr_t) b; - crp->crp_nbits = bits; - - BN_bn2bin(a, b); - 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 = OPENSSL_malloc(bytes)) == NULL) - return (-1); - - for (i = 0; i < bytes; i++) - pd[i] = 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_zalloc(rlen); - if (kop->crk_param[kop->crk_iparams].crp_p == NULL) - return ret; - 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_zalloc(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; - 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)); - 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_OpenSSL(); - printf("OCF asym process failed, Running in software\n"); - ret = RSA_meth_get_bn_mod_exp(meth)(r, a, p, m, ctx, in_mont); - - } else if (ECANCELED == kop.crk_status) { - const RSA_METHOD *meth = RSA_PKCS1_OpenSSL(); - printf("OCF hardware operation cancelled. Running in Software\n"); - ret = RSA_meth_get_bn_mod_exp(meth)(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; - const BIGNUM *n = NULL; - const BIGNUM *d = NULL; - - ctx = BN_CTX_new(); - RSA_get0_key(rsa, &n, NULL, &d); - r = cryptodev_bn_mod_exp(r0, I, d, 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; - const BIGNUM *p = NULL; - const BIGNUM *q = NULL; - const BIGNUM *dmp1 = NULL; - const BIGNUM *dmq1 = NULL; - const BIGNUM *iqmp = NULL; - const BIGNUM *n = NULL; - - RSA_get0_factors(rsa, &p, &q); - RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); - RSA_get0_key(rsa, &n, NULL, NULL); - - if (!p || !q || !dmp1 || !dmq1 || !iqmp) { - /* XXX 0 means failure?? */ - return (0); - } - - 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(p, &kop.crk_param[0])) - goto err; - if (bn2crparam(q, &kop.crk_param[1])) - goto err; - if (bn2crparam(I, &kop.crk_param[2])) - goto err; - if (bn2crparam(dmp1, &kop.crk_param[3])) - goto err; - if (bn2crparam(dmq1, &kop.crk_param[4])) - goto err; - if (bn2crparam(iqmp, &kop.crk_param[5])) - goto err; - kop.crk_iparams = 6; - - if (cryptodev_asym(&kop, BN_num_bytes(n), r0, 0, NULL)) { - const RSA_METHOD *meth = RSA_PKCS1_OpenSSL(); - printf("OCF asym process failed, running in Software\n"); - ret = RSA_meth_get_mod_exp(meth)(r0, I, rsa, ctx); - - } else if (ECANCELED == kop.crk_status) { - const RSA_METHOD *meth = RSA_PKCS1_OpenSSL(); - printf("OCF hardware operation cancelled. Running in Software\n"); - ret = RSA_meth_get_mod_exp(meth)(r0, I, rsa, ctx); - } - /* else cryptodev operation worked ok ==> ret = 1 */ - - err: - zapparams(&kop); - return (ret); -} - -#ifndef OPENSSL_NO_DSA -static int -cryptodev_dsa_bn_mod_exp(DSA *dsa, 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_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, const BIGNUM *g, - const BIGNUM *u1, const BIGNUM *pub_key, - const BIGNUM *u2, const BIGNUM *p, BN_CTX *ctx, - BN_MONT_CTX *mont) -{ - const BIGNUM *dsag, *dsap, *dsapub_key; - BIGNUM *t2; - int ret = 0; - const DSA_METHOD *meth; - int (*bn_mod_exp)(DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *, - BN_CTX *, BN_MONT_CTX *); - - t2 = BN_new(); - if (t2 == NULL) - goto err; - - /* v = ( g^u1 * y^u2 mod p ) mod q */ - /* let t1 = g ^ u1 mod p */ - ret = 0; - - DSA_get0_pqg(dsa, &dsap, NULL, &dsag); - DSA_get0_key(dsa, &dsapub_key, NULL); - - meth = DSA_get_method(dsa); - if (meth == NULL) - goto err; - bn_mod_exp = DSA_meth_get_bn_mod_exp(meth); - if (bn_mod_exp == NULL) - goto err; - - if (!bn_mod_exp(dsa, t1, dsag, u1, dsap, ctx, mont)) - goto err; - - /* let t2 = y ^ u2 mod p */ - if (!bn_mod_exp(dsa, t2, dsapub_key, u2, dsap, ctx, mont)) - goto err; - /* let t1 = t1 * t2 mod p */ - if (!BN_mod_mul(t1, t1, t2, dsap, ctx)) - goto err; - - 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, *s; - const BIGNUM *dsap = NULL, *dsaq = NULL, *dsag = NULL; - const BIGNUM *priv_key = NULL; - DSA_SIG *dsasig, *dsaret = NULL; - - dsasig = DSA_SIG_new(); - if (dsasig == NULL) - goto err; - - 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; - DSA_get0_pqg(dsa, &dsap, &dsaq, &dsag); - DSA_get0_key(dsa, NULL, &priv_key); - if (bn2crparam(dsap, &kop.crk_param[1])) - goto err; - if (bn2crparam(dsaq, &kop.crk_param[2])) - goto err; - if (bn2crparam(dsag, &kop.crk_param[3])) - goto err; - if (bn2crparam(priv_key, &kop.crk_param[4])) - goto err; - kop.crk_iparams = 5; - - r = BN_new(); - if (r == NULL) - goto err; - s = BN_new(); - if (s == NULL) - goto err; - if (cryptodev_asym(&kop, BN_num_bytes(dsaq), r, - BN_num_bytes(dsaq), s) == 0) { - DSA_SIG_set0(dsasig, r, s); - dsaret = dsasig; - } else { - dsaret = DSA_meth_get_sign(DSA_OpenSSL())(dgst, dlen, dsa); - } - err: - if (dsaret != dsasig) - DSA_SIG_free(dsasig); - 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; - const BIGNUM *pr, *ps, *p = NULL, *q = NULL, *g = NULL, *pub_key = NULL; - - 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; - DSA_get0_pqg(dsa, &p, &q, &g); - if (bn2crparam(p, &kop.crk_param[1])) - goto err; - if (bn2crparam(q, &kop.crk_param[2])) - goto err; - if (bn2crparam(g, &kop.crk_param[3])) - goto err; - DSA_get0_key(dsa, &pub_key, NULL); - if (bn2crparam(pub_key, &kop.crk_param[4])) - goto err; - DSA_SIG_get0(sig, &pr, &ps); - if (bn2crparam(pr, &kop.crk_param[5])) - goto err; - if (bn2crparam(ps, &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 { - dsaret = DSA_meth_get_verify(DSA_OpenSSL())(dgst, dlen, sig, dsa); - } - err: - kop.crk_param[0].crp_p = NULL; - zapparams(&kop); - return (dsaret); -} -#endif - -#ifndef OPENSSL_NO_DH -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; - const BIGNUM *p = NULL; - const BIGNUM *priv_key = NULL; - - if ((fd = get_asym_dev_crypto()) < 0) { - const DH_METHOD *meth = DH_OpenSSL(); - - return DH_meth_get_compute_key(meth)(key, pub_key, dh); - } - - DH_get0_pqg(dh, &p, NULL, NULL); - DH_get0_key(dh, NULL, &priv_key); - - keylen = BN_num_bits(p); - - memset(&kop, 0, sizeof(kop)); - kop.crk_op = CRK_DH_COMPUTE_KEY; - - /* inputs: dh->priv_key pub_key dh->p key */ - if (bn2crparam(priv_key, &kop.crk_param[0])) - goto err; - if (bn2crparam(pub_key, &kop.crk_param[1])) - goto err; - if (bn2crparam(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 = DH_meth_get_compute_key(meth)(key, pub_key, dh); - } - err: - kop.crk_param[3].crp_p = NULL; - zapparams(&kop); - return (dhret); -} - -#endif /* ndef OPENSSL_NO_DH */ - -/* - * 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_int(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_destroy_function(engine, cryptodev_engine_destroy) || - !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; - } - - cryptodev_rsa = RSA_meth_dup(RSA_PKCS1_OpenSSL()); - if (cryptodev_rsa != NULL) { - RSA_meth_set1_name(cryptodev_rsa, "cryptodev RSA method"); - RSA_meth_set_flags(cryptodev_rsa, 0); - if (ENGINE_set_RSA(engine, cryptodev_rsa)) { - if (cryptodev_asymfeat & CRF_MOD_EXP) { - RSA_meth_set_bn_mod_exp(cryptodev_rsa, cryptodev_bn_mod_exp); - if (cryptodev_asymfeat & CRF_MOD_EXP_CRT) - RSA_meth_set_mod_exp(cryptodev_rsa, cryptodev_rsa_mod_exp); - else - RSA_meth_set_mod_exp(cryptodev_rsa, - cryptodev_rsa_nocrt_mod_exp); - } - } - } else { - ENGINE_free(engine); - return; - } - -#ifndef OPENSSL_NO_DSA - cryptodev_dsa = DSA_meth_dup(DSA_OpenSSL()); - if (cryptodev_dsa != NULL) { - DSA_meth_set1_name(cryptodev_dsa, "cryptodev DSA method"); - DSA_meth_set_flags(cryptodev_dsa, 0); - if (ENGINE_set_DSA(engine, cryptodev_dsa)) { - if (cryptodev_asymfeat & CRF_DSA_SIGN) - DSA_meth_set_sign(cryptodev_dsa, cryptodev_dsa_do_sign); - if (cryptodev_asymfeat & CRF_MOD_EXP) { - DSA_meth_set_bn_mod_exp(cryptodev_dsa, - cryptodev_dsa_bn_mod_exp); - DSA_meth_set_mod_exp(cryptodev_dsa, cryptodev_dsa_dsa_mod_exp); - } - if (cryptodev_asymfeat & CRF_DSA_VERIFY) - DSA_meth_set_verify(cryptodev_dsa, cryptodev_dsa_verify); - } - } else { - ENGINE_free(engine); - return; - } -#endif - -#ifndef OPENSSL_NO_DH - cryptodev_dh = DH_meth_dup(DH_OpenSSL()); - if (cryptodev_dh != NULL) { - DH_meth_set1_name(cryptodev_dh, "cryptodev DH method"); - DH_meth_set_flags(cryptodev_dh, 0); - if (ENGINE_set_DH(engine, cryptodev_dh)) { - if (cryptodev_asymfeat & CRF_MOD_EXP) { - DH_meth_set_bn_mod_exp(cryptodev_dh, cryptodev_mod_exp_dh); - if (cryptodev_asymfeat & CRF_DH_COMPUTE_KEY) - DH_meth_set_compute_key(cryptodev_dh, - cryptodev_dh_compute_key); - } - } - } else { - ENGINE_free(engine); - return; - } -#endif - - ENGINE_add(engine); - ENGINE_free(engine); - ERR_clear_error(); -} - -#endif /* HAVE_CRYPTODEV */ diff --git a/crypto/engine/eng_ctrl.c b/crypto/engine/eng_ctrl.c index 7925f4fa..3bc4aab1 100644 --- a/crypto/engine/eng_ctrl.c +++ b/crypto/engine/eng_ctrl.c @@ -63,6 +63,8 @@ static int int_ctrl_helper(ENGINE *e, int cmd, long i, void *p, { int idx; char *s = (char *)p; + const ENGINE_CMD_DEFN *cdp; + /* Take care of the easy one first (eg. it requires no searches) */ if (cmd == ENGINE_CTRL_GET_FIRST_CMD_TYPE) { if ((e->cmd_defns == NULL) || int_ctrl_cmd_is_null(e->cmd_defns)) @@ -91,39 +93,29 @@ static int int_ctrl_helper(ENGINE *e, int cmd, long i, void *p, * For the rest of the commands, the 'long' argument must specify a valid * command number - so we need to conduct a search. */ - if ((e->cmd_defns == NULL) || ((idx = int_ctrl_cmd_by_num(e->cmd_defns, - (unsigned int) - i)) < 0)) { + if ((e->cmd_defns == NULL) + || ((idx = int_ctrl_cmd_by_num(e->cmd_defns, (unsigned int)i)) < 0)) { ENGINEerr(ENGINE_F_INT_CTRL_HELPER, ENGINE_R_INVALID_CMD_NUMBER); return -1; } /* Now the logic splits depending on command type */ + cdp = &e->cmd_defns[idx]; switch (cmd) { case ENGINE_CTRL_GET_NEXT_CMD_TYPE: - idx++; - if (int_ctrl_cmd_is_null(e->cmd_defns + idx)) - /* end-of-list */ - return 0; - else - return e->cmd_defns[idx].cmd_num; + cdp++; + return int_ctrl_cmd_is_null(cdp) ? 0 : cdp->cmd_num; case ENGINE_CTRL_GET_NAME_LEN_FROM_CMD: - return strlen(e->cmd_defns[idx].cmd_name); + return strlen(cdp->cmd_name); case ENGINE_CTRL_GET_NAME_FROM_CMD: - return BIO_snprintf(s, strlen(e->cmd_defns[idx].cmd_name) + 1, - "%s", e->cmd_defns[idx].cmd_name); + return strlen(strcpy(s, cdp->cmd_name)); case ENGINE_CTRL_GET_DESC_LEN_FROM_CMD: - if (e->cmd_defns[idx].cmd_desc) - return strlen(e->cmd_defns[idx].cmd_desc); - return strlen(int_no_description); + return strlen(cdp->cmd_desc == NULL ? int_no_description + : cdp->cmd_desc); case ENGINE_CTRL_GET_DESC_FROM_CMD: - if (e->cmd_defns[idx].cmd_desc) - return BIO_snprintf(s, - strlen(e->cmd_defns[idx].cmd_desc) + 1, - "%s", e->cmd_defns[idx].cmd_desc); - return BIO_snprintf(s, strlen(int_no_description) + 1, "%s", - int_no_description); + return strlen(strcpy(s, cdp->cmd_desc == NULL ? int_no_description + : cdp->cmd_desc)); case ENGINE_CTRL_GET_CMD_FLAGS: - return e->cmd_defns[idx].cmd_flags; + return cdp->cmd_flags; } /* Shouldn't really be here ... */ ENGINEerr(ENGINE_F_INT_CTRL_HELPER, ENGINE_R_INTERNAL_LIST_ERROR); diff --git a/crypto/engine/eng_devcrypto.c b/crypto/engine/eng_devcrypto.c new file mode 100644 index 00000000..235e84b4 --- /dev/null +++ b/crypto/engine/eng_devcrypto.c @@ -0,0 +1,678 @@ +/* + * 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 "e_os.h" +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "internal/engine.h" + +#ifdef CRYPTO_ALGORITHM_MIN +# define CHECK_BSD_STYLE_MACROS +#endif + +/****************************************************************************** + * + * Ciphers + * + * Because they all do the same basic operation, we have only one set of + * method functions for them all to share, and a mapping table between + * NIDs and cryptodev IDs, with all the necessary size data. + * + *****/ + +struct cipher_ctx { + int cfd; + struct session_op sess; + + /* to pass from init to do_cipher */ + const unsigned char *iv; + int op; /* COP_ENCRYPT or COP_DECRYPT */ +}; + +static const struct cipher_data_st { + int nid; + int blocksize; + int keylen; + int ivlen; + int flags; + int devcryptoid; +} cipher_data[] = { +#ifndef OPENSSL_NO_DES + { NID_des_cbc, 8, 8, 8, EVP_CIPH_CBC_MODE, CRYPTO_DES_CBC }, + { NID_des_ede3_cbc, 8, 24, 8, EVP_CIPH_CBC_MODE, CRYPTO_3DES_CBC }, +#endif +#ifndef OPENSSL_NO_BF + { NID_bf_cbc, 8, 16, 8, EVP_CIPH_CBC_MODE, CRYPTO_BLF_CBC }, +#endif +#ifndef OPENSSL_NO_CAST + { NID_cast5_cbc, 8, 16, 8, EVP_CIPH_CBC_MODE, CRYPTO_CAST_CBC }, +#endif + { NID_aes_128_cbc, 16, 128 / 8, 16, EVP_CIPH_CBC_MODE, CRYPTO_AES_CBC }, + { NID_aes_192_cbc, 16, 192 / 8, 16, EVP_CIPH_CBC_MODE, CRYPTO_AES_CBC }, + { NID_aes_256_cbc, 16, 256 / 8, 16, EVP_CIPH_CBC_MODE, CRYPTO_AES_CBC }, +#ifndef OPENSSL_NO_RC4 + { NID_rc4, 1, 16, 0, CRYPTO_ARC4 }, +#endif +#if !defined(CHECK_BSD_STYLE_MACROS) || defined(CRYPTO_AES_CTR) + { NID_aes_128_ctr, 16, 128 / 8, 16, EVP_CIPH_CTR_MODE, CRYPTO_AES_CTR }, + { NID_aes_192_ctr, 16, 192 / 8, 16, EVP_CIPH_CTR_MODE, CRYPTO_AES_CTR }, + { NID_aes_256_ctr, 16, 256 / 8, 16, EVP_CIPH_CTR_MODE, CRYPTO_AES_CTR }, +#endif +#if 0 /* Not yet supported */ + { NID_aes_128_xts, 16, 128 / 8 * 2, 16, EVP_CIPH_XTS_MODE, CRYPTO_AES_XTS }, + { NID_aes_256_xts, 16, 256 / 8 * 2, 16, EVP_CIPH_XTS_MODE, CRYPTO_AES_XTS }, +#endif +#if !defined(CHECK_BSD_STYLE_MACROS) || defined(CRYPTO_AES_ECB) + { NID_aes_128_ecb, 16, 128 / 8, 16, EVP_CIPH_ECB_MODE, CRYPTO_AES_ECB }, + { NID_aes_192_ecb, 16, 192 / 8, 16, EVP_CIPH_ECB_MODE, CRYPTO_AES_ECB }, + { NID_aes_256_ecb, 16, 256 / 8, 16, EVP_CIPH_ECB_MODE, CRYPTO_AES_ECB }, +#endif +#if 0 /* Not yet supported */ + { NID_aes_128_gcm, 16, 128 / 8, 16, EVP_CIPH_GCM_MODE, CRYPTO_AES_GCM }, + { NID_aes_192_gcm, 16, 192 / 8, 16, EVP_CIPH_GCM_MODE, CRYPTO_AES_GCM }, + { NID_aes_256_gcm, 16, 256 / 8, 16, EVP_CIPH_GCM_MODE, CRYPTO_AES_GCM }, +#endif +#ifndef OPENSSL_NO_CAMELLIA + { NID_camellia_128_cbc, 16, 128 / 8, 16, EVP_CIPH_CBC_MODE, + CRYPTO_CAMELLIA_CBC }, + { NID_camellia_192_cbc, 16, 192 / 8, 16, EVP_CIPH_CBC_MODE, + CRYPTO_CAMELLIA_CBC }, + { NID_camellia_256_cbc, 16, 256 / 8, 16, EVP_CIPH_CBC_MODE, + CRYPTO_CAMELLIA_CBC }, +#endif +}; + +static size_t get_cipher_data_index(int nid) +{ + size_t i; + + for (i = 0; i < OSSL_NELEM(cipher_data); i++) + if (nid == cipher_data[i].nid) + return i; + + /* + * Code further down must make sure that only NIDs in the table above + * are used. If any other NID reaches this function, there's a grave + * coding error further down. + */ + assert("Code that never should be reached" == NULL); + return -1; +} + +static const struct cipher_data_st *get_cipher_data(int nid) +{ + return &cipher_data[get_cipher_data_index(nid)]; +} + +/* + * Following are the three necessary functions to map OpenSSL functionality + * with cryptodev. + */ + +static int cipher_init(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc) +{ + struct cipher_ctx *cipher_ctx = + (struct cipher_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx); + const struct cipher_data_st *cipher_d = + get_cipher_data(EVP_CIPHER_CTX_nid(ctx)); + + if ((cipher_ctx->cfd = open("/dev/crypto", O_RDWR, 0)) < 0) { + SYSerr(SYS_F_OPEN, errno); + return 0; + } + + memset(&cipher_ctx->sess, 0, sizeof(cipher_ctx->sess)); + cipher_ctx->sess.cipher = cipher_d->devcryptoid; + cipher_ctx->sess.keylen = cipher_d->keylen; + cipher_ctx->sess.key = (void *)key; + cipher_ctx->op = enc ? COP_ENCRYPT : COP_DECRYPT; + if (ioctl(cipher_ctx->cfd, CIOCGSESSION, &cipher_ctx->sess) < 0) { + SYSerr(SYS_F_IOCTL, errno); + close(cipher_ctx->cfd); + return 0; + } + + return 1; +} + +static int cipher_do_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t inl) +{ + struct cipher_ctx *cipher_ctx = + (struct cipher_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx); + struct crypt_op cryp; +#if !defined(COP_FLAG_WRITE_IV) + unsigned char saved_iv[EVP_MAX_IV_LENGTH]; +#endif + + memset(&cryp, 0, sizeof(cryp)); + cryp.ses = cipher_ctx->sess.ses; + cryp.len = inl; + cryp.src = (void *)in; + cryp.dst = (void *)out; + cryp.iv = (void *)EVP_CIPHER_CTX_iv_noconst(ctx); + cryp.op = cipher_ctx->op; +#if !defined(COP_FLAG_WRITE_IV) + cryp.flags = 0; + + if (EVP_CIPHER_CTX_iv_length(ctx) > 0) { + assert(inl >= EVP_CIPHER_CTX_iv_length(ctx)); + if (!EVP_CIPHER_CTX_encrypting(ctx)) { + unsigned char *ivptr = in + inl - EVP_CIPHER_CTX_iv_length(ctx); + + memcpy(saved_iv, ivptr, EVP_CIPHER_CTX_iv_length(ctx)); + } + } +#else + cryp.flags = COP_FLAG_WRITE_IV; +#endif + + if (ioctl(cipher_ctx->cfd, CIOCCRYPT, &cryp) < 0) { + SYSerr(SYS_F_IOCTL, errno); + return 0; + } + +#if !defined(COP_FLAG_WRITE_IV) + if (EVP_CIPHER_CTX_iv_length(ctx) > 0) { + unsigned char *ivptr = saved_iv; + + assert(inl >= EVP_CIPHER_CTX_iv_length(ctx)); + if (!EVP_CIPHER_CTX_encrypting(ctx)) + ivptr = out + inl - EVP_CIPHER_CTX_iv_length(ctx); + + memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), ivptr, + EVP_CIPHER_CTX_iv_length(ctx)); + } +#endif + + return 1; +} + +static int cipher_cleanup(EVP_CIPHER_CTX *ctx) +{ + struct cipher_ctx *cipher_ctx = + (struct cipher_ctx *)EVP_CIPHER_CTX_get_cipher_data(ctx); + + if (ioctl(cipher_ctx->cfd, CIOCFSESSION, &cipher_ctx->sess) < 0) { + SYSerr(SYS_F_IOCTL, errno); + return 0; + } + if (close(cipher_ctx->cfd) < 0) { + SYSerr(SYS_F_CLOSE, errno); + return 0; + } + + return 1; +} + +/* + * Keep a table of known nids and associated methods. + * Note that known_cipher_nids[] isn't necessarily indexed the same way as + * cipher_data[] above, which known_cipher_methods[] is. + */ +static int known_cipher_nids[OSSL_NELEM(cipher_data)]; +static int known_cipher_nids_amount = -1; /* -1 indicates not yet initialised */ +static EVP_CIPHER *known_cipher_methods[OSSL_NELEM(cipher_data)] = { NULL, }; + +static void prepare_cipher_methods() +{ + size_t i; + struct session_op sess; + int cfd; + + if ((cfd = open("/dev/crypto", O_RDWR, 0)) < 0) + return; + + memset(&sess, 0, sizeof(sess)); + sess.key = (void *)"01234567890123456789012345678901234567890123456789"; + + for (i = 0, known_cipher_nids_amount = 0; + i < OSSL_NELEM(cipher_data); i++) { + + /* + * Check that the algo is really availably by trying to open and close + * a session. + */ + sess.cipher = cipher_data[i].devcryptoid; + sess.keylen = cipher_data[i].keylen; + if (ioctl(cfd, CIOCGSESSION, &sess) < 0 + || ioctl(cfd, CIOCFSESSION, &sess) < 0) + continue; + + if ((known_cipher_methods[i] = + EVP_CIPHER_meth_new(cipher_data[i].nid, + cipher_data[i].blocksize, + cipher_data[i].keylen)) == NULL + || !EVP_CIPHER_meth_set_iv_length(known_cipher_methods[i], + cipher_data[i].ivlen) + || !EVP_CIPHER_meth_set_flags(known_cipher_methods[i], + cipher_data[i].flags + | EVP_CIPH_FLAG_DEFAULT_ASN1) + || !EVP_CIPHER_meth_set_init(known_cipher_methods[i], cipher_init) + || !EVP_CIPHER_meth_set_do_cipher(known_cipher_methods[i], + cipher_do_cipher) + || !EVP_CIPHER_meth_set_cleanup(known_cipher_methods[i], + cipher_cleanup) + || !EVP_CIPHER_meth_set_impl_ctx_size(known_cipher_methods[i], + sizeof(struct cipher_ctx))) { + EVP_CIPHER_meth_free(known_cipher_methods[i]); + known_cipher_methods[i] = NULL; + } else { + known_cipher_nids[known_cipher_nids_amount++] = + cipher_data[i].nid; + } + } + + close(cfd); +} + +static const EVP_CIPHER *get_cipher_method(int nid) +{ + size_t i = get_cipher_data_index(nid); + + if (i == (size_t)-1) + return NULL; + return known_cipher_methods[i]; +} + +static int get_cipher_nids(const int **nids) +{ + *nids = known_cipher_nids; + return known_cipher_nids_amount; +} + +static void destroy_cipher_method(int nid) +{ + size_t i = get_cipher_data_index(nid); + + EVP_CIPHER_meth_free(known_cipher_methods[i]); + known_cipher_methods[i] = NULL; +} + +static void destroy_all_cipher_methods() +{ + size_t i; + + for (i = 0; i < OSSL_NELEM(cipher_data); i++) + destroy_cipher_method(cipher_data[i].nid); +} + +static int devcrypto_ciphers(ENGINE *e, const EVP_CIPHER **cipher, + const int **nids, int nid) +{ + if (cipher == NULL) + return get_cipher_nids(nids); + + *cipher = get_cipher_method(nid); + + return *cipher != NULL; +} + +/* + * We only support digests if the cryptodev implementation supports multiple + * data updates. Otherwise, we would be forced to maintain a cache, which is + * perilous if there's a lot of data coming in (if someone wants to checksum + * an OpenSSL tarball, for example). + */ +#if defined(COP_FLAG_UPDATE) && defined(COP_FLAG_FINAL) + +/****************************************************************************** + * + * Digests + * + * Because they all do the same basic operation, we have only one set of + * method functions for them all to share, and a mapping table between + * NIDs and cryptodev IDs, with all the necessary size data. + * + *****/ + +struct digest_ctx { + int cfd; + struct session_op sess; + int init; +}; + +static const struct digest_data_st { + int nid; + int digestlen; + int devcryptoid; +} digest_data[] = { +#ifndef OPENSSL_NO_MD5 + { NID_md5, 16, CRYPTO_MD5 }, +#endif + { NID_sha1, 20, CRYPTO_SHA1 }, +#ifndef OPENSSL_NO_RMD160 +# if !defined(CHECK_BSD_STYLE_MACROS) && defined(CRYPTO_RIPEMD160) + { NID_ripemd160, 20, CRYPTO_RIPEMD160 }, +# endif +#endif +#if !defined(CHECK_BSD_STYLE_MACROS) && defined(CRYPTO_SHA2_224) + { NID_sha224, 224 / 8, CRYPTO_SHA2_224 }, +#endif +#if !defined(CHECK_BSD_STYLE_MACROS) && defined(CRYPTO_SHA2_256) + { NID_sha256, 256 / 8, CRYPTO_SHA2_256 }, +#endif +#if !defined(CHECK_BSD_STYLE_MACROS) && defined(CRYPTO_SHA2_384) + { NID_sha384, 384 / 8, CRYPTO_SHA2_384 }, +#endif +#if !defined(CHECK_BSD_STYLE_MACROS) && defined(CRYPTO_SHA2_512) + { NID_sha512, 512 / 8, CRYPTO_SHA2_512 }, +#endif +}; + +static size_t get_digest_data_index(int nid) +{ + size_t i; + + for (i = 0; i < OSSL_NELEM(digest_data); i++) + if (nid == digest_data[i].nid) + return i; + + /* + * Code further down must make sure that only NIDs in the table above + * are used. If any other NID reaches this function, there's a grave + * coding error further down. + */ + assert("Code that never should be reached" == NULL); + return -1; +} + +static const struct digest_data_st *get_digest_data(int nid) +{ + return &digest_data[get_digest_data_index(nid)]; +} + +/* + * Following are the four necessary functions to map OpenSSL functionality + * with cryptodev. + */ + +static int digest_init(EVP_MD_CTX *ctx) +{ + struct digest_ctx *digest_ctx = + (struct digest_ctx *)EVP_MD_CTX_md_data(ctx); + const struct digest_data_st *digest_d = + get_digest_data(EVP_MD_CTX_type(ctx)); + + if (digest_ctx->init == 0 + && (digest_ctx->cfd = open("/dev/crypto", O_RDWR, 0)) < 0) { + SYSerr(SYS_F_OPEN, errno); + return 0; + } + + digest_ctx->init = 1; + + memset(&digest_ctx->sess, 0, sizeof(digest_ctx->sess)); + digest_ctx->sess.mac = digest_d->devcryptoid; + if (ioctl(digest_ctx->cfd, CIOCGSESSION, &digest_ctx->sess) < 0) { + SYSerr(SYS_F_IOCTL, errno); + close(digest_ctx->cfd); + return 0; + } + + return 1; +} + +static int digest_op(struct digest_ctx *ctx, const void *src, size_t srclen, + void *res, unsigned int flags) +{ + struct crypt_op cryp; + + memset(&cryp, 0, sizeof(cryp)); + cryp.ses = ctx->sess.ses; + cryp.len = srclen; + cryp.src = (void *)src; + cryp.dst = NULL; + cryp.mac = res; + cryp.flags = flags; + return ioctl(ctx->cfd, CIOCCRYPT, &cryp); +} + +static int digest_update(EVP_MD_CTX *ctx, const void *data, size_t count) +{ + struct digest_ctx *digest_ctx = + (struct digest_ctx *)EVP_MD_CTX_md_data(ctx); + + if (count == 0) + return 1; + + if (digest_op(digest_ctx, data, count, NULL, COP_FLAG_UPDATE) < 0) { + SYSerr(SYS_F_IOCTL, errno); + return 0; + } + + return 1; +} + +static int digest_final(EVP_MD_CTX *ctx, unsigned char *md) +{ + struct digest_ctx *digest_ctx = + (struct digest_ctx *)EVP_MD_CTX_md_data(ctx); + + if (digest_op(digest_ctx, NULL, 0, md, COP_FLAG_FINAL) < 0) { + SYSerr(SYS_F_IOCTL, errno); + return 0; + } + if (ioctl(digest_ctx->cfd, CIOCFSESSION, &digest_ctx->sess) < 0) { + SYSerr(SYS_F_IOCTL, errno); + return 0; + } + + return 1; +} + +static int digest_cleanup(EVP_MD_CTX *ctx) +{ + struct digest_ctx *digest_ctx = + (struct digest_ctx *)EVP_MD_CTX_md_data(ctx); + + if (close(digest_ctx->cfd) < 0) { + SYSerr(SYS_F_CLOSE, errno); + return 0; + } + + return 1; +} + +/* + * Keep a table of known nids and associated methods. + * Note that known_digest_nids[] isn't necessarily indexed the same way as + * digest_data[] above, which known_digest_methods[] is. + */ +static int known_digest_nids[OSSL_NELEM(digest_data)]; +static int known_digest_nids_amount = -1; /* -1 indicates not yet initialised */ +static EVP_MD *known_digest_methods[OSSL_NELEM(digest_data)] = { NULL, }; + +static void prepare_digest_methods() +{ + size_t i; + struct session_op sess; + int cfd; + + if ((cfd = open("/dev/crypto", O_RDWR, 0)) < 0) + return; + + memset(&sess, 0, sizeof(sess)); + + for (i = 0, known_digest_nids_amount = 0; i < OSSL_NELEM(digest_data); + i++) { + + /* + * Check that the algo is really availably by trying to open and close + * a session. + */ + sess.mac = digest_data[i].devcryptoid; + if (ioctl(cfd, CIOCGSESSION, &sess) < 0 + || ioctl(cfd, CIOCFSESSION, &sess) < 0) + continue; + + if ((known_digest_methods[i] = EVP_MD_meth_new(digest_data[i].nid, + NID_undef)) == NULL + || !EVP_MD_meth_set_result_size(known_digest_methods[i], + digest_data[i].digestlen) + || !EVP_MD_meth_set_init(known_digest_methods[i], digest_init) + || !EVP_MD_meth_set_update(known_digest_methods[i], digest_update) + || !EVP_MD_meth_set_final(known_digest_methods[i], digest_final) + || !EVP_MD_meth_set_cleanup(known_digest_methods[i], digest_cleanup) + || !EVP_MD_meth_set_app_datasize(known_digest_methods[i], + sizeof(struct digest_ctx))) { + EVP_MD_meth_free(known_digest_methods[i]); + known_digest_methods[i] = NULL; + } else { + known_digest_nids[known_digest_nids_amount++] = digest_data[i].nid; + } + } + + close(cfd); +} + +static const EVP_MD *get_digest_method(int nid) +{ + size_t i = get_digest_data_index(nid); + + if (i == (size_t)-1) + return NULL; + return known_digest_methods[i]; +} + +static int get_digest_nids(const int **nids) +{ + *nids = known_digest_nids; + return known_digest_nids_amount; +} + +static void destroy_digest_method(int nid) +{ + size_t i = get_digest_data_index(nid); + + EVP_MD_meth_free(known_digest_methods[i]); + known_digest_methods[i] = NULL; +} + +static void destroy_all_digest_methods() +{ + size_t i; + + for (i = 0; i < OSSL_NELEM(digest_data); i++) + destroy_digest_method(digest_data[i].nid); +} + +static int devcrypto_digests(ENGINE *e, const EVP_MD **digest, + const int **nids, int nid) +{ + if (digest == NULL) + return get_digest_nids(nids); + + *digest = get_digest_method(nid); + + return *digest != NULL; +} + +#endif + +/****************************************************************************** + * + * LOAD / UNLOAD + * + *****/ + +static int devcrypto_unload(ENGINE *e) +{ + destroy_all_cipher_methods(); +#if defined(COP_FLAG_UPDATE) && defined(COP_FLAG_FINAL) + destroy_all_digest_methods(); +#endif + return 1; +} +/* + * This engine is always built into libcrypto, so it doesn't offer any + * ability to be dynamically loadable. + */ +void engine_load_devcrypto_int() +{ + ENGINE *e = NULL; + + if (access("/dev/crypto", R_OK | W_OK) < 0) { + fprintf(stderr, + "/dev/crypto not present, not enabling devcrypto engine\n"); + return; + } + + prepare_cipher_methods(); +#if defined(COP_FLAG_UPDATE) && defined(COP_FLAG_FINAL) + prepare_digest_methods(); +#endif + + if ((e = ENGINE_new()) == NULL) + return; + + if (!ENGINE_set_id(e, "devcrypto") + || !ENGINE_set_name(e, "/dev/crypto engine") + || !ENGINE_set_destroy_function(e, devcrypto_unload) + +/* + * Asymmetric ciphers aren't well supported with /dev/crypto. Among the BSD + * implementations, it seems to only exist in FreeBSD, and regarding the + * parameters in its crypt_kop, the manual crypto(4) has this to say: + * + * The semantics of these arguments are currently undocumented. + * + * Reading through the FreeBSD source code doesn't give much more than + * their CRK_MOD_EXP implementation for ubsec. + * + * It doesn't look much better with cryptodev-linux. They have the crypt_kop + * structure as well as the command (CRK_*) in cryptodev.h, but no support + * seems to be implemented at all for the moment. + * + * At the time of writing, it seems impossible to write proper support for + * FreeBSD's asym features without some very deep knowledge and access to + * specific kernel modules. + * + * /Richard Levitte, 2017-05-11 + */ +#if 0 +# ifndef OPENSSL_NO_RSA + || !ENGINE_set_RSA(e, devcrypto_rsa) +# endif +# ifndef OPENSSL_NO_DSA + || !ENGINE_set_DSA(e, devcrypto_dsa) +# endif +# ifndef OPENSSL_NO_DH + || !ENGINE_set_DH(e, devcrypto_dh) +# endif +# ifndef OPENSSL_NO_EC + || !ENGINE_set_EC(e, devcrypto_ec) +# endif +#endif + || !ENGINE_set_ciphers(e, devcrypto_ciphers) +#if defined(COP_FLAG_UPDATE) && defined(COP_FLAG_FINAL) + || !ENGINE_set_digests(e, devcrypto_digests) +#endif + ) { + ENGINE_free(e); + return; + } + + ENGINE_add(e); + ENGINE_free(e); /* Loose our local reference */ + ERR_clear_error(); +} diff --git a/crypto/engine/eng_err.c b/crypto/engine/eng_err.c index 5e9d16f3..5f24e998 100644 --- a/crypto/engine/eng_err.c +++ b/crypto/engine/eng_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,103 +8,132 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_ENGINE,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_ENGINE,0,reason) - -static ERR_STRING_DATA ENGINE_str_functs[] = { - {ERR_FUNC(ENGINE_F_DYNAMIC_CTRL), "dynamic_ctrl"}, - {ERR_FUNC(ENGINE_F_DYNAMIC_GET_DATA_CTX), "dynamic_get_data_ctx"}, - {ERR_FUNC(ENGINE_F_DYNAMIC_LOAD), "dynamic_load"}, - {ERR_FUNC(ENGINE_F_DYNAMIC_SET_DATA_CTX), "dynamic_set_data_ctx"}, - {ERR_FUNC(ENGINE_F_ENGINE_ADD), "ENGINE_add"}, - {ERR_FUNC(ENGINE_F_ENGINE_BY_ID), "ENGINE_by_id"}, - {ERR_FUNC(ENGINE_F_ENGINE_CMD_IS_EXECUTABLE), "ENGINE_cmd_is_executable"}, - {ERR_FUNC(ENGINE_F_ENGINE_CTRL), "ENGINE_ctrl"}, - {ERR_FUNC(ENGINE_F_ENGINE_CTRL_CMD), "ENGINE_ctrl_cmd"}, - {ERR_FUNC(ENGINE_F_ENGINE_CTRL_CMD_STRING), "ENGINE_ctrl_cmd_string"}, - {ERR_FUNC(ENGINE_F_ENGINE_FINISH), "ENGINE_finish"}, - {ERR_FUNC(ENGINE_F_ENGINE_GET_CIPHER), "ENGINE_get_cipher"}, - {ERR_FUNC(ENGINE_F_ENGINE_GET_DIGEST), "ENGINE_get_digest"}, - {ERR_FUNC(ENGINE_F_ENGINE_GET_FIRST), "ENGINE_get_first"}, - {ERR_FUNC(ENGINE_F_ENGINE_GET_LAST), "ENGINE_get_last"}, - {ERR_FUNC(ENGINE_F_ENGINE_GET_NEXT), "ENGINE_get_next"}, - {ERR_FUNC(ENGINE_F_ENGINE_GET_PKEY_ASN1_METH), +static const ERR_STRING_DATA ENGINE_str_functs[] = { + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_DIGEST_UPDATE, 0), "digest_update"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_DYNAMIC_CTRL, 0), "dynamic_ctrl"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_DYNAMIC_GET_DATA_CTX, 0), + "dynamic_get_data_ctx"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_DYNAMIC_LOAD, 0), "dynamic_load"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_DYNAMIC_SET_DATA_CTX, 0), + "dynamic_set_data_ctx"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_ADD, 0), "ENGINE_add"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_BY_ID, 0), "ENGINE_by_id"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_CMD_IS_EXECUTABLE, 0), + "ENGINE_cmd_is_executable"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_CTRL, 0), "ENGINE_ctrl"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_CTRL_CMD, 0), "ENGINE_ctrl_cmd"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_CTRL_CMD_STRING, 0), + "ENGINE_ctrl_cmd_string"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_FINISH, 0), "ENGINE_finish"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_CIPHER, 0), + "ENGINE_get_cipher"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_DIGEST, 0), + "ENGINE_get_digest"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_FIRST, 0), + "ENGINE_get_first"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_LAST, 0), "ENGINE_get_last"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_NEXT, 0), "ENGINE_get_next"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_PKEY_ASN1_METH, 0), "ENGINE_get_pkey_asn1_meth"}, - {ERR_FUNC(ENGINE_F_ENGINE_GET_PKEY_METH), "ENGINE_get_pkey_meth"}, - {ERR_FUNC(ENGINE_F_ENGINE_GET_PREV), "ENGINE_get_prev"}, - {ERR_FUNC(ENGINE_F_ENGINE_INIT), "ENGINE_init"}, - {ERR_FUNC(ENGINE_F_ENGINE_LIST_ADD), "engine_list_add"}, - {ERR_FUNC(ENGINE_F_ENGINE_LIST_REMOVE), "engine_list_remove"}, - {ERR_FUNC(ENGINE_F_ENGINE_LOAD_PRIVATE_KEY), "ENGINE_load_private_key"}, - {ERR_FUNC(ENGINE_F_ENGINE_LOAD_PUBLIC_KEY), "ENGINE_load_public_key"}, - {ERR_FUNC(ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT), + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_PKEY_METH, 0), + "ENGINE_get_pkey_meth"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_PREV, 0), "ENGINE_get_prev"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_INIT, 0), "ENGINE_init"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_LIST_ADD, 0), "engine_list_add"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_LIST_REMOVE, 0), + "engine_list_remove"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_LOAD_PRIVATE_KEY, 0), + "ENGINE_load_private_key"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_LOAD_PUBLIC_KEY, 0), + "ENGINE_load_public_key"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT, 0), "ENGINE_load_ssl_client_cert"}, - {ERR_FUNC(ENGINE_F_ENGINE_NEW), "ENGINE_new"}, - {ERR_FUNC(ENGINE_F_ENGINE_PKEY_ASN1_FIND_STR), + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_NEW, 0), "ENGINE_new"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_PKEY_ASN1_FIND_STR, 0), "ENGINE_pkey_asn1_find_str"}, - {ERR_FUNC(ENGINE_F_ENGINE_REMOVE), "ENGINE_remove"}, - {ERR_FUNC(ENGINE_F_ENGINE_SET_DEFAULT_STRING), + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_REMOVE, 0), "ENGINE_remove"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_SET_DEFAULT_STRING, 0), "ENGINE_set_default_string"}, - {ERR_FUNC(ENGINE_F_ENGINE_SET_ID), "ENGINE_set_id"}, - {ERR_FUNC(ENGINE_F_ENGINE_SET_NAME), "ENGINE_set_name"}, - {ERR_FUNC(ENGINE_F_ENGINE_TABLE_REGISTER), "engine_table_register"}, - {ERR_FUNC(ENGINE_F_ENGINE_UNLOCKED_FINISH), "engine_unlocked_finish"}, - {ERR_FUNC(ENGINE_F_ENGINE_UP_REF), "ENGINE_up_ref"}, - {ERR_FUNC(ENGINE_F_INT_CTRL_HELPER), "int_ctrl_helper"}, - {ERR_FUNC(ENGINE_F_INT_ENGINE_CONFIGURE), "int_engine_configure"}, - {ERR_FUNC(ENGINE_F_INT_ENGINE_MODULE_INIT), "int_engine_module_init"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_SET_ID, 0), "ENGINE_set_id"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_SET_NAME, 0), "ENGINE_set_name"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_TABLE_REGISTER, 0), + "engine_table_register"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_UNLOCKED_FINISH, 0), + "engine_unlocked_finish"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_UP_REF, 0), "ENGINE_up_ref"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_INT_CTRL_HELPER, 0), "int_ctrl_helper"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_INT_ENGINE_CONFIGURE, 0), + "int_engine_configure"}, + {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_INT_ENGINE_MODULE_INIT, 0), + "int_engine_module_init"}, {0, NULL} }; -static ERR_STRING_DATA ENGINE_str_reasons[] = { - {ERR_REASON(ENGINE_R_ALREADY_LOADED), "already loaded"}, - {ERR_REASON(ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER), - "argument is not a number"}, - {ERR_REASON(ENGINE_R_CMD_NOT_EXECUTABLE), "cmd not executable"}, - {ERR_REASON(ENGINE_R_COMMAND_TAKES_INPUT), "command takes input"}, - {ERR_REASON(ENGINE_R_COMMAND_TAKES_NO_INPUT), "command takes no input"}, - {ERR_REASON(ENGINE_R_CONFLICTING_ENGINE_ID), "conflicting engine id"}, - {ERR_REASON(ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED), - "ctrl command not implemented"}, - {ERR_REASON(ENGINE_R_DSO_FAILURE), "DSO failure"}, - {ERR_REASON(ENGINE_R_DSO_NOT_FOUND), "dso not found"}, - {ERR_REASON(ENGINE_R_ENGINES_SECTION_ERROR), "engines section error"}, - {ERR_REASON(ENGINE_R_ENGINE_CONFIGURATION_ERROR), - "engine configuration error"}, - {ERR_REASON(ENGINE_R_ENGINE_IS_NOT_IN_LIST), "engine is not in the list"}, - {ERR_REASON(ENGINE_R_ENGINE_SECTION_ERROR), "engine section error"}, - {ERR_REASON(ENGINE_R_FAILED_LOADING_PRIVATE_KEY), - "failed loading private key"}, - {ERR_REASON(ENGINE_R_FAILED_LOADING_PUBLIC_KEY), - "failed loading public key"}, - {ERR_REASON(ENGINE_R_FINISH_FAILED), "finish failed"}, - {ERR_REASON(ENGINE_R_ID_OR_NAME_MISSING), "'id' or 'name' missing"}, - {ERR_REASON(ENGINE_R_INIT_FAILED), "init failed"}, - {ERR_REASON(ENGINE_R_INTERNAL_LIST_ERROR), "internal list error"}, - {ERR_REASON(ENGINE_R_INVALID_ARGUMENT), "invalid argument"}, - {ERR_REASON(ENGINE_R_INVALID_CMD_NAME), "invalid cmd name"}, - {ERR_REASON(ENGINE_R_INVALID_CMD_NUMBER), "invalid cmd number"}, - {ERR_REASON(ENGINE_R_INVALID_INIT_VALUE), "invalid init value"}, - {ERR_REASON(ENGINE_R_INVALID_STRING), "invalid string"}, - {ERR_REASON(ENGINE_R_NOT_INITIALISED), "not initialised"}, - {ERR_REASON(ENGINE_R_NOT_LOADED), "not loaded"}, - {ERR_REASON(ENGINE_R_NO_CONTROL_FUNCTION), "no control function"}, - {ERR_REASON(ENGINE_R_NO_INDEX), "no index"}, - {ERR_REASON(ENGINE_R_NO_LOAD_FUNCTION), "no load function"}, - {ERR_REASON(ENGINE_R_NO_REFERENCE), "no reference"}, - {ERR_REASON(ENGINE_R_NO_SUCH_ENGINE), "no such engine"}, - {ERR_REASON(ENGINE_R_UNIMPLEMENTED_CIPHER), "unimplemented cipher"}, - {ERR_REASON(ENGINE_R_UNIMPLEMENTED_DIGEST), "unimplemented digest"}, - {ERR_REASON(ENGINE_R_UNIMPLEMENTED_PUBLIC_KEY_METHOD), - "unimplemented public key method"}, - {ERR_REASON(ENGINE_R_VERSION_INCOMPATIBILITY), "version incompatibility"}, +static const ERR_STRING_DATA ENGINE_str_reasons[] = { + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ALREADY_LOADED), "already loaded"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER), + "argument is not a number"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_CMD_NOT_EXECUTABLE), + "cmd not executable"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_COMMAND_TAKES_INPUT), + "command takes input"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_COMMAND_TAKES_NO_INPUT), + "command takes no input"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_CONFLICTING_ENGINE_ID), + "conflicting engine id"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED), + "ctrl command not implemented"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_DSO_FAILURE), "DSO failure"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_DSO_NOT_FOUND), "dso not found"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINES_SECTION_ERROR), + "engines section error"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINE_CONFIGURATION_ERROR), + "engine configuration error"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINE_IS_NOT_IN_LIST), + "engine is not in the list"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINE_SECTION_ERROR), + "engine section error"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_FAILED_LOADING_PRIVATE_KEY), + "failed loading private key"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_FAILED_LOADING_PUBLIC_KEY), + "failed loading public key"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_FINISH_FAILED), "finish failed"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ID_OR_NAME_MISSING), + "'id' or 'name' missing"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INIT_FAILED), "init failed"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INTERNAL_LIST_ERROR), + "internal list error"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_ARGUMENT), + "invalid argument"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_CMD_NAME), + "invalid cmd name"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_CMD_NUMBER), + "invalid cmd number"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_INIT_VALUE), + "invalid init value"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_STRING), "invalid string"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NOT_INITIALISED), "not initialised"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NOT_LOADED), "not loaded"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_CONTROL_FUNCTION), + "no control function"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_INDEX), "no index"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_LOAD_FUNCTION), + "no load function"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_REFERENCE), "no reference"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_SUCH_ENGINE), "no such engine"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_UNIMPLEMENTED_CIPHER), + "unimplemented cipher"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_UNIMPLEMENTED_DIGEST), + "unimplemented digest"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_UNIMPLEMENTED_PUBLIC_KEY_METHOD), + "unimplemented public key method"}, + {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_VERSION_INCOMPATIBILITY), + "version incompatibility"}, {0, NULL} }; @@ -113,10 +142,9 @@ static ERR_STRING_DATA ENGINE_str_reasons[] = { int ERR_load_ENGINE_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(ENGINE_str_functs[0].error) == NULL) { - ERR_load_strings(0, ENGINE_str_functs); - ERR_load_strings(0, ENGINE_str_reasons); + ERR_load_strings_const(ENGINE_str_functs); + ERR_load_strings_const(ENGINE_str_reasons); } #endif return 1; diff --git a/crypto/engine/eng_fat.c b/crypto/engine/eng_fat.c index 5cb81874..591fddc8 100644 --- a/crypto/engine/eng_fat.c +++ b/crypto/engine/eng_fat.c @@ -1,5 +1,6 @@ /* * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,12 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * ECDH support in OpenSSL originally developed by - * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. - */ - #include "eng_int.h" #include diff --git a/crypto/engine/eng_init.c b/crypto/engine/eng_init.c index 8be7c6fc..7c235fc4 100644 --- a/crypto/engine/eng_init.c +++ b/crypto/engine/eng_init.c @@ -1,5 +1,5 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-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 @@ -7,6 +7,7 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" #include "eng_int.h" /* diff --git a/crypto/engine/eng_int.h b/crypto/engine/eng_int.h index c604fadd..60fdf820 100644 --- a/crypto/engine/eng_int.h +++ b/crypto/engine/eng_int.h @@ -1,5 +1,6 @@ /* * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,18 +8,13 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * ECDH support in OpenSSL originally developed by - * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. - */ - #ifndef HEADER_ENGINE_INT_H # define HEADER_ENGINE_INT_H # include "internal/cryptlib.h" -# include -# include +# include "internal/engine.h" +# include "internal/thread_once.h" +# include "internal/refcount.h" #ifdef __cplusplus extern "C" { @@ -103,7 +99,7 @@ void engine_table_doall(ENGINE_TABLE *table, engine_table_doall_cb *cb, */ int engine_unlocked_init(ENGINE *e); int engine_unlocked_finish(ENGINE *e, int unlock_for_handlers); -int engine_free_util(ENGINE *e, int locked); +int engine_free_util(ENGINE *e, int not_locked); /* * This function will reset all "set"able values in an ENGINE to NULL. This @@ -156,7 +152,7 @@ struct engine_st { const ENGINE_CMD_DEFN *cmd_defns; int flags; /* reference count on the structure itself */ - int struct_ref; + CRYPTO_REF_COUNT struct_ref; /* * reference count on usability of the engine type. NB: This controls the * loading and initialisation of any functionality required by this diff --git a/crypto/engine/eng_lib.c b/crypto/engine/eng_lib.c index cbefc7eb..48d86b95 100644 --- a/crypto/engine/eng_lib.c +++ b/crypto/engine/eng_lib.c @@ -1,5 +1,5 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2018 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 @@ -7,8 +7,10 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" #include "eng_int.h" #include +#include "internal/refcount.h" CRYPTO_RWLOCK *global_engine_lock; @@ -66,17 +68,21 @@ void engine_set_all_null(ENGINE *e) e->flags = 0; } -int engine_free_util(ENGINE *e, int locked) +int engine_free_util(ENGINE *e, int not_locked) { int i; if (e == NULL) return 1; - if (locked) +#ifdef HAVE_ATOMICS + CRYPTO_DOWN_REF(&e->struct_ref, &i, global_engine_lock); +#else + if (not_locked) CRYPTO_atomic_add(&e->struct_ref, -1, &i, global_engine_lock); else i = --e->struct_ref; - engine_ref_debug(e, 0, -1) +#endif + engine_ref_debug(e, 0, -1); if (i > 0) return 1; REF_ASSERT_ISNT(i < 0); @@ -168,12 +174,12 @@ void engine_cleanup_int(void) int ENGINE_set_ex_data(ENGINE *e, int idx, void *arg) { - return (CRYPTO_set_ex_data(&e->ex_data, idx, arg)); + return CRYPTO_set_ex_data(&e->ex_data, idx, arg); } void *ENGINE_get_ex_data(const ENGINE *e, int idx) { - return (CRYPTO_get_ex_data(&e->ex_data, idx)); + return CRYPTO_get_ex_data(&e->ex_data, idx); } /* diff --git a/crypto/engine/eng_list.c b/crypto/engine/eng_list.c index 934389f7..bfd91e23 100644 --- a/crypto/engine/eng_list.c +++ b/crypto/engine/eng_list.c @@ -1,5 +1,6 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,19 +8,13 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * ECDH support in OpenSSL originally developed by - * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. - */ - #include "eng_int.h" /* * The linked-list of pointers to engine types. engine_list_head incorporates * an implicit structural reference but engine_list_tail does not - the - * latter is a computational niceity and only points to something that is - * already pointed to by its predecessor in the list (or engine_list_head + * latter is a computational optimization and only points to something that + * is already pointed to by its predecessor in the list (or engine_list_head * itself). In the same way, the use of the "prev" pointer in each ENGINE is * to save excessive list iteration, it doesn't correspond to an extra * structural reference. Hence, engine_list_head, and each non-null "next" @@ -322,7 +317,7 @@ ENGINE *ENGINE_by_id(const char *id) * Prevent infinite recursion if we're looking for the dynamic engine. */ if (strcmp(id, "dynamic")) { - if ((load_dir = getenv("OPENSSL_ENGINES")) == 0) + if ((load_dir = getenv("OPENSSL_ENGINES")) == NULL) load_dir = ENGINESDIR; iterator = ENGINE_by_id("dynamic"); if (!iterator || !ENGINE_ctrl_cmd_string(iterator, "ID", id, 0) || @@ -349,6 +344,6 @@ int ENGINE_up_ref(ENGINE *e) ENGINEerr(ENGINE_F_ENGINE_UP_REF, ERR_R_PASSED_NULL_PARAMETER); return 0; } - CRYPTO_atomic_add(&e->struct_ref, 1, &i, global_engine_lock); + CRYPTO_UP_REF(&e->struct_ref, &i, global_engine_lock); return 1; } diff --git a/crypto/engine/eng_openssl.c b/crypto/engine/eng_openssl.c index 9208f7ea..02885f46 100644 --- a/crypto/engine/eng_openssl.c +++ b/crypto/engine/eng_openssl.c @@ -1,5 +1,6 @@ /* * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. 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 @@ -7,16 +8,10 @@ * https://www.openssl.org/source/license.html */ -/* ==================================================================== - * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. - * ECDH support in OpenSSL originally developed by - * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. - */ - #include #include #include "internal/cryptlib.h" -#include +#include "internal/engine.h" #include #include #include diff --git a/crypto/engine/eng_rdrand.c b/crypto/engine/eng_rdrand.c index b3defcbe..7be64e3f 100644 --- a/crypto/engine/eng_rdrand.c +++ b/crypto/engine/eng_rdrand.c @@ -11,7 +11,7 @@ #include #include -#include +#include "internal/engine.h" #include #include #include diff --git a/crypto/engine/eng_table.c b/crypto/engine/eng_table.c index ac4b02fc..219253a3 100644 --- a/crypto/engine/eng_table.c +++ b/crypto/engine/eng_table.c @@ -1,5 +1,5 @@ /* - * Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-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 @@ -109,11 +109,6 @@ int engine_table_register(ENGINE_TABLE **table, ENGINE_CLEANUP_CB *cleanup, } fnd->funct = NULL; (void)lh_ENGINE_PILE_insert(&(*table)->piles, fnd); - if (lh_ENGINE_PILE_retrieve(&(*table)->piles, &tmplate) != fnd) { - sk_ENGINE_free(fnd->sk); - OPENSSL_free(fnd); - goto end; - } } /* A registration shouldn't add duplicate entries */ (void)sk_ENGINE_delete_ptr(fnd->sk, e); diff --git a/crypto/engine/tb_asnmth.c b/crypto/engine/tb_asnmth.c index 480267da..bc6e91cc 100644 --- a/crypto/engine/tb_asnmth.c +++ b/crypto/engine/tb_asnmth.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-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 @@ -7,6 +7,7 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" #include "eng_int.h" #include #include "internal/asn1_int.h" diff --git a/crypto/err/err.c b/crypto/err/err.c index c4399285..d69fbf87 100644 --- a/crypto/err/err.c +++ b/crypto/err/err.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -10,17 +10,17 @@ #include #include #include -#include -#include -#include -#include +#include "internal/cryptlib_int.h" +#include "internal/err.h" +#include "internal/err_int.h" +#include #include #include #include #include -#include +#include "internal/thread_once.h" -static void err_load_strings(int lib, ERR_STRING_DATA *str); +static int err_load_strings(const ERR_STRING_DATA *str); static void ERR_STATE_free(ERR_STATE *s); #ifndef OPENSSL_NO_ERR @@ -59,6 +59,7 @@ static ERR_STRING_DATA ERR_str_libraries[] = { {ERR_PACK(ERR_LIB_CT, 0, 0), "CT routines"}, {ERR_PACK(ERR_LIB_ASYNC, 0, 0), "ASYNC routines"}, {ERR_PACK(ERR_LIB_KDF, 0, 0), "KDF routines"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, 0), "STORE routines"}, {0, NULL}, }; @@ -83,6 +84,11 @@ static ERR_STRING_DATA ERR_str_functs[] = { {ERR_PACK(0, SYS_F_GETSOCKNAME, 0), "getsockname"}, {ERR_PACK(0, SYS_F_GETHOSTBYNAME, 0), "gethostbyname"}, {ERR_PACK(0, SYS_F_FFLUSH, 0), "fflush"}, + {ERR_PACK(0, SYS_F_OPEN, 0), "open"}, + {ERR_PACK(0, SYS_F_CLOSE, 0), "close"}, + {ERR_PACK(0, SYS_F_IOCTL, 0), "ioctl"}, + {ERR_PACK(0, SYS_F_STAT, 0), "stat"}, + {ERR_PACK(0, SYS_F_FCNTL, 0), "fcntl"}, {0, NULL}, }; @@ -103,6 +109,8 @@ static ERR_STRING_DATA ERR_str_reasons[] = { {ERR_R_PKCS7_LIB, "PKCS7 lib"}, {ERR_R_X509V3_LIB, "X509V3 lib"}, {ERR_R_ENGINE_LIB, "ENGINE lib"}, + {ERR_R_UI_LIB, "UI lib"}, + {ERR_R_OSSL_STORE_LIB, "STORE lib"}, {ERR_R_ECDSA_LIB, "ECDSA lib"}, {ERR_R_NESTED_ASN1_ERROR, "nested asn1 error"}, @@ -116,6 +124,7 @@ static ERR_STRING_DATA ERR_str_reasons[] = { {ERR_R_INTERNAL_ERROR, "internal error"}, {ERR_R_DISABLED, "called a function that was disabled at compile-time"}, {ERR_R_INIT_FAIL, "init fail"}, + {ERR_R_OPERATION_FAIL, "operation fail"}, {0, NULL}, }; @@ -153,7 +162,9 @@ static unsigned long err_string_data_hash(const ERR_STRING_DATA *a) static int err_string_data_cmp(const ERR_STRING_DATA *a, const ERR_STRING_DATA *b) { - return (int)(a->error - b->error); + if (a->error == b->error) + return 0; + return a->error > b->error ? 1 : -1; } static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *d) @@ -161,8 +172,7 @@ static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *d) ERR_STRING_DATA *p = NULL; CRYPTO_THREAD_read_lock(err_string_lock); - if (int_error_hash != NULL) - p = lh_ERR_STRING_DATA_retrieve(int_error_hash, d); + p = lh_ERR_STRING_DATA_retrieve(int_error_hash, d); CRYPTO_THREAD_unlock(err_string_lock); return p; @@ -199,7 +209,7 @@ static void build_SYS_str_reasons(void) for (i = 1; i <= NUM_SYS_STR_REASONS; i++) { ERR_STRING_DATA *str = &SYS_str_reasons[i - 1]; - str->error = (unsigned long)i; + str->error = ERR_PACK(ERR_LIB_SYS, 0, i); if (str->string == NULL) { char (*dest)[LEN_SYS_STR_REASON] = &(strerror_tab[i - 1]); if (openssl_strerror_r(i, *dest, sizeof(*dest))) @@ -217,6 +227,7 @@ static void build_SYS_str_reasons(void) init = 0; CRYPTO_THREAD_unlock(err_string_lock); + err_load_strings(SYS_str_reasons); } #endif @@ -256,7 +267,9 @@ DEFINE_RUN_ONCE_STATIC(do_err_strings_init) { OPENSSL_init_crypto(0, NULL); err_string_lock = CRYPTO_THREAD_lock_new(); - return err_string_lock != NULL; + int_error_hash = lh_ERR_STRING_DATA_new(err_string_data_hash, + err_string_data_cmp); + return err_string_lock != NULL && int_error_hash != NULL; } void err_cleanup(void) @@ -265,6 +278,32 @@ void err_cleanup(void) CRYPTO_THREAD_cleanup_local(&err_thread_local); CRYPTO_THREAD_lock_free(err_string_lock); err_string_lock = NULL; + lh_ERR_STRING_DATA_free(int_error_hash); + int_error_hash = NULL; +} + +/* + * Legacy; pack in the library. + */ +static void err_patch(int lib, ERR_STRING_DATA *str) +{ + unsigned long plib = ERR_PACK(lib, 0, 0); + + for (; str->error != 0; str++) + str->error |= plib; +} + +/* + * Hash in |str| error strings. Assumes the URN_ONCE was done. + */ +static int err_load_strings(const ERR_STRING_DATA *str) +{ + CRYPTO_THREAD_write_lock(err_string_lock); + for (; str->error; str++) + (void)lh_ERR_STRING_DATA_insert(int_error_hash, + (ERR_STRING_DATA *)str); + CRYPTO_THREAD_unlock(err_string_lock); + return 1; } int ERR_load_ERR_strings(void) @@ -273,36 +312,30 @@ int ERR_load_ERR_strings(void) if (!RUN_ONCE(&err_string_init, do_err_strings_init)) return 0; - err_load_strings(0, ERR_str_libraries); - err_load_strings(0, ERR_str_reasons); - err_load_strings(ERR_LIB_SYS, ERR_str_functs); + err_load_strings(ERR_str_libraries); + err_load_strings(ERR_str_reasons); + err_patch(ERR_LIB_SYS, ERR_str_functs); + err_load_strings(ERR_str_functs); build_SYS_str_reasons(); - err_load_strings(ERR_LIB_SYS, SYS_str_reasons); #endif return 1; } -static void err_load_strings(int lib, ERR_STRING_DATA *str) -{ - CRYPTO_THREAD_write_lock(err_string_lock); - if (int_error_hash == NULL) - int_error_hash = lh_ERR_STRING_DATA_new(err_string_data_hash, - err_string_data_cmp); - if (int_error_hash != NULL) { - for (; str->error; str++) { - if (lib) - str->error |= ERR_PACK(lib, 0, 0); - (void)lh_ERR_STRING_DATA_insert(int_error_hash, str); - } - } - CRYPTO_THREAD_unlock(err_string_lock); -} - int ERR_load_strings(int lib, ERR_STRING_DATA *str) { if (ERR_load_ERR_strings() == 0) return 0; - err_load_strings(lib, str); + + err_patch(lib, str); + err_load_strings(str); + return 1; +} + +int ERR_load_strings_const(const ERR_STRING_DATA *str) +{ + if (ERR_load_ERR_strings() == 0) + return 0; + err_load_strings(str); return 1; } @@ -312,13 +345,12 @@ int ERR_unload_strings(int lib, ERR_STRING_DATA *str) return 0; CRYPTO_THREAD_write_lock(err_string_lock); - if (int_error_hash != NULL) { - for (; str->error; str++) { - if (lib) - str->error |= ERR_PACK(lib, 0, 0); - (void)lh_ERR_STRING_DATA_delete(int_error_hash, str); - } - } + /* + * We don't need to ERR_PACK the lib, since that was done (to + * the table) when it was loaded. + */ + for (; str->error; str++) + (void)lh_ERR_STRING_DATA_delete(int_error_hash, str); CRYPTO_THREAD_unlock(err_string_lock); return 1; @@ -328,11 +360,6 @@ void err_free_strings_int(void) { if (!RUN_ONCE(&err_string_init, do_err_strings_init)) return; - - CRYPTO_THREAD_write_lock(err_string_lock); - lh_ERR_STRING_DATA_free(int_error_hash); - int_error_hash = NULL; - CRYPTO_THREAD_unlock(err_string_lock); } /********************************************************/ @@ -391,50 +418,50 @@ void ERR_clear_error(void) unsigned long ERR_get_error(void) { - return (get_error_values(1, 0, NULL, NULL, NULL, NULL)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + 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)); + return get_error_values(0, 1, file, line, data, flags); } static unsigned long get_error_values(int inc, int top, const char **file, @@ -475,15 +502,13 @@ static unsigned long get_error_values(int inc, int top, const char **file, es->err_buffer[i] = 0; } - if ((file != NULL) && (line != NULL)) { + if (file != NULL && line != NULL) { if (es->err_file[i] == NULL) { *file = "NA"; - if (line != NULL) - *line = 0; + *line = 0; } else { *file = es->err_file[i]; - if (line != NULL) - *line = es->err_line[i]; + *line = es->err_line[i]; } } @@ -515,45 +540,30 @@ void ERR_error_string_n(unsigned long e, char *buf, size_t len) 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) + if (ls == NULL) { BIO_snprintf(lsbuf, sizeof(lsbuf), "lib(%lu)", l); - if (fs == NULL) + ls = lsbuf; + } + + fs = ERR_func_error_string(e); + f = ERR_GET_FUNC(e); + if (fs == NULL) { BIO_snprintf(fsbuf, sizeof(fsbuf), "func(%lu)", f); - if (rs == NULL) + fs = fsbuf; + } + + rs = ERR_reason_error_string(e); + r = ERR_GET_REASON(e); + if (rs == NULL) { BIO_snprintf(rsbuf, sizeof(rsbuf), "reason(%lu)", r); + rs = rsbuf; + } - BIO_snprintf(buf, len, "error:%08lX:%s:%s:%s", e, ls ? ls : lsbuf, - fs ? fs : fsbuf, rs ? rs : rsbuf); + BIO_snprintf(buf, len, "error:%08lX:%s:%s:%s", e, ls, fs, rs); 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; - } - } + /* Didn't fit; use a minimal format. */ + BIO_snprintf(buf, len, "err:%lx:%lx:%lx:%lx", e, l, f, r); } } @@ -567,8 +577,7 @@ char *ERR_error_string(unsigned long e, char *ret) if (ret == NULL) ret = buf; - ERR_error_string_n(e, ret, 256); - + ERR_error_string_n(e, ret, (int)sizeof(buf)); return ret; } @@ -738,20 +747,19 @@ void ERR_add_error_vdata(int num, va_list args) n = 0; for (i = 0; i < num; i++) { a = va_arg(args, char *); - /* ignore NULLs, thanks to Bob Beck */ - 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; - } - str = p; + if (a == NULL) + a = ""; + n += strlen(a); + if (n > s) { + s = n + 20; + p = OPENSSL_realloc(str, s + 1); + if (p == NULL) { + OPENSSL_free(str); + return; } - OPENSSL_strlcat(str, a, (size_t)s + 1); + str = p; } + OPENSSL_strlcat(str, a, (size_t)s + 1); } ERR_set_error_data(str, ERR_TXT_MALLOCED | ERR_TXT_STRING); } @@ -781,9 +789,7 @@ int ERR_pop_to_mark(void) 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; + es->top = es->top > 0 ? es->top - 1 : ERR_NUM_ERRORS - 1; } if (es->bottom == es->top) @@ -791,3 +797,24 @@ int ERR_pop_to_mark(void) es->err_flags[es->top] &= ~ERR_FLAG_MARK; return 1; } + +int ERR_clear_last_mark(void) +{ + ERR_STATE *es; + int top; + + es = ERR_get_state(); + if (es == NULL) + return 0; + + top = es->top; + while (es->bottom != top + && (es->err_flags[top] & ERR_FLAG_MARK) == 0) { + top = top > 0 ? top - 1 : ERR_NUM_ERRORS - 1; + } + + if (es->bottom == top) + return 0; + es->err_flags[top] &= ~ERR_FLAG_MARK; + return 1; +} diff --git a/crypto/err/err_all.c b/crypto/err/err_all.c index 3b1304f8..d9ec04b6 100644 --- a/crypto/err/err_all.c +++ b/crypto/err/err_all.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -9,43 +9,39 @@ #include #include "internal/err_int.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "internal/dso.h" -#include -#include -#include +#include +#include +#include #include -#ifdef OPENSSL_FIPS -# include -#endif -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include int err_load_crypto_strings_int(void) { if ( -#ifdef OPENSSL_FIPS - FIPS_set_error_callbacks(ERR_put_error, ERR_add_error_vdata) == 0 || -#endif #ifndef OPENSSL_NO_ERR ERR_load_ERR_strings() == 0 || /* include error strings for SYSerr */ ERR_load_BN_strings() == 0 || @@ -88,12 +84,7 @@ int err_load_crypto_strings_int(void) # ifndef OPENSSL_NO_OCSP ERR_load_OCSP_strings() == 0 || # endif -#ifndef OPENSSL_NO_UI ERR_load_UI_strings() == 0 || -#endif -# ifdef OPENSSL_FIPS - ERR_load_FIPS_strings() == 0 || -# endif # ifndef OPENSSL_NO_CMS ERR_load_CMS_strings() == 0 || # endif @@ -102,7 +93,8 @@ int err_load_crypto_strings_int(void) # endif ERR_load_ASYNC_strings() == 0 || #endif - ERR_load_KDF_strings() == 0) + ERR_load_KDF_strings() == 0 || + ERR_load_OSSL_STORE_strings() == 0) return 0; return 1; diff --git a/crypto/err/err_prn.c b/crypto/err/err_prn.c index 6ae12515..c82e6294 100644 --- a/crypto/err/err_prn.c +++ b/crypto/err/err_prn.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,7 +9,6 @@ #include #include "internal/cryptlib.h" -#include #include #include #include diff --git a/crypto/err/openssl.ec b/crypto/err/openssl.ec index 15d151f3..be84c7cb 100644 --- a/crypto/err/openssl.ec +++ b/crypto/err/openssl.ec @@ -1,99 +1,75 @@ -# crypto/err/openssl.ec - # configuration file for util/mkerr.pl -# files that may have to be rewritten by util/mkerr.pl -L ERR NONE NONE -L BN include/openssl/bn.h crypto/bn/bn_err.c -L RSA include/openssl/rsa.h crypto/rsa/rsa_err.c -L DH include/openssl/dh.h crypto/dh/dh_err.c -L EVP include/openssl/evp.h crypto/evp/evp_err.c -L BUF include/openssl/buffer.h crypto/buffer/buf_err.c -L OBJ include/openssl/objects.h crypto/objects/obj_err.c -L PEM include/openssl/pem.h crypto/pem/pem_err.c -L DSA include/openssl/dsa.h crypto/dsa/dsa_err.c -L X509 include/openssl/x509.h crypto/x509/x509_err.c -L ASN1 include/openssl/asn1.h crypto/asn1/asn1_err.c -L CONF include/openssl/conf.h crypto/conf/conf_err.c -L CRYPTO include/openssl/crypto.h crypto/cpt_err.c -L EC include/openssl/ec.h crypto/ec/ec_err.c -L SSL include/openssl/ssl.h ssl/ssl_err.c -L BIO include/openssl/bio.h crypto/bio/bio_err.c -L PKCS7 include/openssl/pkcs7.h crypto/pkcs7/pkcs7err.c -L X509V3 include/openssl/x509v3.h crypto/x509v3/v3err.c -L PKCS12 include/openssl/pkcs12.h crypto/pkcs12/pk12err.c -L RAND include/openssl/rand.h crypto/rand/rand_err.c -L DSO include/internal/dso.h crypto/dso/dso_err.c -L ENGINE include/openssl/engine.h crypto/engine/eng_err.c -L OCSP include/openssl/ocsp.h crypto/ocsp/ocsp_err.c -L UI include/openssl/ui.h crypto/ui/ui_err.c -L COMP include/openssl/comp.h crypto/comp/comp_err.c -L TS include/openssl/ts.h crypto/ts/ts_err.c -#L HMAC include/openssl/hmac.h crypto/hmac/hmac_err.c -L CMS include/openssl/cms.h crypto/cms/cms_err.c -#L FIPS include/openssl/fips.h crypto/fips_err.h -L CT include/openssl/ct.h crypto/ct/ct_err.c -L ASYNC include/openssl/async.h crypto/async/async_err.c -L KDF include/openssl/kdf.h crypto/kdf/kdf_err.c +# The INPUT HEADER is scanned for declarations +# LIBNAME INPUT HEADER ERROR-TABLE FILE +L ERR NONE NONE +L BN include/openssl/bn.h crypto/bn/bn_err.c +L RSA include/openssl/rsa.h crypto/rsa/rsa_err.c +L DH include/openssl/dh.h crypto/dh/dh_err.c +L EVP include/openssl/evp.h crypto/evp/evp_err.c +L BUF include/openssl/buffer.h crypto/buffer/buf_err.c +L OBJ include/openssl/objects.h crypto/objects/obj_err.c +L PEM include/openssl/pem.h crypto/pem/pem_err.c +L DSA include/openssl/dsa.h crypto/dsa/dsa_err.c +L X509 include/openssl/x509.h crypto/x509/x509_err.c +L ASN1 include/openssl/asn1.h crypto/asn1/asn1_err.c +L CONF include/openssl/conf.h crypto/conf/conf_err.c +L CRYPTO include/openssl/crypto.h crypto/cpt_err.c +L EC include/openssl/ec.h crypto/ec/ec_err.c +L SSL include/openssl/ssl.h ssl/ssl_err.c +L BIO include/openssl/bio.h crypto/bio/bio_err.c +L PKCS7 include/openssl/pkcs7.h crypto/pkcs7/pkcs7err.c +L X509V3 include/openssl/x509v3.h crypto/x509v3/v3err.c +L PKCS12 include/openssl/pkcs12.h crypto/pkcs12/pk12err.c +L RAND include/openssl/rand.h crypto/rand/rand_err.c +L DSO include/internal/dso.h crypto/dso/dso_err.c +L ENGINE include/openssl/engine.h crypto/engine/eng_err.c +L OCSP include/openssl/ocsp.h crypto/ocsp/ocsp_err.c +L UI include/openssl/ui.h crypto/ui/ui_err.c +L COMP include/openssl/comp.h crypto/comp/comp_err.c +L TS include/openssl/ts.h crypto/ts/ts_err.c +L CMS include/openssl/cms.h crypto/cms/cms_err.c +L CT include/openssl/ct.h crypto/ct/ct_err.c +L ASYNC include/openssl/async.h crypto/async/async_err.c +L KDF include/openssl/kdf.h crypto/kdf/kdf_err.c +L OSSL_STORE include/openssl/store.h crypto/store/store_err.c # additional header files to be scanned for function names -L NONE include/openssl/x509_vfy.h NONE -L NONE crypto/ec/ec_lcl.h NONE -L NONE crypto/cms/cms_lcl.h NONE -L NONE crypto/ct/ct_locl.h NONE -#L NONE fips/rand/fips_rand.h NONE -L NONE ssl/ssl_locl.h NONE - -F RSAREF_F_RSA_BN2BIN -F RSAREF_F_RSA_PRIVATE_DECRYPT -F RSAREF_F_RSA_PRIVATE_ENCRYPT -F RSAREF_F_RSA_PUBLIC_DECRYPT -F RSAREF_F_RSA_PUBLIC_ENCRYPT - -R SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010 -R SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020 -R SSL_R_TLSV1_ALERT_DECRYPTION_FAILED 1021 -R SSL_R_TLSV1_ALERT_RECORD_OVERFLOW 1022 -R SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE 1030 -R SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE 1040 -R SSL_R_SSLV3_ALERT_NO_CERTIFICATE 1041 -R SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 1042 -R SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE 1043 -R SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED 1044 -R SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED 1045 -R SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 1046 -R SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER 1047 -R SSL_R_TLSV1_ALERT_UNKNOWN_CA 1048 -R SSL_R_TLSV1_ALERT_ACCESS_DENIED 1049 -R SSL_R_TLSV1_ALERT_DECODE_ERROR 1050 -R SSL_R_TLSV1_ALERT_DECRYPT_ERROR 1051 -R SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION 1060 -R SSL_R_TLSV1_ALERT_PROTOCOL_VERSION 1070 -R SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY 1071 -R SSL_R_TLSV1_ALERT_INTERNAL_ERROR 1080 -R SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK 1086 -R SSL_R_TLSV1_ALERT_USER_CANCELLED 1090 -R SSL_R_TLSV1_ALERT_NO_RENEGOTIATION 1100 -R SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110 -R SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE 1111 -R SSL_R_TLSV1_UNRECOGNIZED_NAME 1112 -R SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE 1113 -R SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114 -R TLS1_AD_UNKNOWN_PSK_IDENTITY 1115 -R TLS1_AD_NO_APPLICATION_PROTOCOL 1120 - -R RSAREF_R_CONTENT_ENCODING 0x0400 -R RSAREF_R_DATA 0x0401 -R RSAREF_R_DIGEST_ALGORITHM 0x0402 -R RSAREF_R_ENCODING 0x0403 -R RSAREF_R_KEY 0x0404 -R RSAREF_R_KEY_ENCODING 0x0405 -R RSAREF_R_LEN 0x0406 -R RSAREF_R_MODULUS_LEN 0x0407 -R RSAREF_R_NEED_RANDOM 0x0408 -R RSAREF_R_PRIVATE_KEY 0x0409 -R RSAREF_R_PUBLIC_KEY 0x040a -R RSAREF_R_SIGNATURE 0x040b -R RSAREF_R_SIGNATURE_ENCODING 0x040c -R RSAREF_R_ENCRYPTION_ALGORITHM 0x040d +L NONE include/openssl/x509_vfy.h NONE +L NONE crypto/ec/ec_lcl.h NONE +L NONE crypto/cms/cms_lcl.h NONE +L NONE crypto/ct/ct_locl.h NONE +L NONE ssl/ssl_locl.h NONE +# SSL/TLS alerts +R SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010 +R SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020 +R SSL_R_TLSV1_ALERT_DECRYPTION_FAILED 1021 +R SSL_R_TLSV1_ALERT_RECORD_OVERFLOW 1022 +R SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE 1030 +R SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE 1040 +R SSL_R_SSLV3_ALERT_NO_CERTIFICATE 1041 +R SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 1042 +R SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE 1043 +R SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED 1044 +R SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED 1045 +R SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 1046 +R SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER 1047 +R SSL_R_TLSV1_ALERT_UNKNOWN_CA 1048 +R SSL_R_TLSV1_ALERT_ACCESS_DENIED 1049 +R SSL_R_TLSV1_ALERT_DECODE_ERROR 1050 +R SSL_R_TLSV1_ALERT_DECRYPT_ERROR 1051 +R SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION 1060 +R SSL_R_TLSV1_ALERT_PROTOCOL_VERSION 1070 +R SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY 1071 +R SSL_R_TLSV1_ALERT_INTERNAL_ERROR 1080 +R SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK 1086 +R SSL_R_TLSV1_ALERT_USER_CANCELLED 1090 +R SSL_R_TLSV1_ALERT_NO_RENEGOTIATION 1100 +R SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110 +R SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE 1111 +R SSL_R_TLSV1_UNRECOGNIZED_NAME 1112 +R SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE 1113 +R SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114 +R TLS1_AD_UNKNOWN_PSK_IDENTITY 1115 +R TLS1_AD_NO_APPLICATION_PROTOCOL 1120 diff --git a/crypto/err/openssl.txt b/crypto/err/openssl.txt new file mode 100644 index 00000000..e406becd --- /dev/null +++ b/crypto/err/openssl.txt @@ -0,0 +1,2827 @@ +# Copyright 1999-2018 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 + +# Function codes +ASN1_F_A2D_ASN1_OBJECT:100:a2d_ASN1_OBJECT +ASN1_F_A2I_ASN1_INTEGER:102:a2i_ASN1_INTEGER +ASN1_F_A2I_ASN1_STRING:103:a2i_ASN1_STRING +ASN1_F_APPEND_EXP:176:append_exp +ASN1_F_ASN1_BIT_STRING_SET_BIT:183:ASN1_BIT_STRING_set_bit +ASN1_F_ASN1_CB:177:asn1_cb +ASN1_F_ASN1_CHECK_TLEN:104:asn1_check_tlen +ASN1_F_ASN1_COLLECT:106:asn1_collect +ASN1_F_ASN1_D2I_EX_PRIMITIVE:108:asn1_d2i_ex_primitive +ASN1_F_ASN1_D2I_FP:109:ASN1_d2i_fp +ASN1_F_ASN1_D2I_READ_BIO:107:asn1_d2i_read_bio +ASN1_F_ASN1_DIGEST:184:ASN1_digest +ASN1_F_ASN1_DO_ADB:110:asn1_do_adb +ASN1_F_ASN1_DO_LOCK:233:asn1_do_lock +ASN1_F_ASN1_DUP:111:ASN1_dup +ASN1_F_ASN1_EX_C2I:204:asn1_ex_c2i +ASN1_F_ASN1_FIND_END:190:asn1_find_end +ASN1_F_ASN1_GENERALIZEDTIME_ADJ:216:ASN1_GENERALIZEDTIME_adj +ASN1_F_ASN1_GENERATE_V3:178:ASN1_generate_v3 +ASN1_F_ASN1_GET_INT64:224:asn1_get_int64 +ASN1_F_ASN1_GET_OBJECT:114:ASN1_get_object +ASN1_F_ASN1_GET_UINT64:225:asn1_get_uint64 +ASN1_F_ASN1_I2D_BIO:116:ASN1_i2d_bio +ASN1_F_ASN1_I2D_FP:117:ASN1_i2d_fp +ASN1_F_ASN1_ITEM_D2I_FP:206:ASN1_item_d2i_fp +ASN1_F_ASN1_ITEM_DUP:191:ASN1_item_dup +ASN1_F_ASN1_ITEM_EMBED_D2I:120:asn1_item_embed_d2i +ASN1_F_ASN1_ITEM_EMBED_NEW:121:asn1_item_embed_new +ASN1_F_ASN1_ITEM_I2D_BIO:192:ASN1_item_i2d_bio +ASN1_F_ASN1_ITEM_I2D_FP:193:ASN1_item_i2d_fp +ASN1_F_ASN1_ITEM_PACK:198:ASN1_item_pack +ASN1_F_ASN1_ITEM_SIGN:195:ASN1_item_sign +ASN1_F_ASN1_ITEM_SIGN_CTX:220:ASN1_item_sign_ctx +ASN1_F_ASN1_ITEM_UNPACK:199:ASN1_item_unpack +ASN1_F_ASN1_ITEM_VERIFY:197:ASN1_item_verify +ASN1_F_ASN1_MBSTRING_NCOPY:122:ASN1_mbstring_ncopy +ASN1_F_ASN1_OBJECT_NEW:123:ASN1_OBJECT_new +ASN1_F_ASN1_OUTPUT_DATA:214:asn1_output_data +ASN1_F_ASN1_PCTX_NEW:205:ASN1_PCTX_new +ASN1_F_ASN1_SCTX_NEW:221:ASN1_SCTX_new +ASN1_F_ASN1_SIGN:128:ASN1_sign +ASN1_F_ASN1_STR2TYPE:179:asn1_str2type +ASN1_F_ASN1_STRING_GET_INT64:227:asn1_string_get_int64 +ASN1_F_ASN1_STRING_GET_UINT64:230:asn1_string_get_uint64 +ASN1_F_ASN1_STRING_SET:186:ASN1_STRING_set +ASN1_F_ASN1_STRING_TABLE_ADD:129:ASN1_STRING_TABLE_add +ASN1_F_ASN1_STRING_TO_BN:228:asn1_string_to_bn +ASN1_F_ASN1_STRING_TYPE_NEW:130:ASN1_STRING_type_new +ASN1_F_ASN1_TEMPLATE_EX_D2I:132:asn1_template_ex_d2i +ASN1_F_ASN1_TEMPLATE_NEW:133:asn1_template_new +ASN1_F_ASN1_TEMPLATE_NOEXP_D2I:131:asn1_template_noexp_d2i +ASN1_F_ASN1_TIME_ADJ:217:ASN1_TIME_adj +ASN1_F_ASN1_TYPE_GET_INT_OCTETSTRING:134:ASN1_TYPE_get_int_octetstring +ASN1_F_ASN1_TYPE_GET_OCTETSTRING:135:ASN1_TYPE_get_octetstring +ASN1_F_ASN1_UTCTIME_ADJ:218:ASN1_UTCTIME_adj +ASN1_F_ASN1_VERIFY:137:ASN1_verify +ASN1_F_B64_READ_ASN1:209:b64_read_asn1 +ASN1_F_B64_WRITE_ASN1:210:B64_write_ASN1 +ASN1_F_BIO_NEW_NDEF:208:BIO_new_NDEF +ASN1_F_BITSTR_CB:180:bitstr_cb +ASN1_F_BN_TO_ASN1_STRING:229:bn_to_asn1_string +ASN1_F_C2I_ASN1_BIT_STRING:189:c2i_ASN1_BIT_STRING +ASN1_F_C2I_ASN1_INTEGER:194:c2i_ASN1_INTEGER +ASN1_F_C2I_ASN1_OBJECT:196:c2i_ASN1_OBJECT +ASN1_F_C2I_IBUF:226:c2i_ibuf +ASN1_F_C2I_UINT64_INT:101:c2i_uint64_int +ASN1_F_COLLECT_DATA:140:collect_data +ASN1_F_D2I_ASN1_OBJECT:147:d2i_ASN1_OBJECT +ASN1_F_D2I_ASN1_UINTEGER:150:d2i_ASN1_UINTEGER +ASN1_F_D2I_AUTOPRIVATEKEY:207:d2i_AutoPrivateKey +ASN1_F_D2I_PRIVATEKEY:154:d2i_PrivateKey +ASN1_F_D2I_PUBLICKEY:155:d2i_PublicKey +ASN1_F_DO_TCREATE:222:do_tcreate +ASN1_F_I2D_ASN1_BIO_STREAM:211:i2d_ASN1_bio_stream +ASN1_F_I2D_DSA_PUBKEY:161:i2d_DSA_PUBKEY +ASN1_F_I2D_EC_PUBKEY:181:i2d_EC_PUBKEY +ASN1_F_I2D_PRIVATEKEY:163:i2d_PrivateKey +ASN1_F_I2D_PUBLICKEY:164:i2d_PublicKey +ASN1_F_I2D_RSA_PUBKEY:165:i2d_RSA_PUBKEY +ASN1_F_LONG_C2I:166:long_c2i +ASN1_F_OID_MODULE_INIT:174:oid_module_init +ASN1_F_PARSE_TAGGING:182:parse_tagging +ASN1_F_PKCS5_PBE2_SET_IV:167:PKCS5_pbe2_set_iv +ASN1_F_PKCS5_PBE2_SET_SCRYPT:231:PKCS5_pbe2_set_scrypt +ASN1_F_PKCS5_PBE_SET:202:PKCS5_pbe_set +ASN1_F_PKCS5_PBE_SET0_ALGOR:215:PKCS5_pbe_set0_algor +ASN1_F_PKCS5_PBKDF2_SET:219:PKCS5_pbkdf2_set +ASN1_F_PKCS5_SCRYPT_SET:232:pkcs5_scrypt_set +ASN1_F_SMIME_READ_ASN1:212:SMIME_read_ASN1 +ASN1_F_SMIME_TEXT:213:SMIME_text +ASN1_F_STBL_MODULE_INIT:223:stbl_module_init +ASN1_F_UINT32_C2I:105:uint32_c2i +ASN1_F_UINT64_C2I:112:uint64_c2i +ASN1_F_X509_CRL_ADD0_REVOKED:169:X509_CRL_add0_revoked +ASN1_F_X509_INFO_NEW:170:X509_INFO_new +ASN1_F_X509_NAME_ENCODE:203:x509_name_encode +ASN1_F_X509_NAME_EX_D2I:158:x509_name_ex_d2i +ASN1_F_X509_NAME_EX_NEW:171:x509_name_ex_new +ASN1_F_X509_PKEY_NEW:173:X509_PKEY_new +ASYNC_F_ASYNC_CTX_NEW:100:async_ctx_new +ASYNC_F_ASYNC_INIT_THREAD:101:ASYNC_init_thread +ASYNC_F_ASYNC_JOB_NEW:102:async_job_new +ASYNC_F_ASYNC_PAUSE_JOB:103:ASYNC_pause_job +ASYNC_F_ASYNC_START_FUNC:104:async_start_func +ASYNC_F_ASYNC_START_JOB:105:ASYNC_start_job +BIO_F_ACPT_STATE:100:acpt_state +BIO_F_ADDR_STRINGS:134:addr_strings +BIO_F_BIO_ACCEPT:101:BIO_accept +BIO_F_BIO_ACCEPT_EX:137:BIO_accept_ex +BIO_F_BIO_ADDR_NEW:144:BIO_ADDR_new +BIO_F_BIO_BIND:147:BIO_bind +BIO_F_BIO_CALLBACK_CTRL:131:BIO_callback_ctrl +BIO_F_BIO_CONNECT:138:BIO_connect +BIO_F_BIO_CTRL:103:BIO_ctrl +BIO_F_BIO_GETS:104:BIO_gets +BIO_F_BIO_GET_HOST_IP:106:BIO_get_host_ip +BIO_F_BIO_GET_NEW_INDEX:102:BIO_get_new_index +BIO_F_BIO_GET_PORT:107:BIO_get_port +BIO_F_BIO_LISTEN:139:BIO_listen +BIO_F_BIO_LOOKUP:135:BIO_lookup +BIO_F_BIO_LOOKUP_EX:143:BIO_lookup_ex +BIO_F_BIO_MAKE_PAIR:121:bio_make_pair +BIO_F_BIO_METH_NEW:146:BIO_meth_new +BIO_F_BIO_NEW:108:BIO_new +BIO_F_BIO_NEW_DGRAM_SCTP:145:BIO_new_dgram_sctp +BIO_F_BIO_NEW_FILE:109:BIO_new_file +BIO_F_BIO_NEW_MEM_BUF:126:BIO_new_mem_buf +BIO_F_BIO_NREAD:123:BIO_nread +BIO_F_BIO_NREAD0:124:BIO_nread0 +BIO_F_BIO_NWRITE:125:BIO_nwrite +BIO_F_BIO_NWRITE0:122:BIO_nwrite0 +BIO_F_BIO_PARSE_HOSTSERV:136:BIO_parse_hostserv +BIO_F_BIO_PUTS:110:BIO_puts +BIO_F_BIO_READ:111:BIO_read +BIO_F_BIO_READ_EX:105:BIO_read_ex +BIO_F_BIO_READ_INTERN:120:bio_read_intern +BIO_F_BIO_SOCKET:140:BIO_socket +BIO_F_BIO_SOCKET_NBIO:142:BIO_socket_nbio +BIO_F_BIO_SOCK_INFO:141:BIO_sock_info +BIO_F_BIO_SOCK_INIT:112:BIO_sock_init +BIO_F_BIO_WRITE:113:BIO_write +BIO_F_BIO_WRITE_EX:119:BIO_write_ex +BIO_F_BIO_WRITE_INTERN:128:bio_write_intern +BIO_F_BUFFER_CTRL:114:buffer_ctrl +BIO_F_CONN_CTRL:127:conn_ctrl +BIO_F_CONN_STATE:115:conn_state +BIO_F_DGRAM_SCTP_READ:132:dgram_sctp_read +BIO_F_DGRAM_SCTP_WRITE:133:dgram_sctp_write +BIO_F_FILE_CTRL:116:file_ctrl +BIO_F_FILE_READ:130:file_read +BIO_F_LINEBUFFER_CTRL:129:linebuffer_ctrl +BIO_F_MEM_WRITE:117:mem_write +BIO_F_SSL_NEW:118:SSL_new +BN_F_BNRAND:127:bnrand +BN_F_BNRAND_RANGE:138:bnrand_range +BN_F_BN_BLINDING_CONVERT_EX:100:BN_BLINDING_convert_ex +BN_F_BN_BLINDING_CREATE_PARAM:128:BN_BLINDING_create_param +BN_F_BN_BLINDING_INVERT_EX:101:BN_BLINDING_invert_ex +BN_F_BN_BLINDING_NEW:102:BN_BLINDING_new +BN_F_BN_BLINDING_UPDATE:103:BN_BLINDING_update +BN_F_BN_BN2DEC:104:BN_bn2dec +BN_F_BN_BN2HEX:105:BN_bn2hex +BN_F_BN_COMPUTE_WNAF:142:bn_compute_wNAF +BN_F_BN_CTX_GET:116:BN_CTX_get +BN_F_BN_CTX_NEW:106:BN_CTX_new +BN_F_BN_CTX_START:129:BN_CTX_start +BN_F_BN_DIV:107:BN_div +BN_F_BN_DIV_RECP:130:BN_div_recp +BN_F_BN_EXP:123:BN_exp +BN_F_BN_EXPAND_INTERNAL:120:bn_expand_internal +BN_F_BN_GENCB_NEW:143:BN_GENCB_new +BN_F_BN_GENERATE_DSA_NONCE:140:BN_generate_dsa_nonce +BN_F_BN_GENERATE_PRIME_EX:141:BN_generate_prime_ex +BN_F_BN_GF2M_MOD:131:BN_GF2m_mod +BN_F_BN_GF2M_MOD_EXP:132:BN_GF2m_mod_exp +BN_F_BN_GF2M_MOD_MUL:133:BN_GF2m_mod_mul +BN_F_BN_GF2M_MOD_SOLVE_QUAD:134:BN_GF2m_mod_solve_quad +BN_F_BN_GF2M_MOD_SOLVE_QUAD_ARR:135:BN_GF2m_mod_solve_quad_arr +BN_F_BN_GF2M_MOD_SQR:136:BN_GF2m_mod_sqr +BN_F_BN_GF2M_MOD_SQRT:137:BN_GF2m_mod_sqrt +BN_F_BN_LSHIFT:145:BN_lshift +BN_F_BN_MOD_EXP2_MONT:118:BN_mod_exp2_mont +BN_F_BN_MOD_EXP_MONT:109:BN_mod_exp_mont +BN_F_BN_MOD_EXP_MONT_CONSTTIME:124:BN_mod_exp_mont_consttime +BN_F_BN_MOD_EXP_MONT_WORD:117:BN_mod_exp_mont_word +BN_F_BN_MOD_EXP_RECP:125:BN_mod_exp_recp +BN_F_BN_MOD_EXP_SIMPLE:126:BN_mod_exp_simple +BN_F_BN_MOD_INVERSE:110:BN_mod_inverse +BN_F_BN_MOD_INVERSE_NO_BRANCH:139:BN_mod_inverse_no_branch +BN_F_BN_MOD_LSHIFT_QUICK:119:BN_mod_lshift_quick +BN_F_BN_MOD_SQRT:121:BN_mod_sqrt +BN_F_BN_MPI2BN:112:BN_mpi2bn +BN_F_BN_NEW:113:BN_new +BN_F_BN_RAND:114:BN_rand +BN_F_BN_RAND_RANGE:122:BN_rand_range +BN_F_BN_RSHIFT:146:BN_rshift +BN_F_BN_SET_WORDS:144:bn_set_words +BN_F_BN_USUB:115:BN_usub +BUF_F_BUF_MEM_GROW:100:BUF_MEM_grow +BUF_F_BUF_MEM_GROW_CLEAN:105:BUF_MEM_grow_clean +BUF_F_BUF_MEM_NEW:101:BUF_MEM_new +CMS_F_CHECK_CONTENT:99:check_content +CMS_F_CMS_ADD0_CERT:164:CMS_add0_cert +CMS_F_CMS_ADD0_RECIPIENT_KEY:100:CMS_add0_recipient_key +CMS_F_CMS_ADD0_RECIPIENT_PASSWORD:165:CMS_add0_recipient_password +CMS_F_CMS_ADD1_RECEIPTREQUEST:158:CMS_add1_ReceiptRequest +CMS_F_CMS_ADD1_RECIPIENT_CERT:101:CMS_add1_recipient_cert +CMS_F_CMS_ADD1_SIGNER:102:CMS_add1_signer +CMS_F_CMS_ADD1_SIGNINGTIME:103:cms_add1_signingTime +CMS_F_CMS_COMPRESS:104:CMS_compress +CMS_F_CMS_COMPRESSEDDATA_CREATE:105:cms_CompressedData_create +CMS_F_CMS_COMPRESSEDDATA_INIT_BIO:106:cms_CompressedData_init_bio +CMS_F_CMS_COPY_CONTENT:107:cms_copy_content +CMS_F_CMS_COPY_MESSAGEDIGEST:108:cms_copy_messageDigest +CMS_F_CMS_DATA:109:CMS_data +CMS_F_CMS_DATAFINAL:110:CMS_dataFinal +CMS_F_CMS_DATAINIT:111:CMS_dataInit +CMS_F_CMS_DECRYPT:112:CMS_decrypt +CMS_F_CMS_DECRYPT_SET1_KEY:113:CMS_decrypt_set1_key +CMS_F_CMS_DECRYPT_SET1_PASSWORD:166:CMS_decrypt_set1_password +CMS_F_CMS_DECRYPT_SET1_PKEY:114:CMS_decrypt_set1_pkey +CMS_F_CMS_DIGESTALGORITHM_FIND_CTX:115:cms_DigestAlgorithm_find_ctx +CMS_F_CMS_DIGESTALGORITHM_INIT_BIO:116:cms_DigestAlgorithm_init_bio +CMS_F_CMS_DIGESTEDDATA_DO_FINAL:117:cms_DigestedData_do_final +CMS_F_CMS_DIGEST_VERIFY:118:CMS_digest_verify +CMS_F_CMS_ENCODE_RECEIPT:161:cms_encode_Receipt +CMS_F_CMS_ENCRYPT:119:CMS_encrypt +CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO:120:cms_EncryptedContent_init_bio +CMS_F_CMS_ENCRYPTEDDATA_DECRYPT:121:CMS_EncryptedData_decrypt +CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT:122:CMS_EncryptedData_encrypt +CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY:123:CMS_EncryptedData_set1_key +CMS_F_CMS_ENVELOPEDDATA_CREATE:124:CMS_EnvelopedData_create +CMS_F_CMS_ENVELOPEDDATA_INIT_BIO:125:cms_EnvelopedData_init_bio +CMS_F_CMS_ENVELOPED_DATA_INIT:126:cms_enveloped_data_init +CMS_F_CMS_ENV_ASN1_CTRL:171:cms_env_asn1_ctrl +CMS_F_CMS_FINAL:127:CMS_final +CMS_F_CMS_GET0_CERTIFICATE_CHOICES:128:cms_get0_certificate_choices +CMS_F_CMS_GET0_CONTENT:129:CMS_get0_content +CMS_F_CMS_GET0_ECONTENT_TYPE:130:cms_get0_econtent_type +CMS_F_CMS_GET0_ENVELOPED:131:cms_get0_enveloped +CMS_F_CMS_GET0_REVOCATION_CHOICES:132:cms_get0_revocation_choices +CMS_F_CMS_GET0_SIGNED:133:cms_get0_signed +CMS_F_CMS_MSGSIGDIGEST_ADD1:162:cms_msgSigDigest_add1 +CMS_F_CMS_RECEIPTREQUEST_CREATE0:159:CMS_ReceiptRequest_create0 +CMS_F_CMS_RECEIPT_VERIFY:160:cms_Receipt_verify +CMS_F_CMS_RECIPIENTINFO_DECRYPT:134:CMS_RecipientInfo_decrypt +CMS_F_CMS_RECIPIENTINFO_ENCRYPT:169:CMS_RecipientInfo_encrypt +CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT:178:cms_RecipientInfo_kari_encrypt +CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG:175:CMS_RecipientInfo_kari_get0_alg +CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID:173:\ + CMS_RecipientInfo_kari_get0_orig_id +CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS:172:CMS_RecipientInfo_kari_get0_reks +CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP:174:CMS_RecipientInfo_kari_orig_id_cmp +CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT:135:cms_RecipientInfo_kekri_decrypt +CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT:136:cms_RecipientInfo_kekri_encrypt +CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID:137:CMS_RecipientInfo_kekri_get0_id +CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP:138:CMS_RecipientInfo_kekri_id_cmp +CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP:139:CMS_RecipientInfo_ktri_cert_cmp +CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT:140:cms_RecipientInfo_ktri_decrypt +CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT:141:cms_RecipientInfo_ktri_encrypt +CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS:142:CMS_RecipientInfo_ktri_get0_algs +CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID:143:\ + CMS_RecipientInfo_ktri_get0_signer_id +CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT:167:cms_RecipientInfo_pwri_crypt +CMS_F_CMS_RECIPIENTINFO_SET0_KEY:144:CMS_RecipientInfo_set0_key +CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD:168:CMS_RecipientInfo_set0_password +CMS_F_CMS_RECIPIENTINFO_SET0_PKEY:145:CMS_RecipientInfo_set0_pkey +CMS_F_CMS_SD_ASN1_CTRL:170:cms_sd_asn1_ctrl +CMS_F_CMS_SET1_IAS:176:cms_set1_ias +CMS_F_CMS_SET1_KEYID:177:cms_set1_keyid +CMS_F_CMS_SET1_SIGNERIDENTIFIER:146:cms_set1_SignerIdentifier +CMS_F_CMS_SET_DETACHED:147:CMS_set_detached +CMS_F_CMS_SIGN:148:CMS_sign +CMS_F_CMS_SIGNED_DATA_INIT:149:cms_signed_data_init +CMS_F_CMS_SIGNERINFO_CONTENT_SIGN:150:cms_SignerInfo_content_sign +CMS_F_CMS_SIGNERINFO_SIGN:151:CMS_SignerInfo_sign +CMS_F_CMS_SIGNERINFO_VERIFY:152:CMS_SignerInfo_verify +CMS_F_CMS_SIGNERINFO_VERIFY_CERT:153:cms_signerinfo_verify_cert +CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT:154:CMS_SignerInfo_verify_content +CMS_F_CMS_SIGN_RECEIPT:163:CMS_sign_receipt +CMS_F_CMS_STREAM:155:CMS_stream +CMS_F_CMS_UNCOMPRESS:156:CMS_uncompress +CMS_F_CMS_VERIFY:157:CMS_verify +COMP_F_BIO_ZLIB_FLUSH:99:bio_zlib_flush +COMP_F_BIO_ZLIB_NEW:100:bio_zlib_new +COMP_F_BIO_ZLIB_READ:101:bio_zlib_read +COMP_F_BIO_ZLIB_WRITE:102:bio_zlib_write +CONF_F_CONF_DUMP_FP:104:CONF_dump_fp +CONF_F_CONF_LOAD:100:CONF_load +CONF_F_CONF_LOAD_FP:103:CONF_load_fp +CONF_F_CONF_PARSE_LIST:119:CONF_parse_list +CONF_F_DEF_LOAD:120:def_load +CONF_F_DEF_LOAD_BIO:121:def_load_bio +CONF_F_MODULE_INIT:115:module_init +CONF_F_MODULE_LOAD_DSO:117:module_load_dso +CONF_F_MODULE_RUN:118:module_run +CONF_F_NCONF_DUMP_BIO:105:NCONF_dump_bio +CONF_F_NCONF_DUMP_FP:106:NCONF_dump_fp +CONF_F_NCONF_GET_NUMBER_E:112:NCONF_get_number_e +CONF_F_NCONF_GET_SECTION:108:NCONF_get_section +CONF_F_NCONF_GET_STRING:109:NCONF_get_string +CONF_F_NCONF_LOAD:113:NCONF_load +CONF_F_NCONF_LOAD_BIO:110:NCONF_load_bio +CONF_F_NCONF_LOAD_FP:114:NCONF_load_fp +CONF_F_NCONF_NEW:111:NCONF_new +CONF_F_STR_COPY:101:str_copy +CRYPTO_F_CRYPTO_DUP_EX_DATA:110:CRYPTO_dup_ex_data +CRYPTO_F_CRYPTO_FREE_EX_DATA:111:CRYPTO_free_ex_data +CRYPTO_F_CRYPTO_GET_EX_NEW_INDEX:100:CRYPTO_get_ex_new_index +CRYPTO_F_CRYPTO_MEMDUP:115:CRYPTO_memdup +CRYPTO_F_CRYPTO_NEW_EX_DATA:112:CRYPTO_new_ex_data +CRYPTO_F_CRYPTO_SET_EX_DATA:102:CRYPTO_set_ex_data +CRYPTO_F_FIPS_MODE_SET:109:FIPS_mode_set +CRYPTO_F_GET_AND_LOCK:113:get_and_lock +CRYPTO_F_OPENSSL_BUF2HEXSTR:117:OPENSSL_buf2hexstr +CRYPTO_F_OPENSSL_HEXSTR2BUF:118:OPENSSL_hexstr2buf +CRYPTO_F_OPENSSL_INIT_CRYPTO:116:OPENSSL_init_crypto +CT_F_CTLOG_NEW:117:CTLOG_new +CT_F_CTLOG_NEW_FROM_BASE64:118:CTLOG_new_from_base64 +CT_F_CTLOG_NEW_FROM_CONF:119:ctlog_new_from_conf +CT_F_CTLOG_STORE_LOAD_CTX_NEW:122:ctlog_store_load_ctx_new +CT_F_CTLOG_STORE_LOAD_FILE:123:CTLOG_STORE_load_file +CT_F_CTLOG_STORE_LOAD_LOG:130:ctlog_store_load_log +CT_F_CTLOG_STORE_NEW:131:CTLOG_STORE_new +CT_F_CT_BASE64_DECODE:124:ct_base64_decode +CT_F_CT_POLICY_EVAL_CTX_NEW:133:CT_POLICY_EVAL_CTX_new +CT_F_CT_V1_LOG_ID_FROM_PKEY:125:ct_v1_log_id_from_pkey +CT_F_I2O_SCT:107:i2o_SCT +CT_F_I2O_SCT_LIST:108:i2o_SCT_LIST +CT_F_I2O_SCT_SIGNATURE:109:i2o_SCT_signature +CT_F_O2I_SCT:110:o2i_SCT +CT_F_O2I_SCT_LIST:111:o2i_SCT_LIST +CT_F_O2I_SCT_SIGNATURE:112:o2i_SCT_signature +CT_F_SCT_CTX_NEW:126:SCT_CTX_new +CT_F_SCT_CTX_VERIFY:128:SCT_CTX_verify +CT_F_SCT_NEW:100:SCT_new +CT_F_SCT_NEW_FROM_BASE64:127:SCT_new_from_base64 +CT_F_SCT_SET0_LOG_ID:101:SCT_set0_log_id +CT_F_SCT_SET1_EXTENSIONS:114:SCT_set1_extensions +CT_F_SCT_SET1_LOG_ID:115:SCT_set1_log_id +CT_F_SCT_SET1_SIGNATURE:116:SCT_set1_signature +CT_F_SCT_SET_LOG_ENTRY_TYPE:102:SCT_set_log_entry_type +CT_F_SCT_SET_SIGNATURE_NID:103:SCT_set_signature_nid +CT_F_SCT_SET_VERSION:104:SCT_set_version +DH_F_COMPUTE_KEY:102:compute_key +DH_F_DHPARAMS_PRINT_FP:101:DHparams_print_fp +DH_F_DH_BUILTIN_GENPARAMS:106:dh_builtin_genparams +DH_F_DH_CHECK_EX:121:DH_check_ex +DH_F_DH_CHECK_PARAMS_EX:122:DH_check_params_ex +DH_F_DH_CHECK_PUB_KEY_EX:123:DH_check_pub_key_ex +DH_F_DH_CMS_DECRYPT:114:dh_cms_decrypt +DH_F_DH_CMS_SET_PEERKEY:115:dh_cms_set_peerkey +DH_F_DH_CMS_SET_SHARED_INFO:116:dh_cms_set_shared_info +DH_F_DH_METH_DUP:117:DH_meth_dup +DH_F_DH_METH_NEW:118:DH_meth_new +DH_F_DH_METH_SET1_NAME:119:DH_meth_set1_name +DH_F_DH_NEW_BY_NID:104:DH_new_by_nid +DH_F_DH_NEW_METHOD:105:DH_new_method +DH_F_DH_PARAM_DECODE:107:dh_param_decode +DH_F_DH_PKEY_PUBLIC_CHECK:124:dh_pkey_public_check +DH_F_DH_PRIV_DECODE:110:dh_priv_decode +DH_F_DH_PRIV_ENCODE:111:dh_priv_encode +DH_F_DH_PUB_DECODE:108:dh_pub_decode +DH_F_DH_PUB_ENCODE:109:dh_pub_encode +DH_F_DO_DH_PRINT:100:do_dh_print +DH_F_GENERATE_KEY:103:generate_key +DH_F_PKEY_DH_CTRL_STR:120:pkey_dh_ctrl_str +DH_F_PKEY_DH_DERIVE:112:pkey_dh_derive +DH_F_PKEY_DH_KEYGEN:113:pkey_dh_keygen +DSA_F_DSAPARAMS_PRINT:100:DSAparams_print +DSA_F_DSAPARAMS_PRINT_FP:101:DSAparams_print_fp +DSA_F_DSA_BUILTIN_PARAMGEN:125:dsa_builtin_paramgen +DSA_F_DSA_BUILTIN_PARAMGEN2:126:dsa_builtin_paramgen2 +DSA_F_DSA_DO_SIGN:112:DSA_do_sign +DSA_F_DSA_DO_VERIFY:113:DSA_do_verify +DSA_F_DSA_METH_DUP:127:DSA_meth_dup +DSA_F_DSA_METH_NEW:128:DSA_meth_new +DSA_F_DSA_METH_SET1_NAME:129:DSA_meth_set1_name +DSA_F_DSA_NEW_METHOD:103:DSA_new_method +DSA_F_DSA_PARAM_DECODE:119:dsa_param_decode +DSA_F_DSA_PRINT_FP:105:DSA_print_fp +DSA_F_DSA_PRIV_DECODE:115:dsa_priv_decode +DSA_F_DSA_PRIV_ENCODE:116:dsa_priv_encode +DSA_F_DSA_PUB_DECODE:117:dsa_pub_decode +DSA_F_DSA_PUB_ENCODE:118:dsa_pub_encode +DSA_F_DSA_SIGN:106:DSA_sign +DSA_F_DSA_SIGN_SETUP:107:DSA_sign_setup +DSA_F_DSA_SIG_NEW:102:DSA_SIG_new +DSA_F_OLD_DSA_PRIV_DECODE:122:old_dsa_priv_decode +DSA_F_PKEY_DSA_CTRL:120:pkey_dsa_ctrl +DSA_F_PKEY_DSA_KEYGEN:121:pkey_dsa_keygen +DSO_F_DLFCN_BIND_FUNC:100:dlfcn_bind_func +DSO_F_DLFCN_LOAD:102:dlfcn_load +DSO_F_DLFCN_MERGER:130:dlfcn_merger +DSO_F_DLFCN_NAME_CONVERTER:123:dlfcn_name_converter +DSO_F_DLFCN_UNLOAD:103:dlfcn_unload +DSO_F_DL_BIND_FUNC:104:dl_bind_func +DSO_F_DL_LOAD:106:dl_load +DSO_F_DL_MERGER:131:dl_merger +DSO_F_DL_NAME_CONVERTER:124:dl_name_converter +DSO_F_DL_UNLOAD:107:dl_unload +DSO_F_DSO_BIND_FUNC:108:DSO_bind_func +DSO_F_DSO_CONVERT_FILENAME:126:DSO_convert_filename +DSO_F_DSO_CTRL:110:DSO_ctrl +DSO_F_DSO_FREE:111:DSO_free +DSO_F_DSO_GET_FILENAME:127:DSO_get_filename +DSO_F_DSO_GLOBAL_LOOKUP:139:DSO_global_lookup +DSO_F_DSO_LOAD:112:DSO_load +DSO_F_DSO_MERGE:132:DSO_merge +DSO_F_DSO_NEW_METHOD:113:DSO_new_method +DSO_F_DSO_PATHBYADDR:105:DSO_pathbyaddr +DSO_F_DSO_SET_FILENAME:129:DSO_set_filename +DSO_F_DSO_UP_REF:114:DSO_up_ref +DSO_F_VMS_BIND_SYM:115:vms_bind_sym +DSO_F_VMS_LOAD:116:vms_load +DSO_F_VMS_MERGER:133:vms_merger +DSO_F_VMS_UNLOAD:117:vms_unload +DSO_F_WIN32_BIND_FUNC:101:win32_bind_func +DSO_F_WIN32_GLOBALLOOKUP:142:win32_globallookup +DSO_F_WIN32_JOINER:135:win32_joiner +DSO_F_WIN32_LOAD:120:win32_load +DSO_F_WIN32_MERGER:134:win32_merger +DSO_F_WIN32_NAME_CONVERTER:125:win32_name_converter +DSO_F_WIN32_PATHBYADDR:109:* +DSO_F_WIN32_SPLITTER:136:win32_splitter +DSO_F_WIN32_UNLOAD:121:win32_unload +EC_F_BN_TO_FELEM:224:BN_to_felem +EC_F_D2I_ECPARAMETERS:144:d2i_ECParameters +EC_F_D2I_ECPKPARAMETERS:145:d2i_ECPKParameters +EC_F_D2I_ECPRIVATEKEY:146:d2i_ECPrivateKey +EC_F_DO_EC_KEY_PRINT:221:do_EC_KEY_print +EC_F_ECDH_CMS_DECRYPT:238:ecdh_cms_decrypt +EC_F_ECDH_CMS_SET_SHARED_INFO:239:ecdh_cms_set_shared_info +EC_F_ECDH_COMPUTE_KEY:246:ECDH_compute_key +EC_F_ECDH_SIMPLE_COMPUTE_KEY:257:ecdh_simple_compute_key +EC_F_ECDSA_DO_SIGN_EX:251:ECDSA_do_sign_ex +EC_F_ECDSA_DO_VERIFY:252:ECDSA_do_verify +EC_F_ECDSA_SIGN_EX:254:ECDSA_sign_ex +EC_F_ECDSA_SIGN_SETUP:248:ECDSA_sign_setup +EC_F_ECDSA_SIG_NEW:265:ECDSA_SIG_new +EC_F_ECDSA_VERIFY:253:ECDSA_verify +EC_F_ECD_ITEM_VERIFY:270:ecd_item_verify +EC_F_ECKEY_PARAM2TYPE:223:eckey_param2type +EC_F_ECKEY_PARAM_DECODE:212:eckey_param_decode +EC_F_ECKEY_PRIV_DECODE:213:eckey_priv_decode +EC_F_ECKEY_PRIV_ENCODE:214:eckey_priv_encode +EC_F_ECKEY_PUB_DECODE:215:eckey_pub_decode +EC_F_ECKEY_PUB_ENCODE:216:eckey_pub_encode +EC_F_ECKEY_TYPE2PARAM:220:eckey_type2param +EC_F_ECPARAMETERS_PRINT:147:ECParameters_print +EC_F_ECPARAMETERS_PRINT_FP:148:ECParameters_print_fp +EC_F_ECPKPARAMETERS_PRINT:149:ECPKParameters_print +EC_F_ECPKPARAMETERS_PRINT_FP:150:ECPKParameters_print_fp +EC_F_ECP_NISTZ256_GET_AFFINE:240:ecp_nistz256_get_affine +EC_F_ECP_NISTZ256_INV_MOD_ORD:275:ecp_nistz256_inv_mod_ord +EC_F_ECP_NISTZ256_MULT_PRECOMPUTE:243:ecp_nistz256_mult_precompute +EC_F_ECP_NISTZ256_POINTS_MUL:241:ecp_nistz256_points_mul +EC_F_ECP_NISTZ256_PRE_COMP_NEW:244:ecp_nistz256_pre_comp_new +EC_F_ECP_NISTZ256_WINDOWED_MUL:242:ecp_nistz256_windowed_mul +EC_F_ECX_KEY_OP:266:ecx_key_op +EC_F_ECX_PRIV_ENCODE:267:ecx_priv_encode +EC_F_ECX_PUB_ENCODE:268:ecx_pub_encode +EC_F_EC_ASN1_GROUP2CURVE:153:ec_asn1_group2curve +EC_F_EC_ASN1_GROUP2FIELDID:154:ec_asn1_group2fieldid +EC_F_EC_GF2M_MONTGOMERY_POINT_MULTIPLY:208:ec_GF2m_montgomery_point_multiply +EC_F_EC_GF2M_SIMPLE_GROUP_CHECK_DISCRIMINANT:159:\ + ec_GF2m_simple_group_check_discriminant +EC_F_EC_GF2M_SIMPLE_GROUP_SET_CURVE:195:ec_GF2m_simple_group_set_curve +EC_F_EC_GF2M_SIMPLE_OCT2POINT:160:ec_GF2m_simple_oct2point +EC_F_EC_GF2M_SIMPLE_POINT2OCT:161:ec_GF2m_simple_point2oct +EC_F_EC_GF2M_SIMPLE_POINT_GET_AFFINE_COORDINATES:162:\ + ec_GF2m_simple_point_get_affine_coordinates +EC_F_EC_GF2M_SIMPLE_POINT_SET_AFFINE_COORDINATES:163:\ + ec_GF2m_simple_point_set_affine_coordinates +EC_F_EC_GF2M_SIMPLE_SET_COMPRESSED_COORDINATES:164:\ + ec_GF2m_simple_set_compressed_coordinates +EC_F_EC_GFP_MONT_FIELD_DECODE:133:ec_GFp_mont_field_decode +EC_F_EC_GFP_MONT_FIELD_ENCODE:134:ec_GFp_mont_field_encode +EC_F_EC_GFP_MONT_FIELD_MUL:131:ec_GFp_mont_field_mul +EC_F_EC_GFP_MONT_FIELD_SET_TO_ONE:209:ec_GFp_mont_field_set_to_one +EC_F_EC_GFP_MONT_FIELD_SQR:132:ec_GFp_mont_field_sqr +EC_F_EC_GFP_MONT_GROUP_SET_CURVE:189:ec_GFp_mont_group_set_curve +EC_F_EC_GFP_NISTP224_GROUP_SET_CURVE:225:ec_GFp_nistp224_group_set_curve +EC_F_EC_GFP_NISTP224_POINTS_MUL:228:ec_GFp_nistp224_points_mul +EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES:226:\ + ec_GFp_nistp224_point_get_affine_coordinates +EC_F_EC_GFP_NISTP256_GROUP_SET_CURVE:230:ec_GFp_nistp256_group_set_curve +EC_F_EC_GFP_NISTP256_POINTS_MUL:231:ec_GFp_nistp256_points_mul +EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES:232:\ + ec_GFp_nistp256_point_get_affine_coordinates +EC_F_EC_GFP_NISTP521_GROUP_SET_CURVE:233:ec_GFp_nistp521_group_set_curve +EC_F_EC_GFP_NISTP521_POINTS_MUL:234:ec_GFp_nistp521_points_mul +EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES:235:\ + ec_GFp_nistp521_point_get_affine_coordinates +EC_F_EC_GFP_NIST_FIELD_MUL:200:ec_GFp_nist_field_mul +EC_F_EC_GFP_NIST_FIELD_SQR:201:ec_GFp_nist_field_sqr +EC_F_EC_GFP_NIST_GROUP_SET_CURVE:202:ec_GFp_nist_group_set_curve +EC_F_EC_GFP_SIMPLE_GROUP_CHECK_DISCRIMINANT:165:\ + ec_GFp_simple_group_check_discriminant +EC_F_EC_GFP_SIMPLE_GROUP_SET_CURVE:166:ec_GFp_simple_group_set_curve +EC_F_EC_GFP_SIMPLE_MAKE_AFFINE:102:ec_GFp_simple_make_affine +EC_F_EC_GFP_SIMPLE_OCT2POINT:103:ec_GFp_simple_oct2point +EC_F_EC_GFP_SIMPLE_POINT2OCT:104:ec_GFp_simple_point2oct +EC_F_EC_GFP_SIMPLE_POINTS_MAKE_AFFINE:137:ec_GFp_simple_points_make_affine +EC_F_EC_GFP_SIMPLE_POINT_GET_AFFINE_COORDINATES:167:\ + ec_GFp_simple_point_get_affine_coordinates +EC_F_EC_GFP_SIMPLE_POINT_SET_AFFINE_COORDINATES:168:\ + ec_GFp_simple_point_set_affine_coordinates +EC_F_EC_GFP_SIMPLE_SET_COMPRESSED_COORDINATES:169:\ + ec_GFp_simple_set_compressed_coordinates +EC_F_EC_GROUP_CHECK:170:EC_GROUP_check +EC_F_EC_GROUP_CHECK_DISCRIMINANT:171:EC_GROUP_check_discriminant +EC_F_EC_GROUP_COPY:106:EC_GROUP_copy +EC_F_EC_GROUP_GET_CURVE_GF2M:172:EC_GROUP_get_curve_GF2m +EC_F_EC_GROUP_GET_CURVE_GFP:130:EC_GROUP_get_curve_GFp +EC_F_EC_GROUP_GET_DEGREE:173:EC_GROUP_get_degree +EC_F_EC_GROUP_GET_ECPARAMETERS:261:EC_GROUP_get_ecparameters +EC_F_EC_GROUP_GET_ECPKPARAMETERS:262:EC_GROUP_get_ecpkparameters +EC_F_EC_GROUP_GET_PENTANOMIAL_BASIS:193:EC_GROUP_get_pentanomial_basis +EC_F_EC_GROUP_GET_TRINOMIAL_BASIS:194:EC_GROUP_get_trinomial_basis +EC_F_EC_GROUP_NEW:108:EC_GROUP_new +EC_F_EC_GROUP_NEW_BY_CURVE_NAME:174:EC_GROUP_new_by_curve_name +EC_F_EC_GROUP_NEW_FROM_DATA:175:ec_group_new_from_data +EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS:263:EC_GROUP_new_from_ecparameters +EC_F_EC_GROUP_NEW_FROM_ECPKPARAMETERS:264:EC_GROUP_new_from_ecpkparameters +EC_F_EC_GROUP_SET_CURVE_GF2M:176:EC_GROUP_set_curve_GF2m +EC_F_EC_GROUP_SET_CURVE_GFP:109:EC_GROUP_set_curve_GFp +EC_F_EC_GROUP_SET_GENERATOR:111:EC_GROUP_set_generator +EC_F_EC_KEY_CHECK_KEY:177:EC_KEY_check_key +EC_F_EC_KEY_COPY:178:EC_KEY_copy +EC_F_EC_KEY_GENERATE_KEY:179:EC_KEY_generate_key +EC_F_EC_KEY_NEW:182:EC_KEY_new +EC_F_EC_KEY_NEW_METHOD:245:EC_KEY_new_method +EC_F_EC_KEY_OCT2PRIV:255:EC_KEY_oct2priv +EC_F_EC_KEY_PRINT:180:EC_KEY_print +EC_F_EC_KEY_PRINT_FP:181:EC_KEY_print_fp +EC_F_EC_KEY_PRIV2OCT:256:EC_KEY_priv2oct +EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES:229:\ + EC_KEY_set_public_key_affine_coordinates +EC_F_EC_KEY_SIMPLE_CHECK_KEY:258:ec_key_simple_check_key +EC_F_EC_KEY_SIMPLE_OCT2PRIV:259:ec_key_simple_oct2priv +EC_F_EC_KEY_SIMPLE_PRIV2OCT:260:ec_key_simple_priv2oct +EC_F_EC_PKEY_CHECK:273:ec_pkey_check +EC_F_EC_PKEY_PARAM_CHECK:274:ec_pkey_param_check +EC_F_EC_POINTS_MAKE_AFFINE:136:EC_POINTs_make_affine +EC_F_EC_POINT_ADD:112:EC_POINT_add +EC_F_EC_POINT_CMP:113:EC_POINT_cmp +EC_F_EC_POINT_COPY:114:EC_POINT_copy +EC_F_EC_POINT_DBL:115:EC_POINT_dbl +EC_F_EC_POINT_GET_AFFINE_COORDINATES_GF2M:183:\ + EC_POINT_get_affine_coordinates_GF2m +EC_F_EC_POINT_GET_AFFINE_COORDINATES_GFP:116:EC_POINT_get_affine_coordinates_GFp +EC_F_EC_POINT_GET_JPROJECTIVE_COORDINATES_GFP:117:\ + EC_POINT_get_Jprojective_coordinates_GFp +EC_F_EC_POINT_INVERT:210:EC_POINT_invert +EC_F_EC_POINT_IS_AT_INFINITY:118:EC_POINT_is_at_infinity +EC_F_EC_POINT_IS_ON_CURVE:119:EC_POINT_is_on_curve +EC_F_EC_POINT_MAKE_AFFINE:120:EC_POINT_make_affine +EC_F_EC_POINT_NEW:121:EC_POINT_new +EC_F_EC_POINT_OCT2POINT:122:EC_POINT_oct2point +EC_F_EC_POINT_POINT2OCT:123:EC_POINT_point2oct +EC_F_EC_POINT_SET_AFFINE_COORDINATES_GF2M:185:\ + EC_POINT_set_affine_coordinates_GF2m +EC_F_EC_POINT_SET_AFFINE_COORDINATES_GFP:124:EC_POINT_set_affine_coordinates_GFp +EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GF2M:186:\ + EC_POINT_set_compressed_coordinates_GF2m +EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GFP:125:\ + EC_POINT_set_compressed_coordinates_GFp +EC_F_EC_POINT_SET_JPROJECTIVE_COORDINATES_GFP:126:\ + EC_POINT_set_Jprojective_coordinates_GFp +EC_F_EC_POINT_SET_TO_INFINITY:127:EC_POINT_set_to_infinity +EC_F_EC_PRE_COMP_NEW:196:ec_pre_comp_new +EC_F_EC_WNAF_MUL:187:ec_wNAF_mul +EC_F_EC_WNAF_PRECOMPUTE_MULT:188:ec_wNAF_precompute_mult +EC_F_I2D_ECPARAMETERS:190:i2d_ECParameters +EC_F_I2D_ECPKPARAMETERS:191:i2d_ECPKParameters +EC_F_I2D_ECPRIVATEKEY:192:i2d_ECPrivateKey +EC_F_I2O_ECPUBLICKEY:151:i2o_ECPublicKey +EC_F_NISTP224_PRE_COMP_NEW:227:nistp224_pre_comp_new +EC_F_NISTP256_PRE_COMP_NEW:236:nistp256_pre_comp_new +EC_F_NISTP521_PRE_COMP_NEW:237:nistp521_pre_comp_new +EC_F_O2I_ECPUBLICKEY:152:o2i_ECPublicKey +EC_F_OLD_EC_PRIV_DECODE:222:old_ec_priv_decode +EC_F_OSSL_ECDH_COMPUTE_KEY:247:ossl_ecdh_compute_key +EC_F_OSSL_ECDSA_SIGN_SIG:249:ossl_ecdsa_sign_sig +EC_F_OSSL_ECDSA_VERIFY_SIG:250:ossl_ecdsa_verify_sig +EC_F_PKEY_ECD_CTRL:271:pkey_ecd_ctrl +EC_F_PKEY_ECD_DIGESTSIGN:272:pkey_ecd_digestsign +EC_F_PKEY_ECX_DERIVE:269:pkey_ecx_derive +EC_F_PKEY_EC_CTRL:197:pkey_ec_ctrl +EC_F_PKEY_EC_CTRL_STR:198:pkey_ec_ctrl_str +EC_F_PKEY_EC_DERIVE:217:pkey_ec_derive +EC_F_PKEY_EC_KEYGEN:199:pkey_ec_keygen +EC_F_PKEY_EC_PARAMGEN:219:pkey_ec_paramgen +EC_F_PKEY_EC_SIGN:218:pkey_ec_sign +ENGINE_F_DIGEST_UPDATE:198:digest_update +ENGINE_F_DYNAMIC_CTRL:180:dynamic_ctrl +ENGINE_F_DYNAMIC_GET_DATA_CTX:181:dynamic_get_data_ctx +ENGINE_F_DYNAMIC_LOAD:182:dynamic_load +ENGINE_F_DYNAMIC_SET_DATA_CTX:183:dynamic_set_data_ctx +ENGINE_F_ENGINE_ADD:105:ENGINE_add +ENGINE_F_ENGINE_BY_ID:106:ENGINE_by_id +ENGINE_F_ENGINE_CMD_IS_EXECUTABLE:170:ENGINE_cmd_is_executable +ENGINE_F_ENGINE_CTRL:142:ENGINE_ctrl +ENGINE_F_ENGINE_CTRL_CMD:178:ENGINE_ctrl_cmd +ENGINE_F_ENGINE_CTRL_CMD_STRING:171:ENGINE_ctrl_cmd_string +ENGINE_F_ENGINE_FINISH:107:ENGINE_finish +ENGINE_F_ENGINE_GET_CIPHER:185:ENGINE_get_cipher +ENGINE_F_ENGINE_GET_DIGEST:186:ENGINE_get_digest +ENGINE_F_ENGINE_GET_FIRST:195:ENGINE_get_first +ENGINE_F_ENGINE_GET_LAST:196:ENGINE_get_last +ENGINE_F_ENGINE_GET_NEXT:115:ENGINE_get_next +ENGINE_F_ENGINE_GET_PKEY_ASN1_METH:193:ENGINE_get_pkey_asn1_meth +ENGINE_F_ENGINE_GET_PKEY_METH:192:ENGINE_get_pkey_meth +ENGINE_F_ENGINE_GET_PREV:116:ENGINE_get_prev +ENGINE_F_ENGINE_INIT:119:ENGINE_init +ENGINE_F_ENGINE_LIST_ADD:120:engine_list_add +ENGINE_F_ENGINE_LIST_REMOVE:121:engine_list_remove +ENGINE_F_ENGINE_LOAD_PRIVATE_KEY:150:ENGINE_load_private_key +ENGINE_F_ENGINE_LOAD_PUBLIC_KEY:151:ENGINE_load_public_key +ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT:194:ENGINE_load_ssl_client_cert +ENGINE_F_ENGINE_NEW:122:ENGINE_new +ENGINE_F_ENGINE_PKEY_ASN1_FIND_STR:197:ENGINE_pkey_asn1_find_str +ENGINE_F_ENGINE_REMOVE:123:ENGINE_remove +ENGINE_F_ENGINE_SET_DEFAULT_STRING:189:ENGINE_set_default_string +ENGINE_F_ENGINE_SET_ID:129:ENGINE_set_id +ENGINE_F_ENGINE_SET_NAME:130:ENGINE_set_name +ENGINE_F_ENGINE_TABLE_REGISTER:184:engine_table_register +ENGINE_F_ENGINE_UNLOCKED_FINISH:191:engine_unlocked_finish +ENGINE_F_ENGINE_UP_REF:190:ENGINE_up_ref +ENGINE_F_INT_CTRL_HELPER:172:int_ctrl_helper +ENGINE_F_INT_ENGINE_CONFIGURE:188:int_engine_configure +ENGINE_F_INT_ENGINE_MODULE_INIT:187:int_engine_module_init +EVP_F_AESNI_INIT_KEY:165:aesni_init_key +EVP_F_AES_INIT_KEY:133:aes_init_key +EVP_F_AES_OCB_CIPHER:169:aes_ocb_cipher +EVP_F_AES_T4_INIT_KEY:178:aes_t4_init_key +EVP_F_AES_WRAP_CIPHER:170:aes_wrap_cipher +EVP_F_ALG_MODULE_INIT:177:alg_module_init +EVP_F_ARIA_CCM_INIT_KEY:175:aria_ccm_init_key +EVP_F_ARIA_GCM_INIT_KEY:176:aria_gcm_init_key +EVP_F_ARIA_INIT_KEY:185:aria_init_key +EVP_F_CAMELLIA_INIT_KEY:159:camellia_init_key +EVP_F_CHACHA20_POLY1305_CTRL:182:chacha20_poly1305_ctrl +EVP_F_CMLL_T4_INIT_KEY:179:cmll_t4_init_key +EVP_F_DES_EDE3_WRAP_CIPHER:171:des_ede3_wrap_cipher +EVP_F_DO_SIGVER_INIT:161:do_sigver_init +EVP_F_EVP_CIPHERINIT_EX:123:EVP_CipherInit_ex +EVP_F_EVP_CIPHER_CTX_COPY:163:EVP_CIPHER_CTX_copy +EVP_F_EVP_CIPHER_CTX_CTRL:124:EVP_CIPHER_CTX_ctrl +EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH:122:EVP_CIPHER_CTX_set_key_length +EVP_F_EVP_DECRYPTFINAL_EX:101:EVP_DecryptFinal_ex +EVP_F_EVP_DECRYPTUPDATE:166:EVP_DecryptUpdate +EVP_F_EVP_DIGESTFINALXOF:174:EVP_DigestFinalXOF +EVP_F_EVP_DIGESTINIT_EX:128:EVP_DigestInit_ex +EVP_F_EVP_ENCRYPTFINAL_EX:127:EVP_EncryptFinal_ex +EVP_F_EVP_ENCRYPTUPDATE:167:EVP_EncryptUpdate +EVP_F_EVP_MD_CTX_COPY_EX:110:EVP_MD_CTX_copy_ex +EVP_F_EVP_MD_SIZE:162:EVP_MD_size +EVP_F_EVP_OPENINIT:102:EVP_OpenInit +EVP_F_EVP_PBE_ALG_ADD:115:EVP_PBE_alg_add +EVP_F_EVP_PBE_ALG_ADD_TYPE:160:EVP_PBE_alg_add_type +EVP_F_EVP_PBE_CIPHERINIT:116:EVP_PBE_CipherInit +EVP_F_EVP_PBE_SCRYPT:181:EVP_PBE_scrypt +EVP_F_EVP_PKCS82PKEY:111:EVP_PKCS82PKEY +EVP_F_EVP_PKEY2PKCS8:113:EVP_PKEY2PKCS8 +EVP_F_EVP_PKEY_ASN1_ADD0:188:EVP_PKEY_asn1_add0 +EVP_F_EVP_PKEY_CHECK:186:EVP_PKEY_check +EVP_F_EVP_PKEY_COPY_PARAMETERS:103:EVP_PKEY_copy_parameters +EVP_F_EVP_PKEY_CTX_CTRL:137:EVP_PKEY_CTX_ctrl +EVP_F_EVP_PKEY_CTX_CTRL_STR:150:EVP_PKEY_CTX_ctrl_str +EVP_F_EVP_PKEY_CTX_DUP:156:EVP_PKEY_CTX_dup +EVP_F_EVP_PKEY_CTX_MD:168:EVP_PKEY_CTX_md +EVP_F_EVP_PKEY_DECRYPT:104:EVP_PKEY_decrypt +EVP_F_EVP_PKEY_DECRYPT_INIT:138:EVP_PKEY_decrypt_init +EVP_F_EVP_PKEY_DECRYPT_OLD:151:EVP_PKEY_decrypt_old +EVP_F_EVP_PKEY_DERIVE:153:EVP_PKEY_derive +EVP_F_EVP_PKEY_DERIVE_INIT:154:EVP_PKEY_derive_init +EVP_F_EVP_PKEY_DERIVE_SET_PEER:155:EVP_PKEY_derive_set_peer +EVP_F_EVP_PKEY_ENCRYPT:105:EVP_PKEY_encrypt +EVP_F_EVP_PKEY_ENCRYPT_INIT:139:EVP_PKEY_encrypt_init +EVP_F_EVP_PKEY_ENCRYPT_OLD:152:EVP_PKEY_encrypt_old +EVP_F_EVP_PKEY_GET0_DH:119:EVP_PKEY_get0_DH +EVP_F_EVP_PKEY_GET0_DSA:120:EVP_PKEY_get0_DSA +EVP_F_EVP_PKEY_GET0_EC_KEY:131:EVP_PKEY_get0_EC_KEY +EVP_F_EVP_PKEY_GET0_HMAC:183:EVP_PKEY_get0_hmac +EVP_F_EVP_PKEY_GET0_POLY1305:184:EVP_PKEY_get0_poly1305 +EVP_F_EVP_PKEY_GET0_RSA:121:EVP_PKEY_get0_RSA +EVP_F_EVP_PKEY_GET0_SIPHASH:172:EVP_PKEY_get0_siphash +EVP_F_EVP_PKEY_KEYGEN:146:EVP_PKEY_keygen +EVP_F_EVP_PKEY_KEYGEN_INIT:147:EVP_PKEY_keygen_init +EVP_F_EVP_PKEY_NEW:106:EVP_PKEY_new +EVP_F_EVP_PKEY_PARAMGEN:148:EVP_PKEY_paramgen +EVP_F_EVP_PKEY_PARAMGEN_INIT:149:EVP_PKEY_paramgen_init +EVP_F_EVP_PKEY_PARAM_CHECK:189:EVP_PKEY_param_check +EVP_F_EVP_PKEY_PUBLIC_CHECK:190:EVP_PKEY_public_check +EVP_F_EVP_PKEY_SET1_ENGINE:187:EVP_PKEY_set1_engine +EVP_F_EVP_PKEY_SIGN:140:EVP_PKEY_sign +EVP_F_EVP_PKEY_SIGN_INIT:141:EVP_PKEY_sign_init +EVP_F_EVP_PKEY_VERIFY:142:EVP_PKEY_verify +EVP_F_EVP_PKEY_VERIFY_INIT:143:EVP_PKEY_verify_init +EVP_F_EVP_PKEY_VERIFY_RECOVER:144:EVP_PKEY_verify_recover +EVP_F_EVP_PKEY_VERIFY_RECOVER_INIT:145:EVP_PKEY_verify_recover_init +EVP_F_EVP_SIGNFINAL:107:EVP_SignFinal +EVP_F_EVP_VERIFYFINAL:108:EVP_VerifyFinal +EVP_F_INT_CTX_NEW:157:int_ctx_new +EVP_F_PKCS5_PBE_KEYIVGEN:117:PKCS5_PBE_keyivgen +EVP_F_PKCS5_V2_PBE_KEYIVGEN:118:PKCS5_v2_PBE_keyivgen +EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN:164:PKCS5_v2_PBKDF2_keyivgen +EVP_F_PKCS5_V2_SCRYPT_KEYIVGEN:180:PKCS5_v2_scrypt_keyivgen +EVP_F_PKEY_SET_TYPE:158:pkey_set_type +EVP_F_RC2_MAGIC_TO_METH:109:rc2_magic_to_meth +EVP_F_RC5_CTRL:125:rc5_ctrl +EVP_F_UPDATE:173:update +KDF_F_PKEY_HKDF_CTRL_STR:103:pkey_hkdf_ctrl_str +KDF_F_PKEY_HKDF_DERIVE:102:pkey_hkdf_derive +KDF_F_PKEY_SCRYPT_CTRL_STR:104:pkey_scrypt_ctrl_str +KDF_F_PKEY_SCRYPT_CTRL_UINT64:105:pkey_scrypt_ctrl_uint64 +KDF_F_PKEY_SCRYPT_DERIVE:109:pkey_scrypt_derive +KDF_F_PKEY_TLS1_PRF_CTRL_STR:100:pkey_tls1_prf_ctrl_str +KDF_F_PKEY_TLS1_PRF_DERIVE:101:pkey_tls1_prf_derive +OBJ_F_OBJ_ADD_OBJECT:105:OBJ_add_object +OBJ_F_OBJ_CREATE:100:OBJ_create +OBJ_F_OBJ_DUP:101:OBJ_dup +OBJ_F_OBJ_NAME_NEW_INDEX:106:OBJ_NAME_new_index +OBJ_F_OBJ_NID2LN:102:OBJ_nid2ln +OBJ_F_OBJ_NID2OBJ:103:OBJ_nid2obj +OBJ_F_OBJ_NID2SN:104:OBJ_nid2sn +OCSP_F_D2I_OCSP_NONCE:102:d2i_ocsp_nonce +OCSP_F_OCSP_BASIC_ADD1_STATUS:103:OCSP_basic_add1_status +OCSP_F_OCSP_BASIC_SIGN:104:OCSP_basic_sign +OCSP_F_OCSP_BASIC_SIGN_CTX:119:OCSP_basic_sign_ctx +OCSP_F_OCSP_BASIC_VERIFY:105:OCSP_basic_verify +OCSP_F_OCSP_CERT_ID_NEW:101:OCSP_cert_id_new +OCSP_F_OCSP_CHECK_DELEGATED:106:ocsp_check_delegated +OCSP_F_OCSP_CHECK_IDS:107:ocsp_check_ids +OCSP_F_OCSP_CHECK_ISSUER:108:ocsp_check_issuer +OCSP_F_OCSP_CHECK_VALIDITY:115:OCSP_check_validity +OCSP_F_OCSP_MATCH_ISSUERID:109:ocsp_match_issuerid +OCSP_F_OCSP_PARSE_URL:114:OCSP_parse_url +OCSP_F_OCSP_REQUEST_SIGN:110:OCSP_request_sign +OCSP_F_OCSP_REQUEST_VERIFY:116:OCSP_request_verify +OCSP_F_OCSP_RESPONSE_GET1_BASIC:111:OCSP_response_get1_basic +OCSP_F_PARSE_HTTP_LINE1:118:parse_http_line1 +OSSL_STORE_F_FILE_CTRL:129:file_ctrl +OSSL_STORE_F_FILE_FIND:138:file_find +OSSL_STORE_F_FILE_GET_PASS:118:file_get_pass +OSSL_STORE_F_FILE_LOAD:119:file_load +OSSL_STORE_F_FILE_LOAD_TRY_DECODE:124:file_load_try_decode +OSSL_STORE_F_FILE_NAME_TO_URI:126:file_name_to_uri +OSSL_STORE_F_FILE_OPEN:120:file_open +OSSL_STORE_F_OSSL_STORE_ATTACH_PEM_BIO:127:ossl_store_attach_pem_bio +OSSL_STORE_F_OSSL_STORE_EXPECT:130:OSSL_STORE_expect +OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT:128:\ + ossl_store_file_attach_pem_bio_int +OSSL_STORE_F_OSSL_STORE_FIND:131:OSSL_STORE_find +OSSL_STORE_F_OSSL_STORE_GET0_LOADER_INT:100:ossl_store_get0_loader_int +OSSL_STORE_F_OSSL_STORE_INFO_GET1_CERT:101:OSSL_STORE_INFO_get1_CERT +OSSL_STORE_F_OSSL_STORE_INFO_GET1_CRL:102:OSSL_STORE_INFO_get1_CRL +OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME:103:OSSL_STORE_INFO_get1_NAME +OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME_DESCRIPTION:135:\ + OSSL_STORE_INFO_get1_NAME_description +OSSL_STORE_F_OSSL_STORE_INFO_GET1_PARAMS:104:OSSL_STORE_INFO_get1_PARAMS +OSSL_STORE_F_OSSL_STORE_INFO_GET1_PKEY:105:OSSL_STORE_INFO_get1_PKEY +OSSL_STORE_F_OSSL_STORE_INFO_NEW_CERT:106:OSSL_STORE_INFO_new_CERT +OSSL_STORE_F_OSSL_STORE_INFO_NEW_CRL:107:OSSL_STORE_INFO_new_CRL +OSSL_STORE_F_OSSL_STORE_INFO_NEW_EMBEDDED:123:ossl_store_info_new_EMBEDDED +OSSL_STORE_F_OSSL_STORE_INFO_NEW_NAME:109:OSSL_STORE_INFO_new_NAME +OSSL_STORE_F_OSSL_STORE_INFO_NEW_PARAMS:110:OSSL_STORE_INFO_new_PARAMS +OSSL_STORE_F_OSSL_STORE_INFO_NEW_PKEY:111:OSSL_STORE_INFO_new_PKEY +OSSL_STORE_F_OSSL_STORE_INFO_SET0_NAME_DESCRIPTION:134:\ + OSSL_STORE_INFO_set0_NAME_description +OSSL_STORE_F_OSSL_STORE_INIT_ONCE:112:ossl_store_init_once +OSSL_STORE_F_OSSL_STORE_LOADER_NEW:113:OSSL_STORE_LOADER_new +OSSL_STORE_F_OSSL_STORE_OPEN:114:OSSL_STORE_open +OSSL_STORE_F_OSSL_STORE_OPEN_INT:115:* +OSSL_STORE_F_OSSL_STORE_REGISTER_LOADER_INT:117:ossl_store_register_loader_int +OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ALIAS:132:OSSL_STORE_SEARCH_by_alias +OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ISSUER_SERIAL:133:\ + OSSL_STORE_SEARCH_by_issuer_serial +OSSL_STORE_F_OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT:136:\ + OSSL_STORE_SEARCH_by_key_fingerprint +OSSL_STORE_F_OSSL_STORE_SEARCH_BY_NAME:137:OSSL_STORE_SEARCH_by_name +OSSL_STORE_F_OSSL_STORE_UNREGISTER_LOADER_INT:116:\ + ossl_store_unregister_loader_int +OSSL_STORE_F_TRY_DECODE_PARAMS:121:try_decode_params +OSSL_STORE_F_TRY_DECODE_PKCS12:122:try_decode_PKCS12 +OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED:125:try_decode_PKCS8Encrypted +PEM_F_B2I_DSS:127:b2i_dss +PEM_F_B2I_PVK_BIO:128:b2i_PVK_bio +PEM_F_B2I_RSA:129:b2i_rsa +PEM_F_CHECK_BITLEN_DSA:130:check_bitlen_dsa +PEM_F_CHECK_BITLEN_RSA:131:check_bitlen_rsa +PEM_F_D2I_PKCS8PRIVATEKEY_BIO:120:d2i_PKCS8PrivateKey_bio +PEM_F_D2I_PKCS8PRIVATEKEY_FP:121:d2i_PKCS8PrivateKey_fp +PEM_F_DO_B2I:132:do_b2i +PEM_F_DO_B2I_BIO:133:do_b2i_bio +PEM_F_DO_BLOB_HEADER:134:do_blob_header +PEM_F_DO_PK8PKEY:126:do_pk8pkey +PEM_F_DO_PK8PKEY_FP:125:do_pk8pkey_fp +PEM_F_DO_PVK_BODY:135:do_PVK_body +PEM_F_DO_PVK_HEADER:136:do_PVK_header +PEM_F_GET_HEADER_AND_DATA:143:get_header_and_data +PEM_F_GET_NAME:144:get_name +PEM_F_I2B_PVK:137:i2b_PVK +PEM_F_I2B_PVK_BIO:138:i2b_PVK_bio +PEM_F_LOAD_IV:101:load_iv +PEM_F_PEM_ASN1_READ:102:PEM_ASN1_read +PEM_F_PEM_ASN1_READ_BIO:103:PEM_ASN1_read_bio +PEM_F_PEM_ASN1_WRITE:104:PEM_ASN1_write +PEM_F_PEM_ASN1_WRITE_BIO:105:PEM_ASN1_write_bio +PEM_F_PEM_DEF_CALLBACK:100:PEM_def_callback +PEM_F_PEM_DO_HEADER:106:PEM_do_header +PEM_F_PEM_GET_EVP_CIPHER_INFO:107:PEM_get_EVP_CIPHER_INFO +PEM_F_PEM_READ:108:PEM_read +PEM_F_PEM_READ_BIO:109:PEM_read_bio +PEM_F_PEM_READ_BIO_DHPARAMS:141:PEM_read_bio_DHparams +PEM_F_PEM_READ_BIO_EX:145:PEM_read_bio_ex +PEM_F_PEM_READ_BIO_PARAMETERS:140:PEM_read_bio_Parameters +PEM_F_PEM_READ_BIO_PRIVATEKEY:123:PEM_read_bio_PrivateKey +PEM_F_PEM_READ_DHPARAMS:142:PEM_read_DHparams +PEM_F_PEM_READ_PRIVATEKEY:124:PEM_read_PrivateKey +PEM_F_PEM_SIGNFINAL:112:PEM_SignFinal +PEM_F_PEM_WRITE:113:PEM_write +PEM_F_PEM_WRITE_BIO:114:PEM_write_bio +PEM_F_PEM_WRITE_PRIVATEKEY:139:PEM_write_PrivateKey +PEM_F_PEM_X509_INFO_READ:115:PEM_X509_INFO_read +PEM_F_PEM_X509_INFO_READ_BIO:116:PEM_X509_INFO_read_bio +PEM_F_PEM_X509_INFO_WRITE_BIO:117:PEM_X509_INFO_write_bio +PKCS12_F_PKCS12_CREATE:105:PKCS12_create +PKCS12_F_PKCS12_GEN_MAC:107:PKCS12_gen_mac +PKCS12_F_PKCS12_INIT:109:PKCS12_init +PKCS12_F_PKCS12_ITEM_DECRYPT_D2I:106:PKCS12_item_decrypt_d2i +PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT:108:PKCS12_item_i2d_encrypt +PKCS12_F_PKCS12_ITEM_PACK_SAFEBAG:117:PKCS12_item_pack_safebag +PKCS12_F_PKCS12_KEY_GEN_ASC:110:PKCS12_key_gen_asc +PKCS12_F_PKCS12_KEY_GEN_UNI:111:PKCS12_key_gen_uni +PKCS12_F_PKCS12_KEY_GEN_UTF8:116:PKCS12_key_gen_utf8 +PKCS12_F_PKCS12_NEWPASS:128:PKCS12_newpass +PKCS12_F_PKCS12_PACK_P7DATA:114:PKCS12_pack_p7data +PKCS12_F_PKCS12_PACK_P7ENCDATA:115:PKCS12_pack_p7encdata +PKCS12_F_PKCS12_PARSE:118:PKCS12_parse +PKCS12_F_PKCS12_PBE_CRYPT:119:PKCS12_pbe_crypt +PKCS12_F_PKCS12_PBE_KEYIVGEN:120:PKCS12_PBE_keyivgen +PKCS12_F_PKCS12_SAFEBAG_CREATE0_P8INF:112:PKCS12_SAFEBAG_create0_p8inf +PKCS12_F_PKCS12_SAFEBAG_CREATE0_PKCS8:113:PKCS12_SAFEBAG_create0_pkcs8 +PKCS12_F_PKCS12_SAFEBAG_CREATE_PKCS8_ENCRYPT:133:\ + PKCS12_SAFEBAG_create_pkcs8_encrypt +PKCS12_F_PKCS12_SETUP_MAC:122:PKCS12_setup_mac +PKCS12_F_PKCS12_SET_MAC:123:PKCS12_set_mac +PKCS12_F_PKCS12_UNPACK_AUTHSAFES:130:PKCS12_unpack_authsafes +PKCS12_F_PKCS12_UNPACK_P7DATA:131:PKCS12_unpack_p7data +PKCS12_F_PKCS12_VERIFY_MAC:126:PKCS12_verify_mac +PKCS12_F_PKCS8_ENCRYPT:125:PKCS8_encrypt +PKCS12_F_PKCS8_SET0_PBE:132:PKCS8_set0_pbe +PKCS7_F_DO_PKCS7_SIGNED_ATTRIB:136:do_pkcs7_signed_attrib +PKCS7_F_PKCS7_ADD0_ATTRIB_SIGNING_TIME:135:PKCS7_add0_attrib_signing_time +PKCS7_F_PKCS7_ADD_ATTRIB_SMIMECAP:118:PKCS7_add_attrib_smimecap +PKCS7_F_PKCS7_ADD_CERTIFICATE:100:PKCS7_add_certificate +PKCS7_F_PKCS7_ADD_CRL:101:PKCS7_add_crl +PKCS7_F_PKCS7_ADD_RECIPIENT_INFO:102:PKCS7_add_recipient_info +PKCS7_F_PKCS7_ADD_SIGNATURE:131:PKCS7_add_signature +PKCS7_F_PKCS7_ADD_SIGNER:103:PKCS7_add_signer +PKCS7_F_PKCS7_BIO_ADD_DIGEST:125:PKCS7_bio_add_digest +PKCS7_F_PKCS7_COPY_EXISTING_DIGEST:138:pkcs7_copy_existing_digest +PKCS7_F_PKCS7_CTRL:104:PKCS7_ctrl +PKCS7_F_PKCS7_DATADECODE:112:PKCS7_dataDecode +PKCS7_F_PKCS7_DATAFINAL:128:PKCS7_dataFinal +PKCS7_F_PKCS7_DATAINIT:105:PKCS7_dataInit +PKCS7_F_PKCS7_DATAVERIFY:107:PKCS7_dataVerify +PKCS7_F_PKCS7_DECRYPT:114:PKCS7_decrypt +PKCS7_F_PKCS7_DECRYPT_RINFO:133:pkcs7_decrypt_rinfo +PKCS7_F_PKCS7_ENCODE_RINFO:132:pkcs7_encode_rinfo +PKCS7_F_PKCS7_ENCRYPT:115:PKCS7_encrypt +PKCS7_F_PKCS7_FINAL:134:PKCS7_final +PKCS7_F_PKCS7_FIND_DIGEST:127:PKCS7_find_digest +PKCS7_F_PKCS7_GET0_SIGNERS:124:PKCS7_get0_signers +PKCS7_F_PKCS7_RECIP_INFO_SET:130:PKCS7_RECIP_INFO_set +PKCS7_F_PKCS7_SET_CIPHER:108:PKCS7_set_cipher +PKCS7_F_PKCS7_SET_CONTENT:109:PKCS7_set_content +PKCS7_F_PKCS7_SET_DIGEST:126:PKCS7_set_digest +PKCS7_F_PKCS7_SET_TYPE:110:PKCS7_set_type +PKCS7_F_PKCS7_SIGN:116:PKCS7_sign +PKCS7_F_PKCS7_SIGNATUREVERIFY:113:PKCS7_signatureVerify +PKCS7_F_PKCS7_SIGNER_INFO_SET:129:PKCS7_SIGNER_INFO_set +PKCS7_F_PKCS7_SIGNER_INFO_SIGN:139:PKCS7_SIGNER_INFO_sign +PKCS7_F_PKCS7_SIGN_ADD_SIGNER:137:PKCS7_sign_add_signer +PKCS7_F_PKCS7_SIMPLE_SMIMECAP:119:PKCS7_simple_smimecap +PKCS7_F_PKCS7_VERIFY:117:PKCS7_verify +RAND_F_DRBG_BYTES:101:drbg_bytes +RAND_F_DRBG_GET_ENTROPY:105:drbg_get_entropy +RAND_F_DRBG_SETUP:117:drbg_setup +RAND_F_GET_ENTROPY:106:get_entropy +RAND_F_RAND_BYTES:100:RAND_bytes +RAND_F_RAND_DRBG_ENABLE_LOCKING:119:rand_drbg_enable_locking +RAND_F_RAND_DRBG_GENERATE:107:RAND_DRBG_generate +RAND_F_RAND_DRBG_INSTANTIATE:108:RAND_DRBG_instantiate +RAND_F_RAND_DRBG_NEW:109:RAND_DRBG_new +RAND_F_RAND_DRBG_RESEED:110:RAND_DRBG_reseed +RAND_F_RAND_DRBG_RESTART:102:rand_drbg_restart +RAND_F_RAND_DRBG_SET:104:RAND_DRBG_set +RAND_F_RAND_DRBG_UNINSTANTIATE:118:RAND_DRBG_uninstantiate +RAND_F_RAND_LOAD_FILE:111:RAND_load_file +RAND_F_RAND_POOL_ADD:103:RAND_POOL_add +RAND_F_RAND_POOL_ADD_BEGIN:113:RAND_POOL_add_begin +RAND_F_RAND_POOL_ADD_END:114:RAND_POOL_add_end +RAND_F_RAND_POOL_BYTES_NEEDED:115:RAND_POOL_bytes_needed +RAND_F_RAND_POOL_NEW:116:RAND_POOL_new +RAND_F_RAND_WRITE_FILE:112:RAND_write_file +RSA_F_CHECK_PADDING_MD:140:check_padding_md +RSA_F_ENCODE_PKCS1:146:encode_pkcs1 +RSA_F_INT_RSA_VERIFY:145:int_rsa_verify +RSA_F_OLD_RSA_PRIV_DECODE:147:old_rsa_priv_decode +RSA_F_PKEY_PSS_INIT:165:pkey_pss_init +RSA_F_PKEY_RSA_CTRL:143:pkey_rsa_ctrl +RSA_F_PKEY_RSA_CTRL_STR:144:pkey_rsa_ctrl_str +RSA_F_PKEY_RSA_SIGN:142:pkey_rsa_sign +RSA_F_PKEY_RSA_VERIFY:149:pkey_rsa_verify +RSA_F_PKEY_RSA_VERIFYRECOVER:141:pkey_rsa_verifyrecover +RSA_F_RSA_ALGOR_TO_MD:156:rsa_algor_to_md +RSA_F_RSA_BUILTIN_KEYGEN:129:rsa_builtin_keygen +RSA_F_RSA_CHECK_KEY:123:RSA_check_key +RSA_F_RSA_CHECK_KEY_EX:160:RSA_check_key_ex +RSA_F_RSA_CMS_DECRYPT:159:rsa_cms_decrypt +RSA_F_RSA_CMS_VERIFY:158:rsa_cms_verify +RSA_F_RSA_ITEM_VERIFY:148:rsa_item_verify +RSA_F_RSA_METH_DUP:161:RSA_meth_dup +RSA_F_RSA_METH_NEW:162:RSA_meth_new +RSA_F_RSA_METH_SET1_NAME:163:RSA_meth_set1_name +RSA_F_RSA_MGF1_TO_MD:157:* +RSA_F_RSA_NEW_METHOD:106:RSA_new_method +RSA_F_RSA_NULL:124:* +RSA_F_RSA_NULL_PRIVATE_DECRYPT:132:* +RSA_F_RSA_NULL_PRIVATE_ENCRYPT:133:* +RSA_F_RSA_NULL_PUBLIC_DECRYPT:134:* +RSA_F_RSA_NULL_PUBLIC_ENCRYPT:135:* +RSA_F_RSA_OSSL_PRIVATE_DECRYPT:101:rsa_ossl_private_decrypt +RSA_F_RSA_OSSL_PRIVATE_ENCRYPT:102:rsa_ossl_private_encrypt +RSA_F_RSA_OSSL_PUBLIC_DECRYPT:103:rsa_ossl_public_decrypt +RSA_F_RSA_OSSL_PUBLIC_ENCRYPT:104:rsa_ossl_public_encrypt +RSA_F_RSA_PADDING_ADD_NONE:107:RSA_padding_add_none +RSA_F_RSA_PADDING_ADD_PKCS1_OAEP:121:RSA_padding_add_PKCS1_OAEP +RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1:154:RSA_padding_add_PKCS1_OAEP_mgf1 +RSA_F_RSA_PADDING_ADD_PKCS1_PSS:125:RSA_padding_add_PKCS1_PSS +RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1:152:RSA_padding_add_PKCS1_PSS_mgf1 +RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_1:108:RSA_padding_add_PKCS1_type_1 +RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_2:109:RSA_padding_add_PKCS1_type_2 +RSA_F_RSA_PADDING_ADD_SSLV23:110:RSA_padding_add_SSLv23 +RSA_F_RSA_PADDING_ADD_X931:127:RSA_padding_add_X931 +RSA_F_RSA_PADDING_CHECK_NONE:111:RSA_padding_check_none +RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP:122:RSA_padding_check_PKCS1_OAEP +RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1:153:RSA_padding_check_PKCS1_OAEP_mgf1 +RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1:112:RSA_padding_check_PKCS1_type_1 +RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2:113:RSA_padding_check_PKCS1_type_2 +RSA_F_RSA_PADDING_CHECK_SSLV23:114:RSA_padding_check_SSLv23 +RSA_F_RSA_PADDING_CHECK_X931:128:RSA_padding_check_X931 +RSA_F_RSA_PARAM_DECODE:164:rsa_param_decode +RSA_F_RSA_PRINT:115:RSA_print +RSA_F_RSA_PRINT_FP:116:RSA_print_fp +RSA_F_RSA_PRIV_DECODE:150:rsa_priv_decode +RSA_F_RSA_PRIV_ENCODE:138:rsa_priv_encode +RSA_F_RSA_PSS_GET_PARAM:151:rsa_pss_get_param +RSA_F_RSA_PSS_TO_CTX:155:rsa_pss_to_ctx +RSA_F_RSA_PUB_DECODE:139:rsa_pub_decode +RSA_F_RSA_SETUP_BLINDING:136:RSA_setup_blinding +RSA_F_RSA_SIGN:117:RSA_sign +RSA_F_RSA_SIGN_ASN1_OCTET_STRING:118:RSA_sign_ASN1_OCTET_STRING +RSA_F_RSA_VERIFY:119:RSA_verify +RSA_F_RSA_VERIFY_ASN1_OCTET_STRING:120:RSA_verify_ASN1_OCTET_STRING +RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1:126:RSA_verify_PKCS1_PSS_mgf1 +SSL_F_ADD_CLIENT_KEY_SHARE_EXT:438:* +SSL_F_ADD_KEY_SHARE:512:add_key_share +SSL_F_BYTES_TO_CIPHER_LIST:519:bytes_to_cipher_list +SSL_F_CHECK_SUITEB_CIPHER_LIST:331:check_suiteb_cipher_list +SSL_F_CONSTRUCT_CA_NAMES:552:construct_ca_names +SSL_F_CONSTRUCT_KEY_EXCHANGE_TBS:553:construct_key_exchange_tbs +SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH:539:create_synthetic_message_hash +SSL_F_CT_MOVE_SCTS:345:ct_move_scts +SSL_F_CT_STRICT:349:ct_strict +SSL_F_CUSTOM_EXT_ADD:554:custom_ext_add +SSL_F_CUSTOM_EXT_PARSE:555:custom_ext_parse +SSL_F_D2I_SSL_SESSION:103:d2i_SSL_SESSION +SSL_F_DANE_CTX_ENABLE:347:dane_ctx_enable +SSL_F_DANE_MTYPE_SET:393:dane_mtype_set +SSL_F_DANE_TLSA_ADD:394:dane_tlsa_add +SSL_F_DERIVE_SECRET_KEY_AND_IV:514:derive_secret_key_and_iv +SSL_F_DO_DTLS1_WRITE:245:do_dtls1_write +SSL_F_DO_SSL3_WRITE:104:do_ssl3_write +SSL_F_DTLS1_BUFFER_RECORD:247:dtls1_buffer_record +SSL_F_DTLS1_CHECK_TIMEOUT_NUM:318:dtls1_check_timeout_num +SSL_F_DTLS1_HEARTBEAT:305:* +SSL_F_DTLS1_PREPROCESS_FRAGMENT:288:dtls1_preprocess_fragment +SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS:424:dtls1_process_buffered_records +SSL_F_DTLS1_PROCESS_RECORD:257:dtls1_process_record +SSL_F_DTLS1_READ_BYTES:258:dtls1_read_bytes +SSL_F_DTLS1_READ_FAILED:339:dtls1_read_failed +SSL_F_DTLS1_RETRANSMIT_MESSAGE:390:dtls1_retransmit_message +SSL_F_DTLS1_WRITE_APP_DATA_BYTES:268:dtls1_write_app_data_bytes +SSL_F_DTLS1_WRITE_BYTES:545:dtls1_write_bytes +SSL_F_DTLSV1_LISTEN:350:DTLSv1_listen +SSL_F_DTLS_CONSTRUCT_CHANGE_CIPHER_SPEC:371:dtls_construct_change_cipher_spec +SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST:385:\ + dtls_construct_hello_verify_request +SSL_F_DTLS_GET_REASSEMBLED_MESSAGE:370:dtls_get_reassembled_message +SSL_F_DTLS_PROCESS_HELLO_VERIFY:386:dtls_process_hello_verify +SSL_F_DTLS_WAIT_FOR_DRY:592:dtls_wait_for_dry +SSL_F_EARLY_DATA_COUNT_OK:532:early_data_count_ok +SSL_F_FINAL_EARLY_DATA:556:final_early_data +SSL_F_FINAL_EC_PT_FORMATS:485:final_ec_pt_formats +SSL_F_FINAL_EMS:486:final_ems +SSL_F_FINAL_KEY_SHARE:503:final_key_share +SSL_F_FINAL_MAXFRAGMENTLEN:557:final_maxfragmentlen +SSL_F_FINAL_RENEGOTIATE:483:final_renegotiate +SSL_F_FINAL_SERVER_NAME:558:final_server_name +SSL_F_FINAL_SIG_ALGS:497:final_sig_algs +SSL_F_GET_CERT_VERIFY_TBS_DATA:588:get_cert_verify_tbs_data +SSL_F_NSS_KEYLOG_INT:500:nss_keylog_int +SSL_F_OPENSSL_INIT_SSL:342:OPENSSL_init_ssl +SSL_F_OSSL_STATEM_CLIENT13_READ_TRANSITION:436:* +SSL_F_OSSL_STATEM_CLIENT13_WRITE_TRANSITION:598:\ + ossl_statem_client13_write_transition +SSL_F_OSSL_STATEM_CLIENT_CONSTRUCT_MESSAGE:430:* +SSL_F_OSSL_STATEM_CLIENT_POST_PROCESS_MESSAGE:593:\ + ossl_statem_client_post_process_message +SSL_F_OSSL_STATEM_CLIENT_PROCESS_MESSAGE:594:ossl_statem_client_process_message +SSL_F_OSSL_STATEM_CLIENT_READ_TRANSITION:417:ossl_statem_client_read_transition +SSL_F_OSSL_STATEM_CLIENT_WRITE_TRANSITION:599:\ + ossl_statem_client_write_transition +SSL_F_OSSL_STATEM_SERVER13_READ_TRANSITION:437:* +SSL_F_OSSL_STATEM_SERVER13_WRITE_TRANSITION:600:\ + ossl_statem_server13_write_transition +SSL_F_OSSL_STATEM_SERVER_CONSTRUCT_MESSAGE:431:* +SSL_F_OSSL_STATEM_SERVER_POST_PROCESS_MESSAGE:601:\ + ossl_statem_server_post_process_message +SSL_F_OSSL_STATEM_SERVER_POST_WORK:602:ossl_statem_server_post_work +SSL_F_OSSL_STATEM_SERVER_PROCESS_MESSAGE:603:ossl_statem_server_process_message +SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION:418:ossl_statem_server_read_transition +SSL_F_OSSL_STATEM_SERVER_WRITE_TRANSITION:604:\ + ossl_statem_server_write_transition +SSL_F_PARSE_CA_NAMES:541:parse_ca_names +SSL_F_PROCESS_KEY_SHARE_EXT:439:* +SSL_F_READ_STATE_MACHINE:352:read_state_machine +SSL_F_SET_CLIENT_CIPHERSUITE:540:set_client_ciphersuite +SSL_F_SRP_GENERATE_CLIENT_MASTER_SECRET:595:srp_generate_client_master_secret +SSL_F_SRP_GENERATE_SERVER_MASTER_SECRET:589:srp_generate_server_master_secret +SSL_F_SRP_VERIFY_SERVER_PARAM:596:srp_verify_server_param +SSL_F_SSL3_CHANGE_CIPHER_STATE:129:ssl3_change_cipher_state +SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM:130:ssl3_check_cert_and_algorithm +SSL_F_SSL3_CTRL:213:ssl3_ctrl +SSL_F_SSL3_CTX_CTRL:133:ssl3_ctx_ctrl +SSL_F_SSL3_DIGEST_CACHED_RECORDS:293:ssl3_digest_cached_records +SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC:292:ssl3_do_change_cipher_spec +SSL_F_SSL3_ENC:608:ssl3_enc +SSL_F_SSL3_FINAL_FINISH_MAC:285:ssl3_final_finish_mac +SSL_F_SSL3_FINISH_MAC:587:ssl3_finish_mac +SSL_F_SSL3_GENERATE_KEY_BLOCK:238:ssl3_generate_key_block +SSL_F_SSL3_GENERATE_MASTER_SECRET:388:ssl3_generate_master_secret +SSL_F_SSL3_GET_RECORD:143:ssl3_get_record +SSL_F_SSL3_INIT_FINISHED_MAC:397:ssl3_init_finished_mac +SSL_F_SSL3_OUTPUT_CERT_CHAIN:147:ssl3_output_cert_chain +SSL_F_SSL3_READ_BYTES:148:ssl3_read_bytes +SSL_F_SSL3_READ_N:149:ssl3_read_n +SSL_F_SSL3_SETUP_KEY_BLOCK:157:ssl3_setup_key_block +SSL_F_SSL3_SETUP_READ_BUFFER:156:ssl3_setup_read_buffer +SSL_F_SSL3_SETUP_WRITE_BUFFER:291:ssl3_setup_write_buffer +SSL_F_SSL3_WRITE_BYTES:158:ssl3_write_bytes +SSL_F_SSL3_WRITE_PENDING:159:ssl3_write_pending +SSL_F_SSL_ADD_CERT_CHAIN:316:ssl_add_cert_chain +SSL_F_SSL_ADD_CERT_TO_BUF:319:* +SSL_F_SSL_ADD_CERT_TO_WPACKET:493:ssl_add_cert_to_wpacket +SSL_F_SSL_ADD_CLIENTHELLO_RENEGOTIATE_EXT:298:* +SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT:277:* +SSL_F_SSL_ADD_CLIENTHELLO_USE_SRTP_EXT:307:* +SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK:215:SSL_add_dir_cert_subjects_to_stack +SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK:216:\ + SSL_add_file_cert_subjects_to_stack +SSL_F_SSL_ADD_SERVERHELLO_RENEGOTIATE_EXT:299:* +SSL_F_SSL_ADD_SERVERHELLO_TLSEXT:278:* +SSL_F_SSL_ADD_SERVERHELLO_USE_SRTP_EXT:308:* +SSL_F_SSL_BAD_METHOD:160:ssl_bad_method +SSL_F_SSL_BUILD_CERT_CHAIN:332:ssl_build_cert_chain +SSL_F_SSL_BYTES_TO_CIPHER_LIST:161:SSL_bytes_to_cipher_list +SSL_F_SSL_CACHE_CIPHERLIST:520:ssl_cache_cipherlist +SSL_F_SSL_CERT_ADD0_CHAIN_CERT:346:ssl_cert_add0_chain_cert +SSL_F_SSL_CERT_DUP:221:ssl_cert_dup +SSL_F_SSL_CERT_NEW:162:ssl_cert_new +SSL_F_SSL_CERT_SET0_CHAIN:340:ssl_cert_set0_chain +SSL_F_SSL_CHECK_PRIVATE_KEY:163:SSL_check_private_key +SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT:280:* +SSL_F_SSL_CHECK_SRP_EXT_CLIENTHELLO:606:ssl_check_srp_ext_ClientHello +SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG:279:ssl_check_srvr_ecc_cert_and_alg +SSL_F_SSL_CHOOSE_CLIENT_VERSION:607:ssl_choose_client_version +SSL_F_SSL_CIPHER_LIST_TO_BYTES:425:ssl_cipher_list_to_bytes +SSL_F_SSL_CIPHER_PROCESS_RULESTR:230:ssl_cipher_process_rulestr +SSL_F_SSL_CIPHER_STRENGTH_SORT:231:ssl_cipher_strength_sort +SSL_F_SSL_CLEAR:164:SSL_clear +SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD:165:SSL_COMP_add_compression_method +SSL_F_SSL_CONF_CMD:334:SSL_CONF_cmd +SSL_F_SSL_CREATE_CIPHER_LIST:166:ssl_create_cipher_list +SSL_F_SSL_CTRL:232:SSL_ctrl +SSL_F_SSL_CTX_CHECK_PRIVATE_KEY:168:SSL_CTX_check_private_key +SSL_F_SSL_CTX_ENABLE_CT:398:SSL_CTX_enable_ct +SSL_F_SSL_CTX_MAKE_PROFILES:309:ssl_ctx_make_profiles +SSL_F_SSL_CTX_NEW:169:SSL_CTX_new +SSL_F_SSL_CTX_SET_ALPN_PROTOS:343:SSL_CTX_set_alpn_protos +SSL_F_SSL_CTX_SET_CIPHER_LIST:269:SSL_CTX_set_cipher_list +SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE:290:SSL_CTX_set_client_cert_engine +SSL_F_SSL_CTX_SET_CT_VALIDATION_CALLBACK:396:SSL_CTX_set_ct_validation_callback +SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT:219:SSL_CTX_set_session_id_context +SSL_F_SSL_CTX_SET_SSL_VERSION:170:SSL_CTX_set_ssl_version +SSL_F_SSL_CTX_SET_TLSEXT_MAX_FRAGMENT_LENGTH:551:\ + SSL_CTX_set_tlsext_max_fragment_length +SSL_F_SSL_CTX_USE_CERTIFICATE:171:SSL_CTX_use_certificate +SSL_F_SSL_CTX_USE_CERTIFICATE_ASN1:172:SSL_CTX_use_certificate_ASN1 +SSL_F_SSL_CTX_USE_CERTIFICATE_FILE:173:SSL_CTX_use_certificate_file +SSL_F_SSL_CTX_USE_PRIVATEKEY:174:SSL_CTX_use_PrivateKey +SSL_F_SSL_CTX_USE_PRIVATEKEY_ASN1:175:SSL_CTX_use_PrivateKey_ASN1 +SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE:176:SSL_CTX_use_PrivateKey_file +SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT:272:SSL_CTX_use_psk_identity_hint +SSL_F_SSL_CTX_USE_RSAPRIVATEKEY:177:SSL_CTX_use_RSAPrivateKey +SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_ASN1:178:SSL_CTX_use_RSAPrivateKey_ASN1 +SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE:179:SSL_CTX_use_RSAPrivateKey_file +SSL_F_SSL_CTX_USE_SERVERINFO:336:SSL_CTX_use_serverinfo +SSL_F_SSL_CTX_USE_SERVERINFO_EX:543:SSL_CTX_use_serverinfo_ex +SSL_F_SSL_CTX_USE_SERVERINFO_FILE:337:SSL_CTX_use_serverinfo_file +SSL_F_SSL_DANE_DUP:403:ssl_dane_dup +SSL_F_SSL_DANE_ENABLE:395:SSL_dane_enable +SSL_F_SSL_DERIVE:590:ssl_derive +SSL_F_SSL_DO_CONFIG:391:ssl_do_config +SSL_F_SSL_DO_HANDSHAKE:180:SSL_do_handshake +SSL_F_SSL_DUP_CA_LIST:408:SSL_dup_CA_list +SSL_F_SSL_ENABLE_CT:402:SSL_enable_ct +SSL_F_SSL_GENERATE_PKEY_GROUP:559:ssl_generate_pkey_group +SSL_F_SSL_GENERATE_SESSION_ID:547:ssl_generate_session_id +SSL_F_SSL_GET_NEW_SESSION:181:ssl_get_new_session +SSL_F_SSL_GET_PREV_SESSION:217:ssl_get_prev_session +SSL_F_SSL_GET_SERVER_CERT_INDEX:322:* +SSL_F_SSL_GET_SIGN_PKEY:183:* +SSL_F_SSL_HANDSHAKE_HASH:560:ssl_handshake_hash +SSL_F_SSL_INIT_WBIO_BUFFER:184:ssl_init_wbio_buffer +SSL_F_SSL_KEY_UPDATE:515:SSL_key_update +SSL_F_SSL_LOAD_CLIENT_CA_FILE:185:SSL_load_client_CA_file +SSL_F_SSL_LOG_MASTER_SECRET:498:* +SSL_F_SSL_LOG_RSA_CLIENT_KEY_EXCHANGE:499:ssl_log_rsa_client_key_exchange +SSL_F_SSL_MODULE_INIT:392:ssl_module_init +SSL_F_SSL_NEW:186:SSL_new +SSL_F_SSL_NEXT_PROTO_VALIDATE:565:ssl_next_proto_validate +SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT:300:* +SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT:302:* +SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT:310:* +SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT:301:* +SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT:303:* +SSL_F_SSL_PARSE_SERVERHELLO_USE_SRTP_EXT:311:* +SSL_F_SSL_PEEK:270:SSL_peek +SSL_F_SSL_PEEK_EX:432:SSL_peek_ex +SSL_F_SSL_PEEK_INTERNAL:522:ssl_peek_internal +SSL_F_SSL_READ:223:SSL_read +SSL_F_SSL_READ_EARLY_DATA:529:SSL_read_early_data +SSL_F_SSL_READ_EX:434:SSL_read_ex +SSL_F_SSL_READ_INTERNAL:523:ssl_read_internal +SSL_F_SSL_RENEGOTIATE:516:SSL_renegotiate +SSL_F_SSL_RENEGOTIATE_ABBREVIATED:546:SSL_renegotiate_abbreviated +SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT:320:* +SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT:321:* +SSL_F_SSL_SESSION_DUP:348:ssl_session_dup +SSL_F_SSL_SESSION_NEW:189:SSL_SESSION_new +SSL_F_SSL_SESSION_PRINT_FP:190:SSL_SESSION_print_fp +SSL_F_SSL_SESSION_SET1_ID:423:SSL_SESSION_set1_id +SSL_F_SSL_SESSION_SET1_ID_CONTEXT:312:SSL_SESSION_set1_id_context +SSL_F_SSL_SET_ALPN_PROTOS:344:SSL_set_alpn_protos +SSL_F_SSL_SET_CERT:191:ssl_set_cert +SSL_F_SSL_SET_CIPHER_LIST:271:SSL_set_cipher_list +SSL_F_SSL_SET_CT_VALIDATION_CALLBACK:399:SSL_set_ct_validation_callback +SSL_F_SSL_SET_FD:192:SSL_set_fd +SSL_F_SSL_SET_PKEY:193:ssl_set_pkey +SSL_F_SSL_SET_RFD:194:SSL_set_rfd +SSL_F_SSL_SET_SESSION:195:SSL_set_session +SSL_F_SSL_SET_SESSION_ID_CONTEXT:218:SSL_set_session_id_context +SSL_F_SSL_SET_SESSION_TICKET_EXT:294:SSL_set_session_ticket_ext +SSL_F_SSL_SET_TLSEXT_MAX_FRAGMENT_LENGTH:550:SSL_set_tlsext_max_fragment_length +SSL_F_SSL_SET_WFD:196:SSL_set_wfd +SSL_F_SSL_SHUTDOWN:224:SSL_shutdown +SSL_F_SSL_SRP_CTX_INIT:313:SSL_SRP_CTX_init +SSL_F_SSL_START_ASYNC_JOB:389:ssl_start_async_job +SSL_F_SSL_UNDEFINED_FUNCTION:197:ssl_undefined_function +SSL_F_SSL_UNDEFINED_VOID_FUNCTION:244:ssl_undefined_void_function +SSL_F_SSL_USE_CERTIFICATE:198:SSL_use_certificate +SSL_F_SSL_USE_CERTIFICATE_ASN1:199:SSL_use_certificate_ASN1 +SSL_F_SSL_USE_CERTIFICATE_FILE:200:SSL_use_certificate_file +SSL_F_SSL_USE_PRIVATEKEY:201:SSL_use_PrivateKey +SSL_F_SSL_USE_PRIVATEKEY_ASN1:202:SSL_use_PrivateKey_ASN1 +SSL_F_SSL_USE_PRIVATEKEY_FILE:203:SSL_use_PrivateKey_file +SSL_F_SSL_USE_PSK_IDENTITY_HINT:273:SSL_use_psk_identity_hint +SSL_F_SSL_USE_RSAPRIVATEKEY:204:SSL_use_RSAPrivateKey +SSL_F_SSL_USE_RSAPRIVATEKEY_ASN1:205:SSL_use_RSAPrivateKey_ASN1 +SSL_F_SSL_USE_RSAPRIVATEKEY_FILE:206:SSL_use_RSAPrivateKey_file +SSL_F_SSL_VALIDATE_CT:400:ssl_validate_ct +SSL_F_SSL_VERIFY_CERT_CHAIN:207:ssl_verify_cert_chain +SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE:616:SSL_verify_client_post_handshake +SSL_F_SSL_WRITE:208:SSL_write +SSL_F_SSL_WRITE_EARLY_DATA:526:SSL_write_early_data +SSL_F_SSL_WRITE_EARLY_FINISH:527:* +SSL_F_SSL_WRITE_EX:433:SSL_write_ex +SSL_F_SSL_WRITE_INTERNAL:524:ssl_write_internal +SSL_F_STATE_MACHINE:353:state_machine +SSL_F_TLS12_CHECK_PEER_SIGALG:333:tls12_check_peer_sigalg +SSL_F_TLS12_COPY_SIGALGS:533:tls12_copy_sigalgs +SSL_F_TLS13_CHANGE_CIPHER_STATE:440:tls13_change_cipher_state +SSL_F_TLS13_ENC:609:tls13_enc +SSL_F_TLS13_FINAL_FINISH_MAC:605:tls13_final_finish_mac +SSL_F_TLS13_GENERATE_SECRET:591:tls13_generate_secret +SSL_F_TLS13_HKDF_EXPAND:561:tls13_hkdf_expand +SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA:617:\ + tls13_restore_handshake_digest_for_pha +SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA:618:\ + tls13_save_handshake_digest_for_pha +SSL_F_TLS13_SETUP_KEY_BLOCK:441:tls13_setup_key_block +SSL_F_TLS1_CHANGE_CIPHER_STATE:209:tls1_change_cipher_state +SSL_F_TLS1_CHECK_DUPLICATE_EXTENSIONS:341:* +SSL_F_TLS1_ENC:401:tls1_enc +SSL_F_TLS1_EXPORT_KEYING_MATERIAL:314:tls1_export_keying_material +SSL_F_TLS1_GET_CURVELIST:338:tls1_get_curvelist +SSL_F_TLS1_PRF:284:tls1_PRF +SSL_F_TLS1_SETUP_KEY_BLOCK:211:tls1_setup_key_block +SSL_F_TLS1_SET_SERVER_SIGALGS:335:tls1_set_server_sigalgs +SSL_F_TLS_CHOOSE_SIGALG:513:tls_choose_sigalg +SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK:354:tls_client_key_exchange_post_work +SSL_F_TLS_COLLECT_EXTENSIONS:435:tls_collect_extensions +SSL_F_TLS_CONSTRUCT_CERTIFICATE_AUTHORITIES:542:\ + tls_construct_certificate_authorities +SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST:372:tls_construct_certificate_request +SSL_F_TLS_CONSTRUCT_CERT_STATUS:429:* +SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY:494:tls_construct_cert_status_body +SSL_F_TLS_CONSTRUCT_CERT_VERIFY:496:tls_construct_cert_verify +SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC:427:tls_construct_change_cipher_spec +SSL_F_TLS_CONSTRUCT_CKE_DHE:404:tls_construct_cke_dhe +SSL_F_TLS_CONSTRUCT_CKE_ECDHE:405:tls_construct_cke_ecdhe +SSL_F_TLS_CONSTRUCT_CKE_GOST:406:tls_construct_cke_gost +SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE:407:tls_construct_cke_psk_preamble +SSL_F_TLS_CONSTRUCT_CKE_RSA:409:tls_construct_cke_rsa +SSL_F_TLS_CONSTRUCT_CKE_SRP:410:tls_construct_cke_srp +SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE:484:tls_construct_client_certificate +SSL_F_TLS_CONSTRUCT_CLIENT_HELLO:487:tls_construct_client_hello +SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE:488:tls_construct_client_key_exchange +SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY:489:* +SSL_F_TLS_CONSTRUCT_CTOS_ALPN:466:tls_construct_ctos_alpn +SSL_F_TLS_CONSTRUCT_CTOS_CERTIFICATE:355:* +SSL_F_TLS_CONSTRUCT_CTOS_COOKIE:535:tls_construct_ctos_cookie +SSL_F_TLS_CONSTRUCT_CTOS_EARLY_DATA:530:tls_construct_ctos_early_data +SSL_F_TLS_CONSTRUCT_CTOS_EC_PT_FORMATS:467:tls_construct_ctos_ec_pt_formats +SSL_F_TLS_CONSTRUCT_CTOS_EMS:468:tls_construct_ctos_ems +SSL_F_TLS_CONSTRUCT_CTOS_ETM:469:tls_construct_ctos_etm +SSL_F_TLS_CONSTRUCT_CTOS_HELLO:356:* +SSL_F_TLS_CONSTRUCT_CTOS_KEY_EXCHANGE:357:* +SSL_F_TLS_CONSTRUCT_CTOS_KEY_SHARE:470:tls_construct_ctos_key_share +SSL_F_TLS_CONSTRUCT_CTOS_MAXFRAGMENTLEN:549:tls_construct_ctos_maxfragmentlen +SSL_F_TLS_CONSTRUCT_CTOS_NPN:471:tls_construct_ctos_npn +SSL_F_TLS_CONSTRUCT_CTOS_PADDING:472:tls_construct_ctos_padding +SSL_F_TLS_CONSTRUCT_CTOS_POST_HANDSHAKE_AUTH:619:\ + tls_construct_ctos_post_handshake_auth +SSL_F_TLS_CONSTRUCT_CTOS_PSK:501:tls_construct_ctos_psk +SSL_F_TLS_CONSTRUCT_CTOS_PSK_KEX_MODES:509:tls_construct_ctos_psk_kex_modes +SSL_F_TLS_CONSTRUCT_CTOS_RENEGOTIATE:473:tls_construct_ctos_renegotiate +SSL_F_TLS_CONSTRUCT_CTOS_SCT:474:tls_construct_ctos_sct +SSL_F_TLS_CONSTRUCT_CTOS_SERVER_NAME:475:tls_construct_ctos_server_name +SSL_F_TLS_CONSTRUCT_CTOS_SESSION_TICKET:476:tls_construct_ctos_session_ticket +SSL_F_TLS_CONSTRUCT_CTOS_SIG_ALGS:477:tls_construct_ctos_sig_algs +SSL_F_TLS_CONSTRUCT_CTOS_SRP:478:tls_construct_ctos_srp +SSL_F_TLS_CONSTRUCT_CTOS_STATUS_REQUEST:479:tls_construct_ctos_status_request +SSL_F_TLS_CONSTRUCT_CTOS_SUPPORTED_GROUPS:480:\ + tls_construct_ctos_supported_groups +SSL_F_TLS_CONSTRUCT_CTOS_SUPPORTED_VERSIONS:481:\ + tls_construct_ctos_supported_versions +SSL_F_TLS_CONSTRUCT_CTOS_USE_SRTP:482:tls_construct_ctos_use_srtp +SSL_F_TLS_CONSTRUCT_CTOS_VERIFY:358:* +SSL_F_TLS_CONSTRUCT_ENCRYPTED_EXTENSIONS:443:tls_construct_encrypted_extensions +SSL_F_TLS_CONSTRUCT_END_OF_EARLY_DATA:536:tls_construct_end_of_early_data +SSL_F_TLS_CONSTRUCT_EXTENSIONS:447:tls_construct_extensions +SSL_F_TLS_CONSTRUCT_FINISHED:359:tls_construct_finished +SSL_F_TLS_CONSTRUCT_HELLO_REQUEST:373:* +SSL_F_TLS_CONSTRUCT_HELLO_RETRY_REQUEST:510:tls_construct_hello_retry_request +SSL_F_TLS_CONSTRUCT_KEY_UPDATE:517:tls_construct_key_update +SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET:428:tls_construct_new_session_ticket +SSL_F_TLS_CONSTRUCT_NEXT_PROTO:426:tls_construct_next_proto +SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE:490:tls_construct_server_certificate +SSL_F_TLS_CONSTRUCT_SERVER_HELLO:491:tls_construct_server_hello +SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE:492:tls_construct_server_key_exchange +SSL_F_TLS_CONSTRUCT_STOC_ALPN:451:tls_construct_stoc_alpn +SSL_F_TLS_CONSTRUCT_STOC_CERTIFICATE:374:* +SSL_F_TLS_CONSTRUCT_STOC_COOKIE:613:tls_construct_stoc_cookie +SSL_F_TLS_CONSTRUCT_STOC_CRYPTOPRO_BUG:452:tls_construct_stoc_cryptopro_bug +SSL_F_TLS_CONSTRUCT_STOC_DONE:375:* +SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA:531:tls_construct_stoc_early_data +SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA_INFO:525:* +SSL_F_TLS_CONSTRUCT_STOC_EC_PT_FORMATS:453:tls_construct_stoc_ec_pt_formats +SSL_F_TLS_CONSTRUCT_STOC_EMS:454:tls_construct_stoc_ems +SSL_F_TLS_CONSTRUCT_STOC_ETM:455:tls_construct_stoc_etm +SSL_F_TLS_CONSTRUCT_STOC_HELLO:376:* +SSL_F_TLS_CONSTRUCT_STOC_KEY_EXCHANGE:377:* +SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE:456:tls_construct_stoc_key_share +SSL_F_TLS_CONSTRUCT_STOC_MAXFRAGMENTLEN:548:tls_construct_stoc_maxfragmentlen +SSL_F_TLS_CONSTRUCT_STOC_NEXT_PROTO_NEG:457:tls_construct_stoc_next_proto_neg +SSL_F_TLS_CONSTRUCT_STOC_PSK:504:tls_construct_stoc_psk +SSL_F_TLS_CONSTRUCT_STOC_RENEGOTIATE:458:tls_construct_stoc_renegotiate +SSL_F_TLS_CONSTRUCT_STOC_SERVER_NAME:459:tls_construct_stoc_server_name +SSL_F_TLS_CONSTRUCT_STOC_SESSION_TICKET:460:tls_construct_stoc_session_ticket +SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST:461:tls_construct_stoc_status_request +SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS:544:\ + tls_construct_stoc_supported_groups +SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS:611:\ + tls_construct_stoc_supported_versions +SSL_F_TLS_CONSTRUCT_STOC_USE_SRTP:462:tls_construct_stoc_use_srtp +SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO:521:\ + tls_early_post_process_client_hello +SSL_F_TLS_FINISH_HANDSHAKE:597:tls_finish_handshake +SSL_F_TLS_GET_MESSAGE_BODY:351:tls_get_message_body +SSL_F_TLS_GET_MESSAGE_HEADER:387:tls_get_message_header +SSL_F_TLS_HANDLE_ALPN:562:tls_handle_alpn +SSL_F_TLS_HANDLE_STATUS_REQUEST:563:tls_handle_status_request +SSL_F_TLS_PARSE_CERTIFICATE_AUTHORITIES:566:tls_parse_certificate_authorities +SSL_F_TLS_PARSE_CLIENTHELLO_TLSEXT:449:* +SSL_F_TLS_PARSE_CTOS_ALPN:567:tls_parse_ctos_alpn +SSL_F_TLS_PARSE_CTOS_COOKIE:614:tls_parse_ctos_cookie +SSL_F_TLS_PARSE_CTOS_EARLY_DATA:568:tls_parse_ctos_early_data +SSL_F_TLS_PARSE_CTOS_EC_PT_FORMATS:569:tls_parse_ctos_ec_pt_formats +SSL_F_TLS_PARSE_CTOS_EMS:570:tls_parse_ctos_ems +SSL_F_TLS_PARSE_CTOS_KEY_SHARE:463:tls_parse_ctos_key_share +SSL_F_TLS_PARSE_CTOS_MAXFRAGMENTLEN:571:tls_parse_ctos_maxfragmentlen +SSL_F_TLS_PARSE_CTOS_POST_HANDSHAKE_AUTH:620:tls_parse_ctos_post_handshake_auth +SSL_F_TLS_PARSE_CTOS_PSK:505:tls_parse_ctos_psk +SSL_F_TLS_PARSE_CTOS_PSK_KEX_MODES:572:tls_parse_ctos_psk_kex_modes +SSL_F_TLS_PARSE_CTOS_RENEGOTIATE:464:tls_parse_ctos_renegotiate +SSL_F_TLS_PARSE_CTOS_SERVER_NAME:573:tls_parse_ctos_server_name +SSL_F_TLS_PARSE_CTOS_SESSION_TICKET:574:tls_parse_ctos_session_ticket +SSL_F_TLS_PARSE_CTOS_SIG_ALGS:575:tls_parse_ctos_sig_algs +SSL_F_TLS_PARSE_CTOS_SIG_ALGS_CERT:615:tls_parse_ctos_sig_algs_cert +SSL_F_TLS_PARSE_CTOS_SRP:576:tls_parse_ctos_srp +SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST:577:tls_parse_ctos_status_request +SSL_F_TLS_PARSE_CTOS_SUPPORTED_GROUPS:578:tls_parse_ctos_supported_groups +SSL_F_TLS_PARSE_CTOS_USE_SRTP:465:tls_parse_ctos_use_srtp +SSL_F_TLS_PARSE_STOC_ALPN:579:tls_parse_stoc_alpn +SSL_F_TLS_PARSE_STOC_COOKIE:534:tls_parse_stoc_cookie +SSL_F_TLS_PARSE_STOC_EARLY_DATA:538:tls_parse_stoc_early_data +SSL_F_TLS_PARSE_STOC_EARLY_DATA_INFO:528:* +SSL_F_TLS_PARSE_STOC_EC_PT_FORMATS:580:tls_parse_stoc_ec_pt_formats +SSL_F_TLS_PARSE_STOC_KEY_SHARE:445:tls_parse_stoc_key_share +SSL_F_TLS_PARSE_STOC_MAXFRAGMENTLEN:581:tls_parse_stoc_maxfragmentlen +SSL_F_TLS_PARSE_STOC_NPN:582:tls_parse_stoc_npn +SSL_F_TLS_PARSE_STOC_PSK:502:tls_parse_stoc_psk +SSL_F_TLS_PARSE_STOC_RENEGOTIATE:448:tls_parse_stoc_renegotiate +SSL_F_TLS_PARSE_STOC_SCT:564:tls_parse_stoc_sct +SSL_F_TLS_PARSE_STOC_SERVER_NAME:583:tls_parse_stoc_server_name +SSL_F_TLS_PARSE_STOC_SESSION_TICKET:584:tls_parse_stoc_session_ticket +SSL_F_TLS_PARSE_STOC_STATUS_REQUEST:585:tls_parse_stoc_status_request +SSL_F_TLS_PARSE_STOC_SUPPORTED_VERSIONS:612:tls_parse_stoc_supported_versions +SSL_F_TLS_PARSE_STOC_USE_SRTP:446:tls_parse_stoc_use_srtp +SSL_F_TLS_POST_PROCESS_CLIENT_HELLO:378:tls_post_process_client_hello +SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE:384:\ + tls_post_process_client_key_exchange +SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE:360:tls_prepare_client_certificate +SSL_F_TLS_PROCESS_AS_HELLO_RETRY_REQUEST:610:tls_process_as_hello_retry_request +SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST:361:tls_process_certificate_request +SSL_F_TLS_PROCESS_CERT_STATUS:362:* +SSL_F_TLS_PROCESS_CERT_STATUS_BODY:495:tls_process_cert_status_body +SSL_F_TLS_PROCESS_CERT_VERIFY:379:tls_process_cert_verify +SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC:363:tls_process_change_cipher_spec +SSL_F_TLS_PROCESS_CKE_DHE:411:tls_process_cke_dhe +SSL_F_TLS_PROCESS_CKE_ECDHE:412:tls_process_cke_ecdhe +SSL_F_TLS_PROCESS_CKE_GOST:413:tls_process_cke_gost +SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE:414:tls_process_cke_psk_preamble +SSL_F_TLS_PROCESS_CKE_RSA:415:tls_process_cke_rsa +SSL_F_TLS_PROCESS_CKE_SRP:416:tls_process_cke_srp +SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE:380:tls_process_client_certificate +SSL_F_TLS_PROCESS_CLIENT_HELLO:381:tls_process_client_hello +SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE:382:tls_process_client_key_exchange +SSL_F_TLS_PROCESS_ENCRYPTED_EXTENSIONS:444:tls_process_encrypted_extensions +SSL_F_TLS_PROCESS_END_OF_EARLY_DATA:537:tls_process_end_of_early_data +SSL_F_TLS_PROCESS_FINISHED:364:tls_process_finished +SSL_F_TLS_PROCESS_HELLO_REQ:507:tls_process_hello_req +SSL_F_TLS_PROCESS_HELLO_RETRY_REQUEST:511:tls_process_hello_retry_request +SSL_F_TLS_PROCESS_INITIAL_SERVER_FLIGHT:442:tls_process_initial_server_flight +SSL_F_TLS_PROCESS_KEY_EXCHANGE:365:tls_process_key_exchange +SSL_F_TLS_PROCESS_KEY_UPDATE:518:tls_process_key_update +SSL_F_TLS_PROCESS_NEW_SESSION_TICKET:366:tls_process_new_session_ticket +SSL_F_TLS_PROCESS_NEXT_PROTO:383:tls_process_next_proto +SSL_F_TLS_PROCESS_SERVER_CERTIFICATE:367:tls_process_server_certificate +SSL_F_TLS_PROCESS_SERVER_DONE:368:tls_process_server_done +SSL_F_TLS_PROCESS_SERVER_HELLO:369:tls_process_server_hello +SSL_F_TLS_PROCESS_SKE_DHE:419:tls_process_ske_dhe +SSL_F_TLS_PROCESS_SKE_ECDHE:420:tls_process_ske_ecdhe +SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE:421:tls_process_ske_psk_preamble +SSL_F_TLS_PROCESS_SKE_SRP:422:tls_process_ske_srp +SSL_F_TLS_PSK_DO_BINDER:506:tls_psk_do_binder +SSL_F_TLS_SCAN_CLIENTHELLO_TLSEXT:450:* +SSL_F_TLS_SETUP_HANDSHAKE:508:tls_setup_handshake +SSL_F_USE_CERTIFICATE_CHAIN_FILE:220:use_certificate_chain_file +SSL_F_WRITE_STATE_MACHINE:586:write_state_machine +TS_F_DEF_SERIAL_CB:110:def_serial_cb +TS_F_DEF_TIME_CB:111:def_time_cb +TS_F_ESS_ADD_SIGNING_CERT:112:ess_add_signing_cert +TS_F_ESS_ADD_SIGNING_CERT_V2:147:ess_add_signing_cert_v2 +TS_F_ESS_CERT_ID_NEW_INIT:113:ess_CERT_ID_new_init +TS_F_ESS_CERT_ID_V2_NEW_INIT:156:ess_cert_id_v2_new_init +TS_F_ESS_SIGNING_CERT_NEW_INIT:114:ess_SIGNING_CERT_new_init +TS_F_ESS_SIGNING_CERT_V2_NEW_INIT:157:ess_signing_cert_v2_new_init +TS_F_INT_TS_RESP_VERIFY_TOKEN:149:int_ts_RESP_verify_token +TS_F_PKCS7_TO_TS_TST_INFO:148:PKCS7_to_TS_TST_INFO +TS_F_TS_ACCURACY_SET_MICROS:115:TS_ACCURACY_set_micros +TS_F_TS_ACCURACY_SET_MILLIS:116:TS_ACCURACY_set_millis +TS_F_TS_ACCURACY_SET_SECONDS:117:TS_ACCURACY_set_seconds +TS_F_TS_CHECK_IMPRINTS:100:ts_check_imprints +TS_F_TS_CHECK_NONCES:101:ts_check_nonces +TS_F_TS_CHECK_POLICY:102:ts_check_policy +TS_F_TS_CHECK_SIGNING_CERTS:103:ts_check_signing_certs +TS_F_TS_CHECK_STATUS_INFO:104:ts_check_status_info +TS_F_TS_COMPUTE_IMPRINT:145:ts_compute_imprint +TS_F_TS_CONF_INVALID:151:ts_CONF_invalid +TS_F_TS_CONF_LOAD_CERT:153:TS_CONF_load_cert +TS_F_TS_CONF_LOAD_CERTS:154:TS_CONF_load_certs +TS_F_TS_CONF_LOAD_KEY:155:TS_CONF_load_key +TS_F_TS_CONF_LOOKUP_FAIL:152:ts_CONF_lookup_fail +TS_F_TS_CONF_SET_DEFAULT_ENGINE:146:TS_CONF_set_default_engine +TS_F_TS_GET_STATUS_TEXT:105:ts_get_status_text +TS_F_TS_MSG_IMPRINT_SET_ALGO:118:TS_MSG_IMPRINT_set_algo +TS_F_TS_REQ_SET_MSG_IMPRINT:119:TS_REQ_set_msg_imprint +TS_F_TS_REQ_SET_NONCE:120:TS_REQ_set_nonce +TS_F_TS_REQ_SET_POLICY_ID:121:TS_REQ_set_policy_id +TS_F_TS_RESP_CREATE_RESPONSE:122:TS_RESP_create_response +TS_F_TS_RESP_CREATE_TST_INFO:123:ts_RESP_create_tst_info +TS_F_TS_RESP_CTX_ADD_FAILURE_INFO:124:TS_RESP_CTX_add_failure_info +TS_F_TS_RESP_CTX_ADD_MD:125:TS_RESP_CTX_add_md +TS_F_TS_RESP_CTX_ADD_POLICY:126:TS_RESP_CTX_add_policy +TS_F_TS_RESP_CTX_NEW:127:TS_RESP_CTX_new +TS_F_TS_RESP_CTX_SET_ACCURACY:128:TS_RESP_CTX_set_accuracy +TS_F_TS_RESP_CTX_SET_CERTS:129:TS_RESP_CTX_set_certs +TS_F_TS_RESP_CTX_SET_DEF_POLICY:130:TS_RESP_CTX_set_def_policy +TS_F_TS_RESP_CTX_SET_SIGNER_CERT:131:TS_RESP_CTX_set_signer_cert +TS_F_TS_RESP_CTX_SET_STATUS_INFO:132:TS_RESP_CTX_set_status_info +TS_F_TS_RESP_GET_POLICY:133:ts_RESP_get_policy +TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION:134:TS_RESP_set_genTime_with_precision +TS_F_TS_RESP_SET_STATUS_INFO:135:TS_RESP_set_status_info +TS_F_TS_RESP_SET_TST_INFO:150:TS_RESP_set_tst_info +TS_F_TS_RESP_SIGN:136:ts_RESP_sign +TS_F_TS_RESP_VERIFY_SIGNATURE:106:TS_RESP_verify_signature +TS_F_TS_TST_INFO_SET_ACCURACY:137:TS_TST_INFO_set_accuracy +TS_F_TS_TST_INFO_SET_MSG_IMPRINT:138:TS_TST_INFO_set_msg_imprint +TS_F_TS_TST_INFO_SET_NONCE:139:TS_TST_INFO_set_nonce +TS_F_TS_TST_INFO_SET_POLICY_ID:140:TS_TST_INFO_set_policy_id +TS_F_TS_TST_INFO_SET_SERIAL:141:TS_TST_INFO_set_serial +TS_F_TS_TST_INFO_SET_TIME:142:TS_TST_INFO_set_time +TS_F_TS_TST_INFO_SET_TSA:143:TS_TST_INFO_set_tsa +TS_F_TS_VERIFY:108:* +TS_F_TS_VERIFY_CERT:109:ts_verify_cert +TS_F_TS_VERIFY_CTX_NEW:144:TS_VERIFY_CTX_new +UI_F_CLOSE_CONSOLE:115:close_console +UI_F_ECHO_CONSOLE:116:echo_console +UI_F_GENERAL_ALLOCATE_BOOLEAN:108:general_allocate_boolean +UI_F_GENERAL_ALLOCATE_PROMPT:109:general_allocate_prompt +UI_F_NOECHO_CONSOLE:117:noecho_console +UI_F_OPEN_CONSOLE:114:open_console +UI_F_UI_CREATE_METHOD:112:UI_create_method +UI_F_UI_CTRL:111:UI_ctrl +UI_F_UI_DUP_ERROR_STRING:101:UI_dup_error_string +UI_F_UI_DUP_INFO_STRING:102:UI_dup_info_string +UI_F_UI_DUP_INPUT_BOOLEAN:110:UI_dup_input_boolean +UI_F_UI_DUP_INPUT_STRING:103:UI_dup_input_string +UI_F_UI_DUP_USER_DATA:118:UI_dup_user_data +UI_F_UI_DUP_VERIFY_STRING:106:UI_dup_verify_string +UI_F_UI_GET0_RESULT:107:UI_get0_result +UI_F_UI_GET_RESULT_LENGTH:119:UI_get_result_length +UI_F_UI_NEW_METHOD:104:UI_new_method +UI_F_UI_PROCESS:113:UI_process +UI_F_UI_SET_RESULT:105:UI_set_result +UI_F_UI_SET_RESULT_EX:120:UI_set_result_ex +X509V3_F_A2I_GENERAL_NAME:164:a2i_GENERAL_NAME +X509V3_F_ADDR_VALIDATE_PATH_INTERNAL:166:addr_validate_path_internal +X509V3_F_ASIDENTIFIERCHOICE_CANONIZE:161:ASIdentifierChoice_canonize +X509V3_F_ASIDENTIFIERCHOICE_IS_CANONICAL:162:ASIdentifierChoice_is_canonical +X509V3_F_BIGNUM_TO_STRING:167:bignum_to_string +X509V3_F_COPY_EMAIL:122:copy_email +X509V3_F_COPY_ISSUER:123:copy_issuer +X509V3_F_DO_DIRNAME:144:do_dirname +X509V3_F_DO_EXT_I2D:135:do_ext_i2d +X509V3_F_DO_EXT_NCONF:151:do_ext_nconf +X509V3_F_GNAMES_FROM_SECTNAME:156:gnames_from_sectname +X509V3_F_I2S_ASN1_ENUMERATED:121:i2s_ASN1_ENUMERATED +X509V3_F_I2S_ASN1_IA5STRING:149:i2s_ASN1_IA5STRING +X509V3_F_I2S_ASN1_INTEGER:120:i2s_ASN1_INTEGER +X509V3_F_I2V_AUTHORITY_INFO_ACCESS:138:i2v_AUTHORITY_INFO_ACCESS +X509V3_F_NOTICE_SECTION:132:notice_section +X509V3_F_NREF_NOS:133:nref_nos +X509V3_F_POLICY_SECTION:131:policy_section +X509V3_F_PROCESS_PCI_VALUE:150:process_pci_value +X509V3_F_R2I_CERTPOL:130:r2i_certpol +X509V3_F_R2I_PCI:155:r2i_pci +X509V3_F_S2I_ASN1_IA5STRING:100:s2i_ASN1_IA5STRING +X509V3_F_S2I_ASN1_INTEGER:108:s2i_ASN1_INTEGER +X509V3_F_S2I_ASN1_OCTET_STRING:112:s2i_ASN1_OCTET_STRING +X509V3_F_S2I_SKEY_ID:115:s2i_skey_id +X509V3_F_SET_DIST_POINT_NAME:158:set_dist_point_name +X509V3_F_SXNET_ADD_ID_ASC:125:SXNET_add_id_asc +X509V3_F_SXNET_ADD_ID_INTEGER:126:SXNET_add_id_INTEGER +X509V3_F_SXNET_ADD_ID_ULONG:127:SXNET_add_id_ulong +X509V3_F_SXNET_GET_ID_ASC:128:SXNET_get_id_asc +X509V3_F_SXNET_GET_ID_ULONG:129:SXNET_get_id_ulong +X509V3_F_V2I_ASIDENTIFIERS:163:v2i_ASIdentifiers +X509V3_F_V2I_ASN1_BIT_STRING:101:v2i_ASN1_BIT_STRING +X509V3_F_V2I_AUTHORITY_INFO_ACCESS:139:v2i_AUTHORITY_INFO_ACCESS +X509V3_F_V2I_AUTHORITY_KEYID:119:v2i_AUTHORITY_KEYID +X509V3_F_V2I_BASIC_CONSTRAINTS:102:v2i_BASIC_CONSTRAINTS +X509V3_F_V2I_CRLD:134:v2i_crld +X509V3_F_V2I_EXTENDED_KEY_USAGE:103:v2i_EXTENDED_KEY_USAGE +X509V3_F_V2I_GENERAL_NAMES:118:v2i_GENERAL_NAMES +X509V3_F_V2I_GENERAL_NAME_EX:117:v2i_GENERAL_NAME_ex +X509V3_F_V2I_IDP:157:v2i_idp +X509V3_F_V2I_IPADDRBLOCKS:159:v2i_IPAddrBlocks +X509V3_F_V2I_ISSUER_ALT:153:v2i_issuer_alt +X509V3_F_V2I_NAME_CONSTRAINTS:147:v2i_NAME_CONSTRAINTS +X509V3_F_V2I_POLICY_CONSTRAINTS:146:v2i_POLICY_CONSTRAINTS +X509V3_F_V2I_POLICY_MAPPINGS:145:v2i_POLICY_MAPPINGS +X509V3_F_V2I_SUBJECT_ALT:154:v2i_subject_alt +X509V3_F_V2I_TLS_FEATURE:165:v2i_TLS_FEATURE +X509V3_F_V3_GENERIC_EXTENSION:116:v3_generic_extension +X509V3_F_X509V3_ADD1_I2D:140:X509V3_add1_i2d +X509V3_F_X509V3_ADD_VALUE:105:X509V3_add_value +X509V3_F_X509V3_EXT_ADD:104:X509V3_EXT_add +X509V3_F_X509V3_EXT_ADD_ALIAS:106:X509V3_EXT_add_alias +X509V3_F_X509V3_EXT_I2D:136:X509V3_EXT_i2d +X509V3_F_X509V3_EXT_NCONF:152:X509V3_EXT_nconf +X509V3_F_X509V3_GET_SECTION:142:X509V3_get_section +X509V3_F_X509V3_GET_STRING:143:X509V3_get_string +X509V3_F_X509V3_GET_VALUE_BOOL:110:X509V3_get_value_bool +X509V3_F_X509V3_PARSE_LIST:109:X509V3_parse_list +X509V3_F_X509_PURPOSE_ADD:137:X509_PURPOSE_add +X509V3_F_X509_PURPOSE_SET:141:X509_PURPOSE_set +X509_F_ADD_CERT_DIR:100:add_cert_dir +X509_F_BUILD_CHAIN:106:build_chain +X509_F_BY_FILE_CTRL:101:by_file_ctrl +X509_F_CHECK_NAME_CONSTRAINTS:149:check_name_constraints +X509_F_CHECK_POLICY:145:check_policy +X509_F_DANE_I2D:107:dane_i2d +X509_F_DIR_CTRL:102:dir_ctrl +X509_F_GET_CERT_BY_SUBJECT:103:get_cert_by_subject +X509_F_NETSCAPE_SPKI_B64_DECODE:129:NETSCAPE_SPKI_b64_decode +X509_F_NETSCAPE_SPKI_B64_ENCODE:130:NETSCAPE_SPKI_b64_encode +X509_F_X509AT_ADD1_ATTR:135:X509at_add1_attr +X509_F_X509V3_ADD_EXT:104:X509v3_add_ext +X509_F_X509_ATTRIBUTE_CREATE_BY_NID:136:X509_ATTRIBUTE_create_by_NID +X509_F_X509_ATTRIBUTE_CREATE_BY_OBJ:137:X509_ATTRIBUTE_create_by_OBJ +X509_F_X509_ATTRIBUTE_CREATE_BY_TXT:140:X509_ATTRIBUTE_create_by_txt +X509_F_X509_ATTRIBUTE_GET0_DATA:139:X509_ATTRIBUTE_get0_data +X509_F_X509_ATTRIBUTE_SET1_DATA:138:X509_ATTRIBUTE_set1_data +X509_F_X509_CHECK_PRIVATE_KEY:128:X509_check_private_key +X509_F_X509_CRL_DIFF:105:X509_CRL_diff +X509_F_X509_CRL_PRINT_FP:147:X509_CRL_print_fp +X509_F_X509_EXTENSION_CREATE_BY_NID:108:X509_EXTENSION_create_by_NID +X509_F_X509_EXTENSION_CREATE_BY_OBJ:109:X509_EXTENSION_create_by_OBJ +X509_F_X509_GET_PUBKEY_PARAMETERS:110:X509_get_pubkey_parameters +X509_F_X509_LOAD_CERT_CRL_FILE:132:X509_load_cert_crl_file +X509_F_X509_LOAD_CERT_FILE:111:X509_load_cert_file +X509_F_X509_LOAD_CRL_FILE:112:X509_load_crl_file +X509_F_X509_NAME_ADD_ENTRY:113:X509_NAME_add_entry +X509_F_X509_NAME_ENTRY_CREATE_BY_NID:114:X509_NAME_ENTRY_create_by_NID +X509_F_X509_NAME_ENTRY_CREATE_BY_TXT:131:X509_NAME_ENTRY_create_by_txt +X509_F_X509_NAME_ENTRY_SET_OBJECT:115:X509_NAME_ENTRY_set_object +X509_F_X509_NAME_ONELINE:116:X509_NAME_oneline +X509_F_X509_NAME_PRINT:117:X509_NAME_print +X509_F_X509_OBJECT_NEW:150:X509_OBJECT_new +X509_F_X509_PRINT_EX_FP:118:X509_print_ex_fp +X509_F_X509_PUBKEY_DECODE:148:x509_pubkey_decode +X509_F_X509_PUBKEY_GET0:119:X509_PUBKEY_get0 +X509_F_X509_PUBKEY_SET:120:X509_PUBKEY_set +X509_F_X509_REQ_CHECK_PRIVATE_KEY:144:X509_REQ_check_private_key +X509_F_X509_REQ_PRINT_EX:121:X509_REQ_print_ex +X509_F_X509_REQ_PRINT_FP:122:X509_REQ_print_fp +X509_F_X509_REQ_TO_X509:123:X509_REQ_to_X509 +X509_F_X509_STORE_ADD_CERT:124:X509_STORE_add_cert +X509_F_X509_STORE_ADD_CRL:125:X509_STORE_add_crl +X509_F_X509_STORE_CTX_GET1_ISSUER:146:X509_STORE_CTX_get1_issuer +X509_F_X509_STORE_CTX_INIT:143:X509_STORE_CTX_init +X509_F_X509_STORE_CTX_NEW:142:X509_STORE_CTX_new +X509_F_X509_STORE_CTX_PURPOSE_INHERIT:134:X509_STORE_CTX_purpose_inherit +X509_F_X509_TO_X509_REQ:126:X509_to_X509_REQ +X509_F_X509_TRUST_ADD:133:X509_TRUST_add +X509_F_X509_TRUST_SET:141:X509_TRUST_set +X509_F_X509_VERIFY_CERT:127:X509_verify_cert + +#Reason codes +ASN1_R_ADDING_OBJECT:171:adding object +ASN1_R_ASN1_PARSE_ERROR:203:asn1 parse error +ASN1_R_ASN1_SIG_PARSE_ERROR:204:asn1 sig parse error +ASN1_R_AUX_ERROR:100:aux error +ASN1_R_BAD_OBJECT_HEADER:102:bad object header +ASN1_R_BMPSTRING_IS_WRONG_LENGTH:214:bmpstring is wrong length +ASN1_R_BN_LIB:105:bn lib +ASN1_R_BOOLEAN_IS_WRONG_LENGTH:106:boolean is wrong length +ASN1_R_BUFFER_TOO_SMALL:107:buffer too small +ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER:108:cipher has no object identifier +ASN1_R_CONTEXT_NOT_INITIALISED:217:context not initialised +ASN1_R_DATA_IS_WRONG:109:data is wrong +ASN1_R_DECODE_ERROR:110:decode error +ASN1_R_DEPTH_EXCEEDED:174:depth exceeded +ASN1_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED:198:digest and key type not supported +ASN1_R_ENCODE_ERROR:112:encode error +ASN1_R_ERROR_GETTING_TIME:173:error getting time +ASN1_R_ERROR_LOADING_SECTION:172:error loading section +ASN1_R_ERROR_SETTING_CIPHER_PARAMS:114:error setting cipher params +ASN1_R_EXPECTING_AN_INTEGER:115:expecting an integer +ASN1_R_EXPECTING_AN_OBJECT:116:expecting an object +ASN1_R_EXPLICIT_LENGTH_MISMATCH:119:explicit length mismatch +ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED:120:explicit tag not constructed +ASN1_R_FIELD_MISSING:121:field missing +ASN1_R_FIRST_NUM_TOO_LARGE:122:first num too large +ASN1_R_HEADER_TOO_LONG:123:header too long +ASN1_R_ILLEGAL_BITSTRING_FORMAT:175:illegal bitstring format +ASN1_R_ILLEGAL_BOOLEAN:176:illegal boolean +ASN1_R_ILLEGAL_CHARACTERS:124:illegal characters +ASN1_R_ILLEGAL_FORMAT:177:illegal format +ASN1_R_ILLEGAL_HEX:178:illegal hex +ASN1_R_ILLEGAL_IMPLICIT_TAG:179:illegal implicit tag +ASN1_R_ILLEGAL_INTEGER:180:illegal integer +ASN1_R_ILLEGAL_NEGATIVE_VALUE:226:illegal negative value +ASN1_R_ILLEGAL_NESTED_TAGGING:181:illegal nested tagging +ASN1_R_ILLEGAL_NULL:125:illegal null +ASN1_R_ILLEGAL_NULL_VALUE:182:illegal null value +ASN1_R_ILLEGAL_OBJECT:183:illegal object +ASN1_R_ILLEGAL_OPTIONAL_ANY:126:illegal optional any +ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE:170:illegal options on item template +ASN1_R_ILLEGAL_PADDING:221:illegal padding +ASN1_R_ILLEGAL_TAGGED_ANY:127:illegal tagged any +ASN1_R_ILLEGAL_TIME_VALUE:184:illegal time value +ASN1_R_ILLEGAL_ZERO_CONTENT:222:illegal zero content +ASN1_R_INTEGER_NOT_ASCII_FORMAT:185:integer not ascii format +ASN1_R_INTEGER_TOO_LARGE_FOR_LONG:128:integer too large for long +ASN1_R_INVALID_BIT_STRING_BITS_LEFT:220:invalid bit string bits left +ASN1_R_INVALID_BMPSTRING_LENGTH:129:invalid bmpstring length +ASN1_R_INVALID_DIGIT:130:invalid digit +ASN1_R_INVALID_MIME_TYPE:205:invalid mime type +ASN1_R_INVALID_MODIFIER:186:invalid modifier +ASN1_R_INVALID_NUMBER:187:invalid number +ASN1_R_INVALID_OBJECT_ENCODING:216:invalid object encoding +ASN1_R_INVALID_SCRYPT_PARAMETERS:227:invalid scrypt parameters +ASN1_R_INVALID_SEPARATOR:131:invalid separator +ASN1_R_INVALID_STRING_TABLE_VALUE:218:invalid string table value +ASN1_R_INVALID_UNIVERSALSTRING_LENGTH:133:invalid universalstring length +ASN1_R_INVALID_UTF8STRING:134:invalid utf8string +ASN1_R_INVALID_VALUE:219:invalid value +ASN1_R_LIST_ERROR:188:list error +ASN1_R_MIME_NO_CONTENT_TYPE:206:mime no content type +ASN1_R_MIME_PARSE_ERROR:207:mime parse error +ASN1_R_MIME_SIG_PARSE_ERROR:208:mime sig parse error +ASN1_R_MISSING_EOC:137:missing eoc +ASN1_R_MISSING_SECOND_NUMBER:138:missing second number +ASN1_R_MISSING_VALUE:189:missing value +ASN1_R_MSTRING_NOT_UNIVERSAL:139:mstring not universal +ASN1_R_MSTRING_WRONG_TAG:140:mstring wrong tag +ASN1_R_NESTED_ASN1_STRING:197:nested asn1 string +ASN1_R_NON_HEX_CHARACTERS:141:non hex characters +ASN1_R_NOT_ASCII_FORMAT:190:not ascii format +ASN1_R_NOT_ENOUGH_DATA:142:not enough data +ASN1_R_NO_CONTENT_TYPE:209:no content type +ASN1_R_NO_MATCHING_CHOICE_TYPE:143:no matching choice type +ASN1_R_NO_MULTIPART_BODY_FAILURE:210:no multipart body failure +ASN1_R_NO_MULTIPART_BOUNDARY:211:no multipart boundary +ASN1_R_NO_SIG_CONTENT_TYPE:212:no sig content type +ASN1_R_NULL_IS_WRONG_LENGTH:144:null is wrong length +ASN1_R_OBJECT_NOT_ASCII_FORMAT:191:object not ascii format +ASN1_R_ODD_NUMBER_OF_CHARS:145:odd number of chars +ASN1_R_SECOND_NUMBER_TOO_LARGE:147:second number too large +ASN1_R_SEQUENCE_LENGTH_MISMATCH:148:sequence length mismatch +ASN1_R_SEQUENCE_NOT_CONSTRUCTED:149:sequence not constructed +ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG:192:sequence or set needs config +ASN1_R_SHORT_LINE:150:short line +ASN1_R_SIG_INVALID_MIME_TYPE:213:sig invalid mime type +ASN1_R_STREAMING_NOT_SUPPORTED:202:streaming not supported +ASN1_R_STRING_TOO_LONG:151:string too long +ASN1_R_STRING_TOO_SHORT:152:string too short +ASN1_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD:154:\ + the asn1 object identifier is not known for this md +ASN1_R_TIME_NOT_ASCII_FORMAT:193:time not ascii format +ASN1_R_TOO_LARGE:223:too large +ASN1_R_TOO_LONG:155:too long +ASN1_R_TOO_SMALL:224:too small +ASN1_R_TYPE_NOT_CONSTRUCTED:156:type not constructed +ASN1_R_TYPE_NOT_PRIMITIVE:195:type not primitive +ASN1_R_UNEXPECTED_EOC:159:unexpected eoc +ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH:215:universalstring is wrong length +ASN1_R_UNKNOWN_FORMAT:160:unknown format +ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM:161:unknown message digest algorithm +ASN1_R_UNKNOWN_OBJECT_TYPE:162:unknown object type +ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE:163:unknown public key type +ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM:199:unknown signature algorithm +ASN1_R_UNKNOWN_TAG:194:unknown tag +ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE:164:unsupported any defined by type +ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE:167:unsupported public key type +ASN1_R_UNSUPPORTED_TYPE:196:unsupported type +ASN1_R_WRONG_INTEGER_TYPE:225:wrong integer type +ASN1_R_WRONG_PUBLIC_KEY_TYPE:200:wrong public key type +ASN1_R_WRONG_TAG:168:wrong tag +ASYNC_R_FAILED_TO_SET_POOL:101:failed to set pool +ASYNC_R_FAILED_TO_SWAP_CONTEXT:102:failed to swap context +ASYNC_R_INIT_FAILED:105:init failed +ASYNC_R_INVALID_POOL_SIZE:103:invalid pool size +BIO_R_ACCEPT_ERROR:100:accept error +BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET:141:addrinfo addr is not af inet +BIO_R_AMBIGUOUS_HOST_OR_SERVICE:129:ambiguous host or service +BIO_R_BAD_FOPEN_MODE:101:bad fopen mode +BIO_R_BROKEN_PIPE:124:broken pipe +BIO_R_CONNECT_ERROR:103:connect error +BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET:107:gethostbyname addr is not af inet +BIO_R_GETSOCKNAME_ERROR:132:getsockname error +BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS:133:getsockname truncated address +BIO_R_GETTING_SOCKTYPE:134:getting socktype +BIO_R_INVALID_ARGUMENT:125:invalid argument +BIO_R_INVALID_SOCKET:135:invalid socket +BIO_R_IN_USE:123:in use +BIO_R_LENGTH_TOO_LONG:102:length too long +BIO_R_LISTEN_V6_ONLY:136:listen v6 only +BIO_R_LOOKUP_RETURNED_NOTHING:142:lookup returned nothing +BIO_R_MALFORMED_HOST_OR_SERVICE:130:malformed host or service +BIO_R_NBIO_CONNECT_ERROR:110:nbio connect error +BIO_R_NO_ACCEPT_ADDR_OR_SERVICE_SPECIFIED:143:\ + no accept addr or service specified +BIO_R_NO_HOSTNAME_OR_SERVICE_SPECIFIED:144:no hostname or service specified +BIO_R_NO_PORT_DEFINED:113:no port defined +BIO_R_NO_SUCH_FILE:128:no such file +BIO_R_NULL_PARAMETER:115:null parameter +BIO_R_UNABLE_TO_BIND_SOCKET:117:unable to bind socket +BIO_R_UNABLE_TO_CREATE_SOCKET:118:unable to create socket +BIO_R_UNABLE_TO_KEEPALIVE:137:unable to keepalive +BIO_R_UNABLE_TO_LISTEN_SOCKET:119:unable to listen socket +BIO_R_UNABLE_TO_NODELAY:138:unable to nodelay +BIO_R_UNABLE_TO_REUSEADDR:139:unable to reuseaddr +BIO_R_UNAVAILABLE_IP_FAMILY:145:unavailable ip family +BIO_R_UNINITIALIZED:120:uninitialized +BIO_R_UNKNOWN_INFO_TYPE:140:unknown info type +BIO_R_UNSUPPORTED_IP_FAMILY:146:unsupported ip family +BIO_R_UNSUPPORTED_METHOD:121:unsupported method +BIO_R_UNSUPPORTED_PROTOCOL_FAMILY:131:unsupported protocol family +BIO_R_WRITE_TO_READ_ONLY_BIO:126:write to read only BIO +BIO_R_WSASTARTUP:122:WSAStartup +BN_R_ARG2_LT_ARG3:100:arg2 lt arg3 +BN_R_BAD_RECIPROCAL:101:bad reciprocal +BN_R_BIGNUM_TOO_LONG:114:bignum too long +BN_R_BITS_TOO_SMALL:118:bits too small +BN_R_CALLED_WITH_EVEN_MODULUS:102:called with even modulus +BN_R_DIV_BY_ZERO:103:div by zero +BN_R_ENCODING_ERROR:104:encoding error +BN_R_EXPAND_ON_STATIC_BIGNUM_DATA:105:expand on static bignum data +BN_R_INPUT_NOT_REDUCED:110:input not reduced +BN_R_INVALID_LENGTH:106:invalid length +BN_R_INVALID_RANGE:115:invalid range +BN_R_INVALID_SHIFT:119:invalid shift +BN_R_NOT_A_SQUARE:111:not a square +BN_R_NOT_INITIALIZED:107:not initialized +BN_R_NO_INVERSE:108:no inverse +BN_R_NO_SOLUTION:116:no solution +BN_R_PRIVATE_KEY_TOO_LARGE:117:private key too large +BN_R_P_IS_NOT_PRIME:112:p is not prime +BN_R_TOO_MANY_ITERATIONS:113:too many iterations +BN_R_TOO_MANY_TEMPORARY_VARIABLES:109:too many temporary variables +CMS_R_ADD_SIGNER_ERROR:99:add signer error +CMS_R_CERTIFICATE_ALREADY_PRESENT:175:certificate already present +CMS_R_CERTIFICATE_HAS_NO_KEYID:160:certificate has no keyid +CMS_R_CERTIFICATE_VERIFY_ERROR:100:certificate verify error +CMS_R_CIPHER_INITIALISATION_ERROR:101:cipher initialisation error +CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR:102:\ + cipher parameter initialisation error +CMS_R_CMS_DATAFINAL_ERROR:103:cms datafinal error +CMS_R_CMS_LIB:104:cms lib +CMS_R_CONTENTIDENTIFIER_MISMATCH:170:contentidentifier mismatch +CMS_R_CONTENT_NOT_FOUND:105:content not found +CMS_R_CONTENT_TYPE_MISMATCH:171:content type mismatch +CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA:106:content type not compressed data +CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA:107:content type not enveloped data +CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA:108:content type not signed data +CMS_R_CONTENT_VERIFY_ERROR:109:content verify error +CMS_R_CTRL_ERROR:110:ctrl error +CMS_R_CTRL_FAILURE:111:ctrl failure +CMS_R_DECRYPT_ERROR:112:decrypt error +CMS_R_ERROR_GETTING_PUBLIC_KEY:113:error getting public key +CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE:114:\ + error reading messagedigest attribute +CMS_R_ERROR_SETTING_KEY:115:error setting key +CMS_R_ERROR_SETTING_RECIPIENTINFO:116:error setting recipientinfo +CMS_R_INVALID_ENCRYPTED_KEY_LENGTH:117:invalid encrypted key length +CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER:176:invalid key encryption parameter +CMS_R_INVALID_KEY_LENGTH:118:invalid key length +CMS_R_MD_BIO_INIT_ERROR:119:md bio init error +CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH:120:\ + messagedigest attribute wrong length +CMS_R_MESSAGEDIGEST_WRONG_LENGTH:121:messagedigest wrong length +CMS_R_MSGSIGDIGEST_ERROR:172:msgsigdigest error +CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE:162:msgsigdigest verification failure +CMS_R_MSGSIGDIGEST_WRONG_LENGTH:163:msgsigdigest wrong length +CMS_R_NEED_ONE_SIGNER:164:need one signer +CMS_R_NOT_A_SIGNED_RECEIPT:165:not a signed receipt +CMS_R_NOT_ENCRYPTED_DATA:122:not encrypted data +CMS_R_NOT_KEK:123:not kek +CMS_R_NOT_KEY_AGREEMENT:181:not key agreement +CMS_R_NOT_KEY_TRANSPORT:124:not key transport +CMS_R_NOT_PWRI:177:not pwri +CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE:125:not supported for this key type +CMS_R_NO_CIPHER:126:no cipher +CMS_R_NO_CONTENT:127:no content +CMS_R_NO_CONTENT_TYPE:173:no content type +CMS_R_NO_DEFAULT_DIGEST:128:no default digest +CMS_R_NO_DIGEST_SET:129:no digest set +CMS_R_NO_KEY:130:no key +CMS_R_NO_KEY_OR_CERT:174:no key or cert +CMS_R_NO_MATCHING_DIGEST:131:no matching digest +CMS_R_NO_MATCHING_RECIPIENT:132:no matching recipient +CMS_R_NO_MATCHING_SIGNATURE:166:no matching signature +CMS_R_NO_MSGSIGDIGEST:167:no msgsigdigest +CMS_R_NO_PASSWORD:178:no password +CMS_R_NO_PRIVATE_KEY:133:no private key +CMS_R_NO_PUBLIC_KEY:134:no public key +CMS_R_NO_RECEIPT_REQUEST:168:no receipt request +CMS_R_NO_SIGNERS:135:no signers +CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE:136:\ + private key does not match certificate +CMS_R_RECEIPT_DECODE_ERROR:169:receipt decode error +CMS_R_RECIPIENT_ERROR:137:recipient error +CMS_R_SIGNER_CERTIFICATE_NOT_FOUND:138:signer certificate not found +CMS_R_SIGNFINAL_ERROR:139:signfinal error +CMS_R_SMIME_TEXT_ERROR:140:smime text error +CMS_R_STORE_INIT_ERROR:141:store init error +CMS_R_TYPE_NOT_COMPRESSED_DATA:142:type not compressed data +CMS_R_TYPE_NOT_DATA:143:type not data +CMS_R_TYPE_NOT_DIGESTED_DATA:144:type not digested data +CMS_R_TYPE_NOT_ENCRYPTED_DATA:145:type not encrypted data +CMS_R_TYPE_NOT_ENVELOPED_DATA:146:type not enveloped data +CMS_R_UNABLE_TO_FINALIZE_CONTEXT:147:unable to finalize context +CMS_R_UNKNOWN_CIPHER:148:unknown cipher +CMS_R_UNKNOWN_DIGEST_ALGORITHM:149:unknown digest algorithm +CMS_R_UNKNOWN_ID:150:unknown id +CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM:151:unsupported compression algorithm +CMS_R_UNSUPPORTED_CONTENT_TYPE:152:unsupported content type +CMS_R_UNSUPPORTED_KEK_ALGORITHM:153:unsupported kek algorithm +CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM:179:\ + unsupported key encryption algorithm +CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE:155:unsupported recipientinfo type +CMS_R_UNSUPPORTED_RECIPIENT_TYPE:154:unsupported recipient type +CMS_R_UNSUPPORTED_TYPE:156:unsupported type +CMS_R_UNWRAP_ERROR:157:unwrap error +CMS_R_UNWRAP_FAILURE:180:unwrap failure +CMS_R_VERIFICATION_FAILURE:158:verification failure +CMS_R_WRAP_ERROR:159:wrap error +COMP_R_ZLIB_DEFLATE_ERROR:99:zlib deflate error +COMP_R_ZLIB_INFLATE_ERROR:100:zlib inflate error +COMP_R_ZLIB_NOT_SUPPORTED:101:zlib not supported +CONF_R_ERROR_LOADING_DSO:110:error loading dso +CONF_R_LIST_CANNOT_BE_NULL:115:list cannot be null +CONF_R_MISSING_CLOSE_SQUARE_BRACKET:100:missing close square bracket +CONF_R_MISSING_EQUAL_SIGN:101:missing equal sign +CONF_R_MISSING_INIT_FUNCTION:112:missing init function +CONF_R_MODULE_INITIALIZATION_ERROR:109:module initialization error +CONF_R_NO_CLOSE_BRACE:102:no close brace +CONF_R_NO_CONF:105:no conf +CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE:106:no conf or environment variable +CONF_R_NO_SECTION:107:no section +CONF_R_NO_SUCH_FILE:114:no such file +CONF_R_NO_VALUE:108:no value +CONF_R_UNABLE_TO_CREATE_NEW_SECTION:103:unable to create new section +CONF_R_UNKNOWN_MODULE_NAME:113:unknown module name +CONF_R_VARIABLE_EXPANSION_TOO_LONG:116:variable expansion too long +CONF_R_VARIABLE_HAS_NO_VALUE:104:variable has no value +CRYPTO_R_FIPS_MODE_NOT_SUPPORTED:101:fips mode not supported +CRYPTO_R_ILLEGAL_HEX_DIGIT:102:illegal hex digit +CRYPTO_R_ODD_NUMBER_OF_DIGITS:103:odd number of digits +CT_R_BASE64_DECODE_ERROR:108:base64 decode error +CT_R_INVALID_LOG_ID_LENGTH:100:invalid log id length +CT_R_LOG_CONF_INVALID:109:log conf invalid +CT_R_LOG_CONF_INVALID_KEY:110:log conf invalid key +CT_R_LOG_CONF_MISSING_DESCRIPTION:111:log conf missing description +CT_R_LOG_CONF_MISSING_KEY:112:log conf missing key +CT_R_LOG_KEY_INVALID:113:log key invalid +CT_R_SCT_FUTURE_TIMESTAMP:116:sct future timestamp +CT_R_SCT_INVALID:104:sct invalid +CT_R_SCT_INVALID_SIGNATURE:107:sct invalid signature +CT_R_SCT_LIST_INVALID:105:sct list invalid +CT_R_SCT_LOG_ID_MISMATCH:114:sct log id mismatch +CT_R_SCT_NOT_SET:106:sct not set +CT_R_SCT_UNSUPPORTED_VERSION:115:sct unsupported version +CT_R_UNRECOGNIZED_SIGNATURE_NID:101:unrecognized signature nid +CT_R_UNSUPPORTED_ENTRY_TYPE:102:unsupported entry type +CT_R_UNSUPPORTED_VERSION:103:unsupported version +DH_R_BAD_GENERATOR:101:bad generator +DH_R_BN_DECODE_ERROR:109:bn decode error +DH_R_BN_ERROR:106:bn error +DH_R_CHECK_INVALID_J_VALUE:115:check invalid j value +DH_R_CHECK_INVALID_Q_VALUE:116:check invalid q value +DH_R_CHECK_PUBKEY_INVALID:122:check pubkey invalid +DH_R_CHECK_PUBKEY_TOO_LARGE:123:check pubkey too large +DH_R_CHECK_PUBKEY_TOO_SMALL:124:check pubkey too small +DH_R_CHECK_P_NOT_PRIME:117:check p not prime +DH_R_CHECK_P_NOT_SAFE_PRIME:118:check p not safe prime +DH_R_CHECK_Q_NOT_PRIME:119:check q not prime +DH_R_DECODE_ERROR:104:decode error +DH_R_INVALID_PARAMETER_NAME:110:invalid parameter name +DH_R_INVALID_PARAMETER_NID:114:invalid parameter nid +DH_R_INVALID_PUBKEY:102:invalid public key +DH_R_KDF_PARAMETER_ERROR:112:kdf parameter error +DH_R_KEYS_NOT_SET:108:keys not set +DH_R_MISSING_PUBKEY:125:missing pubkey +DH_R_MODULUS_TOO_LARGE:103:modulus too large +DH_R_NOT_SUITABLE_GENERATOR:120:not suitable generator +DH_R_NO_PARAMETERS_SET:107:no parameters set +DH_R_NO_PRIVATE_VALUE:100:no private value +DH_R_PARAMETER_ENCODING_ERROR:105:parameter encoding error +DH_R_PEER_KEY_ERROR:111:peer key error +DH_R_SHARED_INFO_ERROR:113:shared info error +DH_R_UNABLE_TO_CHECK_GENERATOR:121:unable to check generator +DSA_R_BAD_Q_VALUE:102:bad q value +DSA_R_BN_DECODE_ERROR:108:bn decode error +DSA_R_BN_ERROR:109:bn error +DSA_R_DECODE_ERROR:104:decode error +DSA_R_INVALID_DIGEST_TYPE:106:invalid digest type +DSA_R_INVALID_PARAMETERS:112:invalid parameters +DSA_R_MISSING_PARAMETERS:101:missing parameters +DSA_R_MODULUS_TOO_LARGE:103:modulus too large +DSA_R_NO_PARAMETERS_SET:107:no parameters set +DSA_R_PARAMETER_ENCODING_ERROR:105:parameter encoding error +DSA_R_Q_NOT_PRIME:113:q not prime +DSA_R_SEED_LEN_SMALL:110:seed_len is less than the length of q +DSO_R_CTRL_FAILED:100:control command failed +DSO_R_DSO_ALREADY_LOADED:110:dso already loaded +DSO_R_EMPTY_FILE_STRUCTURE:113:empty file structure +DSO_R_FAILURE:114:failure +DSO_R_FILENAME_TOO_BIG:101:filename too big +DSO_R_FINISH_FAILED:102:cleanup method function failed +DSO_R_INCORRECT_FILE_SYNTAX:115:incorrect file syntax +DSO_R_LOAD_FAILED:103:could not load the shared library +DSO_R_NAME_TRANSLATION_FAILED:109:name translation failed +DSO_R_NO_FILENAME:111:no filename +DSO_R_NULL_HANDLE:104:a null shared library handle was used +DSO_R_SET_FILENAME_FAILED:112:set filename failed +DSO_R_STACK_ERROR:105:the meth_data stack is corrupt +DSO_R_SYM_FAILURE:106:could not bind to the requested symbol name +DSO_R_UNLOAD_FAILED:107:could not unload the shared library +DSO_R_UNSUPPORTED:108:functionality not supported +EC_R_ASN1_ERROR:115:asn1 error +EC_R_BAD_SIGNATURE:156:bad signature +EC_R_BIGNUM_OUT_OF_RANGE:144:bignum out of range +EC_R_BUFFER_TOO_SMALL:100:buffer too small +EC_R_COORDINATES_OUT_OF_RANGE:146:coordinates out of range +EC_R_CURVE_DOES_NOT_SUPPORT_ECDH:160:curve does not support ecdh +EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING:159:curve does not support signing +EC_R_D2I_ECPKPARAMETERS_FAILURE:117:d2i ecpkparameters failure +EC_R_DECODE_ERROR:142:decode error +EC_R_DISCRIMINANT_IS_ZERO:118:discriminant is zero +EC_R_EC_GROUP_NEW_BY_NAME_FAILURE:119:ec group new by name failure +EC_R_FIELD_TOO_LARGE:143:field too large +EC_R_GF2M_NOT_SUPPORTED:147:gf2m not supported +EC_R_GROUP2PKPARAMETERS_FAILURE:120:group2pkparameters failure +EC_R_I2D_ECPKPARAMETERS_FAILURE:121:i2d ecpkparameters failure +EC_R_INCOMPATIBLE_OBJECTS:101:incompatible objects +EC_R_INVALID_ARGUMENT:112:invalid argument +EC_R_INVALID_COMPRESSED_POINT:110:invalid compressed point +EC_R_INVALID_COMPRESSION_BIT:109:invalid compression bit +EC_R_INVALID_CURVE:141:invalid curve +EC_R_INVALID_DIGEST:151:invalid digest +EC_R_INVALID_DIGEST_TYPE:138:invalid digest type +EC_R_INVALID_ENCODING:102:invalid encoding +EC_R_INVALID_FIELD:103:invalid field +EC_R_INVALID_FORM:104:invalid form +EC_R_INVALID_GROUP_ORDER:122:invalid group order +EC_R_INVALID_KEY:116:invalid key +EC_R_INVALID_OUTPUT_LENGTH:161:invalid output length +EC_R_INVALID_PEER_KEY:133:invalid peer key +EC_R_INVALID_PENTANOMIAL_BASIS:132:invalid pentanomial basis +EC_R_INVALID_PRIVATE_KEY:123:invalid private key +EC_R_INVALID_TRINOMIAL_BASIS:137:invalid trinomial basis +EC_R_KDF_PARAMETER_ERROR:148:kdf parameter error +EC_R_KEYS_NOT_SET:140:keys not set +EC_R_MISSING_PARAMETERS:124:missing parameters +EC_R_MISSING_PRIVATE_KEY:125:missing private key +EC_R_NEED_NEW_SETUP_VALUES:157:need new setup values +EC_R_NOT_A_NIST_PRIME:135:not a NIST prime +EC_R_NOT_IMPLEMENTED:126:not implemented +EC_R_NOT_INITIALIZED:111:not initialized +EC_R_NO_PARAMETERS_SET:139:no parameters set +EC_R_NO_PRIVATE_VALUE:154:no private value +EC_R_OPERATION_NOT_SUPPORTED:152:operation not supported +EC_R_PASSED_NULL_PARAMETER:134:passed null parameter +EC_R_PEER_KEY_ERROR:149:peer key error +EC_R_PKPARAMETERS2GROUP_FAILURE:127:pkparameters2group failure +EC_R_POINT_ARITHMETIC_FAILURE:155:point arithmetic failure +EC_R_POINT_AT_INFINITY:106:point at infinity +EC_R_POINT_IS_NOT_ON_CURVE:107:point is not on curve +EC_R_RANDOM_NUMBER_GENERATION_FAILED:158:random number generation failed +EC_R_SHARED_INFO_ERROR:150:shared info error +EC_R_SLOT_FULL:108:slot full +EC_R_UNDEFINED_GENERATOR:113:undefined generator +EC_R_UNDEFINED_ORDER:128:undefined order +EC_R_UNKNOWN_GROUP:129:unknown group +EC_R_UNKNOWN_ORDER:114:unknown order +EC_R_UNSUPPORTED_FIELD:131:unsupported field +EC_R_WRONG_CURVE_PARAMETERS:145:wrong curve parameters +EC_R_WRONG_ORDER:130:wrong order +ENGINE_R_ALREADY_LOADED:100:already loaded +ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER:133:argument is not a number +ENGINE_R_CMD_NOT_EXECUTABLE:134:cmd not executable +ENGINE_R_COMMAND_TAKES_INPUT:135:command takes input +ENGINE_R_COMMAND_TAKES_NO_INPUT:136:command takes no input +ENGINE_R_CONFLICTING_ENGINE_ID:103:conflicting engine id +ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED:119:ctrl command not implemented +ENGINE_R_DSO_FAILURE:104:DSO failure +ENGINE_R_DSO_NOT_FOUND:132:dso not found +ENGINE_R_ENGINES_SECTION_ERROR:148:engines section error +ENGINE_R_ENGINE_CONFIGURATION_ERROR:102:engine configuration error +ENGINE_R_ENGINE_IS_NOT_IN_LIST:105:engine is not in the list +ENGINE_R_ENGINE_SECTION_ERROR:149:engine section error +ENGINE_R_FAILED_LOADING_PRIVATE_KEY:128:failed loading private key +ENGINE_R_FAILED_LOADING_PUBLIC_KEY:129:failed loading public key +ENGINE_R_FINISH_FAILED:106:finish failed +ENGINE_R_ID_OR_NAME_MISSING:108:'id' or 'name' missing +ENGINE_R_INIT_FAILED:109:init failed +ENGINE_R_INTERNAL_LIST_ERROR:110:internal list error +ENGINE_R_INVALID_ARGUMENT:143:invalid argument +ENGINE_R_INVALID_CMD_NAME:137:invalid cmd name +ENGINE_R_INVALID_CMD_NUMBER:138:invalid cmd number +ENGINE_R_INVALID_INIT_VALUE:151:invalid init value +ENGINE_R_INVALID_STRING:150:invalid string +ENGINE_R_NOT_INITIALISED:117:not initialised +ENGINE_R_NOT_LOADED:112:not loaded +ENGINE_R_NO_CONTROL_FUNCTION:120:no control function +ENGINE_R_NO_INDEX:144:no index +ENGINE_R_NO_LOAD_FUNCTION:125:no load function +ENGINE_R_NO_REFERENCE:130:no reference +ENGINE_R_NO_SUCH_ENGINE:116:no such engine +ENGINE_R_UNIMPLEMENTED_CIPHER:146:unimplemented cipher +ENGINE_R_UNIMPLEMENTED_DIGEST:147:unimplemented digest +ENGINE_R_UNIMPLEMENTED_PUBLIC_KEY_METHOD:101:unimplemented public key method +ENGINE_R_VERSION_INCOMPATIBILITY:145:version incompatibility +EVP_R_AES_KEY_SETUP_FAILED:143:aes key setup failed +EVP_R_ARIA_KEY_SETUP_FAILED:176:aria key setup failed +EVP_R_BAD_DECRYPT:100:bad decrypt +EVP_R_BUFFER_TOO_SMALL:155:buffer too small +EVP_R_CAMELLIA_KEY_SETUP_FAILED:157:camellia key setup failed +EVP_R_CIPHER_PARAMETER_ERROR:122:cipher parameter error +EVP_R_COMMAND_NOT_SUPPORTED:147:command not supported +EVP_R_COPY_ERROR:173:copy error +EVP_R_CTRL_NOT_IMPLEMENTED:132:ctrl not implemented +EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED:133:ctrl operation not implemented +EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH:138:data not multiple of block length +EVP_R_DECODE_ERROR:114:decode error +EVP_R_DIFFERENT_KEY_TYPES:101:different key types +EVP_R_DIFFERENT_PARAMETERS:153:different parameters +EVP_R_ERROR_LOADING_SECTION:165:error loading section +EVP_R_ERROR_SETTING_FIPS_MODE:166:error setting fips mode +EVP_R_EXPECTING_AN_HMAC_KEY:174:expecting an hmac key +EVP_R_EXPECTING_AN_RSA_KEY:127:expecting an rsa key +EVP_R_EXPECTING_A_DH_KEY:128:expecting a dh key +EVP_R_EXPECTING_A_DSA_KEY:129:expecting a dsa key +EVP_R_EXPECTING_A_EC_KEY:142:expecting a ec key +EVP_R_EXPECTING_A_POLY1305_KEY:164:expecting a poly1305 key +EVP_R_EXPECTING_A_SIPHASH_KEY:175:expecting a siphash key +EVP_R_FIPS_MODE_NOT_SUPPORTED:167:fips mode not supported +EVP_R_ILLEGAL_SCRYPT_PARAMETERS:171:illegal scrypt parameters +EVP_R_INITIALIZATION_ERROR:134:initialization error +EVP_R_INPUT_NOT_INITIALIZED:111:input not initialized +EVP_R_INVALID_DIGEST:152:invalid digest +EVP_R_INVALID_FIPS_MODE:168:invalid fips mode +EVP_R_INVALID_KEY:163:invalid key +EVP_R_INVALID_KEY_LENGTH:130:invalid key length +EVP_R_INVALID_OPERATION:148:invalid operation +EVP_R_KEYGEN_FAILURE:120:keygen failure +EVP_R_MEMORY_LIMIT_EXCEEDED:172:memory limit exceeded +EVP_R_MESSAGE_DIGEST_IS_NULL:159:message digest is null +EVP_R_METHOD_NOT_SUPPORTED:144:method not supported +EVP_R_MISSING_PARAMETERS:103:missing parameters +EVP_R_NOT_XOF_OR_INVALID_LENGTH:178:not XOF or invalid length +EVP_R_NO_CIPHER_SET:131:no cipher set +EVP_R_NO_DEFAULT_DIGEST:158:no default digest +EVP_R_NO_DIGEST_SET:139:no digest set +EVP_R_NO_KEY_SET:154:no key set +EVP_R_NO_OPERATION_SET:149:no operation set +EVP_R_ONLY_ONESHOT_SUPPORTED:177:only oneshot supported +EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE:150:\ + operation not supported for this keytype +EVP_R_OPERATON_NOT_INITIALIZED:151:operaton not initialized +EVP_R_PARTIALLY_OVERLAPPING:162:partially overlapping buffers +EVP_R_PKEY_APPLICATION_ASN1_METHOD_ALREADY_REGISTERED:179:\ + pkey application asn1 method already registered +EVP_R_PRIVATE_KEY_DECODE_ERROR:145:private key decode error +EVP_R_PRIVATE_KEY_ENCODE_ERROR:146:private key encode error +EVP_R_PUBLIC_KEY_NOT_RSA:106:public key not rsa +EVP_R_UNKNOWN_CIPHER:160:unknown cipher +EVP_R_UNKNOWN_DIGEST:161:unknown digest +EVP_R_UNKNOWN_OPTION:169:unknown option +EVP_R_UNKNOWN_PBE_ALGORITHM:121:unknown pbe algorithm +EVP_R_UNSUPPORTED_ALGORITHM:156:unsupported algorithm +EVP_R_UNSUPPORTED_CIPHER:107:unsupported cipher +EVP_R_UNSUPPORTED_KEYLENGTH:123:unsupported keylength +EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION:124:\ + unsupported key derivation function +EVP_R_UNSUPPORTED_KEY_SIZE:108:unsupported key size +EVP_R_UNSUPPORTED_NUMBER_OF_ROUNDS:135:unsupported number of rounds +EVP_R_UNSUPPORTED_PRF:125:unsupported prf +EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM:118:unsupported private key algorithm +EVP_R_UNSUPPORTED_SALT_TYPE:126:unsupported salt type +EVP_R_WRAP_MODE_NOT_ALLOWED:170:wrap mode not allowed +EVP_R_WRONG_FINAL_BLOCK_LENGTH:109:wrong final block length +KDF_R_INVALID_DIGEST:100:invalid digest +KDF_R_MISSING_ITERATION_COUNT:109:missing iteration count +KDF_R_MISSING_KEY:104:missing key +KDF_R_MISSING_MESSAGE_DIGEST:105:missing message digest +KDF_R_MISSING_PARAMETER:101:missing parameter +KDF_R_MISSING_PASS:110:missing pass +KDF_R_MISSING_SALT:111:missing salt +KDF_R_MISSING_SECRET:107:missing secret +KDF_R_MISSING_SEED:106:missing seed +KDF_R_UNKNOWN_PARAMETER_TYPE:103:unknown parameter type +KDF_R_VALUE_ERROR:108:value error +KDF_R_VALUE_MISSING:102:value missing +OBJ_R_OID_EXISTS:102:oid exists +OBJ_R_UNKNOWN_NID:101:unknown nid +OCSP_R_CERTIFICATE_VERIFY_ERROR:101:certificate verify error +OCSP_R_DIGEST_ERR:102:digest err +OCSP_R_ERROR_IN_NEXTUPDATE_FIELD:122:error in nextupdate field +OCSP_R_ERROR_IN_THISUPDATE_FIELD:123:error in thisupdate field +OCSP_R_ERROR_PARSING_URL:121:error parsing url +OCSP_R_MISSING_OCSPSIGNING_USAGE:103:missing ocspsigning usage +OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE:124:nextupdate before thisupdate +OCSP_R_NOT_BASIC_RESPONSE:104:not basic response +OCSP_R_NO_CERTIFICATES_IN_CHAIN:105:no certificates in chain +OCSP_R_NO_RESPONSE_DATA:108:no response data +OCSP_R_NO_REVOKED_TIME:109:no revoked time +OCSP_R_NO_SIGNER_KEY:130:no signer key +OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE:110:\ + private key does not match certificate +OCSP_R_REQUEST_NOT_SIGNED:128:request not signed +OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA:111:\ + response contains no revocation data +OCSP_R_ROOT_CA_NOT_TRUSTED:112:root ca not trusted +OCSP_R_SERVER_RESPONSE_ERROR:114:server response error +OCSP_R_SERVER_RESPONSE_PARSE_ERROR:115:server response parse error +OCSP_R_SIGNATURE_FAILURE:117:signature failure +OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND:118:signer certificate not found +OCSP_R_STATUS_EXPIRED:125:status expired +OCSP_R_STATUS_NOT_YET_VALID:126:status not yet valid +OCSP_R_STATUS_TOO_OLD:127:status too old +OCSP_R_UNKNOWN_MESSAGE_DIGEST:119:unknown message digest +OCSP_R_UNKNOWN_NID:120:unknown nid +OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE:129:unsupported requestorname type +OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE:107:ambiguous content type +OSSL_STORE_R_BAD_PASSWORD_READ:115:bad password read +OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC:113:error verifying pkcs12 mac +OSSL_STORE_R_FINGERPRINT_SIZE_DOES_NOT_MATCH_DIGEST:121:\ + fingerprint size does not match digest +OSSL_STORE_R_INVALID_SCHEME:106:invalid scheme +OSSL_STORE_R_IS_NOT_A:112:is not a +OSSL_STORE_R_LOADER_INCOMPLETE:116:loader incomplete +OSSL_STORE_R_LOADING_STARTED:117:loading started +OSSL_STORE_R_NOT_A_CERTIFICATE:100:not a certificate +OSSL_STORE_R_NOT_A_CRL:101:not a crl +OSSL_STORE_R_NOT_A_KEY:102:not a key +OSSL_STORE_R_NOT_A_NAME:103:not a name +OSSL_STORE_R_NOT_PARAMETERS:104:not parameters +OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR:114:passphrase callback error +OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE:108:path must be absolute +OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES:119:\ + search only supported for directories +OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED:109:\ + ui process interrupted or cancelled +OSSL_STORE_R_UNREGISTERED_SCHEME:105:unregistered scheme +OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE:110:unsupported content type +OSSL_STORE_R_UNSUPPORTED_OPERATION:118:unsupported operation +OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE:120:unsupported search type +OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED:111:uri authority unsupported +PEM_R_BAD_BASE64_DECODE:100:bad base64 decode +PEM_R_BAD_DECRYPT:101:bad decrypt +PEM_R_BAD_END_LINE:102:bad end line +PEM_R_BAD_IV_CHARS:103:bad iv chars +PEM_R_BAD_MAGIC_NUMBER:116:bad magic number +PEM_R_BAD_PASSWORD_READ:104:bad password read +PEM_R_BAD_VERSION_NUMBER:117:bad version number +PEM_R_BIO_WRITE_FAILURE:118:bio write failure +PEM_R_CIPHER_IS_NULL:127:cipher is null +PEM_R_ERROR_CONVERTING_PRIVATE_KEY:115:error converting private key +PEM_R_EXPECTING_PRIVATE_KEY_BLOB:119:expecting private key blob +PEM_R_EXPECTING_PUBLIC_KEY_BLOB:120:expecting public key blob +PEM_R_HEADER_TOO_LONG:128:header too long +PEM_R_INCONSISTENT_HEADER:121:inconsistent header +PEM_R_KEYBLOB_HEADER_PARSE_ERROR:122:keyblob header parse error +PEM_R_KEYBLOB_TOO_SHORT:123:keyblob too short +PEM_R_MISSING_DEK_IV:129:missing dek iv +PEM_R_NOT_DEK_INFO:105:not dek info +PEM_R_NOT_ENCRYPTED:106:not encrypted +PEM_R_NOT_PROC_TYPE:107:not proc type +PEM_R_NO_START_LINE:108:no start line +PEM_R_PROBLEMS_GETTING_PASSWORD:109:problems getting password +PEM_R_PVK_DATA_TOO_SHORT:124:pvk data too short +PEM_R_PVK_TOO_SHORT:125:pvk too short +PEM_R_READ_KEY:111:read key +PEM_R_SHORT_HEADER:112:short header +PEM_R_UNEXPECTED_DEK_IV:130:unexpected dek iv +PEM_R_UNSUPPORTED_CIPHER:113:unsupported cipher +PEM_R_UNSUPPORTED_ENCRYPTION:114:unsupported encryption +PEM_R_UNSUPPORTED_KEY_COMPONENTS:126:unsupported key components +PKCS12_R_CANT_PACK_STRUCTURE:100:cant pack structure +PKCS12_R_CONTENT_TYPE_NOT_DATA:121:content type not data +PKCS12_R_DECODE_ERROR:101:decode error +PKCS12_R_ENCODE_ERROR:102:encode error +PKCS12_R_ENCRYPT_ERROR:103:encrypt error +PKCS12_R_ERROR_SETTING_ENCRYPTED_DATA_TYPE:120:error setting encrypted data type +PKCS12_R_INVALID_NULL_ARGUMENT:104:invalid null argument +PKCS12_R_INVALID_NULL_PKCS12_POINTER:105:invalid null pkcs12 pointer +PKCS12_R_IV_GEN_ERROR:106:iv gen error +PKCS12_R_KEY_GEN_ERROR:107:key gen error +PKCS12_R_MAC_ABSENT:108:mac absent +PKCS12_R_MAC_GENERATION_ERROR:109:mac generation error +PKCS12_R_MAC_SETUP_ERROR:110:mac setup error +PKCS12_R_MAC_STRING_SET_ERROR:111:mac string set error +PKCS12_R_MAC_VERIFY_FAILURE:113:mac verify failure +PKCS12_R_PARSE_ERROR:114:parse error +PKCS12_R_PKCS12_ALGOR_CIPHERINIT_ERROR:115:pkcs12 algor cipherinit error +PKCS12_R_PKCS12_CIPHERFINAL_ERROR:116:pkcs12 cipherfinal error +PKCS12_R_PKCS12_PBE_CRYPT_ERROR:117:pkcs12 pbe crypt error +PKCS12_R_UNKNOWN_DIGEST_ALGORITHM:118:unknown digest algorithm +PKCS12_R_UNSUPPORTED_PKCS12_MODE:119:unsupported pkcs12 mode +PKCS7_R_CERTIFICATE_VERIFY_ERROR:117:certificate verify error +PKCS7_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER:144:cipher has no object identifier +PKCS7_R_CIPHER_NOT_INITIALIZED:116:cipher not initialized +PKCS7_R_CONTENT_AND_DATA_PRESENT:118:content and data present +PKCS7_R_CTRL_ERROR:152:ctrl error +PKCS7_R_DECRYPT_ERROR:119:decrypt error +PKCS7_R_DIGEST_FAILURE:101:digest failure +PKCS7_R_ENCRYPTION_CTRL_FAILURE:149:encryption ctrl failure +PKCS7_R_ENCRYPTION_NOT_SUPPORTED_FOR_THIS_KEY_TYPE:150:\ + encryption not supported for this key type +PKCS7_R_ERROR_ADDING_RECIPIENT:120:error adding recipient +PKCS7_R_ERROR_SETTING_CIPHER:121:error setting cipher +PKCS7_R_INVALID_NULL_POINTER:143:invalid null pointer +PKCS7_R_INVALID_SIGNED_DATA_TYPE:155:invalid signed data type +PKCS7_R_NO_CONTENT:122:no content +PKCS7_R_NO_DEFAULT_DIGEST:151:no default digest +PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND:154:no matching digest type found +PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE:115:no recipient matches certificate +PKCS7_R_NO_SIGNATURES_ON_DATA:123:no signatures on data +PKCS7_R_NO_SIGNERS:142:no signers +PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE:104:\ + operation not supported on this type +PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR:124:pkcs7 add signature error +PKCS7_R_PKCS7_ADD_SIGNER_ERROR:153:pkcs7 add signer error +PKCS7_R_PKCS7_DATASIGN:145:pkcs7 datasign +PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE:127:\ + private key does not match certificate +PKCS7_R_SIGNATURE_FAILURE:105:signature failure +PKCS7_R_SIGNER_CERTIFICATE_NOT_FOUND:128:signer certificate not found +PKCS7_R_SIGNING_CTRL_FAILURE:147:signing ctrl failure +PKCS7_R_SIGNING_NOT_SUPPORTED_FOR_THIS_KEY_TYPE:148:\ + signing not supported for this key type +PKCS7_R_SMIME_TEXT_ERROR:129:smime text error +PKCS7_R_UNABLE_TO_FIND_CERTIFICATE:106:unable to find certificate +PKCS7_R_UNABLE_TO_FIND_MEM_BIO:107:unable to find mem bio +PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST:108:unable to find message digest +PKCS7_R_UNKNOWN_DIGEST_TYPE:109:unknown digest type +PKCS7_R_UNKNOWN_OPERATION:110:unknown operation +PKCS7_R_UNSUPPORTED_CIPHER_TYPE:111:unsupported cipher type +PKCS7_R_UNSUPPORTED_CONTENT_TYPE:112:unsupported content type +PKCS7_R_WRONG_CONTENT_TYPE:113:wrong content type +PKCS7_R_WRONG_PKCS7_TYPE:114:wrong pkcs7 type +RAND_R_ADDITIONAL_INPUT_TOO_LONG:102:additional input too long +RAND_R_ALREADY_INSTANTIATED:103:already instantiated +RAND_R_ARGUMENT_OUT_OF_RANGE:105:argument out of range +RAND_R_CANNOT_OPEN_FILE:121:Cannot open file +RAND_R_DRBG_ALREADY_INITIALIZED:129:drbg already initialized +RAND_R_DRBG_NOT_INITIALISED:104:drbg not initialised +RAND_R_ENTROPY_INPUT_TOO_LONG:106:entropy input too long +RAND_R_ENTROPY_OUT_OF_RANGE:124:entropy out of range +RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED:127:error entropy pool was ignored +RAND_R_ERROR_INITIALISING_DRBG:107:error initialising drbg +RAND_R_ERROR_INSTANTIATING_DRBG:108:error instantiating drbg +RAND_R_ERROR_RETRIEVING_ADDITIONAL_INPUT:109:error retrieving additional input +RAND_R_ERROR_RETRIEVING_ENTROPY:110:error retrieving entropy +RAND_R_ERROR_RETRIEVING_NONCE:111:error retrieving nonce +RAND_R_FAILED_TO_CREATE_LOCK:126:failed to create lock +RAND_R_FUNC_NOT_IMPLEMENTED:101:Function not implemented +RAND_R_FWRITE_ERROR:123:Error writing file +RAND_R_GENERATE_ERROR:112:generate error +RAND_R_INTERNAL_ERROR:113:internal error +RAND_R_IN_ERROR_STATE:114:in error state +RAND_R_NOT_A_REGULAR_FILE:122:Not a regular file +RAND_R_NOT_INSTANTIATED:115:not instantiated +RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED:128:no drbg implementation selected +RAND_R_PARENT_LOCKING_NOT_ENABLED:130:parent locking not enabled +RAND_R_PERSONALISATION_STRING_TOO_LONG:116:personalisation string too long +RAND_R_PRNG_NOT_SEEDED:100:PRNG not seeded +RAND_R_RANDOM_POOL_OVERFLOW:125:random pool overflow +RAND_R_REQUEST_TOO_LARGE_FOR_DRBG:117:request too large for drbg +RAND_R_RESEED_ERROR:118:reseed error +RAND_R_SELFTEST_FAILURE:119:selftest failure +RAND_R_UNSUPPORTED_DRBG_TYPE:120:unsupported drbg type +RSA_R_ALGORITHM_MISMATCH:100:algorithm mismatch +RSA_R_BAD_E_VALUE:101:bad e value +RSA_R_BAD_FIXED_HEADER_DECRYPT:102:bad fixed header decrypt +RSA_R_BAD_PAD_BYTE_COUNT:103:bad pad byte count +RSA_R_BAD_SIGNATURE:104:bad signature +RSA_R_BLOCK_TYPE_IS_NOT_01:106:block type is not 01 +RSA_R_BLOCK_TYPE_IS_NOT_02:107:block type is not 02 +RSA_R_DATA_GREATER_THAN_MOD_LEN:108:data greater than mod len +RSA_R_DATA_TOO_LARGE:109:data too large +RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE:110:data too large for key size +RSA_R_DATA_TOO_LARGE_FOR_MODULUS:132:data too large for modulus +RSA_R_DATA_TOO_SMALL:111:data too small +RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE:122:data too small for key size +RSA_R_DIGEST_DOES_NOT_MATCH:158:digest does not match +RSA_R_DIGEST_NOT_ALLOWED:145:digest not allowed +RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY:112:digest too big for rsa key +RSA_R_DMP1_NOT_CONGRUENT_TO_D:124:dmp1 not congruent to d +RSA_R_DMQ1_NOT_CONGRUENT_TO_D:125:dmq1 not congruent to d +RSA_R_D_E_NOT_CONGRUENT_TO_1:123:d e not congruent to 1 +RSA_R_FIRST_OCTET_INVALID:133:first octet invalid +RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE:144:\ + illegal or unsupported padding mode +RSA_R_INVALID_DIGEST:157:invalid digest +RSA_R_INVALID_DIGEST_LENGTH:143:invalid digest length +RSA_R_INVALID_HEADER:137:invalid header +RSA_R_INVALID_LABEL:160:invalid label +RSA_R_INVALID_MESSAGE_LENGTH:131:invalid message length +RSA_R_INVALID_MGF1_MD:156:invalid mgf1 md +RSA_R_INVALID_MULTI_PRIME_KEY:167:invalid multi prime key +RSA_R_INVALID_OAEP_PARAMETERS:161:invalid oaep parameters +RSA_R_INVALID_PADDING:138:invalid padding +RSA_R_INVALID_PADDING_MODE:141:invalid padding mode +RSA_R_INVALID_PSS_PARAMETERS:149:invalid pss parameters +RSA_R_INVALID_PSS_SALTLEN:146:invalid pss saltlen +RSA_R_INVALID_SALT_LENGTH:150:invalid salt length +RSA_R_INVALID_TRAILER:139:invalid trailer +RSA_R_INVALID_X931_DIGEST:142:invalid x931 digest +RSA_R_IQMP_NOT_INVERSE_OF_Q:126:iqmp not inverse of q +RSA_R_KEY_PRIME_NUM_INVALID:165:key prime num invalid +RSA_R_KEY_SIZE_TOO_SMALL:120:key size too small +RSA_R_LAST_OCTET_INVALID:134:last octet invalid +RSA_R_MGF1_DIGEST_NOT_ALLOWED:152:mgf1 digest not allowed +RSA_R_MODULUS_TOO_LARGE:105:modulus too large +RSA_R_MP_COEFFICIENT_NOT_INVERSE_OF_R:168:mp coefficient not inverse of r +RSA_R_MP_EXPONENT_NOT_CONGRUENT_TO_D:169:mp exponent not congruent to d +RSA_R_MP_R_NOT_PRIME:170:mp r not prime +RSA_R_NO_PUBLIC_EXPONENT:140:no public exponent +RSA_R_NULL_BEFORE_BLOCK_MISSING:113:null before block missing +RSA_R_N_DOES_NOT_EQUAL_PRODUCT_OF_PRIMES:172:n does not equal product of primes +RSA_R_N_DOES_NOT_EQUAL_P_Q:127:n does not equal p q +RSA_R_OAEP_DECODING_ERROR:121:oaep decoding error +RSA_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE:148:\ + operation not supported for this keytype +RSA_R_PADDING_CHECK_FAILED:114:padding check failed +RSA_R_PKCS_DECODING_ERROR:159:pkcs decoding error +RSA_R_PSS_SALTLEN_TOO_SMALL:164:pss saltlen too small +RSA_R_P_NOT_PRIME:128:p not prime +RSA_R_Q_NOT_PRIME:129:q not prime +RSA_R_RSA_OPERATIONS_NOT_SUPPORTED:130:rsa operations not supported +RSA_R_SLEN_CHECK_FAILED:136:salt length check failed +RSA_R_SLEN_RECOVERY_FAILED:135:salt length recovery failed +RSA_R_SSLV3_ROLLBACK_ATTACK:115:sslv3 rollback attack +RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD:116:\ + the asn1 object identifier is not known for this md +RSA_R_UNKNOWN_ALGORITHM_TYPE:117:unknown algorithm type +RSA_R_UNKNOWN_DIGEST:166:unknown digest +RSA_R_UNKNOWN_MASK_DIGEST:151:unknown mask digest +RSA_R_UNKNOWN_PADDING_TYPE:118:unknown padding type +RSA_R_UNSUPPORTED_ENCRYPTION_TYPE:162:unsupported encryption type +RSA_R_UNSUPPORTED_LABEL_SOURCE:163:unsupported label source +RSA_R_UNSUPPORTED_MASK_ALGORITHM:153:unsupported mask algorithm +RSA_R_UNSUPPORTED_MASK_PARAMETER:154:unsupported mask parameter +RSA_R_UNSUPPORTED_SIGNATURE_TYPE:155:unsupported signature type +RSA_R_VALUE_MISSING:147:value missing +RSA_R_WRONG_SIGNATURE_LENGTH:119:wrong signature length +SSL_R_APP_DATA_IN_HANDSHAKE:100:app data in handshake +SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT:272:\ + attempt to reuse session in different context +SSL_R_AT_LEAST_TLS_1_0_NEEDED_IN_FIPS_MODE:143:\ + at least TLS 1.0 needed in FIPS mode +SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE:158:\ + at least (D)TLS 1.2 needed in Suite B mode +SSL_R_BAD_CHANGE_CIPHER_SPEC:103:bad change cipher spec +SSL_R_BAD_CIPHER:186:bad cipher +SSL_R_BAD_DATA:390:bad data +SSL_R_BAD_DATA_RETURNED_BY_CALLBACK:106:bad data returned by callback +SSL_R_BAD_DECOMPRESSION:107:bad decompression +SSL_R_BAD_DH_VALUE:102:bad dh value +SSL_R_BAD_DIGEST_LENGTH:111:bad digest length +SSL_R_BAD_EARLY_DATA:233:bad early data +SSL_R_BAD_ECC_CERT:304:bad ecc cert +SSL_R_BAD_ECPOINT:306:bad ecpoint +SSL_R_BAD_EXTENSION:110:bad extension +SSL_R_BAD_HANDSHAKE_LENGTH:332:bad handshake length +SSL_R_BAD_HANDSHAKE_STATE:236:bad handshake state +SSL_R_BAD_HELLO_REQUEST:105:bad hello request +SSL_R_BAD_HRR_VERSION:263:bad hrr version +SSL_R_BAD_KEY_SHARE:108:bad key share +SSL_R_BAD_KEY_UPDATE:122:bad key update +SSL_R_BAD_LENGTH:271:bad length +SSL_R_BAD_PACKET:240:bad packet +SSL_R_BAD_PACKET_LENGTH:115:bad packet length +SSL_R_BAD_PROTOCOL_VERSION_NUMBER:116:bad protocol version number +SSL_R_BAD_PSK:219:bad psk +SSL_R_BAD_PSK_IDENTITY:114:bad psk identity +SSL_R_BAD_RECORD_TYPE:443:bad record type +SSL_R_BAD_RSA_ENCRYPT:119:bad rsa encrypt +SSL_R_BAD_SIGNATURE:123:bad signature +SSL_R_BAD_SRP_A_LENGTH:347:bad srp a length +SSL_R_BAD_SRP_PARAMETERS:371:bad srp parameters +SSL_R_BAD_SRTP_MKI_VALUE:352:bad srtp mki value +SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST:353:bad srtp protection profile list +SSL_R_BAD_SSL_FILETYPE:124:bad ssl filetype +SSL_R_BAD_VALUE:384:bad value +SSL_R_BAD_WRITE_RETRY:127:bad write retry +SSL_R_BINDER_DOES_NOT_VERIFY:253:binder does not verify +SSL_R_BIO_NOT_SET:128:bio not set +SSL_R_BLOCK_CIPHER_PAD_IS_WRONG:129:block cipher pad is wrong +SSL_R_BN_LIB:130:bn lib +SSL_R_CALLBACK_FAILED:234:callback failed +SSL_R_CANNOT_CHANGE_CIPHER:109:cannot change cipher +SSL_R_CA_DN_LENGTH_MISMATCH:131:ca dn length mismatch +SSL_R_CA_KEY_TOO_SMALL:397:ca key too small +SSL_R_CA_MD_TOO_WEAK:398:ca md too weak +SSL_R_CCS_RECEIVED_EARLY:133:ccs received early +SSL_R_CERTIFICATE_VERIFY_FAILED:134:certificate verify failed +SSL_R_CERT_CB_ERROR:377:cert cb error +SSL_R_CERT_LENGTH_MISMATCH:135:cert length mismatch +SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED:218:ciphersuite digest has changed +SSL_R_CIPHER_CODE_WRONG_LENGTH:137:cipher code wrong length +SSL_R_CIPHER_OR_HASH_UNAVAILABLE:138:cipher or hash unavailable +SSL_R_CLIENTHELLO_TLSEXT:226:clienthello tlsext +SSL_R_COMPRESSED_LENGTH_TOO_LONG:140:compressed length too long +SSL_R_COMPRESSION_DISABLED:343:compression disabled +SSL_R_COMPRESSION_FAILURE:141:compression failure +SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE:307:\ + compression id not within private range +SSL_R_COMPRESSION_LIBRARY_ERROR:142:compression library error +SSL_R_CONNECTION_TYPE_NOT_SET:144:connection type not set +SSL_R_CONTEXT_NOT_DANE_ENABLED:167:context not dane enabled +SSL_R_COOKIE_GEN_CALLBACK_FAILURE:400:cookie gen callback failure +SSL_R_COOKIE_MISMATCH:308:cookie mismatch +SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED:206:\ + custom ext handler already installed +SSL_R_DANE_ALREADY_ENABLED:172:dane already enabled +SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL:173:dane cannot override mtype full +SSL_R_DANE_NOT_ENABLED:175:dane not enabled +SSL_R_DANE_TLSA_BAD_CERTIFICATE:180:dane tlsa bad certificate +SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE:184:dane tlsa bad certificate usage +SSL_R_DANE_TLSA_BAD_DATA_LENGTH:189:dane tlsa bad data length +SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH:192:dane tlsa bad digest length +SSL_R_DANE_TLSA_BAD_MATCHING_TYPE:200:dane tlsa bad matching type +SSL_R_DANE_TLSA_BAD_PUBLIC_KEY:201:dane tlsa bad public key +SSL_R_DANE_TLSA_BAD_SELECTOR:202:dane tlsa bad selector +SSL_R_DANE_TLSA_NULL_DATA:203:dane tlsa null data +SSL_R_DATA_BETWEEN_CCS_AND_FINISHED:145:data between ccs and finished +SSL_R_DATA_LENGTH_TOO_LONG:146:data length too long +SSL_R_DECRYPTION_FAILED:147:decryption failed +SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC:281:\ + decryption failed or bad record mac +SSL_R_DH_KEY_TOO_SMALL:394:dh key too small +SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG:148:dh public value length is wrong +SSL_R_DIGEST_CHECK_FAILED:149:digest check failed +SSL_R_DTLS_MESSAGE_TOO_BIG:334:dtls message too big +SSL_R_DUPLICATE_COMPRESSION_ID:309:duplicate compression id +SSL_R_ECC_CERT_NOT_FOR_SIGNING:318:ecc cert not for signing +SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE:374:ecdh required for suiteb mode +SSL_R_EE_KEY_TOO_SMALL:399:ee key too small +SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST:354:empty srtp protection profile list +SSL_R_ENCRYPTED_LENGTH_TOO_LONG:150:encrypted length too long +SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST:151:error in received cipher list +SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN:204:error setting tlsa base domain +SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE:194:exceeds max fragment size +SSL_R_EXCESSIVE_MESSAGE_SIZE:152:excessive message size +SSL_R_EXTENSION_NOT_RECEIVED:279:extension not received +SSL_R_EXTRA_DATA_IN_MESSAGE:153:extra data in message +SSL_R_EXT_LENGTH_MISMATCH:163:ext length mismatch +SSL_R_FAILED_TO_INIT_ASYNC:405:failed to init async +SSL_R_FRAGMENTED_CLIENT_HELLO:401:fragmented client hello +SSL_R_GOT_A_FIN_BEFORE_A_CCS:154:got a fin before a ccs +SSL_R_HTTPS_PROXY_REQUEST:155:https proxy request +SSL_R_HTTP_REQUEST:156:http request +SSL_R_ILLEGAL_POINT_COMPRESSION:162:illegal point compression +SSL_R_ILLEGAL_SUITEB_DIGEST:380:illegal Suite B digest +SSL_R_INAPPROPRIATE_FALLBACK:373:inappropriate fallback +SSL_R_INCONSISTENT_COMPRESSION:340:inconsistent compression +SSL_R_INCONSISTENT_EARLY_DATA_ALPN:222:inconsistent early data alpn +SSL_R_INCONSISTENT_EARLY_DATA_SNI:231:inconsistent early data sni +SSL_R_INCONSISTENT_EXTMS:104:inconsistent extms +SSL_R_INSUFFICIENT_SECURITY:241:insufficient security +SSL_R_INVALID_ALERT:205:invalid alert +SSL_R_INVALID_CCS_MESSAGE:260:invalid ccs message +SSL_R_INVALID_CERTIFICATE_OR_ALG:238:invalid certificate or alg +SSL_R_INVALID_COMMAND:280:invalid command +SSL_R_INVALID_COMPRESSION_ALGORITHM:341:invalid compression algorithm +SSL_R_INVALID_CONFIG:283:invalid config +SSL_R_INVALID_CONFIGURATION_NAME:113:invalid configuration name +SSL_R_INVALID_CONTEXT:282:invalid context +SSL_R_INVALID_CT_VALIDATION_TYPE:212:invalid ct validation type +SSL_R_INVALID_KEY_UPDATE_TYPE:120:invalid key update type +SSL_R_INVALID_MAX_EARLY_DATA:174:invalid max early data +SSL_R_INVALID_NULL_CMD_NAME:385:invalid null cmd name +SSL_R_INVALID_SEQUENCE_NUMBER:402:invalid sequence number +SSL_R_INVALID_SERVERINFO_DATA:388:invalid serverinfo data +SSL_R_INVALID_SESSION_ID:999:invalid session id +SSL_R_INVALID_SRP_USERNAME:357:invalid srp username +SSL_R_INVALID_STATUS_RESPONSE:328:invalid status response +SSL_R_INVALID_TICKET_KEYS_LENGTH:325:invalid ticket keys length +SSL_R_LENGTH_MISMATCH:159:length mismatch +SSL_R_LENGTH_TOO_LONG:404:length too long +SSL_R_LENGTH_TOO_SHORT:160:length too short +SSL_R_LIBRARY_BUG:274:library bug +SSL_R_LIBRARY_HAS_NO_CIPHERS:161:library has no ciphers +SSL_R_MISSING_DSA_SIGNING_CERT:165:missing dsa signing cert +SSL_R_MISSING_ECDSA_SIGNING_CERT:381:missing ecdsa signing cert +SSL_R_MISSING_FATAL:256:missing fatal +SSL_R_MISSING_RSA_CERTIFICATE:168:missing rsa certificate +SSL_R_MISSING_RSA_ENCRYPTING_CERT:169:missing rsa encrypting cert +SSL_R_MISSING_RSA_SIGNING_CERT:170:missing rsa signing cert +SSL_R_MISSING_SIGALGS_EXTENSION:112:missing sigalgs extension +SSL_R_MISSING_SIGNING_CERT:221:missing signing cert +SSL_R_MISSING_SRP_PARAM:358:can't find SRP server param +SSL_R_MISSING_SUPPORTED_GROUPS_EXTENSION:209:missing supported groups extension +SSL_R_MISSING_TMP_DH_KEY:171:missing tmp dh key +SSL_R_MISSING_TMP_ECDH_KEY:311:missing tmp ecdh key +SSL_R_NOT_ON_RECORD_BOUNDARY:182:not on record boundary +SSL_R_NOT_SERVER:284:not server +SSL_R_NO_APPLICATION_PROTOCOL:235:no application protocol +SSL_R_NO_CERTIFICATES_RETURNED:176:no certificates returned +SSL_R_NO_CERTIFICATE_ASSIGNED:177:no certificate assigned +SSL_R_NO_CERTIFICATE_SET:179:no certificate set +SSL_R_NO_CHANGE_FOLLOWING_HRR:214:no change following hrr +SSL_R_NO_CIPHERS_AVAILABLE:181:no ciphers available +SSL_R_NO_CIPHERS_SPECIFIED:183:no ciphers specified +SSL_R_NO_CIPHER_MATCH:185:no cipher match +SSL_R_NO_CLIENT_CERT_METHOD:331:no client cert method +SSL_R_NO_COMPRESSION_SPECIFIED:187:no compression specified +SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER:330:\ + Peer haven't sent GOST certificate, required for selected ciphersuite +SSL_R_NO_METHOD_SPECIFIED:188:no method specified +SSL_R_NO_PEM_EXTENSIONS:389:no pem extensions +SSL_R_NO_PRIVATE_KEY_ASSIGNED:190:no private key assigned +SSL_R_NO_PROTOCOLS_AVAILABLE:191:no protocols available +SSL_R_NO_RENEGOTIATION:339:no renegotiation +SSL_R_NO_REQUIRED_DIGEST:324:no required digest +SSL_R_NO_SHARED_CIPHER:193:no shared cipher +SSL_R_NO_SHARED_GROUPS:410:no shared groups +SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS:376:no shared signature algorithms +SSL_R_NO_SRTP_PROFILES:359:no srtp profiles +SSL_R_NO_SUITABLE_KEY_SHARE:101:no suitable key share +SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM:118:no suitable signature algorithm +SSL_R_NO_VALID_SCTS:216:no valid scts +SSL_R_NO_VERIFY_COOKIE_CALLBACK:403:no verify cookie callback +SSL_R_NULL_SSL_CTX:195:null ssl ctx +SSL_R_NULL_SSL_METHOD_PASSED:196:null ssl method passed +SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED:197:old session cipher not returned +SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED:344:\ + old session compression algorithm not returned +SSL_R_OVERFLOW_ERROR:237:overflow error +SSL_R_PACKET_LENGTH_TOO_LONG:198:packet length too long +SSL_R_PARSE_TLSEXT:227:parse tlsext +SSL_R_PATH_TOO_LONG:270:path too long +SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE:199:peer did not return a certificate +SSL_R_PEM_NAME_BAD_PREFIX:391:pem name bad prefix +SSL_R_PEM_NAME_TOO_SHORT:392:pem name too short +SSL_R_PIPELINE_FAILURE:406:pipeline failure +SSL_R_POST_HANDSHAKE_AUTH_ENCODING_ERR:278:post handshake auth encoding err +SSL_R_PROTOCOL_IS_SHUTDOWN:207:protocol is shutdown +SSL_R_PSK_IDENTITY_NOT_FOUND:223:psk identity not found +SSL_R_PSK_NO_CLIENT_CB:224:psk no client cb +SSL_R_PSK_NO_SERVER_CB:225:psk no server cb +SSL_R_READ_BIO_NOT_SET:211:read bio not set +SSL_R_READ_TIMEOUT_EXPIRED:312:read timeout expired +SSL_R_RECORD_LENGTH_MISMATCH:213:record length mismatch +SSL_R_RECORD_TOO_SMALL:298:record too small +SSL_R_RENEGOTIATE_EXT_TOO_LONG:335:renegotiate ext too long +SSL_R_RENEGOTIATION_ENCODING_ERR:336:renegotiation encoding err +SSL_R_RENEGOTIATION_MISMATCH:337:renegotiation mismatch +SSL_R_REQUEST_PENDING:285:request pending +SSL_R_REQUEST_SENT:286:request sent +SSL_R_REQUIRED_CIPHER_MISSING:215:required cipher missing +SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING:342:\ + required compression algorithm missing +SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING:345:scsv received when renegotiating +SSL_R_SCT_VERIFICATION_FAILED:208:sct verification failed +SSL_R_SERVERHELLO_TLSEXT:275:serverhello tlsext +SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED:277:session id context uninitialized +SSL_R_SHUTDOWN_WHILE_IN_INIT:407:shutdown while in init +SSL_R_SIGNATURE_ALGORITHMS_ERROR:360:signature algorithms error +SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE:220:\ + signature for non signing certificate +SSL_R_SRP_A_CALC:361:error with the srp params +SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES:362:srtp could not allocate profiles +SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG:363:\ + srtp protection profile list too long +SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE:364:srtp unknown protection profile +SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH:232:\ + ssl3 ext invalid max fragment length +SSL_R_SSL3_EXT_INVALID_SERVERNAME:319:ssl3 ext invalid servername +SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE:320:ssl3 ext invalid servername type +SSL_R_SSL3_SESSION_ID_TOO_LONG:300:ssl3 session id too long +SSL_R_SSL_COMMAND_SECTION_EMPTY:117:ssl command section empty +SSL_R_SSL_COMMAND_SECTION_NOT_FOUND:125:ssl command section not found +SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION:228:ssl ctx has no default ssl version +SSL_R_SSL_HANDSHAKE_FAILURE:229:ssl handshake failure +SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS:230:ssl library has no ciphers +SSL_R_SSL_NEGATIVE_LENGTH:372:ssl negative length +SSL_R_SSL_SECTION_EMPTY:126:ssl section empty +SSL_R_SSL_SECTION_NOT_FOUND:136:ssl section not found +SSL_R_SSL_SESSION_ID_CALLBACK_FAILED:301:ssl session id callback failed +SSL_R_SSL_SESSION_ID_CONFLICT:302:ssl session id conflict +SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG:273:ssl session id context too long +SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH:303:ssl session id has bad length +SSL_R_SSL_SESSION_ID_TOO_LONG:408:ssl session id too long +SSL_R_SSL_SESSION_VERSION_MISMATCH:210:ssl session version mismatch +SSL_R_STILL_IN_INIT:121:still in init +SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT:365:peer does not accept heartbeats +SSL_R_TLS_HEARTBEAT_PENDING:366:heartbeat request already pending +SSL_R_TLS_ILLEGAL_EXPORTER_LABEL:367:tls illegal exporter label +SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST:157:tls invalid ecpointformat list +SSL_R_TOO_MANY_KEY_UPDATES:132:too many key updates +SSL_R_TOO_MANY_WARN_ALERTS:409:too many warn alerts +SSL_R_TOO_MUCH_EARLY_DATA:164:too much early data +SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS:314:unable to find ecdh parameters +SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS:239:\ + unable to find public key parameters +SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES:242:unable to load ssl3 md5 routines +SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES:243:unable to load ssl3 sha1 routines +SSL_R_UNEXPECTED_CCS_MESSAGE:262:unexpected ccs message +SSL_R_UNEXPECTED_END_OF_EARLY_DATA:178:unexpected end of early data +SSL_R_UNEXPECTED_MESSAGE:244:unexpected message +SSL_R_UNEXPECTED_RECORD:245:unexpected record +SSL_R_UNINITIALIZED:276:uninitialized +SSL_R_UNKNOWN_ALERT_TYPE:246:unknown alert type +SSL_R_UNKNOWN_CERTIFICATE_TYPE:247:unknown certificate type +SSL_R_UNKNOWN_CIPHER_RETURNED:248:unknown cipher returned +SSL_R_UNKNOWN_CIPHER_TYPE:249:unknown cipher type +SSL_R_UNKNOWN_CMD_NAME:386:unknown cmd name +SSL_R_UNKNOWN_COMMAND:139:unknown command +SSL_R_UNKNOWN_DIGEST:368:unknown digest +SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE:250:unknown key exchange type +SSL_R_UNKNOWN_PKEY_TYPE:251:unknown pkey type +SSL_R_UNKNOWN_PROTOCOL:252:unknown protocol +SSL_R_UNKNOWN_SSL_VERSION:254:unknown ssl version +SSL_R_UNKNOWN_STATE:255:unknown state +SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED:338:\ + unsafe legacy renegotiation disabled +SSL_R_UNSOLICITED_EXTENSION:217:unsolicited extension +SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM:257:unsupported compression algorithm +SSL_R_UNSUPPORTED_ELLIPTIC_CURVE:315:unsupported elliptic curve +SSL_R_UNSUPPORTED_PROTOCOL:258:unsupported protocol +SSL_R_UNSUPPORTED_SSL_VERSION:259:unsupported ssl version +SSL_R_UNSUPPORTED_STATUS_TYPE:329:unsupported status type +SSL_R_USE_SRTP_NOT_NEGOTIATED:369:use srtp not negotiated +SSL_R_VERSION_TOO_HIGH:166:version too high +SSL_R_VERSION_TOO_LOW:396:version too low +SSL_R_WRONG_CERTIFICATE_TYPE:383:wrong certificate type +SSL_R_WRONG_CIPHER_RETURNED:261:wrong cipher returned +SSL_R_WRONG_CURVE:378:wrong curve +SSL_R_WRONG_SIGNATURE_LENGTH:264:wrong signature length +SSL_R_WRONG_SIGNATURE_SIZE:265:wrong signature size +SSL_R_WRONG_SIGNATURE_TYPE:370:wrong signature type +SSL_R_WRONG_SSL_VERSION:266:wrong ssl version +SSL_R_WRONG_VERSION_NUMBER:267:wrong version number +SSL_R_X509_LIB:268:x509 lib +SSL_R_X509_VERIFICATION_SETUP_PROBLEMS:269:x509 verification setup problems +TS_R_BAD_PKCS7_TYPE:132:bad pkcs7 type +TS_R_BAD_TYPE:133:bad type +TS_R_CANNOT_LOAD_CERT:137:cannot load certificate +TS_R_CANNOT_LOAD_KEY:138:cannot load private key +TS_R_CERTIFICATE_VERIFY_ERROR:100:certificate verify error +TS_R_COULD_NOT_SET_ENGINE:127:could not set engine +TS_R_COULD_NOT_SET_TIME:115:could not set time +TS_R_DETACHED_CONTENT:134:detached content +TS_R_ESS_ADD_SIGNING_CERT_ERROR:116:ess add signing cert error +TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR:139:ess add signing cert v2 error +TS_R_ESS_SIGNING_CERTIFICATE_ERROR:101:ess signing certificate error +TS_R_INVALID_NULL_POINTER:102:invalid null pointer +TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE:117:invalid signer certificate purpose +TS_R_MESSAGE_IMPRINT_MISMATCH:103:message imprint mismatch +TS_R_NONCE_MISMATCH:104:nonce mismatch +TS_R_NONCE_NOT_RETURNED:105:nonce not returned +TS_R_NO_CONTENT:106:no content +TS_R_NO_TIME_STAMP_TOKEN:107:no time stamp token +TS_R_PKCS7_ADD_SIGNATURE_ERROR:118:pkcs7 add signature error +TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR:119:pkcs7 add signed attr error +TS_R_PKCS7_TO_TS_TST_INFO_FAILED:129:pkcs7 to ts tst info failed +TS_R_POLICY_MISMATCH:108:policy mismatch +TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE:120:\ + private key does not match certificate +TS_R_RESPONSE_SETUP_ERROR:121:response setup error +TS_R_SIGNATURE_FAILURE:109:signature failure +TS_R_THERE_MUST_BE_ONE_SIGNER:110:there must be one signer +TS_R_TIME_SYSCALL_ERROR:122:time syscall error +TS_R_TOKEN_NOT_PRESENT:130:token not present +TS_R_TOKEN_PRESENT:131:token present +TS_R_TSA_NAME_MISMATCH:111:tsa name mismatch +TS_R_TSA_UNTRUSTED:112:tsa untrusted +TS_R_TST_INFO_SETUP_ERROR:123:tst info setup error +TS_R_TS_DATASIGN:124:ts datasign +TS_R_UNACCEPTABLE_POLICY:125:unacceptable policy +TS_R_UNSUPPORTED_MD_ALGORITHM:126:unsupported md algorithm +TS_R_UNSUPPORTED_VERSION:113:unsupported version +TS_R_VAR_BAD_VALUE:135:var bad value +TS_R_VAR_LOOKUP_FAILURE:136:cannot find config variable +TS_R_WRONG_CONTENT_TYPE:114:wrong content type +UI_R_COMMON_OK_AND_CANCEL_CHARACTERS:104:common ok and cancel characters +UI_R_INDEX_TOO_LARGE:102:index too large +UI_R_INDEX_TOO_SMALL:103:index too small +UI_R_NO_RESULT_BUFFER:105:no result buffer +UI_R_PROCESSING_ERROR:107:processing error +UI_R_RESULT_TOO_LARGE:100:result too large +UI_R_RESULT_TOO_SMALL:101:result too small +UI_R_SYSASSIGN_ERROR:109:sys$assign error +UI_R_SYSDASSGN_ERROR:110:sys$dassgn error +UI_R_SYSQIOW_ERROR:111:sys$qiow error +UI_R_UNKNOWN_CONTROL_COMMAND:106:unknown control command +UI_R_UNKNOWN_TTYGET_ERRNO_VALUE:108:unknown ttyget errno value +UI_R_USER_DATA_DUPLICATION_UNSUPPORTED:112:user data duplication unsupported +X509V3_R_BAD_IP_ADDRESS:118:bad ip address +X509V3_R_BAD_OBJECT:119:bad object +X509V3_R_BN_DEC2BN_ERROR:100:bn dec2bn error +X509V3_R_BN_TO_ASN1_INTEGER_ERROR:101:bn to asn1 integer error +X509V3_R_DIRNAME_ERROR:149:dirname error +X509V3_R_DISTPOINT_ALREADY_SET:160:distpoint already set +X509V3_R_DUPLICATE_ZONE_ID:133:duplicate zone id +X509V3_R_ERROR_CONVERTING_ZONE:131:error converting zone +X509V3_R_ERROR_CREATING_EXTENSION:144:error creating extension +X509V3_R_ERROR_IN_EXTENSION:128:error in extension +X509V3_R_EXPECTED_A_SECTION_NAME:137:expected a section name +X509V3_R_EXTENSION_EXISTS:145:extension exists +X509V3_R_EXTENSION_NAME_ERROR:115:extension name error +X509V3_R_EXTENSION_NOT_FOUND:102:extension not found +X509V3_R_EXTENSION_SETTING_NOT_SUPPORTED:103:extension setting not supported +X509V3_R_EXTENSION_VALUE_ERROR:116:extension value error +X509V3_R_ILLEGAL_EMPTY_EXTENSION:151:illegal empty extension +X509V3_R_INCORRECT_POLICY_SYNTAX_TAG:152:incorrect policy syntax tag +X509V3_R_INVALID_ASNUMBER:162:invalid asnumber +X509V3_R_INVALID_ASRANGE:163:invalid asrange +X509V3_R_INVALID_BOOLEAN_STRING:104:invalid boolean string +X509V3_R_INVALID_EXTENSION_STRING:105:invalid extension string +X509V3_R_INVALID_INHERITANCE:165:invalid inheritance +X509V3_R_INVALID_IPADDRESS:166:invalid ipaddress +X509V3_R_INVALID_MULTIPLE_RDNS:161:invalid multiple rdns +X509V3_R_INVALID_NAME:106:invalid name +X509V3_R_INVALID_NULL_ARGUMENT:107:invalid null argument +X509V3_R_INVALID_NULL_NAME:108:invalid null name +X509V3_R_INVALID_NULL_VALUE:109:invalid null value +X509V3_R_INVALID_NUMBER:140:invalid number +X509V3_R_INVALID_NUMBERS:141:invalid numbers +X509V3_R_INVALID_OBJECT_IDENTIFIER:110:invalid object identifier +X509V3_R_INVALID_OPTION:138:invalid option +X509V3_R_INVALID_POLICY_IDENTIFIER:134:invalid policy identifier +X509V3_R_INVALID_PROXY_POLICY_SETTING:153:invalid proxy policy setting +X509V3_R_INVALID_PURPOSE:146:invalid purpose +X509V3_R_INVALID_SAFI:164:invalid safi +X509V3_R_INVALID_SECTION:135:invalid section +X509V3_R_INVALID_SYNTAX:143:invalid syntax +X509V3_R_ISSUER_DECODE_ERROR:126:issuer decode error +X509V3_R_MISSING_VALUE:124:missing value +X509V3_R_NEED_ORGANIZATION_AND_NUMBERS:142:need organization and numbers +X509V3_R_NO_CONFIG_DATABASE:136:no config database +X509V3_R_NO_ISSUER_CERTIFICATE:121:no issuer certificate +X509V3_R_NO_ISSUER_DETAILS:127:no issuer details +X509V3_R_NO_POLICY_IDENTIFIER:139:no policy identifier +X509V3_R_NO_PROXY_CERT_POLICY_LANGUAGE_DEFINED:154:\ + no proxy cert policy language defined +X509V3_R_NO_PUBLIC_KEY:114:no public key +X509V3_R_NO_SUBJECT_DETAILS:125:no subject details +X509V3_R_OPERATION_NOT_DEFINED:148:operation not defined +X509V3_R_OTHERNAME_ERROR:147:othername error +X509V3_R_POLICY_LANGUAGE_ALREADY_DEFINED:155:policy language already defined +X509V3_R_POLICY_PATH_LENGTH:156:policy path length +X509V3_R_POLICY_PATH_LENGTH_ALREADY_DEFINED:157:\ + policy path length already defined +X509V3_R_POLICY_WHEN_PROXY_LANGUAGE_REQUIRES_NO_POLICY:159:\ + policy when proxy language requires no policy +X509V3_R_SECTION_NOT_FOUND:150:section not found +X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS:122:unable to get issuer details +X509V3_R_UNABLE_TO_GET_ISSUER_KEYID:123:unable to get issuer keyid +X509V3_R_UNKNOWN_BIT_STRING_ARGUMENT:111:unknown bit string argument +X509V3_R_UNKNOWN_EXTENSION:129:unknown extension +X509V3_R_UNKNOWN_EXTENSION_NAME:130:unknown extension name +X509V3_R_UNKNOWN_OPTION:120:unknown option +X509V3_R_UNSUPPORTED_OPTION:117:unsupported option +X509V3_R_UNSUPPORTED_TYPE:167:unsupported type +X509V3_R_USER_TOO_LONG:132:user too long +X509_R_AKID_MISMATCH:110:akid mismatch +X509_R_BAD_SELECTOR:133:bad selector +X509_R_BAD_X509_FILETYPE:100:bad x509 filetype +X509_R_BASE64_DECODE_ERROR:118:base64 decode error +X509_R_CANT_CHECK_DH_KEY:114:cant check dh key +X509_R_CERT_ALREADY_IN_HASH_TABLE:101:cert already in hash table +X509_R_CRL_ALREADY_DELTA:127:crl already delta +X509_R_CRL_VERIFY_FAILURE:131:crl verify failure +X509_R_IDP_MISMATCH:128:idp mismatch +X509_R_INVALID_DIRECTORY:113:invalid directory +X509_R_INVALID_FIELD_NAME:119:invalid field name +X509_R_INVALID_TRUST:123:invalid trust +X509_R_ISSUER_MISMATCH:129:issuer mismatch +X509_R_KEY_TYPE_MISMATCH:115:key type mismatch +X509_R_KEY_VALUES_MISMATCH:116:key values mismatch +X509_R_LOADING_CERT_DIR:103:loading cert dir +X509_R_LOADING_DEFAULTS:104:loading defaults +X509_R_METHOD_NOT_SUPPORTED:124:method not supported +X509_R_NAME_TOO_LONG:134:name too long +X509_R_NEWER_CRL_NOT_NEWER:132:newer crl not newer +X509_R_NO_CERTIFICATE_FOUND:135:no certificate found +X509_R_NO_CERTIFICATE_OR_CRL_FOUND:136:no certificate or crl found +X509_R_NO_CERT_SET_FOR_US_TO_VERIFY:105:no cert set for us to verify +X509_R_NO_CRL_FOUND:137:no crl found +X509_R_NO_CRL_NUMBER:130:no crl number +X509_R_PUBLIC_KEY_DECODE_ERROR:125:public key decode error +X509_R_PUBLIC_KEY_ENCODE_ERROR:126:public key encode error +X509_R_SHOULD_RETRY:106:should retry +X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN:107:unable to find parameters in chain +X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY:108:unable to get certs public key +X509_R_UNKNOWN_KEY_TYPE:117:unknown key type +X509_R_UNKNOWN_NID:109:unknown nid +X509_R_UNKNOWN_PURPOSE_ID:121:unknown purpose id +X509_R_UNKNOWN_TRUST_ID:120:unknown trust id +X509_R_UNSUPPORTED_ALGORITHM:111:unsupported algorithm +X509_R_WRONG_LOOKUP_TYPE:112:wrong lookup type +X509_R_WRONG_TYPE:122:wrong type diff --git a/crypto/evp/bio_b64.c b/crypto/evp/bio_b64.c index a86e8db0..cade6f8f 100644 --- a/crypto/evp/bio_b64.c +++ b/crypto/evp/bio_b64.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -17,9 +17,6 @@ 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); @@ -49,7 +46,11 @@ typedef struct b64_struct { static const BIO_METHOD methods_b64 = { BIO_TYPE_BASE64, "base64 encoding", + /* TODO: Convert to new style write function */ + bwrite_conv, b64_write, + /* TODO: Convert to new style read function */ + bread_conv, b64_read, b64_puts, NULL, /* b64_gets, */ @@ -113,7 +114,7 @@ static int b64_read(BIO *b, char *out, int outl) BIO *next; if (out == NULL) - return (0); + return 0; ctx = (BIO_B64_CTX *)BIO_get_data(b); next = BIO_next(b); @@ -288,14 +289,6 @@ static int b64_read(BIO *b, char *out, int outl) (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; @@ -354,7 +347,7 @@ static int b64_write(BIO *b, const char *in, int inl) i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n); if (i <= 0) { BIO_copy_next_retry(b); - return (i); + return i; } OPENSSL_assert(i <= n); ctx->buf_off += i; @@ -367,7 +360,7 @@ static int b64_write(BIO *b, const char *in, int inl) ctx->buf_len = 0; if ((in == NULL) || (inl <= 0)) - return (0); + return 0; while (inl > 0) { n = (inl > B64_BLOCK_SIZE) ? B64_BLOCK_SIZE : inl; @@ -440,7 +433,7 @@ static int b64_write(BIO *b, const char *in, int inl) ctx->buf_len = 0; ctx->buf_off = 0; } - return (ret); + return ret; } static long b64_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -542,7 +535,7 @@ static long b64_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) ret = BIO_callback_ctrl(next, cmd, fp); break; } - return (ret); + return ret; } static int b64_puts(BIO *b, const char *str) diff --git a/crypto/evp/bio_enc.c b/crypto/evp/bio_enc.c index e62d1dfd..30f09e6d 100644 --- a/crypto/evp/bio_enc.c +++ b/crypto/evp/bio_enc.c @@ -16,12 +16,6 @@ static int enc_write(BIO *h, const char *buf, int num); static int enc_read(BIO *h, char *buf, int size); -/* - * static int enc_puts(BIO *h, const char *str); - */ -/* - * static int enc_gets(BIO *h, char *str, int size); - */ static long enc_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int enc_new(BIO *h); static int enc_free(BIO *data); @@ -48,7 +42,11 @@ typedef struct enc_struct { static const BIO_METHOD methods_enc = { BIO_TYPE_CIPHER, "cipher", + /* TODO: Convert to new style write function */ + bwrite_conv, enc_write, + /* TODO: Convert to new style read function */ + bread_conv, enc_read, NULL, /* enc_puts, */ NULL, /* enc_gets, */ @@ -60,7 +58,7 @@ static const BIO_METHOD methods_enc = { const BIO_METHOD *BIO_f_cipher(void) { - return (&methods_enc); + return &methods_enc; } static int enc_new(BIO *bi) @@ -111,7 +109,7 @@ static int enc_read(BIO *b, char *out, int outl) BIO *next; if (out == NULL) - return (0); + return 0; ctx = BIO_get_data(b); next = BIO_next(b); @@ -251,7 +249,7 @@ static int enc_write(BIO *b, const char *in, int inl) i = BIO_write(next, &(ctx->buf[ctx->buf_off]), n); if (i <= 0) { BIO_copy_next_retry(b); - return (i); + return i; } ctx->buf_off += i; n -= i; @@ -259,7 +257,7 @@ static int enc_write(BIO *b, const char *in, int inl) /* at this point all pending data has been written */ if ((in == NULL) || (inl <= 0)) - return (0); + return 0; ctx->buf_off = 0; while (inl > 0) { @@ -289,7 +287,7 @@ static int enc_write(BIO *b, const char *in, int inl) ctx->buf_off = 0; } BIO_copy_next_retry(b); - return (ret); + return ret; } static long enc_ctrl(BIO *b, int cmd, long num, void *ptr) @@ -384,7 +382,7 @@ static long enc_ctrl(BIO *b, int cmd, long num, void *ptr) ret = BIO_ctrl(next, cmd, num, ptr); break; } - return (ret); + return ret; } static long enc_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) @@ -393,35 +391,15 @@ static long enc_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) BIO *next = BIO_next(b); if (next == NULL) - return (0); + return 0; switch (cmd) { default: ret = BIO_callback_ctrl(next, cmd, fp); break; } - return (ret); + return ret; } -/*- -void BIO_set_cipher_ctx(b,c) -BIO *b; -EVP_CIPHER_ctx *c; - { - if (b == NULL) return; - - if ((b->callback != NULL) && - (b->callback(b,BIO_CB_CTRL,(char *)c,BIO_CTRL_SET,e,0L) <= 0)) - return; - - b->init=1; - ctx=(BIO_ENC_CTX *)b->ptr; - memcpy(ctx->cipher,c,sizeof(EVP_CIPHER_CTX)); - - if (b->callback != NULL) - b->callback(b,BIO_CB_CTRL,(char *)c,BIO_CTRL_SET,e,1L); - } -*/ - int BIO_set_cipher(BIO *b, const EVP_CIPHER *c, const unsigned char *k, const unsigned char *i, int e) { diff --git a/crypto/evp/bio_md.c b/crypto/evp/bio_md.c index 2f0f2831..288dee01 100644 --- a/crypto/evp/bio_md.c +++ b/crypto/evp/bio_md.c @@ -22,9 +22,6 @@ static int md_write(BIO *h, char const *buf, int num); static int md_read(BIO *h, char *buf, int size); -/* - * static int md_puts(BIO *h, const char *str); - */ static int md_gets(BIO *h, char *str, int size); static long md_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int md_new(BIO *h); @@ -34,7 +31,11 @@ static long md_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static const BIO_METHOD methods_md = { BIO_TYPE_MD, "message digest", + /* TODO: Convert to new style write function */ + bwrite_conv, md_write, + /* TODO: Convert to new style read function */ + bread_conv, md_read, NULL, /* md_puts, */ md_gets, @@ -46,7 +47,7 @@ static const BIO_METHOD methods_md = { const BIO_METHOD *BIO_f_md(void) { - return (&methods_md); + return &methods_md; } static int md_new(BIO *bi) @@ -55,7 +56,7 @@ static int md_new(BIO *bi) ctx = EVP_MD_CTX_new(); if (ctx == NULL) - return (0); + return 0; BIO_set_init(bi, 1); BIO_set_data(bi, ctx); @@ -66,7 +67,7 @@ static int md_new(BIO *bi) static int md_free(BIO *a) { if (a == NULL) - return (0); + return 0; EVP_MD_CTX_free(BIO_get_data(a)); BIO_set_data(a, NULL); BIO_set_init(a, 0); @@ -81,25 +82,25 @@ static int md_read(BIO *b, char *out, int outl) BIO *next; if (out == NULL) - return (0); + return 0; ctx = BIO_get_data(b); next = BIO_next(b); if ((ctx == NULL) || (next == NULL)) - return (0); + return 0; ret = BIO_read(next, out, outl); if (BIO_get_init(b)) { if (ret > 0) { if (EVP_DigestUpdate(ctx, (unsigned char *)out, (unsigned int)ret) <= 0) - return (-1); + return -1; } } BIO_clear_retry_flags(b); BIO_copy_next_retry(b); - return (ret); + return ret; } static int md_write(BIO *b, const char *in, int inl) @@ -194,7 +195,7 @@ static long md_ctrl(BIO *b, int cmd, long num, void *ptr) ret = BIO_ctrl(next, cmd, num, ptr); break; } - return (ret); + return ret; } static long md_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) @@ -212,7 +213,7 @@ static long md_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) ret = BIO_callback_ctrl(next, cmd, fp); break; } - return (ret); + return ret; } static int md_gets(BIO *bp, char *buf, int size) @@ -228,5 +229,5 @@ static int md_gets(BIO *bp, char *buf, int size) if (EVP_DigestFinal_ex(ctx, (unsigned char *)buf, &ret) <= 0) return -1; - return ((int)ret); + return (int)ret; } diff --git a/crypto/evp/bio_ok.c b/crypto/evp/bio_ok.c index b156e62e..5871e632 100644 --- a/crypto/evp/bio_ok.c +++ b/crypto/evp/bio_ok.c @@ -8,7 +8,7 @@ */ /*- - From: Arne Ansper + From: Arne Ansper Why BIO_f_reliable? @@ -110,7 +110,11 @@ typedef struct ok_struct { static const BIO_METHOD methods_ok = { BIO_TYPE_CIPHER, "reliable", + /* TODO: Convert to new style write function */ + bwrite_conv, ok_write, + /* TODO: Convert to new style read function */ + bread_conv, ok_read, NULL, /* ok_puts, */ NULL, /* ok_gets, */ @@ -122,7 +126,7 @@ static const BIO_METHOD methods_ok = { const BIO_METHOD *BIO_f_reliable(void) { - return (&methods_ok); + return &methods_ok; } static int ok_new(BIO *bi) @@ -263,7 +267,7 @@ static int ok_write(BIO *b, const char *in, int inl) ret = inl; if ((ctx == NULL) || (next == NULL) || (BIO_get_init(b) == 0)) - return (0); + return 0; if (ctx->sigio && !sig_out(b)) return 0; @@ -277,7 +281,7 @@ static int ok_write(BIO *b, const char *in, int inl) BIO_copy_next_retry(b); if (!BIO_should_retry(b)) ctx->cont = 0; - return (i); + return i; } ctx->buf_off += i; n -= i; @@ -291,7 +295,7 @@ static int ok_write(BIO *b, const char *in, int inl) } if ((in == NULL) || (inl <= 0)) - return (0); + return 0; n = (inl + ctx->buf_len > OK_BLOCK_SIZE + OK_BLOCK_BLOCK) ? (int)(OK_BLOCK_SIZE + OK_BLOCK_BLOCK - ctx->buf_len) : inl; @@ -311,7 +315,7 @@ static int ok_write(BIO *b, const char *in, int inl) BIO_clear_retry_flags(b); BIO_copy_next_retry(b); - return (ret); + return ret; } static long ok_ctrl(BIO *b, int cmd, long num, void *ptr) diff --git a/crypto/evp/build.info b/crypto/evp/build.info index bf633dc7..03057380 100644 --- a/crypto/evp/build.info +++ b/crypto/evp/build.info @@ -2,14 +2,14 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ encode.c digest.c evp_enc.c evp_key.c evp_cnf.c \ e_des.c e_bf.c e_idea.c e_des3.c e_camellia.c\ - e_rc4.c e_aes.c names.c e_seed.c \ + e_rc4.c e_aes.c names.c e_seed.c e_aria.c e_sm4.c \ e_xcbc_d.c e_rc2.c e_cast.c e_rc5.c \ m_null.c m_md2.c m_md4.c m_md5.c m_sha1.c m_wp.c \ - m_md5_sha1.c m_mdc2.c m_ripemd.c \ + m_md5_sha1.c m_mdc2.c m_ripemd.c m_sha3.c \ p_open.c p_seal.c p_sign.c p_verify.c p_lib.c p_enc.c p_dec.c \ bio_md.c bio_b64.c bio_enc.c evp_err.c e_null.c \ c_allc.c c_alld.c evp_lib.c bio_ok.c \ - evp_pkey.c evp_pbe.c p5_crpt.c p5_crpt2.c scrypt.c \ + evp_pkey.c evp_pbe.c p5_crpt.c p5_crpt2.c pbe_scrypt.c \ e_old.c pmeth_lib.c pmeth_fn.c pmeth_gn.c m_sigver.c \ e_aes_cbc_hmac_sha1.c e_aes_cbc_hmac_sha256.c e_rc4_hmac_md5.c \ e_chacha20_poly1305.c cmeth_lib.c @@ -17,6 +17,8 @@ SOURCE[../../libcrypto]=\ INCLUDE[e_aes.o]=.. ../modes INCLUDE[e_aes_cbc_hmac_sha1.o]=../modes INCLUDE[e_aes_cbc_hmac_sha256.o]=../modes +INCLUDE[e_aria.o]=.. ../modes INCLUDE[e_camellia.o]=.. ../modes +INCLUDE[e_sm4.o]=.. ../modes INCLUDE[e_des.o]=.. INCLUDE[e_des3.o]=.. diff --git a/crypto/evp/c_allc.c b/crypto/evp/c_allc.c index 6ed31edb..086b3c4d 100644 --- a/crypto/evp/c_allc.c +++ b/crypto/evp/c_allc.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -10,7 +10,7 @@ #include #include "internal/cryptlib.h" #include -#include +#include "internal/evp_int.h" #include #include @@ -79,6 +79,16 @@ void openssl_add_all_ciphers_int(void) EVP_add_cipher_alias(SN_seed_cbc, "seed"); #endif +#ifndef OPENSSL_NO_SM4 + EVP_add_cipher(EVP_sm4_ecb()); + EVP_add_cipher(EVP_sm4_cbc()); + EVP_add_cipher(EVP_sm4_cfb()); + EVP_add_cipher(EVP_sm4_ofb()); + EVP_add_cipher(EVP_sm4_ctr()); + EVP_add_cipher_alias(SN_sm4_cbc, "SM4"); + EVP_add_cipher_alias(SN_sm4_cbc, "sm4"); +#endif + #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_ecb()); EVP_add_cipher(EVP_rc2_cfb()); @@ -181,6 +191,42 @@ void openssl_add_all_ciphers_int(void) EVP_add_cipher(EVP_aes_128_cbc_hmac_sha256()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha256()); +#ifndef OPENSSL_NO_ARIA + EVP_add_cipher(EVP_aria_128_ecb()); + EVP_add_cipher(EVP_aria_128_cbc()); + EVP_add_cipher(EVP_aria_128_cfb()); + EVP_add_cipher(EVP_aria_128_cfb1()); + EVP_add_cipher(EVP_aria_128_cfb8()); + EVP_add_cipher(EVP_aria_128_ctr()); + EVP_add_cipher(EVP_aria_128_ofb()); + EVP_add_cipher(EVP_aria_128_gcm()); + EVP_add_cipher(EVP_aria_128_ccm()); + EVP_add_cipher_alias(SN_aria_128_cbc, "ARIA128"); + EVP_add_cipher_alias(SN_aria_128_cbc, "aria128"); + EVP_add_cipher(EVP_aria_192_ecb()); + EVP_add_cipher(EVP_aria_192_cbc()); + EVP_add_cipher(EVP_aria_192_cfb()); + EVP_add_cipher(EVP_aria_192_cfb1()); + EVP_add_cipher(EVP_aria_192_cfb8()); + EVP_add_cipher(EVP_aria_192_ctr()); + EVP_add_cipher(EVP_aria_192_ofb()); + EVP_add_cipher(EVP_aria_192_gcm()); + EVP_add_cipher(EVP_aria_192_ccm()); + EVP_add_cipher_alias(SN_aria_192_cbc, "ARIA192"); + EVP_add_cipher_alias(SN_aria_192_cbc, "aria192"); + EVP_add_cipher(EVP_aria_256_ecb()); + EVP_add_cipher(EVP_aria_256_cbc()); + EVP_add_cipher(EVP_aria_256_cfb()); + EVP_add_cipher(EVP_aria_256_cfb1()); + EVP_add_cipher(EVP_aria_256_cfb8()); + EVP_add_cipher(EVP_aria_256_ctr()); + EVP_add_cipher(EVP_aria_256_ofb()); + EVP_add_cipher(EVP_aria_256_gcm()); + EVP_add_cipher(EVP_aria_256_ccm()); + EVP_add_cipher_alias(SN_aria_256_cbc, "ARIA256"); + EVP_add_cipher_alias(SN_aria_256_cbc, "aria256"); +#endif + #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_ecb()); EVP_add_cipher(EVP_camellia_128_cbc()); diff --git a/crypto/evp/c_alld.c b/crypto/evp/c_alld.c index ec79734e..1267531a 100644 --- a/crypto/evp/c_alld.c +++ b/crypto/evp/c_alld.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -10,7 +10,7 @@ #include #include "internal/cryptlib.h" #include -#include +#include "internal/evp_int.h" #include #include @@ -39,11 +39,22 @@ void openssl_add_all_digests_int(void) EVP_add_digest(EVP_sha256()); EVP_add_digest(EVP_sha384()); EVP_add_digest(EVP_sha512()); + EVP_add_digest(EVP_sha512_224()); + EVP_add_digest(EVP_sha512_256()); #ifndef OPENSSL_NO_WHIRLPOOL EVP_add_digest(EVP_whirlpool()); #endif +#ifndef OPENSSL_NO_SM3 + EVP_add_digest(EVP_sm3()); +#endif #ifndef OPENSSL_NO_BLAKE2 EVP_add_digest(EVP_blake2b512()); EVP_add_digest(EVP_blake2s256()); #endif + EVP_add_digest(EVP_sha3_224()); + EVP_add_digest(EVP_sha3_256()); + EVP_add_digest(EVP_sha3_384()); + EVP_add_digest(EVP_sha3_512()); + EVP_add_digest(EVP_shake128()); + EVP_add_digest(EVP_shake256()); } diff --git a/crypto/evp/digest.c b/crypto/evp/digest.c index 65eff7c8..c380dca0 100644 --- a/crypto/evp/digest.c +++ b/crypto/evp/digest.c @@ -174,6 +174,27 @@ int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *size) return ret; } +int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, unsigned char *md, size_t size) +{ + int ret = 0; + + if (ctx->digest->flags & EVP_MD_FLAG_XOF + && size <= INT_MAX + && ctx->digest->md_ctrl(ctx, EVP_MD_CTRL_XOF_LEN, (int)size, NULL)) { + ret = ctx->digest->final(ctx, md); + + if (ctx->digest->cleanup != NULL) { + ctx->digest->cleanup(ctx); + EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED); + } + OPENSSL_cleanse(ctx->md_data, ctx->digest->ctx_size); + } else { + EVPerr(EVP_F_EVP_DIGESTFINALXOF, EVP_R_NOT_XOF_OR_INVALID_LENGTH); + } + + return ret; +} + int EVP_MD_CTX_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in) { EVP_MD_CTX_reset(out); diff --git a/crypto/evp/e_aes.c b/crypto/evp/e_aes.c index 3f36d707..1d5007ac 100644 --- a/crypto/evp/e_aes.c +++ b/crypto/evp/e_aes.c @@ -136,10 +136,10 @@ void AES_ctr32_encrypt(const unsigned char *in, unsigned char *out, const unsigned char ivec[AES_BLOCK_SIZE]); #endif #ifdef AES_XTS_ASM -void AES_xts_encrypt(const char *inp, char *out, size_t len, +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 char *inp, char *out, size_t len, +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 @@ -950,6 +950,1287 @@ static const EVP_CIPHER aes_##keylen##_##mode = { \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; } +#elif defined(OPENSSL_CPUID_OBJ) && defined(__s390__) +/* + * IBM S390X support + */ +# include "s390x_arch.h" + +typedef struct { + union { + double align; + /*- + * KMA-GCM-AES parameter block - begin + * (see z/Architecture Principles of Operation >= SA22-7832-11) + */ + struct { + unsigned char reserved[12]; + union { + unsigned int w; + unsigned char b[4]; + } cv; + union { + unsigned long long g[2]; + unsigned char b[16]; + } t; + unsigned char h[16]; + unsigned long long taadl; + unsigned long long tpcl; + union { + unsigned long long g[2]; + unsigned int w[4]; + } j0; + unsigned char k[32]; + } param; + /* KMA-GCM-AES parameter block - end */ + } kma; + unsigned int fc; + int key_set; + + unsigned char *iv; + int ivlen; + int iv_set; + int iv_gen; + + int taglen; + + unsigned char ares[16]; + unsigned char mres[16]; + unsigned char kres[16]; + int areslen; + int mreslen; + int kreslen; + + int tls_aad_len; +} S390X_AES_GCM_CTX; + +typedef struct { + union { + double align; + /*- + * Padding is chosen so that ccm.kmac_param.k overlaps with key.k and + * ccm.fc with key.k.rounds. Remember that on s390x, an AES_KEY's + * rounds field is used to store the function code and that the key + * schedule is not stored (if aes hardware support is detected). + */ + struct { + unsigned char pad[16]; + AES_KEY k; + } key; + + struct { + /*- + * KMAC-AES parameter block - begin + * (see z/Architecture Principles of Operation >= SA22-7832-08) + */ + struct { + union { + unsigned long long g[2]; + unsigned char b[16]; + } icv; + unsigned char k[32]; + } kmac_param; + /* KMAC-AES paramater block - end */ + + union { + unsigned long long g[2]; + unsigned char b[16]; + } nonce; + union { + unsigned long long g[2]; + unsigned char b[16]; + } buf; + + unsigned long long blocks; + int l; + int m; + int tls_aad_len; + int iv_set; + int tag_set; + int len_set; + int key_set; + + unsigned char pad[140]; + unsigned int fc; + } ccm; + } aes; +} S390X_AES_CCM_CTX; + +# define S390X_aes_128_CAPABLE ((OPENSSL_s390xcap_P.km[0] & \ + S390X_CAPBIT(S390X_AES_128)) &&\ + (OPENSSL_s390xcap_P.kmc[0] & \ + S390X_CAPBIT(S390X_AES_128))) +# define S390X_aes_192_CAPABLE ((OPENSSL_s390xcap_P.km[0] & \ + S390X_CAPBIT(S390X_AES_192)) &&\ + (OPENSSL_s390xcap_P.kmc[0] & \ + S390X_CAPBIT(S390X_AES_192))) +# define S390X_aes_256_CAPABLE ((OPENSSL_s390xcap_P.km[0] & \ + S390X_CAPBIT(S390X_AES_256)) &&\ + (OPENSSL_s390xcap_P.kmc[0] & \ + S390X_CAPBIT(S390X_AES_256))) + +# define s390x_aes_init_key aes_init_key +static int s390x_aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc); + +# define S390X_aes_128_cbc_CAPABLE 1 /* checked by callee */ +# define S390X_aes_192_cbc_CAPABLE 1 +# define S390X_aes_256_cbc_CAPABLE 1 + +# define s390x_aes_cbc_cipher aes_cbc_cipher +static int s390x_aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len); + +# define S390X_aes_128_ecb_CAPABLE 0 +# define S390X_aes_192_ecb_CAPABLE 0 +# define S390X_aes_256_ecb_CAPABLE 0 + +# define s390x_aes_ecb_cipher aes_ecb_cipher +static int s390x_aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len); + +# define S390X_aes_128_ofb_CAPABLE 0 +# define S390X_aes_192_ofb_CAPABLE 0 +# define S390X_aes_256_ofb_CAPABLE 0 + +# define s390x_aes_ofb_cipher aes_ofb_cipher +static int s390x_aes_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len); + +# define S390X_aes_128_cfb_CAPABLE 0 +# define S390X_aes_192_cfb_CAPABLE 0 +# define S390X_aes_256_cfb_CAPABLE 0 + +# define s390x_aes_cfb_cipher aes_cfb_cipher +static int s390x_aes_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len); + +# define S390X_aes_128_cfb8_CAPABLE 0 +# define S390X_aes_192_cfb8_CAPABLE 0 +# define S390X_aes_256_cfb8_CAPABLE 0 + +# define s390x_aes_cfb8_cipher aes_cfb8_cipher +static int s390x_aes_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len); + +# define S390X_aes_128_cfb1_CAPABLE 0 +# define S390X_aes_192_cfb1_CAPABLE 0 +# define S390X_aes_256_cfb1_CAPABLE 0 + +# define s390x_aes_cfb1_cipher aes_cfb1_cipher +static int s390x_aes_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len); + +# define S390X_aes_128_ctr_CAPABLE 1 /* checked by callee */ +# define S390X_aes_192_ctr_CAPABLE 1 +# define S390X_aes_256_ctr_CAPABLE 1 + +# define s390x_aes_ctr_cipher aes_ctr_cipher +static int s390x_aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len); + +# define S390X_aes_128_gcm_CAPABLE (S390X_aes_128_CAPABLE && \ + (OPENSSL_s390xcap_P.kma[0] & \ + S390X_CAPBIT(S390X_AES_128))) +# define S390X_aes_192_gcm_CAPABLE (S390X_aes_192_CAPABLE && \ + (OPENSSL_s390xcap_P.kma[0] & \ + S390X_CAPBIT(S390X_AES_192))) +# define S390X_aes_256_gcm_CAPABLE (S390X_aes_256_CAPABLE && \ + (OPENSSL_s390xcap_P.kma[0] & \ + S390X_CAPBIT(S390X_AES_256))) + +/* iv + padding length for iv lenghts != 12 */ +# define S390X_gcm_ivpadlen(i) ((((i) + 15) >> 4 << 4) + 16) + +/*- + * Process additional authenticated data. Returns 0 on success. Code is + * big-endian. + */ +static int s390x_aes_gcm_aad(S390X_AES_GCM_CTX *ctx, const unsigned char *aad, + size_t len) +{ + unsigned long long alen; + int n, rem; + + if (ctx->kma.param.tpcl) + return -2; + + alen = ctx->kma.param.taadl + len; + if (alen > (U64(1) << 61) || (sizeof(len) == 8 && alen < len)) + return -1; + ctx->kma.param.taadl = alen; + + n = ctx->areslen; + if (n) { + while (n && len) { + ctx->ares[n] = *aad; + n = (n + 1) & 0xf; + ++aad; + --len; + } + /* ctx->ares contains a complete block if offset has wrapped around */ + if (!n) { + s390x_kma(ctx->ares, 16, NULL, 0, NULL, ctx->fc, &ctx->kma.param); + ctx->fc |= S390X_KMA_HS; + } + ctx->areslen = n; + } + + rem = len & 0xf; + + len &= ~0xf; + if (len) { + s390x_kma(aad, len, NULL, 0, NULL, ctx->fc, &ctx->kma.param); + aad += len; + ctx->fc |= S390X_KMA_HS; + } + + if (rem) { + ctx->areslen = rem; + + do { + --rem; + ctx->ares[rem] = aad[rem]; + } while (rem); + } + return 0; +} + +/*- + * En/de-crypt plain/cipher-text and authenticate ciphertext. Returns 0 for + * success. Code is big-endian. + */ +static int s390x_aes_gcm(S390X_AES_GCM_CTX *ctx, const unsigned char *in, + unsigned char *out, size_t len) +{ + const unsigned char *inptr; + unsigned long long mlen; + union { + unsigned int w[4]; + unsigned char b[16]; + } buf; + size_t inlen; + int n, rem, i; + + mlen = ctx->kma.param.tpcl + len; + if (mlen > ((U64(1) << 36) - 32) || (sizeof(len) == 8 && mlen < len)) + return -1; + ctx->kma.param.tpcl = mlen; + + n = ctx->mreslen; + if (n) { + inptr = in; + inlen = len; + while (n && inlen) { + ctx->mres[n] = *inptr; + n = (n + 1) & 0xf; + ++inptr; + --inlen; + } + /* ctx->mres contains a complete block if offset has wrapped around */ + if (!n) { + s390x_kma(ctx->ares, ctx->areslen, ctx->mres, 16, buf.b, + ctx->fc | S390X_KMA_LAAD, &ctx->kma.param); + ctx->fc |= S390X_KMA_HS; + ctx->areslen = 0; + + /* previous call already encrypted/decrypted its remainder, + * see comment below */ + n = ctx->mreslen; + while (n) { + *out = buf.b[n]; + n = (n + 1) & 0xf; + ++out; + ++in; + --len; + } + ctx->mreslen = 0; + } + } + + rem = len & 0xf; + + len &= ~0xf; + if (len) { + s390x_kma(ctx->ares, ctx->areslen, in, len, out, + ctx->fc | S390X_KMA_LAAD, &ctx->kma.param); + in += len; + out += len; + ctx->fc |= S390X_KMA_HS; + ctx->areslen = 0; + } + + /*- + * If there is a remainder, it has to be saved such that it can be + * processed by kma later. However, we also have to do the for-now + * unauthenticated encryption/decryption part here and now... + */ + if (rem) { + if (!ctx->mreslen) { + buf.w[0] = ctx->kma.param.j0.w[0]; + buf.w[1] = ctx->kma.param.j0.w[1]; + buf.w[2] = ctx->kma.param.j0.w[2]; + buf.w[3] = ctx->kma.param.cv.w + 1; + s390x_km(buf.b, 16, ctx->kres, ctx->fc & 0x1f, &ctx->kma.param.k); + } + + n = ctx->mreslen; + for (i = 0; i < rem; i++) { + ctx->mres[n + i] = in[i]; + out[i] = in[i] ^ ctx->kres[n + i]; + } + + ctx->mreslen += rem; + } + return 0; +} + +/*- + * Initialize context structure. Code is big-endian. + */ +static void s390x_aes_gcm_setiv(S390X_AES_GCM_CTX *ctx, + const unsigned char *iv) +{ + ctx->kma.param.t.g[0] = 0; + ctx->kma.param.t.g[1] = 0; + ctx->kma.param.tpcl = 0; + ctx->kma.param.taadl = 0; + ctx->mreslen = 0; + ctx->areslen = 0; + ctx->kreslen = 0; + + if (ctx->ivlen == 12) { + memcpy(&ctx->kma.param.j0, iv, ctx->ivlen); + ctx->kma.param.j0.w[3] = 1; + ctx->kma.param.cv.w = 1; + } else { + /* ctx->iv has the right size and is already padded. */ + memcpy(ctx->iv, iv, ctx->ivlen); + s390x_kma(ctx->iv, S390X_gcm_ivpadlen(ctx->ivlen), NULL, 0, NULL, + ctx->fc, &ctx->kma.param); + ctx->fc |= S390X_KMA_HS; + + ctx->kma.param.j0.g[0] = ctx->kma.param.t.g[0]; + ctx->kma.param.j0.g[1] = ctx->kma.param.t.g[1]; + ctx->kma.param.cv.w = ctx->kma.param.j0.w[3]; + ctx->kma.param.t.g[0] = 0; + ctx->kma.param.t.g[1] = 0; + } +} + +/*- + * Performs various operations on the context structure depending on control + * type. Returns 1 for success, 0 for failure and -1 for unknown control type. + * Code is big-endian. + */ +static int s390x_aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) +{ + S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, c); + S390X_AES_GCM_CTX *gctx_out; + EVP_CIPHER_CTX *out; + unsigned char *buf, *iv; + int ivlen, enc, len; + + switch (type) { + case EVP_CTRL_INIT: + ivlen = EVP_CIPHER_CTX_iv_length(c); + iv = EVP_CIPHER_CTX_iv_noconst(c); + gctx->key_set = 0; + gctx->iv_set = 0; + gctx->ivlen = ivlen; + gctx->iv = iv; + gctx->taglen = -1; + gctx->iv_gen = 0; + gctx->tls_aad_len = -1; + return 1; + + case EVP_CTRL_AEAD_SET_IVLEN: + if (arg <= 0) + return 0; + + if (arg != 12) { + iv = EVP_CIPHER_CTX_iv_noconst(c); + len = S390X_gcm_ivpadlen(arg); + + /* Allocate memory for iv if needed. */ + if (gctx->ivlen == 12 || len > S390X_gcm_ivpadlen(gctx->ivlen)) { + if (gctx->iv != iv) + OPENSSL_free(gctx->iv); + + gctx->iv = OPENSSL_malloc(len); + if (gctx->iv == NULL) + return 0; + } + /* Add padding. */ + memset(gctx->iv + arg, 0, len - arg - 8); + *((unsigned long long *)(gctx->iv + len - 8)) = arg << 3; + } + gctx->ivlen = arg; + return 1; + + case EVP_CTRL_AEAD_SET_TAG: + buf = EVP_CIPHER_CTX_buf_noconst(c); + enc = EVP_CIPHER_CTX_encrypting(c); + if (arg <= 0 || arg > 16 || enc) + return 0; + + memcpy(buf, ptr, arg); + gctx->taglen = arg; + return 1; + + case EVP_CTRL_AEAD_GET_TAG: + enc = EVP_CIPHER_CTX_encrypting(c); + if (arg <= 0 || arg > 16 || !enc || gctx->taglen < 0) + return 0; + + memcpy(ptr, gctx->kma.param.t.b, 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); + + enc = EVP_CIPHER_CTX_encrypting(c); + if (enc && 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; + + s390x_aes_gcm_setiv(gctx, gctx->iv); + + 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. + */ + (*(unsigned long long *)(gctx->iv + gctx->ivlen - 8))++; + gctx->iv_set = 1; + return 1; + + case EVP_CTRL_GCM_SET_IV_INV: + enc = EVP_CIPHER_CTX_encrypting(c); + if (gctx->iv_gen == 0 || gctx->key_set == 0 || enc) + return 0; + + memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); + s390x_aes_gcm_setiv(gctx, gctx->iv); + 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; + + buf = EVP_CIPHER_CTX_buf_noconst(c); + memcpy(buf, ptr, arg); + gctx->tls_aad_len = arg; + + len = buf[arg - 2] << 8 | 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. */ + enc = EVP_CIPHER_CTX_encrypting(c); + if (!enc) { + if (len < EVP_GCM_TLS_TAG_LEN) + return 0; + len -= EVP_GCM_TLS_TAG_LEN; + } + buf[arg - 2] = len >> 8; + buf[arg - 1] = len & 0xff; + /* Extra padding: tag appended to record. */ + return EVP_GCM_TLS_TAG_LEN; + + case EVP_CTRL_COPY: + out = ptr; + gctx_out = EVP_C_DATA(S390X_AES_GCM_CTX, out); + iv = EVP_CIPHER_CTX_iv_noconst(c); + + if (gctx->iv == iv) { + gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out); + } else { + len = S390X_gcm_ivpadlen(gctx->ivlen); + + gctx_out->iv = OPENSSL_malloc(len); + if (gctx_out->iv == NULL) + return 0; + + memcpy(gctx_out->iv, gctx->iv, len); + } + return 1; + + default: + return -1; + } +} + +/*- + * Set key and/or iv. Returns 1 on success. Otherwise 0 is returned. + */ +static int s390x_aes_gcm_init_key(EVP_CIPHER_CTX *ctx, + const unsigned char *key, + const unsigned char *iv, int enc) +{ + S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, ctx); + int keylen; + + if (iv == NULL && key == NULL) + return 1; + + if (key != NULL) { + keylen = EVP_CIPHER_CTX_key_length(ctx); + memcpy(&gctx->kma.param.k, key, keylen); + + /* Convert key size to function code. */ + gctx->fc = S390X_AES_128 + (((keylen << 3) - 128) >> 6); + if (!enc) + gctx->fc |= S390X_DECRYPT; + + if (iv == NULL && gctx->iv_set) + iv = gctx->iv; + + if (iv != NULL) { + s390x_aes_gcm_setiv(gctx, iv); + gctx->iv_set = 1; + } + gctx->key_set = 1; + } else { + if (gctx->key_set) + s390x_aes_gcm_setiv(gctx, iv); + else + memcpy(gctx->iv, iv, gctx->ivlen); + + gctx->iv_set = 1; + gctx->iv_gen = 0; + } + return 1; +} + +/*- + * En/de-crypt and authenticate TLS packet. Returns the number of bytes written + * if successful. Otherwise -1 is returned. Code is big-endian. + */ +static int s390x_aes_gcm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, ctx); + const unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx); + const int enc = EVP_CIPHER_CTX_encrypting(ctx); + int rv = -1; + + if (out != in || len < (EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN)) + return -1; + + if (EVP_CIPHER_CTX_ctrl(ctx, enc ? EVP_CTRL_GCM_IV_GEN + : EVP_CTRL_GCM_SET_IV_INV, + EVP_GCM_TLS_EXPLICIT_IV_LEN, out) <= 0) + goto err; + + 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; + + gctx->kma.param.taadl = gctx->tls_aad_len << 3; + gctx->kma.param.tpcl = len << 3; + s390x_kma(buf, gctx->tls_aad_len, in, len, out, + gctx->fc | S390X_KMA_LAAD | S390X_KMA_LPC, &gctx->kma.param); + + if (enc) { + memcpy(out + len, gctx->kma.param.t.b, EVP_GCM_TLS_TAG_LEN); + rv = len + EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN; + } else { + if (CRYPTO_memcmp(gctx->kma.param.t.b, 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; +} + +/*- + * Called from EVP layer to initialize context, process additional + * authenticated data, en/de-crypt plain/cipher-text and authenticate + * ciphertext or process a TLS packet, depending on context. Returns bytes + * written on success. Otherwise -1 is returned. Code is big-endian. + */ +static int s390x_aes_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, ctx); + unsigned char *buf, tmp[16]; + int enc; + + if (!gctx->key_set) + return -1; + + if (gctx->tls_aad_len >= 0) + return s390x_aes_gcm_tls_cipher(ctx, out, in, len); + + if (!gctx->iv_set) + return -1; + + if (in != NULL) { + if (out == NULL) { + if (s390x_aes_gcm_aad(gctx, in, len)) + return -1; + } else { + if (s390x_aes_gcm(gctx, in, out, len)) + return -1; + } + return len; + } else { + gctx->kma.param.taadl <<= 3; + gctx->kma.param.tpcl <<= 3; + s390x_kma(gctx->ares, gctx->areslen, gctx->mres, gctx->mreslen, tmp, + gctx->fc | S390X_KMA_LAAD | S390X_KMA_LPC, &gctx->kma.param); + /* recall that we already did en-/decrypt gctx->mres + * and returned it to caller... */ + OPENSSL_cleanse(tmp, gctx->mreslen); + gctx->iv_set = 0; + + enc = EVP_CIPHER_CTX_encrypting(ctx); + if (enc) { + gctx->taglen = 16; + } else { + if (gctx->taglen < 0) + return -1; + + buf = EVP_CIPHER_CTX_buf_noconst(ctx); + if (CRYPTO_memcmp(buf, gctx->kma.param.t.b, gctx->taglen)) + return -1; + } + return 0; + } +} + +static int s390x_aes_gcm_cleanup(EVP_CIPHER_CTX *c) +{ + S390X_AES_GCM_CTX *gctx = EVP_C_DATA(S390X_AES_GCM_CTX, c); + const unsigned char *iv; + + if (gctx == NULL) + return 0; + + iv = EVP_CIPHER_CTX_iv(c); + if (iv != gctx->iv) + OPENSSL_free(gctx->iv); + + OPENSSL_cleanse(gctx, sizeof(*gctx)); + return 1; +} + +# define S390X_AES_XTS_CTX EVP_AES_XTS_CTX +# define S390X_aes_128_xts_CAPABLE 1 /* checked by callee */ +# define S390X_aes_256_xts_CAPABLE 1 + +# define s390x_aes_xts_init_key aes_xts_init_key +static int s390x_aes_xts_init_key(EVP_CIPHER_CTX *ctx, + const unsigned char *key, + const unsigned char *iv, int enc); +# define s390x_aes_xts_cipher aes_xts_cipher +static int s390x_aes_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len); +# define s390x_aes_xts_ctrl aes_xts_ctrl +static int s390x_aes_xts_ctrl(EVP_CIPHER_CTX *, int type, int arg, void *ptr); +# define s390x_aes_xts_cleanup aes_xts_cleanup + +# define S390X_aes_128_ccm_CAPABLE (S390X_aes_128_CAPABLE && \ + (OPENSSL_s390xcap_P.kmac[0] & \ + S390X_CAPBIT(S390X_AES_128))) +# define S390X_aes_192_ccm_CAPABLE (S390X_aes_192_CAPABLE && \ + (OPENSSL_s390xcap_P.kmac[0] & \ + S390X_CAPBIT(S390X_AES_192))) +# define S390X_aes_256_ccm_CAPABLE (S390X_aes_256_CAPABLE && \ + (OPENSSL_s390xcap_P.kmac[0] & \ + S390X_CAPBIT(S390X_AES_256))) + +# define S390X_CCM_AAD_FLAG 0x40 + +/*- + * Set nonce and length fields. Code is big-endian. + */ +static inline void s390x_aes_ccm_setiv(S390X_AES_CCM_CTX *ctx, + const unsigned char *nonce, + size_t mlen) +{ + ctx->aes.ccm.nonce.b[0] &= ~S390X_CCM_AAD_FLAG; + ctx->aes.ccm.nonce.g[1] = mlen; + memcpy(ctx->aes.ccm.nonce.b + 1, nonce, 15 - ctx->aes.ccm.l); +} + +/*- + * Process additional authenticated data. Code is big-endian. + */ +static void s390x_aes_ccm_aad(S390X_AES_CCM_CTX *ctx, const unsigned char *aad, + size_t alen) +{ + unsigned char *ptr; + int i, rem; + + if (!alen) + return; + + ctx->aes.ccm.nonce.b[0] |= S390X_CCM_AAD_FLAG; + + /* Suppress 'type-punned pointer dereference' warning. */ + ptr = ctx->aes.ccm.buf.b; + + if (alen < ((1 << 16) - (1 << 8))) { + *(uint16_t *)ptr = alen; + i = 2; + } else if (sizeof(alen) == 8 + && alen >= (size_t)1 << (32 % (sizeof(alen) * 8))) { + *(uint16_t *)ptr = 0xffff; + *(uint64_t *)(ptr + 2) = alen; + i = 10; + } else { + *(uint16_t *)ptr = 0xfffe; + *(uint32_t *)(ptr + 2) = alen; + i = 6; + } + + while (i < 16 && alen) { + ctx->aes.ccm.buf.b[i] = *aad; + ++aad; + --alen; + ++i; + } + while (i < 16) { + ctx->aes.ccm.buf.b[i] = 0; + ++i; + } + + ctx->aes.ccm.kmac_param.icv.g[0] = 0; + ctx->aes.ccm.kmac_param.icv.g[1] = 0; + s390x_kmac(ctx->aes.ccm.nonce.b, 32, ctx->aes.ccm.fc, + &ctx->aes.ccm.kmac_param); + ctx->aes.ccm.blocks += 2; + + rem = alen & 0xf; + alen &= ~0xf; + if (alen) { + s390x_kmac(aad, alen, ctx->aes.ccm.fc, &ctx->aes.ccm.kmac_param); + ctx->aes.ccm.blocks += alen >> 4; + aad += alen; + } + if (rem) { + for (i = 0; i < rem; i++) + ctx->aes.ccm.kmac_param.icv.b[i] ^= aad[i]; + + s390x_km(ctx->aes.ccm.kmac_param.icv.b, 16, + ctx->aes.ccm.kmac_param.icv.b, ctx->aes.ccm.fc, + ctx->aes.ccm.kmac_param.k); + ctx->aes.ccm.blocks++; + } +} + +/*- + * En/de-crypt plain/cipher-text. Compute tag from plaintext. Returns 0 for + * success. + */ +static int s390x_aes_ccm(S390X_AES_CCM_CTX *ctx, const unsigned char *in, + unsigned char *out, size_t len, int enc) +{ + size_t n, rem; + unsigned int i, l, num; + unsigned char flags; + + flags = ctx->aes.ccm.nonce.b[0]; + if (!(flags & S390X_CCM_AAD_FLAG)) { + s390x_km(ctx->aes.ccm.nonce.b, 16, ctx->aes.ccm.kmac_param.icv.b, + ctx->aes.ccm.fc, ctx->aes.ccm.kmac_param.k); + ctx->aes.ccm.blocks++; + } + l = flags & 0x7; + ctx->aes.ccm.nonce.b[0] = l; + + /*- + * Reconstruct length from encoded length field + * and initialize it with counter value. + */ + n = 0; + for (i = 15 - l; i < 15; i++) { + n |= ctx->aes.ccm.nonce.b[i]; + ctx->aes.ccm.nonce.b[i] = 0; + n <<= 8; + } + n |= ctx->aes.ccm.nonce.b[15]; + ctx->aes.ccm.nonce.b[15] = 1; + + if (n != len) + return -1; /* length mismatch */ + + if (enc) { + /* Two operations per block plus one for tag encryption */ + ctx->aes.ccm.blocks += (((len + 15) >> 4) << 1) + 1; + if (ctx->aes.ccm.blocks > (1ULL << 61)) + return -2; /* too much data */ + } + + num = 0; + rem = len & 0xf; + len &= ~0xf; + + if (enc) { + /* mac-then-encrypt */ + if (len) + s390x_kmac(in, len, ctx->aes.ccm.fc, &ctx->aes.ccm.kmac_param); + if (rem) { + for (i = 0; i < rem; i++) + ctx->aes.ccm.kmac_param.icv.b[i] ^= in[len + i]; + + s390x_km(ctx->aes.ccm.kmac_param.icv.b, 16, + ctx->aes.ccm.kmac_param.icv.b, ctx->aes.ccm.fc, + ctx->aes.ccm.kmac_param.k); + } + + CRYPTO_ctr128_encrypt_ctr32(in, out, len + rem, &ctx->aes.key.k, + ctx->aes.ccm.nonce.b, ctx->aes.ccm.buf.b, + &num, (ctr128_f)AES_ctr32_encrypt); + } else { + /* decrypt-then-mac */ + CRYPTO_ctr128_encrypt_ctr32(in, out, len + rem, &ctx->aes.key.k, + ctx->aes.ccm.nonce.b, ctx->aes.ccm.buf.b, + &num, (ctr128_f)AES_ctr32_encrypt); + + if (len) + s390x_kmac(out, len, ctx->aes.ccm.fc, &ctx->aes.ccm.kmac_param); + if (rem) { + for (i = 0; i < rem; i++) + ctx->aes.ccm.kmac_param.icv.b[i] ^= out[len + i]; + + s390x_km(ctx->aes.ccm.kmac_param.icv.b, 16, + ctx->aes.ccm.kmac_param.icv.b, ctx->aes.ccm.fc, + ctx->aes.ccm.kmac_param.k); + } + } + /* encrypt tag */ + for (i = 15 - l; i < 16; i++) + ctx->aes.ccm.nonce.b[i] = 0; + + s390x_km(ctx->aes.ccm.nonce.b, 16, ctx->aes.ccm.buf.b, ctx->aes.ccm.fc, + ctx->aes.ccm.kmac_param.k); + ctx->aes.ccm.kmac_param.icv.g[0] ^= ctx->aes.ccm.buf.g[0]; + ctx->aes.ccm.kmac_param.icv.g[1] ^= ctx->aes.ccm.buf.g[1]; + + ctx->aes.ccm.nonce.b[0] = flags; /* restore flags field */ + return 0; +} + +/*- + * En/de-crypt and authenticate TLS packet. Returns the number of bytes written + * if successful. Otherwise -1 is returned. + */ +static int s390x_aes_ccm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, ctx); + unsigned char *ivec = EVP_CIPHER_CTX_iv_noconst(ctx); + unsigned char *buf = EVP_CIPHER_CTX_buf_noconst(ctx); + const int enc = EVP_CIPHER_CTX_encrypting(ctx); + + if (out != in + || len < (EVP_CCM_TLS_EXPLICIT_IV_LEN + (size_t)cctx->aes.ccm.m)) + return -1; + + if (enc) { + /* Set explicit iv (sequence number). */ + memcpy(out, buf, EVP_CCM_TLS_EXPLICIT_IV_LEN); + } + + len -= EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->aes.ccm.m; + /*- + * Get explicit iv (sequence number). We already have fixed iv + * (server/client_write_iv) here. + */ + memcpy(ivec + EVP_CCM_TLS_FIXED_IV_LEN, in, EVP_CCM_TLS_EXPLICIT_IV_LEN); + s390x_aes_ccm_setiv(cctx, ivec, len); + + /* Process aad (sequence number|type|version|length) */ + s390x_aes_ccm_aad(cctx, buf, cctx->aes.ccm.tls_aad_len); + + in += EVP_CCM_TLS_EXPLICIT_IV_LEN; + out += EVP_CCM_TLS_EXPLICIT_IV_LEN; + + if (enc) { + if (s390x_aes_ccm(cctx, in, out, len, enc)) + return -1; + + memcpy(out + len, cctx->aes.ccm.kmac_param.icv.b, cctx->aes.ccm.m); + return len + EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->aes.ccm.m; + } else { + if (!s390x_aes_ccm(cctx, in, out, len, enc)) { + if (!CRYPTO_memcmp(cctx->aes.ccm.kmac_param.icv.b, in + len, + cctx->aes.ccm.m)) + return len; + } + + OPENSSL_cleanse(out, len); + return -1; + } +} + +/*- + * Set key and flag field and/or iv. Returns 1 if successful. Otherwise 0 is + * returned. + */ +static int s390x_aes_ccm_init_key(EVP_CIPHER_CTX *ctx, + const unsigned char *key, + const unsigned char *iv, int enc) +{ + S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, ctx); + unsigned char *ivec; + int keylen; + + if (iv == NULL && key == NULL) + return 1; + + if (key != NULL) { + keylen = EVP_CIPHER_CTX_key_length(ctx); + /* Convert key size to function code. */ + cctx->aes.ccm.fc = S390X_AES_128 + (((keylen << 3) - 128) >> 6); + memcpy(cctx->aes.ccm.kmac_param.k, key, keylen); + + /* Store encoded m and l. */ + cctx->aes.ccm.nonce.b[0] = ((cctx->aes.ccm.l - 1) & 0x7) + | (((cctx->aes.ccm.m - 2) >> 1) & 0x7) << 3; + memset(cctx->aes.ccm.nonce.b + 1, 0, + sizeof(cctx->aes.ccm.nonce.b)); + cctx->aes.ccm.blocks = 0; + + cctx->aes.ccm.key_set = 1; + } + + if (iv != NULL) { + ivec = EVP_CIPHER_CTX_iv_noconst(ctx); + memcpy(ivec, iv, 15 - cctx->aes.ccm.l); + + cctx->aes.ccm.iv_set = 1; + } + + return 1; +} + +/*- + * Called from EVP layer to initialize context, process additional + * authenticated data, en/de-crypt plain/cipher-text and authenticate + * plaintext or process a TLS packet, depending on context. Returns bytes + * written on success. Otherwise -1 is returned. + */ +static int s390x_aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, ctx); + const int enc = EVP_CIPHER_CTX_encrypting(ctx); + int rv; + unsigned char *buf, *ivec; + + if (!cctx->aes.ccm.key_set) + return -1; + + if (cctx->aes.ccm.tls_aad_len >= 0) + return s390x_aes_ccm_tls_cipher(ctx, out, in, len); + + /*- + * Final(): Does not return any data. Recall that ccm is mac-then-encrypt + * so integrity must be checked already at Update() i.e., before + * potentially corrupted data is output. + */ + if (in == NULL && out != NULL) + return 0; + + if (!cctx->aes.ccm.iv_set) + return -1; + + if (!enc && !cctx->aes.ccm.tag_set) + return -1; + + if (out == NULL) { + /* Update(): Pass message length. */ + if (in == NULL) { + ivec = EVP_CIPHER_CTX_iv_noconst(ctx); + s390x_aes_ccm_setiv(cctx, ivec, len); + + cctx->aes.ccm.len_set = 1; + return len; + } + + /* Update(): Process aad. */ + if (!cctx->aes.ccm.len_set && len) + return -1; + + s390x_aes_ccm_aad(cctx, in, len); + return len; + } + + /* Update(): Process message. */ + + if (!cctx->aes.ccm.len_set) { + /*- + * In case message length was not previously set explicitely via + * Update(), set it now. + */ + ivec = EVP_CIPHER_CTX_iv_noconst(ctx); + s390x_aes_ccm_setiv(cctx, ivec, len); + + cctx->aes.ccm.len_set = 1; + } + + if (enc) { + if (s390x_aes_ccm(cctx, in, out, len, enc)) + return -1; + + cctx->aes.ccm.tag_set = 1; + return len; + } else { + rv = -1; + + if (!s390x_aes_ccm(cctx, in, out, len, enc)) { + buf = EVP_CIPHER_CTX_buf_noconst(ctx); + if (!CRYPTO_memcmp(cctx->aes.ccm.kmac_param.icv.b, buf, + cctx->aes.ccm.m)) + rv = len; + } + + if (rv == -1) + OPENSSL_cleanse(out, len); + + cctx->aes.ccm.iv_set = 0; + cctx->aes.ccm.tag_set = 0; + cctx->aes.ccm.len_set = 0; + return rv; + } +} + +/*- + * Performs various operations on the context structure depending on control + * type. Returns 1 for success, 0 for failure and -1 for unknown control type. + * Code is big-endian. + */ +static int s390x_aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) +{ + S390X_AES_CCM_CTX *cctx = EVP_C_DATA(S390X_AES_CCM_CTX, c); + unsigned char *buf, *iv; + int enc, len; + + switch (type) { + case EVP_CTRL_INIT: + cctx->aes.ccm.key_set = 0; + cctx->aes.ccm.iv_set = 0; + cctx->aes.ccm.l = 8; + cctx->aes.ccm.m = 12; + cctx->aes.ccm.tag_set = 0; + cctx->aes.ccm.len_set = 0; + cctx->aes.ccm.tls_aad_len = -1; + return 1; + + case EVP_CTRL_AEAD_TLS1_AAD: + if (arg != EVP_AEAD_TLS1_AAD_LEN) + return 0; + + /* Save the aad for later use. */ + buf = EVP_CIPHER_CTX_buf_noconst(c); + memcpy(buf, ptr, arg); + cctx->aes.ccm.tls_aad_len = arg; + + len = *(uint16_t *)(buf + arg - 2); + if (len < EVP_CCM_TLS_EXPLICIT_IV_LEN) + return 0; + + /* Correct length for explicit iv. */ + len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; + + enc = EVP_CIPHER_CTX_encrypting(c); + if (!enc) { + if (len < cctx->aes.ccm.m) + return 0; + + /* Correct length for tag. */ + len -= cctx->aes.ccm.m; + } + + *(uint16_t *)(buf + arg - 2) = len; + /* Extra padding: tag appended to record. */ + return cctx->aes.ccm.m; + + case EVP_CTRL_CCM_SET_IV_FIXED: + if (arg != EVP_CCM_TLS_FIXED_IV_LEN) + return 0; + + /* Copy to first part of the iv. */ + iv = EVP_CIPHER_CTX_iv_noconst(c); + memcpy(iv, ptr, arg); + return 1; + + case EVP_CTRL_AEAD_SET_IVLEN: + arg = 15 - arg; + /* fall-through */ + + case EVP_CTRL_CCM_SET_L: + if (arg < 2 || arg > 8) + return 0; + + cctx->aes.ccm.l = arg; + return 1; + + case EVP_CTRL_AEAD_SET_TAG: + if ((arg & 1) || arg < 4 || arg > 16) + return 0; + + enc = EVP_CIPHER_CTX_encrypting(c); + if (enc && ptr) + return 0; + + if (ptr) { + cctx->aes.ccm.tag_set = 1; + buf = EVP_CIPHER_CTX_buf_noconst(c); + memcpy(buf, ptr, arg); + } + + cctx->aes.ccm.m = arg; + return 1; + + case EVP_CTRL_AEAD_GET_TAG: + enc = EVP_CIPHER_CTX_encrypting(c); + if (!enc || !cctx->aes.ccm.tag_set) + return 0; + + if(arg < cctx->aes.ccm.m) + return 0; + + memcpy(ptr, cctx->aes.ccm.kmac_param.icv.b, cctx->aes.ccm.m); + cctx->aes.ccm.tag_set = 0; + cctx->aes.ccm.iv_set = 0; + cctx->aes.ccm.len_set = 0; + return 1; + + case EVP_CTRL_COPY: + return 1; + + default: + return -1; + } +} + +# define s390x_aes_ccm_cleanup aes_ccm_cleanup + +# ifndef OPENSSL_NO_OCB +# define S390X_AES_OCB_CTX EVP_AES_OCB_CTX +# define S390X_aes_128_ocb_CAPABLE 0 +# define S390X_aes_192_ocb_CAPABLE 0 +# define S390X_aes_256_ocb_CAPABLE 0 + +# define s390x_aes_ocb_init_key aes_ocb_init_key +static int s390x_aes_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc); +# define s390x_aes_ocb_cipher aes_ocb_cipher +static int s390x_aes_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len); +# define s390x_aes_ocb_cleanup aes_ocb_cleanup +static int s390x_aes_ocb_cleanup(EVP_CIPHER_CTX *); +# define s390x_aes_ocb_ctrl aes_ocb_ctrl +static int s390x_aes_ocb_ctrl(EVP_CIPHER_CTX *, int type, int arg, void *ptr); +# endif + +# define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode, \ + MODE,flags) \ +static const EVP_CIPHER s390x_aes_##keylen##_##mode = { \ + nid##_##keylen##_##nmode,blocksize, \ + keylen / 8, \ + ivlen, \ + flags | EVP_CIPH_##MODE##_MODE, \ + s390x_aes_init_key, \ + s390x_aes_##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 S390X_aes_##keylen##_##mode##_CAPABLE ? \ + &s390x_aes_##keylen##_##mode : &aes_##keylen##_##mode; \ +} + +# define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags)\ +static const EVP_CIPHER s390x_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, \ + s390x_aes_##mode##_init_key, \ + s390x_aes_##mode##_cipher, \ + s390x_aes_##mode##_cleanup, \ + sizeof(S390X_AES_##MODE##_CTX), \ + NULL, \ + NULL, \ + s390x_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 S390X_aes_##keylen##_##mode##_CAPABLE ? \ + &s390x_aes_##keylen##_##mode : &aes_##keylen##_##mode; \ +} + #else # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ @@ -2132,6 +3413,10 @@ static int aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, if (cctx->tls_aad_len >= 0) return aes_ccm_tls_cipher(ctx, out, in, len); + /* EVP_*Final() doesn't return any data */ + if (in == NULL && out != NULL) + return 0; + if (!cctx->iv_set) return -1; @@ -2151,9 +3436,6 @@ static int aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, 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, EVP_CIPHER_CTX_iv_noconst(ctx), diff --git a/crypto/evp/e_aes_cbc_hmac_sha1.c b/crypto/evp/e_aes_cbc_hmac_sha1.c index f30f722e..09d24dc3 100644 --- a/crypto/evp/e_aes_cbc_hmac_sha1.c +++ b/crypto/evp/e_aes_cbc_hmac_sha1.c @@ -570,7 +570,7 @@ static int aesni_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, } # endif -# if 1 +# if 1 /* see original reference version in #else */ len -= SHA_DIGEST_LENGTH; /* amend mac */ if (len >= (256 + SHA_CBLOCK)) { j = (len - (256 + SHA_CBLOCK)) & (0 - SHA_CBLOCK); @@ -664,7 +664,7 @@ static int aesni_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, } # endif len += SHA_DIGEST_LENGTH; -# else +# else /* pre-lucky-13 reference version of above */ SHA1_Update(&key->md, out, inp_len); res = key->md.num; SHA1_Final(pmac->c, &key->md); @@ -691,7 +691,7 @@ static int aesni_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, /* verify HMAC */ out += inp_len; len -= inp_len; -# if 1 +# if 1 /* see original reference version in #else */ { unsigned char *p = out + len - 1 - maxpad - SHA_DIGEST_LENGTH; size_t off = out - p; @@ -713,7 +713,7 @@ static int aesni_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; } -# else +# else /* pre-lucky-13 reference version of above */ for (res = 0, i = 0; i < SHA_DIGEST_LENGTH; i++) res |= out[i] ^ pmac->c[i]; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); diff --git a/crypto/evp/e_aes_cbc_hmac_sha256.c b/crypto/evp/e_aes_cbc_hmac_sha256.c index 13973f11..caac0c9d 100644 --- a/crypto/evp/e_aes_cbc_hmac_sha256.c +++ b/crypto/evp/e_aes_cbc_hmac_sha256.c @@ -559,7 +559,7 @@ static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx, key->md = key->head; SHA256_Update(&key->md, key->aux.tls_aad, plen); -# if 1 +# if 1 /* see original reference version in #else */ len -= SHA256_DIGEST_LENGTH; /* amend mac */ if (len >= (256 + SHA256_CBLOCK)) { j = (len - (256 + SHA256_CBLOCK)) & (0 - SHA256_CBLOCK); @@ -687,7 +687,7 @@ static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx, for (; inp_blocks < pad_blocks; inp_blocks++) sha1_block_data_order(&key->md, data, 1); } -# endif +# endif /* pre-lucky-13 reference version of above */ key->md = key->tail; SHA256_Update(&key->md, pmac->c, SHA256_DIGEST_LENGTH); SHA256_Final(pmac->c, &key->md); @@ -695,7 +695,7 @@ static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx, /* verify HMAC */ out += inp_len; len -= inp_len; -# if 1 +# if 1 /* see original reference version in #else */ { unsigned char *p = out + len - 1 - maxpad - SHA256_DIGEST_LENGTH; @@ -718,7 +718,7 @@ static int aesni_cbc_hmac_sha256_cipher(EVP_CIPHER_CTX *ctx, res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; } -# else +# else /* pre-lucky-13 reference version of above */ for (res = 0, i = 0; i < SHA256_DIGEST_LENGTH; i++) res |= out[i] ^ pmac->c[i]; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); diff --git a/crypto/evp/e_aria.c b/crypto/evp/e_aria.c new file mode 100644 index 00000000..00e008a3 --- /dev/null +++ b/crypto/evp/e_aria.c @@ -0,0 +1,753 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2017, Oracle and/or its affiliates. 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 "internal/cryptlib.h" +#ifndef OPENSSL_NO_ARIA +# include +# include +# include +# include "internal/aria.h" +# include "internal/evp_int.h" +# include "modes_lcl.h" +# include "evp_locl.h" + +/* ARIA subkey Structure */ +typedef struct { + ARIA_KEY ks; +} EVP_ARIA_KEY; + +/* ARIA GCM context */ +typedef struct { + union { + double align; + ARIA_KEY ks; + } ks; /* ARIA subkey 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 */ +} EVP_ARIA_GCM_CTX; + +/* ARIA CCM context */ +typedef struct { + union { + double align; + ARIA_KEY ks; + } ks; /* ARIA 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 */ + int tls_aad_len; /* TLS AAD length */ + CCM128_CONTEXT ccm; + ccm128_f str; +} EVP_ARIA_CCM_CTX; + +/* The subkey for ARIA is generated. */ +static int aria_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc) +{ + int ret; + int mode = EVP_CIPHER_CTX_mode(ctx); + + if (enc || (mode != EVP_CIPH_ECB_MODE && mode != EVP_CIPH_CBC_MODE)) + ret = aria_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, + EVP_CIPHER_CTX_get_cipher_data(ctx)); + else + ret = aria_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, + EVP_CIPHER_CTX_get_cipher_data(ctx)); + if (ret < 0) { + EVPerr(EVP_F_ARIA_INIT_KEY,EVP_R_ARIA_KEY_SETUP_FAILED); + return 0; + } + return 1; +} + +static void aria_cbc_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const ARIA_KEY *key, + unsigned char *ivec, const int enc) +{ + + if (enc) + CRYPTO_cbc128_encrypt(in, out, len, key, ivec, + (block128_f) aria_encrypt); + else + CRYPTO_cbc128_decrypt(in, out, len, key, ivec, + (block128_f) aria_encrypt); +} + +static void aria_cfb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const ARIA_KEY *key, + unsigned char *ivec, int *num, const int enc) +{ + + CRYPTO_cfb128_encrypt(in, out, length, key, ivec, num, enc, + (block128_f) aria_encrypt); +} + +static void aria_cfb1_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const ARIA_KEY *key, + unsigned char *ivec, int *num, const int enc) +{ + CRYPTO_cfb128_1_encrypt(in, out, length, key, ivec, num, enc, + (block128_f) aria_encrypt); +} + +static void aria_cfb8_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const ARIA_KEY *key, + unsigned char *ivec, int *num, const int enc) +{ + CRYPTO_cfb128_8_encrypt(in, out, length, key, ivec, num, enc, + (block128_f) aria_encrypt); +} + +static void aria_ecb_encrypt(const unsigned char *in, unsigned char *out, + const ARIA_KEY *key, const int enc) +{ + aria_encrypt(in, out, key); +} + +static void aria_ofb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const ARIA_KEY *key, + unsigned char *ivec, int *num) +{ + CRYPTO_ofb128_encrypt(in, out, length, key, ivec, num, + (block128_f) aria_encrypt); +} + +IMPLEMENT_BLOCK_CIPHER(aria_128, ks, aria, EVP_ARIA_KEY, + NID_aria_128, 16, 16, 16, 128, + 0, aria_init_key, NULL, + EVP_CIPHER_set_asn1_iv, + EVP_CIPHER_get_asn1_iv, + NULL) +IMPLEMENT_BLOCK_CIPHER(aria_192, ks, aria, EVP_ARIA_KEY, + NID_aria_192, 16, 24, 16, 128, + 0, aria_init_key, NULL, + EVP_CIPHER_set_asn1_iv, + EVP_CIPHER_get_asn1_iv, + NULL) +IMPLEMENT_BLOCK_CIPHER(aria_256, ks, aria, EVP_ARIA_KEY, + NID_aria_256, 16, 32, 16, 128, + 0, aria_init_key, NULL, + EVP_CIPHER_set_asn1_iv, + EVP_CIPHER_get_asn1_iv, + NULL) + +# define IMPLEMENT_ARIA_CFBR(ksize,cbits) \ + IMPLEMENT_CFBR(aria,aria,EVP_ARIA_KEY,ks,ksize,cbits,16,0) +IMPLEMENT_ARIA_CFBR(128,1) +IMPLEMENT_ARIA_CFBR(192,1) +IMPLEMENT_ARIA_CFBR(256,1) +IMPLEMENT_ARIA_CFBR(128,8) +IMPLEMENT_ARIA_CFBR(192,8) +IMPLEMENT_ARIA_CFBR(256,8) + +# define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ +static const EVP_CIPHER aria_##keylen##_##mode = { \ + nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \ + flags|EVP_CIPH_##MODE##_MODE, \ + aria_init_key, \ + aria_##mode##_cipher, \ + NULL, \ + sizeof(EVP_ARIA_KEY), \ + NULL,NULL,NULL,NULL }; \ +const EVP_CIPHER *EVP_aria_##keylen##_##mode(void) \ +{ return &aria_##keylen##_##mode; } + +static int aria_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + unsigned int num = EVP_CIPHER_CTX_num(ctx); + EVP_ARIA_KEY *dat = EVP_C_DATA(EVP_ARIA_KEY,ctx); + + CRYPTO_ctr128_encrypt(in, out, len, &dat->ks, + EVP_CIPHER_CTX_iv_noconst(ctx), + EVP_CIPHER_CTX_buf_noconst(ctx), &num, + (block128_f) aria_encrypt); + EVP_CIPHER_CTX_set_num(ctx, num); + return 1; +} + +BLOCK_CIPHER_generic(NID_aria, 128, 1, 16, ctr, ctr, CTR, 0) +BLOCK_CIPHER_generic(NID_aria, 192, 1, 16, ctr, ctr, CTR, 0) +BLOCK_CIPHER_generic(NID_aria, 256, 1, 16, ctr, ctr, CTR, 0) + +/* Authenticated cipher modes (GCM/CCM) */ + +/* 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 aria_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc) +{ + int ret; + EVP_ARIA_GCM_CTX *gctx = EVP_C_DATA(EVP_ARIA_GCM_CTX,ctx); + + if (!iv && !key) + return 1; + if (key) { + ret = aria_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, + &gctx->ks.ks); + CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, + (block128_f) aria_encrypt); + if (ret < 0) { + EVPerr(EVP_F_ARIA_GCM_INIT_KEY,EVP_R_ARIA_KEY_SETUP_FAILED); + 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; +} + +static int aria_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) +{ + EVP_ARIA_GCM_CTX *gctx = EVP_C_DATA(EVP_ARIA_GCM_CTX,c); + + switch (type) { + case EVP_CTRL_INIT: + gctx->key_set = 0; + gctx->iv_set = 0; + gctx->ivlen = EVP_CIPHER_CTX_iv_length(c); + gctx->iv = EVP_CIPHER_CTX_iv_noconst(c); + gctx->taglen = -1; + gctx->iv_gen = 0; + gctx->tls_aad_len = -1; + return 1; + + case EVP_CTRL_AEAD_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 != EVP_CIPHER_CTX_iv_noconst(c)) + OPENSSL_free(gctx->iv); + gctx->iv = OPENSSL_malloc(arg); + if (gctx->iv == NULL) + return 0; + } + gctx->ivlen = arg; + return 1; + + case EVP_CTRL_AEAD_SET_TAG: + if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_encrypting(c)) + return 0; + memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); + gctx->taglen = arg; + return 1; + + case EVP_CTRL_AEAD_GET_TAG: + if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_encrypting(c) + || gctx->taglen < 0) + return 0; + memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), 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 (EVP_CIPHER_CTX_encrypting(c) + && 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 + || EVP_CIPHER_CTX_encrypting(c)) + 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(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); + gctx->tls_aad_len = arg; + { + unsigned int len = + EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 + | EVP_CIPHER_CTX_buf_noconst(c)[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 (!EVP_CIPHER_CTX_encrypting(c)) { + if (len < EVP_GCM_TLS_TAG_LEN) + return 0; + len -= EVP_GCM_TLS_TAG_LEN; + } + EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; + EVP_CIPHER_CTX_buf_noconst(c)[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_ARIA_GCM_CTX *gctx_out = EVP_C_DATA(EVP_ARIA_GCM_CTX,out); + if (gctx->gcm.key) { + if (gctx->gcm.key != &gctx->ks) + return 0; + gctx_out->gcm.key = &gctx_out->ks; + } + if (gctx->iv == EVP_CIPHER_CTX_iv_noconst(c)) + gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out); + else { + gctx_out->iv = OPENSSL_malloc(gctx->ivlen); + if (gctx_out->iv == NULL) + return 0; + memcpy(gctx_out->iv, gctx->iv, gctx->ivlen); + } + return 1; + } + + default: + return -1; + + } +} + +static int aria_gcm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + EVP_ARIA_GCM_CTX *gctx = EVP_C_DATA(EVP_ARIA_GCM_CTX,ctx); + 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, EVP_CIPHER_CTX_encrypting(ctx) ? + 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, EVP_CIPHER_CTX_buf_noconst(ctx), + 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 (EVP_CIPHER_CTX_encrypting(ctx)) { + /* Encrypt payload */ + if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, len)) + 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 (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, len)) + goto err; + /* Retrieve tag */ + CRYPTO_gcm128_tag(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), + EVP_GCM_TLS_TAG_LEN); + /* If tag mismatch wipe buffer */ + if (CRYPTO_memcmp(EVP_CIPHER_CTX_buf_noconst(ctx), 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 aria_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + EVP_ARIA_GCM_CTX *gctx = EVP_C_DATA(EVP_ARIA_GCM_CTX,ctx); + + /* If not set up, return error */ + if (!gctx->key_set) + return -1; + + if (gctx->tls_aad_len >= 0) + return aria_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 (EVP_CIPHER_CTX_encrypting(ctx)) { + if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, len)) + return -1; + } else { + if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, len)) + return -1; + } + return len; + } + if (!EVP_CIPHER_CTX_encrypting(ctx)) { + if (gctx->taglen < 0) + return -1; + if (CRYPTO_gcm128_finish(&gctx->gcm, + EVP_CIPHER_CTX_buf_noconst(ctx), + gctx->taglen) != 0) + return -1; + gctx->iv_set = 0; + return 0; + } + CRYPTO_gcm128_tag(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), 16); + gctx->taglen = 16; + /* Don't reuse the IV */ + gctx->iv_set = 0; + return 0; +} + +static int aria_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc) +{ + int ret; + EVP_ARIA_CCM_CTX *cctx = EVP_C_DATA(EVP_ARIA_CCM_CTX,ctx); + + if (!iv && !key) + return 1; + + if (key) { + ret = aria_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, + &cctx->ks.ks); + CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, + &cctx->ks, (block128_f) aria_encrypt); + if (ret < 0) { + EVPerr(EVP_F_ARIA_CCM_INIT_KEY,EVP_R_ARIA_KEY_SETUP_FAILED); + return 0; + } + cctx->str = NULL; + cctx->key_set = 1; + } + if (iv) { + memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, 15 - cctx->L); + cctx->iv_set = 1; + } + return 1; +} + +static int aria_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) +{ + EVP_ARIA_CCM_CTX *cctx = EVP_C_DATA(EVP_ARIA_CCM_CTX,c); + + 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; + cctx->tls_aad_len = -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(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); + cctx->tls_aad_len = arg; + { + uint16_t len = + EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 + | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; + /* Correct length for explicit IV */ + if (len < EVP_CCM_TLS_EXPLICIT_IV_LEN) + return 0; + len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; + /* If decrypting correct for tag too */ + if (!EVP_CIPHER_CTX_encrypting(c)) { + if (len < cctx->M) + return 0; + len -= cctx->M; + } + EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; + EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; + } + /* Extra padding: tag appended to record */ + return cctx->M; + + case EVP_CTRL_CCM_SET_IV_FIXED: + /* Sanity check length */ + if (arg != EVP_CCM_TLS_FIXED_IV_LEN) + return 0; + /* Just copy to first part of IV */ + memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg); + return 1; + + case EVP_CTRL_AEAD_SET_IVLEN: + arg = 15 - arg; + /* fall thru */ + case EVP_CTRL_CCM_SET_L: + if (arg < 2 || arg > 8) + return 0; + cctx->L = arg; + return 1; + case EVP_CTRL_AEAD_SET_TAG: + if ((arg & 1) || arg < 4 || arg > 16) + return 0; + if (EVP_CIPHER_CTX_encrypting(c) && ptr) + return 0; + if (ptr) { + cctx->tag_set = 1; + memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); + } + cctx->M = arg; + return 1; + + case EVP_CTRL_AEAD_GET_TAG: + if (!EVP_CIPHER_CTX_encrypting(c) || !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_ARIA_CCM_CTX *cctx_out = EVP_C_DATA(EVP_ARIA_CCM_CTX,out); + 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 aria_ccm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + EVP_ARIA_CCM_CTX *cctx = EVP_C_DATA(EVP_ARIA_CCM_CTX,ctx); + CCM128_CONTEXT *ccm = &cctx->ccm; + + /* Encrypt/decrypt must be performed in place */ + if (out != in || len < (EVP_CCM_TLS_EXPLICIT_IV_LEN + (size_t)cctx->M)) + return -1; + /* If encrypting set explicit IV from sequence number (start of AAD) */ + if (EVP_CIPHER_CTX_encrypting(ctx)) + memcpy(out, EVP_CIPHER_CTX_buf_noconst(ctx), + EVP_CCM_TLS_EXPLICIT_IV_LEN); + /* Get rest of IV from explicit IV */ + memcpy(EVP_CIPHER_CTX_iv_noconst(ctx) + EVP_CCM_TLS_FIXED_IV_LEN, in, + EVP_CCM_TLS_EXPLICIT_IV_LEN); + /* Correct length value */ + len -= EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->M; + if (CRYPTO_ccm128_setiv(ccm, EVP_CIPHER_CTX_iv_noconst(ctx), 15 - cctx->L, + len)) + return -1; + /* Use saved AAD */ + CRYPTO_ccm128_aad(ccm, EVP_CIPHER_CTX_buf_noconst(ctx), cctx->tls_aad_len); + /* Fix buffer to point to payload */ + in += EVP_CCM_TLS_EXPLICIT_IV_LEN; + out += EVP_CCM_TLS_EXPLICIT_IV_LEN; + if (EVP_CIPHER_CTX_encrypting(ctx)) { + if (cctx->str ? CRYPTO_ccm128_encrypt_ccm64(ccm, in, out, len, cctx->str) + : CRYPTO_ccm128_encrypt(ccm, in, out, len)) + return -1; + if (!CRYPTO_ccm128_tag(ccm, out + len, cctx->M)) + return -1; + return len + EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->M; + } else { + 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, in + len, cctx->M)) + return len; + } + } + OPENSSL_cleanse(out, len); + return -1; + } +} + +static int aria_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + EVP_ARIA_CCM_CTX *cctx = EVP_C_DATA(EVP_ARIA_CCM_CTX,ctx); + CCM128_CONTEXT *ccm = &cctx->ccm; + + /* If not set up, return error */ + if (!cctx->key_set) + return -1; + + if (cctx->tls_aad_len >= 0) + return aria_ccm_tls_cipher(ctx, out, in, len); + + /* EVP_*Final() doesn't return any data */ + if (in == NULL && out != NULL) + return 0; + + if (!cctx->iv_set) + return -1; + + if (!EVP_CIPHER_CTX_encrypting(ctx) && !cctx->tag_set) + return -1; + if (!out) { + if (!in) { + if (CRYPTO_ccm128_setiv(ccm, EVP_CIPHER_CTX_iv_noconst(ctx), + 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; + } + /* If not set length yet do it */ + if (!cctx->len_set) { + if (CRYPTO_ccm128_setiv(ccm, EVP_CIPHER_CTX_iv_noconst(ctx), + 15 - cctx->L, len)) + return -1; + cctx->len_set = 1; + } + if (EVP_CIPHER_CTX_encrypting(ctx)) { + 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, EVP_CIPHER_CTX_buf_noconst(ctx), + 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 ARIA_AUTH_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 | EVP_CIPH_FLAG_AEAD_CIPHER) + +#define BLOCK_CIPHER_aead(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ +static const EVP_CIPHER aria_##keylen##_##mode = { \ + nid##_##keylen##_##nmode, \ + blocksize, keylen/8, ivlen, \ + ARIA_AUTH_FLAGS|EVP_CIPH_##MODE##_MODE, \ + aria_##mode##_init_key, \ + aria_##mode##_cipher, \ + NULL, \ + sizeof(EVP_ARIA_##MODE##_CTX), \ + NULL,NULL,aria_##mode##_ctrl,NULL }; \ +const EVP_CIPHER *EVP_aria_##keylen##_##mode(void) \ +{ return (EVP_CIPHER*)&aria_##keylen##_##mode; } + +BLOCK_CIPHER_aead(NID_aria, 128, 1, 12, gcm, gcm, GCM, 0) +BLOCK_CIPHER_aead(NID_aria, 192, 1, 12, gcm, gcm, GCM, 0) +BLOCK_CIPHER_aead(NID_aria, 256, 1, 12, gcm, gcm, GCM, 0) + +BLOCK_CIPHER_aead(NID_aria, 128, 1, 12, ccm, ccm, CCM, 0) +BLOCK_CIPHER_aead(NID_aria, 192, 1, 12, ccm, ccm, CCM, 0) +BLOCK_CIPHER_aead(NID_aria, 256, 1, 12, ccm, ccm, CCM, 0) + +#endif diff --git a/crypto/evp/e_chacha20_poly1305.c b/crypto/evp/e_chacha20_poly1305.c index 7fd4f8df..9bf98f16 100644 --- a/crypto/evp/e_chacha20_poly1305.c +++ b/crypto/evp/e_chacha20_poly1305.c @@ -140,7 +140,7 @@ static const EVP_CIPHER chacha20 = { const EVP_CIPHER *EVP_chacha20(void) { - return (&chacha20); + return &chacha20; } # ifndef OPENSSL_NO_POLY1305 diff --git a/crypto/evp/e_null.c b/crypto/evp/e_null.c index 0dfc48ab..18a84682 100644 --- a/crypto/evp/e_null.c +++ b/crypto/evp/e_null.c @@ -32,7 +32,7 @@ static const EVP_CIPHER n_cipher = { const EVP_CIPHER *EVP_enc_null(void) { - return (&n_cipher); + return &n_cipher; } static int null_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, diff --git a/crypto/evp/e_rc2.c b/crypto/evp/e_rc2.c index ed10bb33..80afe316 100644 --- a/crypto/evp/e_rc2.c +++ b/crypto/evp/e_rc2.c @@ -72,12 +72,12 @@ static const EVP_CIPHER r2_40_cbc_cipher = { const EVP_CIPHER *EVP_rc2_64_cbc(void) { - return (&r2_64_cbc_cipher); + return &r2_64_cbc_cipher; } const EVP_CIPHER *EVP_rc2_40_cbc(void) { - return (&r2_40_cbc_cipher); + return &r2_40_cbc_cipher; } static int rc2_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, @@ -94,13 +94,13 @@ static int rc2_meth_to_magic(EVP_CIPHER_CTX *e) EVP_CIPHER_CTX_ctrl(e, EVP_CTRL_GET_RC2_KEY_BITS, 0, &i); if (i == 128) - return (RC2_128_MAGIC); + return RC2_128_MAGIC; else if (i == 64) - return (RC2_64_MAGIC); + return RC2_64_MAGIC; else if (i == 40) - return (RC2_40_MAGIC); + return RC2_40_MAGIC; else - return (0); + return 0; } static int rc2_magic_to_meth(int i) @@ -113,7 +113,7 @@ static int rc2_magic_to_meth(int i) return 40; else { EVPerr(EVP_F_RC2_MAGIC_TO_METH, EVP_R_UNSUPPORTED_KEY_SIZE); - return (0); + return 0; } } @@ -155,7 +155,7 @@ static int rc2_set_asn1_type_and_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type) (unsigned char *)EVP_CIPHER_CTX_original_iv(c), j); } - return (i); + return i; } static int rc2_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) diff --git a/crypto/evp/e_rc4.c b/crypto/evp/e_rc4.c index ea95deab..d16abdd0 100644 --- a/crypto/evp/e_rc4.c +++ b/crypto/evp/e_rc4.c @@ -58,12 +58,12 @@ static const EVP_CIPHER r4_40_cipher = { const EVP_CIPHER *EVP_rc4(void) { - return (&r4_cipher); + return &r4_cipher; } const EVP_CIPHER *EVP_rc4_40(void) { - return (&r4_40_cipher); + return &r4_40_cipher; } static int rc4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, diff --git a/crypto/evp/e_rc4_hmac_md5.c b/crypto/evp/e_rc4_hmac_md5.c index 8ab18c14..b1e8ccd6 100644 --- a/crypto/evp/e_rc4_hmac_md5.c +++ b/crypto/evp/e_rc4_hmac_md5.c @@ -257,6 +257,6 @@ static EVP_CIPHER r4_hmac_md5_cipher = { const EVP_CIPHER *EVP_rc4_hmac_md5(void) { - return (&r4_hmac_md5_cipher); + return &r4_hmac_md5_cipher; } #endif diff --git a/crypto/evp/e_rc5.c b/crypto/evp/e_rc5.c index f69ba5b2..a2f26d8c 100644 --- a/crypto/evp/e_rc5.c +++ b/crypto/evp/e_rc5.c @@ -13,7 +13,7 @@ #ifndef OPENSSL_NO_RC5 # include -# include +# include "internal/evp_int.h" # include # include "evp_locl.h" # include diff --git a/crypto/evp/e_sm4.c b/crypto/evp/e_sm4.c new file mode 100644 index 00000000..79deb656 --- /dev/null +++ b/crypto/evp/e_sm4.c @@ -0,0 +1,100 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 Ribose Inc. All Rights Reserved. + * Ported from Ribose contributions from Botan. + * + * 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 "internal/cryptlib.h" +#ifndef OPENSSL_NO_SM4 +# include +# include +# include "internal/sm4.h" +# include "internal/evp_int.h" + +typedef struct { + SM4_KEY ks; +} EVP_SM4_KEY; + +static int sm4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, + const unsigned char *iv, int enc) +{ + SM4_set_key(key, EVP_CIPHER_CTX_get_cipher_data(ctx)); + return 1; +} + +static void sm4_cbc_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const SM4_KEY *key, + unsigned char *ivec, const int enc) +{ + if (enc) + CRYPTO_cbc128_encrypt(in, out, len, key, ivec, + (block128_f)SM4_encrypt); + else + CRYPTO_cbc128_decrypt(in, out, len, key, ivec, + (block128_f)SM4_decrypt); +} + +static void sm4_cfb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const SM4_KEY *key, + unsigned char *ivec, int *num, const int enc) +{ + CRYPTO_cfb128_encrypt(in, out, length, key, ivec, num, enc, + (block128_f)SM4_encrypt); +} + +static void sm4_ecb_encrypt(const unsigned char *in, unsigned char *out, + const SM4_KEY *key, const int enc) +{ + if (enc) + SM4_encrypt(in, out, key); + else + SM4_decrypt(in, out, key); +} + +static void sm4_ofb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const SM4_KEY *key, + unsigned char *ivec, int *num) +{ + CRYPTO_ofb128_encrypt(in, out, length, key, ivec, num, + (block128_f)SM4_encrypt); +} + +IMPLEMENT_BLOCK_CIPHER(sm4, ks, sm4, EVP_SM4_KEY, NID_sm4, + 16, 16, 16, 128, EVP_CIPH_FLAG_DEFAULT_ASN1, + sm4_init_key, 0, 0, 0, 0) + +static int sm4_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, + const unsigned char *in, size_t len) +{ + unsigned int num = EVP_CIPHER_CTX_num(ctx); + EVP_SM4_KEY *dat = EVP_C_DATA(EVP_SM4_KEY, ctx); + + CRYPTO_ctr128_encrypt(in, out, len, &dat->ks, + EVP_CIPHER_CTX_iv_noconst(ctx), + EVP_CIPHER_CTX_buf_noconst(ctx), &num, + (block128_f)SM4_encrypt); + EVP_CIPHER_CTX_set_num(ctx, num); + return 1; +} + +static const EVP_CIPHER sm4_ctr_mode = { + NID_sm4_ctr, 1, 16, 16, + EVP_CIPH_CTR_MODE, + sm4_init_key, + sm4_ctr_cipher, + NULL, + sizeof(EVP_SM4_KEY), + NULL, NULL, NULL, NULL +}; + +const EVP_CIPHER *EVP_sm4_ctr(void) +{ + return &sm4_ctr_mode; +} + +#endif diff --git a/crypto/evp/e_xcbc_d.c b/crypto/evp/e_xcbc_d.c index effaf5cc..57ce813d 100644 --- a/crypto/evp/e_xcbc_d.c +++ b/crypto/evp/e_xcbc_d.c @@ -46,7 +46,7 @@ static const EVP_CIPHER d_xcbc_cipher = { const EVP_CIPHER *EVP_desx_cbc(void) { - return (&d_xcbc_cipher); + return &d_xcbc_cipher; } static int desx_cbc_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, diff --git a/crypto/evp/encode.c b/crypto/evp/encode.c index abb10443..17198ff6 100644 --- a/crypto/evp/encode.c +++ b/crypto/evp/encode.c @@ -212,7 +212,7 @@ int EVP_EncodeBlock(unsigned char *t, const unsigned char *f, int dlen) } *t = '\0'; - return (ret); + return ret; } void EVP_DecodeInit(EVP_ENCODE_CTX *ctx) @@ -345,7 +345,7 @@ end: /* Legacy behaviour. This should probably rather be zeroed on error. */ *outl = ret; ctx->num = n; - return (rv); + return rv; } int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n) @@ -367,7 +367,7 @@ int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n) n--; if (n % 4 != 0) - return (-1); + return -1; for (i = 0; i < n; i += 4) { a = conv_ascii2bin(*(f++)); @@ -375,7 +375,7 @@ int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n) c = conv_ascii2bin(*(f++)); d = conv_ascii2bin(*(f++)); if ((a & 0x80) || (b & 0x80) || (c & 0x80) || (d & 0x80)) - return (-1); + return -1; l = ((((unsigned long)a) << 18L) | (((unsigned long)b) << 12L) | (((unsigned long)c) << 6L) | (((unsigned long)d))); @@ -384,7 +384,7 @@ int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n) *(t++) = (unsigned char)(l) & 0xff; ret += 3; } - return (ret); + return ret; } int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl) @@ -395,10 +395,10 @@ int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl) if (ctx->num != 0) { i = EVP_DecodeBlock(out, ctx->enc_data, ctx->num); if (i < 0) - return (-1); + return -1; ctx->num = 0; *outl = i; - return (1); + return 1; } else - return (1); + return 1; } diff --git a/crypto/evp/evp_cnf.c b/crypto/evp/evp_cnf.c index 71d13b8d..8df2c06e 100644 --- a/crypto/evp/evp_cnf.c +++ b/crypto/evp/evp_cnf.c @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2012-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 @@ -8,7 +8,6 @@ */ #include -#include #include #include "internal/cryptlib.h" #include @@ -38,16 +37,8 @@ static int alg_module_init(CONF_IMODULE *md, const CONF *cnf) return 0; } if (m > 0) { -#ifdef OPENSSL_FIPS - if (!FIPS_mode() && !FIPS_mode_set(1)) { - EVPerr(EVP_F_ALG_MODULE_INIT, - EVP_R_ERROR_SETTING_FIPS_MODE); - return 0; - } -#else EVPerr(EVP_F_ALG_MODULE_INIT, EVP_R_FIPS_MODE_NOT_SUPPORTED); return 0; -#endif } } else { EVPerr(EVP_F_ALG_MODULE_INIT, EVP_R_UNKNOWN_OPTION); diff --git a/crypto/evp/evp_enc.c b/crypto/evp/evp_enc.c index e5807edd..2c4a2db6 100644 --- a/crypto/evp/evp_enc.c +++ b/crypto/evp/evp_enc.c @@ -523,7 +523,7 @@ int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) if (b > 1) { if (ctx->buf_len || !ctx->final_used) { EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH); - return (0); + return 0; } OPENSSL_assert(b <= sizeof(ctx->final)); @@ -534,12 +534,12 @@ int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) n = ctx->final[b - 1]; if (n == 0 || n > (int)b) { EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT); - return (0); + 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); + return 0; } } n = ctx->cipher->block_size - n; @@ -548,7 +548,7 @@ int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) *outl = n; } else *outl = 0; - return (1); + return 1; } int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen) diff --git a/crypto/evp/evp_err.c b/crypto/evp/evp_err.c index c4b163f0..a43de746 100644 --- a/crypto/evp/evp_err.c +++ b/crypto/evp/evp_err.c @@ -8,166 +8,235 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_EVP,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_EVP,0,reason) - -static ERR_STRING_DATA EVP_str_functs[] = { - {ERR_FUNC(EVP_F_AESNI_INIT_KEY), "aesni_init_key"}, - {ERR_FUNC(EVP_F_AES_INIT_KEY), "aes_init_key"}, - {ERR_FUNC(EVP_F_AES_OCB_CIPHER), "aes_ocb_cipher"}, - {ERR_FUNC(EVP_F_AES_T4_INIT_KEY), "aes_t4_init_key"}, - {ERR_FUNC(EVP_F_AES_WRAP_CIPHER), "aes_wrap_cipher"}, - {ERR_FUNC(EVP_F_ALG_MODULE_INIT), "alg_module_init"}, - {ERR_FUNC(EVP_F_CAMELLIA_INIT_KEY), "camellia_init_key"}, - {ERR_FUNC(EVP_F_CHACHA20_POLY1305_CTRL), "chacha20_poly1305_ctrl"}, - {ERR_FUNC(EVP_F_CMLL_T4_INIT_KEY), "cmll_t4_init_key"}, - {ERR_FUNC(EVP_F_DES_EDE3_WRAP_CIPHER), "des_ede3_wrap_cipher"}, - {ERR_FUNC(EVP_F_DO_SIGVER_INIT), "do_sigver_init"}, - {ERR_FUNC(EVP_F_EVP_CIPHERINIT_EX), "EVP_CipherInit_ex"}, - {ERR_FUNC(EVP_F_EVP_CIPHER_CTX_COPY), "EVP_CIPHER_CTX_copy"}, - {ERR_FUNC(EVP_F_EVP_CIPHER_CTX_CTRL), "EVP_CIPHER_CTX_ctrl"}, - {ERR_FUNC(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH), +static const ERR_STRING_DATA EVP_str_functs[] = { + {ERR_PACK(ERR_LIB_EVP, EVP_F_AESNI_INIT_KEY, 0), "aesni_init_key"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_AES_INIT_KEY, 0), "aes_init_key"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_AES_OCB_CIPHER, 0), "aes_ocb_cipher"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_AES_T4_INIT_KEY, 0), "aes_t4_init_key"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_AES_WRAP_CIPHER, 0), "aes_wrap_cipher"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_ALG_MODULE_INIT, 0), "alg_module_init"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_ARIA_CCM_INIT_KEY, 0), "aria_ccm_init_key"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_ARIA_GCM_INIT_KEY, 0), "aria_gcm_init_key"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_ARIA_INIT_KEY, 0), "aria_init_key"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_CAMELLIA_INIT_KEY, 0), "camellia_init_key"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_CHACHA20_POLY1305_CTRL, 0), + "chacha20_poly1305_ctrl"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_CMLL_T4_INIT_KEY, 0), "cmll_t4_init_key"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_DES_EDE3_WRAP_CIPHER, 0), + "des_ede3_wrap_cipher"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_DO_SIGVER_INIT, 0), "do_sigver_init"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_CIPHERINIT_EX, 0), "EVP_CipherInit_ex"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_CIPHER_CTX_COPY, 0), + "EVP_CIPHER_CTX_copy"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_CIPHER_CTX_CTRL, 0), + "EVP_CIPHER_CTX_ctrl"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, 0), "EVP_CIPHER_CTX_set_key_length"}, - {ERR_FUNC(EVP_F_EVP_DECRYPTFINAL_EX), "EVP_DecryptFinal_ex"}, - {ERR_FUNC(EVP_F_EVP_DECRYPTUPDATE), "EVP_DecryptUpdate"}, - {ERR_FUNC(EVP_F_EVP_DIGESTINIT_EX), "EVP_DigestInit_ex"}, - {ERR_FUNC(EVP_F_EVP_ENCRYPTFINAL_EX), "EVP_EncryptFinal_ex"}, - {ERR_FUNC(EVP_F_EVP_ENCRYPTUPDATE), "EVP_EncryptUpdate"}, - {ERR_FUNC(EVP_F_EVP_MD_CTX_COPY_EX), "EVP_MD_CTX_copy_ex"}, - {ERR_FUNC(EVP_F_EVP_MD_SIZE), "EVP_MD_size"}, - {ERR_FUNC(EVP_F_EVP_OPENINIT), "EVP_OpenInit"}, - {ERR_FUNC(EVP_F_EVP_PBE_ALG_ADD), "EVP_PBE_alg_add"}, - {ERR_FUNC(EVP_F_EVP_PBE_ALG_ADD_TYPE), "EVP_PBE_alg_add_type"}, - {ERR_FUNC(EVP_F_EVP_PBE_CIPHERINIT), "EVP_PBE_CipherInit"}, - {ERR_FUNC(EVP_F_EVP_PBE_SCRYPT), "EVP_PBE_scrypt"}, - {ERR_FUNC(EVP_F_EVP_PKCS82PKEY), "EVP_PKCS82PKEY"}, - {ERR_FUNC(EVP_F_EVP_PKEY2PKCS8), "EVP_PKEY2PKCS8"}, - {ERR_FUNC(EVP_F_EVP_PKEY_ASN1_ADD0), "EVP_PKEY_asn1_add0"}, - {ERR_FUNC(EVP_F_EVP_PKEY_COPY_PARAMETERS), "EVP_PKEY_copy_parameters"}, - {ERR_FUNC(EVP_F_EVP_PKEY_CTX_CTRL), "EVP_PKEY_CTX_ctrl"}, - {ERR_FUNC(EVP_F_EVP_PKEY_CTX_CTRL_STR), "EVP_PKEY_CTX_ctrl_str"}, - {ERR_FUNC(EVP_F_EVP_PKEY_CTX_DUP), "EVP_PKEY_CTX_dup"}, - {ERR_FUNC(EVP_F_EVP_PKEY_DECRYPT), "EVP_PKEY_decrypt"}, - {ERR_FUNC(EVP_F_EVP_PKEY_DECRYPT_INIT), "EVP_PKEY_decrypt_init"}, - {ERR_FUNC(EVP_F_EVP_PKEY_DECRYPT_OLD), "EVP_PKEY_decrypt_old"}, - {ERR_FUNC(EVP_F_EVP_PKEY_DERIVE), "EVP_PKEY_derive"}, - {ERR_FUNC(EVP_F_EVP_PKEY_DERIVE_INIT), "EVP_PKEY_derive_init"}, - {ERR_FUNC(EVP_F_EVP_PKEY_DERIVE_SET_PEER), "EVP_PKEY_derive_set_peer"}, - {ERR_FUNC(EVP_F_EVP_PKEY_ENCRYPT), "EVP_PKEY_encrypt"}, - {ERR_FUNC(EVP_F_EVP_PKEY_ENCRYPT_INIT), "EVP_PKEY_encrypt_init"}, - {ERR_FUNC(EVP_F_EVP_PKEY_ENCRYPT_OLD), "EVP_PKEY_encrypt_old"}, - {ERR_FUNC(EVP_F_EVP_PKEY_GET0_DH), "EVP_PKEY_get0_DH"}, - {ERR_FUNC(EVP_F_EVP_PKEY_GET0_DSA), "EVP_PKEY_get0_DSA"}, - {ERR_FUNC(EVP_F_EVP_PKEY_GET0_EC_KEY), "EVP_PKEY_get0_EC_KEY"}, - {ERR_FUNC(EVP_F_EVP_PKEY_GET0_HMAC), "EVP_PKEY_get0_hmac"}, - {ERR_FUNC(EVP_F_EVP_PKEY_GET0_RSA), "EVP_PKEY_get0_RSA"}, - {ERR_FUNC(EVP_F_EVP_PKEY_KEYGEN), "EVP_PKEY_keygen"}, - {ERR_FUNC(EVP_F_EVP_PKEY_KEYGEN_INIT), "EVP_PKEY_keygen_init"}, - {ERR_FUNC(EVP_F_EVP_PKEY_NEW), "EVP_PKEY_new"}, - {ERR_FUNC(EVP_F_EVP_PKEY_PARAMGEN), "EVP_PKEY_paramgen"}, - {ERR_FUNC(EVP_F_EVP_PKEY_PARAMGEN_INIT), "EVP_PKEY_paramgen_init"}, - {ERR_FUNC(EVP_F_EVP_PKEY_SET1_ENGINE), "EVP_PKEY_set1_engine"}, - {ERR_FUNC(EVP_F_EVP_PKEY_SIGN), "EVP_PKEY_sign"}, - {ERR_FUNC(EVP_F_EVP_PKEY_SIGN_INIT), "EVP_PKEY_sign_init"}, - {ERR_FUNC(EVP_F_EVP_PKEY_VERIFY), "EVP_PKEY_verify"}, - {ERR_FUNC(EVP_F_EVP_PKEY_VERIFY_INIT), "EVP_PKEY_verify_init"}, - {ERR_FUNC(EVP_F_EVP_PKEY_VERIFY_RECOVER), "EVP_PKEY_verify_recover"}, - {ERR_FUNC(EVP_F_EVP_PKEY_VERIFY_RECOVER_INIT), + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_DECRYPTFINAL_EX, 0), + "EVP_DecryptFinal_ex"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_DECRYPTUPDATE, 0), "EVP_DecryptUpdate"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_DIGESTFINALXOF, 0), "EVP_DigestFinalXOF"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_DIGESTINIT_EX, 0), "EVP_DigestInit_ex"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_ENCRYPTFINAL_EX, 0), + "EVP_EncryptFinal_ex"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_ENCRYPTUPDATE, 0), "EVP_EncryptUpdate"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_MD_CTX_COPY_EX, 0), "EVP_MD_CTX_copy_ex"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_MD_SIZE, 0), "EVP_MD_size"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_OPENINIT, 0), "EVP_OpenInit"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PBE_ALG_ADD, 0), "EVP_PBE_alg_add"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PBE_ALG_ADD_TYPE, 0), + "EVP_PBE_alg_add_type"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PBE_CIPHERINIT, 0), "EVP_PBE_CipherInit"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PBE_SCRYPT, 0), "EVP_PBE_scrypt"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKCS82PKEY, 0), "EVP_PKCS82PKEY"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY2PKCS8, 0), "EVP_PKEY2PKCS8"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_ASN1_ADD0, 0), "EVP_PKEY_asn1_add0"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_CHECK, 0), "EVP_PKEY_check"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_COPY_PARAMETERS, 0), + "EVP_PKEY_copy_parameters"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_CTX_CTRL, 0), "EVP_PKEY_CTX_ctrl"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_CTX_CTRL_STR, 0), + "EVP_PKEY_CTX_ctrl_str"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_CTX_DUP, 0), "EVP_PKEY_CTX_dup"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_CTX_MD, 0), "EVP_PKEY_CTX_md"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_DECRYPT, 0), "EVP_PKEY_decrypt"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_DECRYPT_INIT, 0), + "EVP_PKEY_decrypt_init"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_DECRYPT_OLD, 0), + "EVP_PKEY_decrypt_old"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_DERIVE, 0), "EVP_PKEY_derive"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_DERIVE_INIT, 0), + "EVP_PKEY_derive_init"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_DERIVE_SET_PEER, 0), + "EVP_PKEY_derive_set_peer"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_ENCRYPT, 0), "EVP_PKEY_encrypt"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_ENCRYPT_INIT, 0), + "EVP_PKEY_encrypt_init"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_ENCRYPT_OLD, 0), + "EVP_PKEY_encrypt_old"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_GET0_DH, 0), "EVP_PKEY_get0_DH"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_GET0_DSA, 0), "EVP_PKEY_get0_DSA"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_GET0_EC_KEY, 0), + "EVP_PKEY_get0_EC_KEY"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_GET0_HMAC, 0), "EVP_PKEY_get0_hmac"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_GET0_POLY1305, 0), + "EVP_PKEY_get0_poly1305"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_GET0_RSA, 0), "EVP_PKEY_get0_RSA"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_GET0_SIPHASH, 0), + "EVP_PKEY_get0_siphash"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_KEYGEN, 0), "EVP_PKEY_keygen"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_KEYGEN_INIT, 0), + "EVP_PKEY_keygen_init"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_NEW, 0), "EVP_PKEY_new"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_PARAMGEN, 0), "EVP_PKEY_paramgen"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_PARAMGEN_INIT, 0), + "EVP_PKEY_paramgen_init"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_PARAM_CHECK, 0), + "EVP_PKEY_param_check"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_PUBLIC_CHECK, 0), + "EVP_PKEY_public_check"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_SET1_ENGINE, 0), + "EVP_PKEY_set1_engine"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_SIGN, 0), "EVP_PKEY_sign"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_SIGN_INIT, 0), "EVP_PKEY_sign_init"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_VERIFY, 0), "EVP_PKEY_verify"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_VERIFY_INIT, 0), + "EVP_PKEY_verify_init"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_VERIFY_RECOVER, 0), + "EVP_PKEY_verify_recover"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_PKEY_VERIFY_RECOVER_INIT, 0), "EVP_PKEY_verify_recover_init"}, - {ERR_FUNC(EVP_F_EVP_SIGNFINAL), "EVP_SignFinal"}, - {ERR_FUNC(EVP_F_EVP_VERIFYFINAL), "EVP_VerifyFinal"}, - {ERR_FUNC(EVP_F_INT_CTX_NEW), "int_ctx_new"}, - {ERR_FUNC(EVP_F_PKCS5_PBE_KEYIVGEN), "PKCS5_PBE_keyivgen"}, - {ERR_FUNC(EVP_F_PKCS5_V2_PBE_KEYIVGEN), "PKCS5_v2_PBE_keyivgen"}, - {ERR_FUNC(EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN), "PKCS5_v2_PBKDF2_keyivgen"}, - {ERR_FUNC(EVP_F_PKCS5_V2_SCRYPT_KEYIVGEN), "PKCS5_v2_scrypt_keyivgen"}, - {ERR_FUNC(EVP_F_PKEY_SET_TYPE), "pkey_set_type"}, - {ERR_FUNC(EVP_F_RC2_MAGIC_TO_METH), "rc2_magic_to_meth"}, - {ERR_FUNC(EVP_F_RC5_CTRL), "rc5_ctrl"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_SIGNFINAL, 0), "EVP_SignFinal"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_EVP_VERIFYFINAL, 0), "EVP_VerifyFinal"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_INT_CTX_NEW, 0), "int_ctx_new"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_PKCS5_PBE_KEYIVGEN, 0), "PKCS5_PBE_keyivgen"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_PKCS5_V2_PBE_KEYIVGEN, 0), + "PKCS5_v2_PBE_keyivgen"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN, 0), + "PKCS5_v2_PBKDF2_keyivgen"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_PKCS5_V2_SCRYPT_KEYIVGEN, 0), + "PKCS5_v2_scrypt_keyivgen"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_PKEY_SET_TYPE, 0), "pkey_set_type"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_RC2_MAGIC_TO_METH, 0), "rc2_magic_to_meth"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_RC5_CTRL, 0), "rc5_ctrl"}, + {ERR_PACK(ERR_LIB_EVP, EVP_F_UPDATE, 0), "update"}, {0, NULL} }; -static ERR_STRING_DATA EVP_str_reasons[] = { - {ERR_REASON(EVP_R_AES_KEY_SETUP_FAILED), "aes key setup failed"}, - {ERR_REASON(EVP_R_BAD_DECRYPT), "bad decrypt"}, - {ERR_REASON(EVP_R_BUFFER_TOO_SMALL), "buffer too small"}, - {ERR_REASON(EVP_R_CAMELLIA_KEY_SETUP_FAILED), - "camellia key setup failed"}, - {ERR_REASON(EVP_R_CIPHER_PARAMETER_ERROR), "cipher parameter error"}, - {ERR_REASON(EVP_R_COMMAND_NOT_SUPPORTED), "command not supported"}, - {ERR_REASON(EVP_R_COPY_ERROR), "copy error"}, - {ERR_REASON(EVP_R_CTRL_NOT_IMPLEMENTED), "ctrl not implemented"}, - {ERR_REASON(EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED), - "ctrl operation not implemented"}, - {ERR_REASON(EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH), - "data not multiple of block length"}, - {ERR_REASON(EVP_R_DECODE_ERROR), "decode error"}, - {ERR_REASON(EVP_R_DIFFERENT_KEY_TYPES), "different key types"}, - {ERR_REASON(EVP_R_DIFFERENT_PARAMETERS), "different parameters"}, - {ERR_REASON(EVP_R_ERROR_LOADING_SECTION), "error loading section"}, - {ERR_REASON(EVP_R_ERROR_SETTING_FIPS_MODE), "error setting fips mode"}, - {ERR_REASON(EVP_R_EXPECTING_AN_HMAC_KEY), "expecting an hmac key"}, - {ERR_REASON(EVP_R_EXPECTING_AN_RSA_KEY), "expecting an rsa key"}, - {ERR_REASON(EVP_R_EXPECTING_A_DH_KEY), "expecting a dh key"}, - {ERR_REASON(EVP_R_EXPECTING_A_DSA_KEY), "expecting a dsa key"}, - {ERR_REASON(EVP_R_EXPECTING_A_EC_KEY), "expecting a ec key"}, - {ERR_REASON(EVP_R_FIPS_MODE_NOT_SUPPORTED), "fips mode not supported"}, - {ERR_REASON(EVP_R_ILLEGAL_SCRYPT_PARAMETERS), - "illegal scrypt parameters"}, - {ERR_REASON(EVP_R_INITIALIZATION_ERROR), "initialization error"}, - {ERR_REASON(EVP_R_INPUT_NOT_INITIALIZED), "input not initialized"}, - {ERR_REASON(EVP_R_INVALID_DIGEST), "invalid digest"}, - {ERR_REASON(EVP_R_INVALID_FIPS_MODE), "invalid fips mode"}, - {ERR_REASON(EVP_R_INVALID_KEY), "invalid key"}, - {ERR_REASON(EVP_R_INVALID_KEY_LENGTH), "invalid key length"}, - {ERR_REASON(EVP_R_INVALID_OPERATION), "invalid operation"}, - {ERR_REASON(EVP_R_KEYGEN_FAILURE), "keygen failure"}, - {ERR_REASON(EVP_R_MEMORY_LIMIT_EXCEEDED), "memory limit exceeded"}, - {ERR_REASON(EVP_R_MESSAGE_DIGEST_IS_NULL), "message digest is null"}, - {ERR_REASON(EVP_R_METHOD_NOT_SUPPORTED), "method not supported"}, - {ERR_REASON(EVP_R_MISSING_PARAMETERS), "missing parameters"}, - {ERR_REASON(EVP_R_NO_CIPHER_SET), "no cipher set"}, - {ERR_REASON(EVP_R_NO_DEFAULT_DIGEST), "no default digest"}, - {ERR_REASON(EVP_R_NO_DIGEST_SET), "no digest set"}, - {ERR_REASON(EVP_R_NO_KEY_SET), "no key set"}, - {ERR_REASON(EVP_R_NO_OPERATION_SET), "no operation set"}, - {ERR_REASON(EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE), - "operation not supported for this keytype"}, - {ERR_REASON(EVP_R_OPERATON_NOT_INITIALIZED), "operaton not initialized"}, - {ERR_REASON(EVP_R_PARTIALLY_OVERLAPPING), - "partially overlapping buffers"}, - {ERR_REASON(EVP_R_PKEY_APPLICATION_ASN1_METHOD_ALREADY_REGISTERED), - "pkey application asn1 method already registered"}, - {ERR_REASON(EVP_R_PKEY_ASN1_METHOD_ALREADY_REGISTERED), - "pkey asn1 method already registered"}, - {ERR_REASON(EVP_R_PRIVATE_KEY_DECODE_ERROR), "private key decode error"}, - {ERR_REASON(EVP_R_PRIVATE_KEY_ENCODE_ERROR), "private key encode error"}, - {ERR_REASON(EVP_R_PUBLIC_KEY_NOT_RSA), "public key not rsa"}, - {ERR_REASON(EVP_R_UNKNOWN_CIPHER), "unknown cipher"}, - {ERR_REASON(EVP_R_UNKNOWN_DIGEST), "unknown digest"}, - {ERR_REASON(EVP_R_UNKNOWN_OPTION), "unknown option"}, - {ERR_REASON(EVP_R_UNKNOWN_PBE_ALGORITHM), "unknown pbe algorithm"}, - {ERR_REASON(EVP_R_UNSUPPORTED_ALGORITHM), "unsupported algorithm"}, - {ERR_REASON(EVP_R_UNSUPPORTED_CIPHER), "unsupported cipher"}, - {ERR_REASON(EVP_R_UNSUPPORTED_KEYLENGTH), "unsupported keylength"}, - {ERR_REASON(EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION), - "unsupported key derivation function"}, - {ERR_REASON(EVP_R_UNSUPPORTED_KEY_SIZE), "unsupported key size"}, - {ERR_REASON(EVP_R_UNSUPPORTED_NUMBER_OF_ROUNDS), - "unsupported number of rounds"}, - {ERR_REASON(EVP_R_UNSUPPORTED_PRF), "unsupported prf"}, - {ERR_REASON(EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM), - "unsupported private key algorithm"}, - {ERR_REASON(EVP_R_UNSUPPORTED_SALT_TYPE), "unsupported salt type"}, - {ERR_REASON(EVP_R_WRAP_MODE_NOT_ALLOWED), "wrap mode not allowed"}, - {ERR_REASON(EVP_R_WRONG_FINAL_BLOCK_LENGTH), "wrong final block length"}, +static const ERR_STRING_DATA EVP_str_reasons[] = { + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_AES_KEY_SETUP_FAILED), + "aes key setup failed"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_ARIA_KEY_SETUP_FAILED), + "aria key setup failed"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_BAD_DECRYPT), "bad decrypt"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_BUFFER_TOO_SMALL), "buffer too small"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CAMELLIA_KEY_SETUP_FAILED), + "camellia key setup failed"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CIPHER_PARAMETER_ERROR), + "cipher parameter error"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_COMMAND_NOT_SUPPORTED), + "command not supported"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_COPY_ERROR), "copy error"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CTRL_NOT_IMPLEMENTED), + "ctrl not implemented"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED), + "ctrl operation not implemented"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH), + "data not multiple of block length"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_DECODE_ERROR), "decode error"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_DIFFERENT_KEY_TYPES), + "different key types"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_DIFFERENT_PARAMETERS), + "different parameters"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_ERROR_LOADING_SECTION), + "error loading section"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_ERROR_SETTING_FIPS_MODE), + "error setting fips mode"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_AN_HMAC_KEY), + "expecting an hmac key"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_AN_RSA_KEY), + "expecting an rsa key"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_DH_KEY), "expecting a dh key"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_DSA_KEY), + "expecting a dsa key"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_EC_KEY), "expecting a ec key"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_POLY1305_KEY), + "expecting a poly1305 key"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_A_SIPHASH_KEY), + "expecting a siphash key"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_FIPS_MODE_NOT_SUPPORTED), + "fips mode not supported"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_ILLEGAL_SCRYPT_PARAMETERS), + "illegal scrypt parameters"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INITIALIZATION_ERROR), + "initialization error"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INPUT_NOT_INITIALIZED), + "input not initialized"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_DIGEST), "invalid digest"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_FIPS_MODE), "invalid fips mode"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_KEY), "invalid key"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_KEY_LENGTH), "invalid key length"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_INVALID_OPERATION), "invalid operation"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_KEYGEN_FAILURE), "keygen failure"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_MEMORY_LIMIT_EXCEEDED), + "memory limit exceeded"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_MESSAGE_DIGEST_IS_NULL), + "message digest is null"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_METHOD_NOT_SUPPORTED), + "method not supported"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_MISSING_PARAMETERS), "missing parameters"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NOT_XOF_OR_INVALID_LENGTH), + "not XOF or invalid length"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_CIPHER_SET), "no cipher set"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_DEFAULT_DIGEST), "no default digest"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_DIGEST_SET), "no digest set"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_KEY_SET), "no key set"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_NO_OPERATION_SET), "no operation set"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_ONLY_ONESHOT_SUPPORTED), + "only oneshot supported"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE), + "operation not supported for this keytype"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_OPERATON_NOT_INITIALIZED), + "operaton not initialized"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PARTIALLY_OVERLAPPING), + "partially overlapping buffers"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PKEY_APPLICATION_ASN1_METHOD_ALREADY_REGISTERED), + "pkey application asn1 method already registered"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PRIVATE_KEY_DECODE_ERROR), + "private key decode error"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PRIVATE_KEY_ENCODE_ERROR), + "private key encode error"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_PUBLIC_KEY_NOT_RSA), "public key not rsa"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_CIPHER), "unknown cipher"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_DIGEST), "unknown digest"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_OPTION), "unknown option"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNKNOWN_PBE_ALGORITHM), + "unknown pbe algorithm"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_ALGORITHM), + "unsupported algorithm"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_CIPHER), "unsupported cipher"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_KEYLENGTH), + "unsupported keylength"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION), + "unsupported key derivation function"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_KEY_SIZE), + "unsupported key size"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_NUMBER_OF_ROUNDS), + "unsupported number of rounds"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_PRF), "unsupported prf"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM), + "unsupported private key algorithm"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_UNSUPPORTED_SALT_TYPE), + "unsupported salt type"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_WRAP_MODE_NOT_ALLOWED), + "wrap mode not allowed"}, + {ERR_PACK(ERR_LIB_EVP, 0, EVP_R_WRONG_FINAL_BLOCK_LENGTH), + "wrong final block length"}, {0, NULL} }; @@ -176,10 +245,9 @@ static ERR_STRING_DATA EVP_str_reasons[] = { int ERR_load_EVP_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(EVP_str_functs[0].error) == NULL) { - ERR_load_strings(0, EVP_str_functs); - ERR_load_strings(0, EVP_str_reasons); + ERR_load_strings_const(EVP_str_functs); + ERR_load_strings_const(EVP_str_reasons); } #endif return 1; diff --git a/crypto/evp/evp_key.c b/crypto/evp/evp_key.c index 52011307..e5ac107c 100644 --- a/crypto/evp/evp_key.c +++ b/crypto/evp/evp_key.c @@ -14,7 +14,6 @@ #include #include -#ifndef OPENSSL_NO_UI /* should be init to zeros. */ static char prompt_string[80]; @@ -31,9 +30,9 @@ void EVP_set_pw_prompt(const char *prompt) char *EVP_get_pw_prompt(void) { if (prompt_string[0] == '\0') - return (NULL); + return NULL; else - return (prompt_string); + return prompt_string; } /* @@ -71,7 +70,6 @@ int EVP_read_pw_string_min(char *buf, int min, int len, const char *prompt, UI_free(ui); return ret; } -#endif /* OPENSSL_NO_UI */ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, const unsigned char *salt, const unsigned char *data, @@ -89,7 +87,7 @@ int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md, OPENSSL_assert(niv <= EVP_MAX_IV_LENGTH); if (data == NULL) - return (nkey); + return nkey; c = EVP_MD_CTX_new(); if (c == NULL) diff --git a/crypto/evp/evp_lib.c b/crypto/evp/evp_lib.c index 0c76db5a..c337dca6 100644 --- a/crypto/evp/evp_lib.c +++ b/crypto/evp/evp_lib.c @@ -40,7 +40,7 @@ int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type) } } else ret = -1; - return (ret); + return ret; } int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type) @@ -69,7 +69,7 @@ int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type) } } else ret = -1; - return (ret); + return ret; } int EVP_CIPHER_get_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type) @@ -82,11 +82,11 @@ int EVP_CIPHER_get_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type) OPENSSL_assert(l <= sizeof(c->iv)); i = ASN1_TYPE_get_octetstring(type, c->oiv, l); if (i != (int)l) - return (-1); + return -1; else if (i > 0) memcpy(c->iv, c->oiv, l); } - return (i); + return i; } int EVP_CIPHER_set_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type) @@ -99,7 +99,7 @@ int EVP_CIPHER_set_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type) OPENSSL_assert(j <= sizeof(c->iv)); i = ASN1_TYPE_set_octetstring(type, c->oiv, j); } - return (i); + return i; } /* Convert the various cipher NIDs and dummies to a proper OID NID */ diff --git a/crypto/evp/evp_pbe.c b/crypto/evp/evp_pbe.c index eb7344c2..7a3c61d6 100644 --- a/crypto/evp/evp_pbe.c +++ b/crypto/evp/evp_pbe.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-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 @@ -61,6 +61,8 @@ static const EVP_PBE_CTL builtin_pbe[] = { NID_des_cbc, NID_sha1, PKCS5_PBE_keyivgen}, {EVP_PBE_TYPE_PRF, NID_hmacWithSHA1, -1, NID_sha1, 0}, + {EVP_PBE_TYPE_PRF, NID_hmac_md5, -1, NID_md5, 0}, + {EVP_PBE_TYPE_PRF, NID_hmac_sha1, -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}, diff --git a/crypto/evp/evp_pkey.c b/crypto/evp/evp_pkey.c index 81bffa6d..e61a8761 100644 --- a/crypto/evp/evp_pkey.c +++ b/crypto/evp/evp_pkey.c @@ -80,7 +80,6 @@ PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(EVP_PKEY *pkey) EVPerr(EVP_F_EVP_PKEY2PKCS8, EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM); goto error; } - RAND_add(p8->pkey->data, p8->pkey->length, 0.0); return p8; error: PKCS8_PRIV_KEY_INFO_free(p8); diff --git a/crypto/evp/m_md4.c b/crypto/evp/m_md4.c index f3decaaf..0efc586d 100644 --- a/crypto/evp/m_md4.c +++ b/crypto/evp/m_md4.c @@ -50,6 +50,6 @@ static const EVP_MD md4_md = { const EVP_MD *EVP_md4(void) { - return (&md4_md); + return &md4_md; } #endif diff --git a/crypto/evp/m_md5.c b/crypto/evp/m_md5.c index f4dc0c43..3d96ae93 100644 --- a/crypto/evp/m_md5.c +++ b/crypto/evp/m_md5.c @@ -50,6 +50,6 @@ static const EVP_MD md5_md = { const EVP_MD *EVP_md5(void) { - return (&md5_md); + return &md5_md; } #endif diff --git a/crypto/evp/m_mdc2.c b/crypto/evp/m_mdc2.c index b7f0fd8c..1051a907 100644 --- a/crypto/evp/m_mdc2.c +++ b/crypto/evp/m_mdc2.c @@ -50,6 +50,6 @@ static const EVP_MD mdc2_md = { const EVP_MD *EVP_mdc2(void) { - return (&mdc2_md); + return &mdc2_md; } #endif diff --git a/crypto/evp/m_null.c b/crypto/evp/m_null.c index 6c4daf56..5dce1d51 100644 --- a/crypto/evp/m_null.c +++ b/crypto/evp/m_null.c @@ -45,5 +45,5 @@ static const EVP_MD null_md = { const EVP_MD *EVP_md_null(void) { - return (&null_md); + return &null_md; } diff --git a/crypto/evp/m_ripemd.c b/crypto/evp/m_ripemd.c index 07b46bd5..7ab32084 100644 --- a/crypto/evp/m_ripemd.c +++ b/crypto/evp/m_ripemd.c @@ -50,6 +50,6 @@ static const EVP_MD ripemd160_md = { const EVP_MD *EVP_ripemd160(void) { - return (&ripemd160_md); + return &ripemd160_md; } #endif diff --git a/crypto/evp/m_sha1.c b/crypto/evp/m_sha1.c index e68f32a0..ac524178 100644 --- a/crypto/evp/m_sha1.c +++ b/crypto/evp/m_sha1.c @@ -15,6 +15,7 @@ #include #include #include "internal/evp_int.h" +#include "internal/sha.h" static int init(EVP_MD_CTX *ctx) { @@ -107,7 +108,7 @@ static const EVP_MD sha1_md = { const EVP_MD *EVP_sha1(void) { - return (&sha1_md); + return &sha1_md; } static int init224(EVP_MD_CTX *ctx) @@ -156,7 +157,7 @@ static const EVP_MD sha224_md = { const EVP_MD *EVP_sha224(void) { - return (&sha224_md); + return &sha224_md; } static const EVP_MD sha256_md = { @@ -175,7 +176,17 @@ static const EVP_MD sha256_md = { const EVP_MD *EVP_sha256(void) { - return (&sha256_md); + return &sha256_md; +} + +static int init512_224(EVP_MD_CTX *ctx) +{ + return sha512_224_init(EVP_MD_CTX_md_data(ctx)); +} + +static int init512_256(EVP_MD_CTX *ctx) +{ + return sha512_256_init(EVP_MD_CTX_md_data(ctx)); } static int init384(EVP_MD_CTX *ctx) @@ -209,6 +220,44 @@ static int final512(EVP_MD_CTX *ctx, unsigned char *md) return SHA512_Final(md, EVP_MD_CTX_md_data(ctx)); } +static const EVP_MD sha512_224_md = { + NID_sha512_224, + NID_sha512_224WithRSAEncryption, + SHA224_DIGEST_LENGTH, + EVP_MD_FLAG_DIGALGID_ABSENT, + init512_224, + update512, + final512, + NULL, + NULL, + SHA512_CBLOCK, + sizeof(EVP_MD *) + sizeof(SHA512_CTX), +}; + +const EVP_MD *EVP_sha512_224(void) +{ + return &sha512_224_md; +} + +static const EVP_MD sha512_256_md = { + NID_sha512_256, + NID_sha512_256WithRSAEncryption, + SHA256_DIGEST_LENGTH, + EVP_MD_FLAG_DIGALGID_ABSENT, + init512_256, + update512, + final512, + NULL, + NULL, + SHA512_CBLOCK, + sizeof(EVP_MD *) + sizeof(SHA512_CTX), +}; + +const EVP_MD *EVP_sha512_256(void) +{ + return &sha512_256_md; +} + static const EVP_MD sha384_md = { NID_sha384, NID_sha384WithRSAEncryption, @@ -225,7 +274,7 @@ static const EVP_MD sha384_md = { const EVP_MD *EVP_sha384(void) { - return (&sha384_md); + return &sha384_md; } static const EVP_MD sha512_md = { @@ -244,5 +293,5 @@ static const EVP_MD sha512_md = { const EVP_MD *EVP_sha512(void) { - return (&sha512_md); + return &sha512_md; } diff --git a/crypto/evp/m_sha3.c b/crypto/evp/m_sha3.c new file mode 100644 index 00000000..cf902e74 --- /dev/null +++ b/crypto/evp/m_sha3.c @@ -0,0 +1,182 @@ +/* + * 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 +#include + +#include +#include +#include "internal/evp_int.h" +#include "evp_locl.h" + +size_t SHA3_absorb(uint64_t A[5][5], const unsigned char *inp, size_t len, + size_t r); +void SHA3_squeeze(uint64_t A[5][5], unsigned char *out, size_t len, size_t r); + +#define KECCAK1600_WIDTH 1600 + +typedef struct { + uint64_t A[5][5]; + size_t block_size; /* cached ctx->digest->block_size */ + size_t md_size; /* output length, variable in XOF */ + size_t num; /* used bytes in below buffer */ + unsigned char buf[KECCAK1600_WIDTH / 8 - 32]; + unsigned char pad; +} KECCAK1600_CTX; + +static int init(EVP_MD_CTX *evp_ctx, unsigned char pad) +{ + KECCAK1600_CTX *ctx = evp_ctx->md_data; + size_t bsz = evp_ctx->digest->block_size; + + if (bsz <= sizeof(ctx->buf)) { + memset(ctx->A, 0, sizeof(ctx->A)); + + ctx->num = 0; + ctx->block_size = bsz; + ctx->md_size = evp_ctx->digest->md_size; + ctx->pad = pad; + + return 1; + } + + return 0; +} + +static int sha3_init(EVP_MD_CTX *evp_ctx) +{ + return init(evp_ctx, '\x06'); +} + +static int shake_init(EVP_MD_CTX *evp_ctx) +{ + return init(evp_ctx, '\x1f'); +} + +static int sha3_update(EVP_MD_CTX *evp_ctx, const void *_inp, size_t len) +{ + KECCAK1600_CTX *ctx = evp_ctx->md_data; + const unsigned char *inp = _inp; + size_t bsz = ctx->block_size; + size_t num, rem; + + if ((num = ctx->num) != 0) { /* process intermediate buffer? */ + rem = bsz - num; + + if (len < rem) { + memcpy(ctx->buf + num, inp, len); + ctx->num += len; + return 1; + } + /* + * We have enough data to fill or overflow the intermediate + * buffer. So we append |rem| bytes and process the block, + * leaving the rest for later processing... + */ + memcpy(ctx->buf + num, inp, rem); + inp += rem, len -= rem; + (void)SHA3_absorb(ctx->A, ctx->buf, bsz, bsz); + ctx->num = 0; + /* ctx->buf is processed, ctx->num is guaranteed to be zero */ + } + + if (len >= bsz) + rem = SHA3_absorb(ctx->A, inp, len, bsz); + else + rem = len; + + if (rem) { + memcpy(ctx->buf, inp + len - rem, rem); + ctx->num = rem; + } + + return 1; +} + +static int sha3_final(EVP_MD_CTX *evp_ctx, unsigned char *md) +{ + KECCAK1600_CTX *ctx = evp_ctx->md_data; + size_t bsz = ctx->block_size; + size_t num = ctx->num; + + /* + * Pad the data with 10*1. Note that |num| can be |bsz - 1| + * in which case both byte operations below are performed on + * same byte... + */ + memset(ctx->buf + num, 0, bsz - num); + ctx->buf[num] = ctx->pad; + ctx->buf[bsz - 1] |= 0x80; + + (void)SHA3_absorb(ctx->A, ctx->buf, bsz, bsz); + + SHA3_squeeze(ctx->A, md, ctx->md_size, bsz); + + return 1; +} + +static int shake_ctrl(EVP_MD_CTX *evp_ctx, int cmd, int p1, void *p2) +{ + KECCAK1600_CTX *ctx = evp_ctx->md_data; + + switch (cmd) { + case EVP_MD_CTRL_XOF_LEN: + ctx->md_size = p1; + return 1; + default: + return 0; + } +} + +#define EVP_MD_SHA3(bitlen) \ +const EVP_MD *EVP_sha3_##bitlen(void) \ +{ \ + static const EVP_MD sha3_##bitlen##_md = { \ + NID_sha3_##bitlen, \ + NID_RSA_SHA3_##bitlen, \ + bitlen / 8, \ + EVP_MD_FLAG_DIGALGID_ABSENT, \ + sha3_init, \ + sha3_update, \ + sha3_final, \ + NULL, \ + NULL, \ + (KECCAK1600_WIDTH - bitlen * 2) / 8, \ + sizeof(KECCAK1600_CTX), \ + }; \ + return &sha3_##bitlen##_md; \ +} + +EVP_MD_SHA3(224) +EVP_MD_SHA3(256) +EVP_MD_SHA3(384) +EVP_MD_SHA3(512) + +#define EVP_MD_SHAKE(bitlen) \ +const EVP_MD *EVP_shake##bitlen(void) \ +{ \ + static const EVP_MD shake##bitlen##_md = { \ + NID_shake##bitlen, \ + 0, \ + bitlen / 8, \ + EVP_MD_FLAG_XOF, \ + shake_init, \ + sha3_update, \ + sha3_final, \ + NULL, \ + NULL, \ + (KECCAK1600_WIDTH - bitlen * 2) / 8, \ + sizeof(KECCAK1600_CTX), \ + shake_ctrl \ + }; \ + return &shake##bitlen##_md; \ +} + +EVP_MD_SHAKE(128) +EVP_MD_SHAKE(256) diff --git a/crypto/evp/m_sigver.c b/crypto/evp/m_sigver.c index 582e563d..2377944f 100644 --- a/crypto/evp/m_sigver.c +++ b/crypto/evp/m_sigver.c @@ -15,6 +15,12 @@ #include "internal/evp_int.h" #include "evp_locl.h" +static int update(EVP_MD_CTX *ctx, const void *data, size_t datalen) +{ + EVPerr(EVP_F_UPDATE, EVP_R_ONLY_ONESHOT_SUPPORTED); + return 0; +} + static int do_sigver_init(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey, int ver) @@ -43,15 +49,23 @@ static int do_sigver_init(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, if (ctx->pctx->pmeth->verifyctx_init(ctx->pctx, ctx) <= 0) return 0; ctx->pctx->operation = EVP_PKEY_OP_VERIFYCTX; - } else if (EVP_PKEY_verify_init(ctx->pctx) <= 0) + } else if (ctx->pctx->pmeth->digestverify != 0) { + ctx->pctx->operation = EVP_PKEY_OP_VERIFY; + ctx->update = update; + } else if (EVP_PKEY_verify_init(ctx->pctx) <= 0) { return 0; + } } else { if (ctx->pctx->pmeth->signctx_init) { if (ctx->pctx->pmeth->signctx_init(ctx->pctx, ctx) <= 0) return 0; ctx->pctx->operation = EVP_PKEY_OP_SIGNCTX; - } else if (EVP_PKEY_sign_init(ctx->pctx) <= 0) + } else if (ctx->pctx->pmeth->digestsign != 0) { + ctx->pctx->operation = EVP_PKEY_OP_SIGN; + ctx->update = update; + } else if (EVP_PKEY_sign_init(ctx->pctx) <= 0) { return 0; + } } if (EVP_PKEY_CTX_set_signature_md(ctx->pctx, type) <= 0) return 0; @@ -139,6 +153,16 @@ int EVP_DigestSignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, return 1; } +int EVP_DigestSign(EVP_MD_CTX *ctx, unsigned char *sigret, size_t *siglen, + const unsigned char *tbs, size_t tbslen) +{ + if (ctx->pctx->pmeth->digestsign != NULL) + return ctx->pctx->pmeth->digestsign(ctx, sigret, siglen, tbs, tbslen); + if (sigret != NULL && EVP_DigestSignUpdate(ctx, tbs, tbslen) <= 0) + return 0; + return EVP_DigestSignFinal(ctx, sigret, siglen); +} + int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig, size_t siglen) { @@ -175,3 +199,13 @@ int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig, return r; return EVP_PKEY_verify(ctx->pctx, sig, siglen, md, mdlen); } + +int EVP_DigestVerify(EVP_MD_CTX *ctx, const unsigned char *sigret, + size_t siglen, const unsigned char *tbs, size_t tbslen) +{ + if (ctx->pctx->pmeth->digestverify != NULL) + return ctx->pctx->pmeth->digestverify(ctx, sigret, siglen, tbs, tbslen); + if (EVP_DigestVerifyUpdate(ctx, tbs, tbslen) <= 0) + return -1; + return EVP_DigestVerifyFinal(ctx, sigret, siglen); +} diff --git a/crypto/evp/m_wp.c b/crypto/evp/m_wp.c index 94fac226..27e2b3c5 100644 --- a/crypto/evp/m_wp.c +++ b/crypto/evp/m_wp.c @@ -49,6 +49,6 @@ static const EVP_MD whirlpool_md = { const EVP_MD *EVP_whirlpool(void) { - return (&whirlpool_md); + return &whirlpool_md; } #endif diff --git a/crypto/evp/names.c b/crypto/evp/names.c index a92be1fe..077c2a6c 100644 --- a/crypto/evp/names.c +++ b/crypto/evp/names.c @@ -10,7 +10,7 @@ #include #include "internal/cryptlib.h" #include -#include +#include "internal/objects.h" #include #include "internal/evp_int.h" @@ -24,10 +24,10 @@ int EVP_add_cipher(const EVP_CIPHER *c) r = OBJ_NAME_add(OBJ_nid2sn(c->nid), OBJ_NAME_TYPE_CIPHER_METH, (const char *)c); if (r == 0) - return (0); + return 0; r = OBJ_NAME_add(OBJ_nid2ln(c->nid), OBJ_NAME_TYPE_CIPHER_METH, (const char *)c); - return (r); + return r; } int EVP_add_digest(const EVP_MD *md) @@ -38,21 +38,21 @@ int EVP_add_digest(const EVP_MD *md) name = OBJ_nid2sn(md->type); r = OBJ_NAME_add(name, OBJ_NAME_TYPE_MD_METH, (const char *)md); if (r == 0) - return (0); + return 0; r = OBJ_NAME_add(OBJ_nid2ln(md->type), OBJ_NAME_TYPE_MD_METH, (const char *)md); if (r == 0) - return (0); + return 0; if (md->pkey_type && md->type != md->pkey_type) { r = OBJ_NAME_add(OBJ_nid2sn(md->pkey_type), OBJ_NAME_TYPE_MD_METH | OBJ_NAME_ALIAS, name); if (r == 0) - return (0); + return 0; r = OBJ_NAME_add(OBJ_nid2ln(md->pkey_type), OBJ_NAME_TYPE_MD_METH | OBJ_NAME_ALIAS, name); } - return (r); + return r; } const EVP_CIPHER *EVP_get_cipherbyname(const char *name) @@ -63,7 +63,7 @@ const EVP_CIPHER *EVP_get_cipherbyname(const char *name) return NULL; cp = (const EVP_CIPHER *)OBJ_NAME_get(name, OBJ_NAME_TYPE_CIPHER_METH); - return (cp); + return cp; } const EVP_MD *EVP_get_digestbyname(const char *name) @@ -74,7 +74,7 @@ const EVP_MD *EVP_get_digestbyname(const char *name) return NULL; cp = (const EVP_MD *)OBJ_NAME_get(name, OBJ_NAME_TYPE_MD_METH); - return (cp); + return cp; } void evp_cleanup_int(void) @@ -90,6 +90,8 @@ void evp_cleanup_int(void) EVP_PBE_cleanup(); OBJ_sigid_free(); + + evp_app_cleanup_int(); } struct doall_cipher { diff --git a/crypto/evp/p5_crpt2.c b/crypto/evp/p5_crpt2.c index 6d5f289b..e819eb9b 100644 --- a/crypto/evp/p5_crpt2.c +++ b/crypto/evp/p5_crpt2.c @@ -25,8 +25,7 @@ static void h__dump(const unsigned char *p, int len); /* * 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 to the PKCS-TNG - * mailing list. + * posted by Peter Gutmann to the PKCS-TNG mailing list. */ int PKCS5_PBKDF2_HMAC(const char *pass, int passlen, @@ -88,7 +87,6 @@ int PKCS5_PBKDF2_HMAC(const char *pass, int passlen, HMAC_CTX_free(hctx_tpl); return 0; } - HMAC_CTX_reset(hctx); memcpy(p, digtmp, cplen); for (j = 1; j < iter; j++) { if (!HMAC_CTX_copy(hctx, hctx_tpl)) { @@ -102,7 +100,6 @@ int PKCS5_PBKDF2_HMAC(const char *pass, int passlen, HMAC_CTX_free(hctx_tpl); return 0; } - HMAC_CTX_reset(hctx); for (k = 0; k < cplen; k++) p[k] ^= digtmp[k]; } @@ -132,18 +129,6 @@ int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen, 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 diff --git a/crypto/evp/p_dec.c b/crypto/evp/p_dec.c index 6bec4062..a150a26e 100644 --- a/crypto/evp/p_dec.c +++ b/crypto/evp/p_dec.c @@ -32,5 +32,5 @@ int EVP_PKEY_decrypt_old(unsigned char *key, const unsigned char *ek, int ekl, RSA_PKCS1_PADDING); err: #endif - return (ret); + return ret; } diff --git a/crypto/evp/p_enc.c b/crypto/evp/p_enc.c index 3277fbb0..04d67cb5 100644 --- a/crypto/evp/p_enc.c +++ b/crypto/evp/p_enc.c @@ -31,5 +31,5 @@ int EVP_PKEY_encrypt_old(unsigned char *ek, const unsigned char *key, RSA_PKCS1_PADDING); err: #endif - return (ret); + return ret; } diff --git a/crypto/evp/p_lib.c b/crypto/evp/p_lib.c index d7372aa1..6177e044 100644 --- a/crypto/evp/p_lib.c +++ b/crypto/evp/p_lib.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,6 +9,7 @@ #include #include "internal/cryptlib.h" +#include "internal/refcount.h" #include #include #include @@ -55,7 +56,7 @@ int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode) if (mode >= 0) pkey->save_parameters = mode; - return (ret); + return ret; } #endif #ifndef OPENSSL_NO_EC @@ -64,10 +65,10 @@ int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode) if (mode >= 0) pkey->save_parameters = mode; - return (ret); + return ret; } #endif - return (0); + return 0; } int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from) @@ -160,7 +161,7 @@ int EVP_PKEY_up_ref(EVP_PKEY *pkey) { int i; - if (CRYPTO_atomic_add(&pkey->references, 1, &i, pkey->lock) <= 0) + if (CRYPTO_UP_REF(&pkey->references, &i, pkey->lock) <= 0) return 0; REF_PRINT_COUNT("EVP_PKEY", pkey); @@ -269,6 +270,35 @@ const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len) return os->data; } +#ifndef OPENSSL_NO_POLY1305 +const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len) +{ + ASN1_OCTET_STRING *os = NULL; + if (pkey->type != EVP_PKEY_POLY1305) { + EVPerr(EVP_F_EVP_PKEY_GET0_POLY1305, EVP_R_EXPECTING_A_POLY1305_KEY); + return NULL; + } + os = EVP_PKEY_get0(pkey); + *len = os->length; + return os->data; +} +#endif + +#ifndef OPENSSL_NO_SIPHASH +const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len) +{ + ASN1_OCTET_STRING *os = NULL; + + if (pkey->type != EVP_PKEY_SIPHASH) { + EVPerr(EVP_F_EVP_PKEY_GET0_SIPHASH, EVP_R_EXPECTING_A_SIPHASH_KEY); + return NULL; + } + os = EVP_PKEY_get0(pkey); + *len = os->length; + return os->data; +} +#endif + #ifndef OPENSSL_NO_RSA int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key) { @@ -412,7 +442,7 @@ void EVP_PKEY_free(EVP_PKEY *x) if (x == NULL) return; - CRYPTO_atomic_add(&x->references, -1, &i, x->lock); + CRYPTO_DOWN_REF(&x->references, &i, x->lock); REF_PRINT_COUNT("EVP_PKEY", x); if (i > 0) return; diff --git a/crypto/evp/p_open.c b/crypto/evp/p_open.c index b65bc74e..f2976f8a 100644 --- a/crypto/evp/p_open.c +++ b/crypto/evp/p_open.c @@ -58,7 +58,7 @@ int EVP_OpenInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ret = 1; err: OPENSSL_clear_free(key, size); - return (ret); + return ret; } int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) @@ -68,6 +68,6 @@ int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) i = EVP_DecryptFinal_ex(ctx, out, outl); if (i) i = EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL); - return (i); + return i; } #endif diff --git a/crypto/evp/p_seal.c b/crypto/evp/p_seal.c index faa24648..50ea6023 100644 --- a/crypto/evp/p_seal.c +++ b/crypto/evp/p_seal.c @@ -43,23 +43,11 @@ int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, EVP_PKEY_encrypt_old(ek[i], key, EVP_CIPHER_CTX_key_length(ctx), pubk[i]); if (ekl[i] <= 0) - return (-1); + return -1; } - return (npubk); + return npubk; } -/*- MACRO -void EVP_SealUpdate(ctx,out,outl,in,inl) -EVP_CIPHER_CTX *ctx; -unsigned char *out; -int *outl; -unsigned char *in; -int inl; - { - EVP_EncryptUpdate(ctx,out,outl,in,inl); - } -*/ - int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl) { int i; diff --git a/crypto/evp/pbe_scrypt.c b/crypto/evp/pbe_scrypt.c new file mode 100644 index 00000000..fddabc9a --- /dev/null +++ b/crypto/evp/pbe_scrypt.c @@ -0,0 +1,253 @@ +/* + * Copyright 2015-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 + */ + +#include +#include +#include +#include +#include +#include "internal/numbers.h" + +#ifndef OPENSSL_NO_SCRYPT + +#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b)))) +static void salsa208_word_specification(uint32_t inout[16]) +{ + int i; + uint32_t x[16]; + memcpy(x, inout, sizeof(x)); + for (i = 8; i > 0; i -= 2) { + x[4] ^= R(x[0] + x[12], 7); + x[8] ^= R(x[4] + x[0], 9); + x[12] ^= R(x[8] + x[4], 13); + x[0] ^= R(x[12] + x[8], 18); + x[9] ^= R(x[5] + x[1], 7); + x[13] ^= R(x[9] + x[5], 9); + x[1] ^= R(x[13] + x[9], 13); + x[5] ^= R(x[1] + x[13], 18); + x[14] ^= R(x[10] + x[6], 7); + x[2] ^= R(x[14] + x[10], 9); + x[6] ^= R(x[2] + x[14], 13); + x[10] ^= R(x[6] + x[2], 18); + x[3] ^= R(x[15] + x[11], 7); + x[7] ^= R(x[3] + x[15], 9); + x[11] ^= R(x[7] + x[3], 13); + x[15] ^= R(x[11] + x[7], 18); + x[1] ^= R(x[0] + x[3], 7); + x[2] ^= R(x[1] + x[0], 9); + x[3] ^= R(x[2] + x[1], 13); + x[0] ^= R(x[3] + x[2], 18); + x[6] ^= R(x[5] + x[4], 7); + x[7] ^= R(x[6] + x[5], 9); + x[4] ^= R(x[7] + x[6], 13); + x[5] ^= R(x[4] + x[7], 18); + x[11] ^= R(x[10] + x[9], 7); + x[8] ^= R(x[11] + x[10], 9); + x[9] ^= R(x[8] + x[11], 13); + x[10] ^= R(x[9] + x[8], 18); + x[12] ^= R(x[15] + x[14], 7); + x[13] ^= R(x[12] + x[15], 9); + x[14] ^= R(x[13] + x[12], 13); + x[15] ^= R(x[14] + x[13], 18); + } + for (i = 0; i < 16; ++i) + inout[i] += x[i]; + OPENSSL_cleanse(x, sizeof(x)); +} + +static void scryptBlockMix(uint32_t *B_, uint32_t *B, uint64_t r) +{ + uint64_t i, j; + uint32_t X[16], *pB; + + memcpy(X, B + (r * 2 - 1) * 16, sizeof(X)); + pB = B; + for (i = 0; i < r * 2; i++) { + for (j = 0; j < 16; j++) + X[j] ^= *pB++; + salsa208_word_specification(X); + memcpy(B_ + (i / 2 + (i & 1) * r) * 16, X, sizeof(X)); + } + OPENSSL_cleanse(X, sizeof(X)); +} + +static void scryptROMix(unsigned char *B, uint64_t r, uint64_t N, + uint32_t *X, uint32_t *T, uint32_t *V) +{ + unsigned char *pB; + uint32_t *pV; + uint64_t i, k; + + /* Convert from little endian input */ + for (pV = V, i = 0, pB = B; i < 32 * r; i++, pV++) { + *pV = *pB++; + *pV |= *pB++ << 8; + *pV |= *pB++ << 16; + *pV |= (uint32_t)*pB++ << 24; + } + + for (i = 1; i < N; i++, pV += 32 * r) + scryptBlockMix(pV, pV - 32 * r, r); + + scryptBlockMix(X, V + (N - 1) * 32 * r, r); + + for (i = 0; i < N; i++) { + uint32_t j; + j = X[16 * (2 * r - 1)] % N; + pV = V + 32 * r * j; + for (k = 0; k < 32 * r; k++) + T[k] = X[k] ^ *pV++; + scryptBlockMix(X, T, r); + } + /* Convert output to little endian */ + for (i = 0, pB = B; i < 32 * r; i++) { + uint32_t xtmp = X[i]; + *pB++ = xtmp & 0xff; + *pB++ = (xtmp >> 8) & 0xff; + *pB++ = (xtmp >> 16) & 0xff; + *pB++ = (xtmp >> 24) & 0xff; + } +} + +#ifndef SIZE_MAX +# define SIZE_MAX ((size_t)-1) +#endif + +/* + * Maximum power of two that will fit in uint64_t: this should work on + * most (all?) platforms. + */ + +#define LOG2_UINT64_MAX (sizeof(uint64_t) * 8 - 1) + +/* + * Maximum value of p * r: + * p <= ((2^32-1) * hLen) / MFLen => + * p <= ((2^32-1) * 32) / (128 * r) => + * p * r <= (2^30-1) + * + */ + +#define SCRYPT_PR_MAX ((1 << 30) - 1) + +/* + * Maximum permitted memory allow this to be overridden with Configuration + * option: e.g. -DSCRYPT_MAX_MEM=0 for maximum possible. + */ + +#ifdef SCRYPT_MAX_MEM +# if SCRYPT_MAX_MEM == 0 +# undef SCRYPT_MAX_MEM +/* + * Although we could theoretically allocate SIZE_MAX memory that would leave + * no memory available for anything else so set limit as half that. + */ +# define SCRYPT_MAX_MEM (SIZE_MAX/2) +# endif +#else +/* Default memory limit: 32 MB */ +# define SCRYPT_MAX_MEM (1024 * 1024 * 32) +#endif + +int EVP_PBE_scrypt(const char *pass, size_t passlen, + const unsigned char *salt, size_t saltlen, + uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem, + unsigned char *key, size_t keylen) +{ + int rv = 0; + unsigned char *B; + uint32_t *X, *V, *T; + uint64_t i, Blen, Vlen; + + /* Sanity check parameters */ + /* initial check, r,p must be non zero, N >= 2 and a power of 2 */ + if (r == 0 || p == 0 || N < 2 || (N & (N - 1))) + return 0; + /* Check p * r < SCRYPT_PR_MAX avoiding overflow */ + if (p > SCRYPT_PR_MAX / r) + return 0; + + /* + * Need to check N: if 2^(128 * r / 8) overflows limit this is + * automatically satisfied since N <= UINT64_MAX. + */ + + if (16 * r <= LOG2_UINT64_MAX) { + if (N >= (((uint64_t)1) << (16 * r))) + return 0; + } + + /* Memory checks: check total allocated buffer size fits in uint64_t */ + + /* + * B size in section 5 step 1.S + * Note: we know p * 128 * r < UINT64_MAX because we already checked + * p * r < SCRYPT_PR_MAX + */ + Blen = p * 128 * r; + /* + * Yet we pass it as integer to PKCS5_PBKDF2_HMAC... [This would + * have to be revised when/if PKCS5_PBKDF2_HMAC accepts size_t.] + */ + if (Blen > INT_MAX) { + EVPerr(EVP_F_EVP_PBE_SCRYPT, EVP_R_MEMORY_LIMIT_EXCEEDED); + return 0; + } + + /* + * Check 32 * r * (N + 2) * sizeof(uint32_t) fits in uint64_t + * This is combined size V, X and T (section 4) + */ + i = UINT64_MAX / (32 * sizeof(uint32_t)); + if (N + 2 > i / r) + return 0; + Vlen = 32 * r * (N + 2) * sizeof(uint32_t); + + /* check total allocated size fits in uint64_t */ + if (Blen > UINT64_MAX - Vlen) + return 0; + + if (maxmem == 0) + maxmem = SCRYPT_MAX_MEM; + + /* Check that the maximum memory doesn't exceed a size_t limits */ + if (maxmem > SIZE_MAX) + maxmem = SIZE_MAX; + + if (Blen + Vlen > maxmem) { + EVPerr(EVP_F_EVP_PBE_SCRYPT, EVP_R_MEMORY_LIMIT_EXCEEDED); + return 0; + } + + /* If no key return to indicate parameters are OK */ + if (key == NULL) + return 1; + + B = OPENSSL_malloc((size_t)(Blen + Vlen)); + if (B == NULL) + return 0; + X = (uint32_t *)(B + Blen); + T = X + 32 * r; + V = T + 32 * r; + if (PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, 1, EVP_sha256(), + (int)Blen, B) == 0) + goto err; + + for (i = 0; i < p; i++) + scryptROMix(B + 128 * r * i, r, N, X, T, V); + + if (PKCS5_PBKDF2_HMAC(pass, passlen, B, (int)Blen, 1, EVP_sha256(), + keylen, key) == 0) + goto err; + rv = 1; + err: + OPENSSL_clear_free(B, (size_t)(Blen + Vlen)); + return rv; +} +#endif diff --git a/crypto/evp/pmeth_fn.c b/crypto/evp/pmeth_fn.c index eb638019..de1c07e1 100644 --- a/crypto/evp/pmeth_fn.c +++ b/crypto/evp/pmeth_fn.c @@ -255,7 +255,7 @@ int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer) } /* - * ran@cryptocom.ru: For clarity. The error is if parameters in peer are + * For clarity. The error is if parameters in peer are * present (!missing) but don't match. EVP_PKEY_cmp_parameters may return * 1 (match), 0 (don't match) and -2 (comparison is not defined). -1 * (different key types) is impossible here because it is checked earlier. diff --git a/crypto/evp/pmeth_gn.c b/crypto/evp/pmeth_gn.c index 6adc3a9c..e14965f3 100644 --- a/crypto/evp/pmeth_gn.c +++ b/crypto/evp/pmeth_gn.c @@ -13,6 +13,7 @@ #include #include #include "internal/bn_int.h" +#include "internal/asn1_int.h" #include "internal/evp_int.h" int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx) @@ -167,3 +168,72 @@ EVP_PKEY *EVP_PKEY_new_mac_key(int type, ENGINE *e, EVP_PKEY_CTX_free(mac_ctx); return mac_key; } + +int EVP_PKEY_check(EVP_PKEY_CTX *ctx) +{ + EVP_PKEY *pkey = ctx->pkey; + + if (pkey == NULL) { + EVPerr(EVP_F_EVP_PKEY_CHECK, EVP_R_NO_KEY_SET); + return 0; + } + + /* call customized check function first */ + if (ctx->pmeth->check != NULL) + return ctx->pmeth->check(pkey); + + /* use default check function in ameth */ + if (pkey->ameth == NULL || pkey->ameth->pkey_check == NULL) { + EVPerr(EVP_F_EVP_PKEY_CHECK, + EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return -2; + } + + return pkey->ameth->pkey_check(pkey); +} + +int EVP_PKEY_public_check(EVP_PKEY_CTX *ctx) +{ + EVP_PKEY *pkey = ctx->pkey; + + if (pkey == NULL) { + EVPerr(EVP_F_EVP_PKEY_PUBLIC_CHECK, EVP_R_NO_KEY_SET); + return 0; + } + + /* call customized public key check function first */ + if (ctx->pmeth->public_check != NULL) + return ctx->pmeth->public_check(pkey); + + /* use default public key check function in ameth */ + if (pkey->ameth == NULL || pkey->ameth->pkey_public_check == NULL) { + EVPerr(EVP_F_EVP_PKEY_PUBLIC_CHECK, + EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return -2; + } + + return pkey->ameth->pkey_public_check(pkey); +} + +int EVP_PKEY_param_check(EVP_PKEY_CTX *ctx) +{ + EVP_PKEY *pkey = ctx->pkey; + + if (pkey == NULL) { + EVPerr(EVP_F_EVP_PKEY_PARAM_CHECK, EVP_R_NO_KEY_SET); + return 0; + } + + /* call customized param check function first */ + if (ctx->pmeth->param_check != NULL) + return ctx->pmeth->param_check(pkey); + + /* use default param check function in ameth */ + if (pkey->ameth == NULL || pkey->ameth->pkey_param_check == NULL) { + EVPerr(EVP_F_EVP_PKEY_PARAM_CHECK, + EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); + return -2; + } + + return pkey->ameth->pkey_param_check(pkey); +} diff --git a/crypto/evp/pmeth_lib.c b/crypto/evp/pmeth_lib.c index 5e650a9d..2d9f4fc6 100644 --- a/crypto/evp/pmeth_lib.c +++ b/crypto/evp/pmeth_lib.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-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 @@ -21,6 +21,7 @@ typedef int sk_cmp_fn_type(const char *const *a, const char *const *b); static STACK_OF(EVP_PKEY_METHOD) *app_pkey_methods = NULL; +/* This array needs to be in order of NIDs */ static const EVP_PKEY_METHOD *standard_methods[] = { #ifndef OPENSSL_NO_RSA &rsa_pkey_meth, @@ -38,14 +39,29 @@ static const EVP_PKEY_METHOD *standard_methods[] = { #ifndef OPENSSL_NO_CMAC &cmac_pkey_meth, #endif +#ifndef OPENSSL_NO_RSA + &rsa_pss_pkey_meth, +#endif #ifndef OPENSSL_NO_DH &dhx_pkey_meth, +#endif +#ifndef OPENSSL_NO_SCRYPT + &scrypt_pkey_meth, #endif &tls1_prf_pkey_meth, #ifndef OPENSSL_NO_EC &ecx25519_pkey_meth, #endif - &hkdf_pkey_meth + &hkdf_pkey_meth, +#ifndef OPENSSL_NO_POLY1305 + &poly1305_pkey_meth, +#endif +#ifndef OPENSSL_NO_SIPHASH + &siphash_pkey_meth, +#endif +#ifndef OPENSSL_NO_EC + &ed25519_pkey_meth, +#endif }; DECLARE_OBJ_BSEARCH_CMP_FN(const EVP_PKEY_METHOD *, const EVP_PKEY_METHOD *, @@ -207,6 +223,8 @@ void EVP_PKEY_meth_copy(EVP_PKEY_METHOD *dst, const EVP_PKEY_METHOD *src) dst->ctrl = src->ctrl; dst->ctrl_str = src->ctrl_str; + + dst->check = src->check; } void EVP_PKEY_meth_free(EVP_PKEY_METHOD *pmeth) @@ -282,6 +300,42 @@ int EVP_PKEY_meth_add0(const EVP_PKEY_METHOD *pmeth) return 1; } +void evp_app_cleanup_int(void) +{ + if (app_pkey_methods != NULL) + sk_EVP_PKEY_METHOD_pop_free(app_pkey_methods, EVP_PKEY_meth_free); +} + +int EVP_PKEY_meth_remove(const EVP_PKEY_METHOD *pmeth) +{ + const EVP_PKEY_METHOD *ret; + + ret = sk_EVP_PKEY_METHOD_delete_ptr(app_pkey_methods, pmeth); + + return ret == NULL ? 0 : 1; +} + +size_t EVP_PKEY_meth_get_count(void) +{ + size_t rv = OSSL_NELEM(standard_methods); + + if (app_pkey_methods) + rv += sk_EVP_PKEY_METHOD_num(app_pkey_methods); + return rv; +} + +const EVP_PKEY_METHOD *EVP_PKEY_meth_get0(size_t idx) +{ + if (idx < OSSL_NELEM(standard_methods)) + return standard_methods[idx]; + if (app_pkey_methods == NULL) + return NULL; + idx -= OSSL_NELEM(standard_methods); + if (idx >= (size_t)sk_EVP_PKEY_METHOD_num(app_pkey_methods)) + return NULL; + return sk_EVP_PKEY_METHOD_value(app_pkey_methods, idx); +} + void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx) { if (ctx == NULL) @@ -326,6 +380,12 @@ int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, } +int EVP_PKEY_CTX_ctrl_uint64(EVP_PKEY_CTX *ctx, int keytype, int optype, + int cmd, uint64_t value) +{ + return EVP_PKEY_CTX_ctrl(ctx, keytype, optype, cmd, 0, &value); +} + int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX *ctx, const char *name, const char *value) { @@ -333,14 +393,9 @@ int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX *ctx, EVPerr(EVP_F_EVP_PKEY_CTX_CTRL_STR, EVP_R_COMMAND_NOT_SUPPORTED); return -2; } - if (strcmp(name, "digest") == 0) { - const EVP_MD *md; - if (value == NULL || (md = EVP_get_digestbyname(value)) == NULL) { - EVPerr(EVP_F_EVP_PKEY_CTX_CTRL_STR, EVP_R_INVALID_DIGEST); - return 0; - } - return EVP_PKEY_CTX_set_signature_md(ctx, md); - } + if (strcmp(name, "digest") == 0) + return EVP_PKEY_CTX_md(ctx, EVP_PKEY_OP_TYPE_SIG, EVP_PKEY_CTRL_MD, + value); return ctx->pmeth->ctrl_str(ctx, name, value); } @@ -371,6 +426,18 @@ int EVP_PKEY_CTX_hex2ctrl(EVP_PKEY_CTX *ctx, int cmd, const char *hex) return rv; } +/* Pass a message digest to a ctrl */ +int EVP_PKEY_CTX_md(EVP_PKEY_CTX *ctx, int optype, int cmd, const char *md) +{ + const EVP_MD *m; + + if (md == NULL || (m = EVP_get_digestbyname(md)) == NULL) { + EVPerr(EVP_F_EVP_PKEY_CTX_MD, EVP_R_INVALID_DIGEST); + return 0; + } + return EVP_PKEY_CTX_ctrl(ctx, -1, optype, cmd, 0, (void *)m); +} + int EVP_PKEY_CTX_get_operation(EVP_PKEY_CTX *ctx) { return ctx->operation; @@ -557,6 +624,24 @@ void EVP_PKEY_meth_set_ctrl(EVP_PKEY_METHOD *pmeth, pmeth->ctrl_str = ctrl_str; } +void EVP_PKEY_meth_set_check(EVP_PKEY_METHOD *pmeth, + int (*check) (EVP_PKEY *pkey)) +{ + pmeth->check = check; +} + +void EVP_PKEY_meth_set_public_check(EVP_PKEY_METHOD *pmeth, + int (*check) (EVP_PKEY *pkey)) +{ + pmeth->public_check = check; +} + +void EVP_PKEY_meth_set_param_check(EVP_PKEY_METHOD *pmeth, + int (*check) (EVP_PKEY *pkey)) +{ + pmeth->param_check = check; +} + void EVP_PKEY_meth_get_init(EVP_PKEY_METHOD *pmeth, int (**pinit) (EVP_PKEY_CTX *ctx)) { @@ -723,3 +808,24 @@ void EVP_PKEY_meth_get_ctrl(EVP_PKEY_METHOD *pmeth, if (pctrl_str) *pctrl_str = pmeth->ctrl_str; } + +void EVP_PKEY_meth_get_check(EVP_PKEY_METHOD *pmeth, + int (**pcheck) (EVP_PKEY *pkey)) +{ + if (*pcheck) + *pcheck = pmeth->check; +} + +void EVP_PKEY_meth_get_public_check(EVP_PKEY_METHOD *pmeth, + int (**pcheck) (EVP_PKEY *pkey)) +{ + if (*pcheck) + *pcheck = pmeth->public_check; +} + +void EVP_PKEY_meth_get_param_check(EVP_PKEY_METHOD *pmeth, + int (**pcheck) (EVP_PKEY *pkey)) +{ + if (*pcheck) + *pcheck = pmeth->param_check; +} diff --git a/crypto/evp/scrypt.c b/crypto/evp/scrypt.c deleted file mode 100644 index 101bb1ed..00000000 --- a/crypto/evp/scrypt.c +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright 2015-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 - */ - -#include -#include -#include -#include -#include -#include - -#ifndef OPENSSL_NO_SCRYPT - -#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b)))) -static void salsa208_word_specification(uint32_t inout[16]) -{ - int i; - uint32_t x[16]; - memcpy(x, inout, sizeof(x)); - for (i = 8; i > 0; i -= 2) { - x[4] ^= R(x[0] + x[12], 7); - x[8] ^= R(x[4] + x[0], 9); - x[12] ^= R(x[8] + x[4], 13); - x[0] ^= R(x[12] + x[8], 18); - x[9] ^= R(x[5] + x[1], 7); - x[13] ^= R(x[9] + x[5], 9); - x[1] ^= R(x[13] + x[9], 13); - x[5] ^= R(x[1] + x[13], 18); - x[14] ^= R(x[10] + x[6], 7); - x[2] ^= R(x[14] + x[10], 9); - x[6] ^= R(x[2] + x[14], 13); - x[10] ^= R(x[6] + x[2], 18); - x[3] ^= R(x[15] + x[11], 7); - x[7] ^= R(x[3] + x[15], 9); - x[11] ^= R(x[7] + x[3], 13); - x[15] ^= R(x[11] + x[7], 18); - x[1] ^= R(x[0] + x[3], 7); - x[2] ^= R(x[1] + x[0], 9); - x[3] ^= R(x[2] + x[1], 13); - x[0] ^= R(x[3] + x[2], 18); - x[6] ^= R(x[5] + x[4], 7); - x[7] ^= R(x[6] + x[5], 9); - x[4] ^= R(x[7] + x[6], 13); - x[5] ^= R(x[4] + x[7], 18); - x[11] ^= R(x[10] + x[9], 7); - x[8] ^= R(x[11] + x[10], 9); - x[9] ^= R(x[8] + x[11], 13); - x[10] ^= R(x[9] + x[8], 18); - x[12] ^= R(x[15] + x[14], 7); - x[13] ^= R(x[12] + x[15], 9); - x[14] ^= R(x[13] + x[12], 13); - x[15] ^= R(x[14] + x[13], 18); - } - for (i = 0; i < 16; ++i) - inout[i] += x[i]; - OPENSSL_cleanse(x, sizeof(x)); -} - -static void scryptBlockMix(uint32_t *B_, uint32_t *B, uint64_t r) -{ - uint64_t i, j; - uint32_t X[16], *pB; - - memcpy(X, B + (r * 2 - 1) * 16, sizeof(X)); - pB = B; - for (i = 0; i < r * 2; i++) { - for (j = 0; j < 16; j++) - X[j] ^= *pB++; - salsa208_word_specification(X); - memcpy(B_ + (i / 2 + (i & 1) * r) * 16, X, sizeof(X)); - } - OPENSSL_cleanse(X, sizeof(X)); -} - -static void scryptROMix(unsigned char *B, uint64_t r, uint64_t N, - uint32_t *X, uint32_t *T, uint32_t *V) -{ - unsigned char *pB; - uint32_t *pV; - uint64_t i, k; - - /* Convert from little endian input */ - for (pV = V, i = 0, pB = B; i < 32 * r; i++, pV++) { - *pV = *pB++; - *pV |= *pB++ << 8; - *pV |= *pB++ << 16; - *pV |= (uint32_t)*pB++ << 24; - } - - for (i = 1; i < N; i++, pV += 32 * r) - scryptBlockMix(pV, pV - 32 * r, r); - - scryptBlockMix(X, V + (N - 1) * 32 * r, r); - - for (i = 0; i < N; i++) { - uint32_t j; - j = X[16 * (2 * r - 1)] % N; - pV = V + 32 * r * j; - for (k = 0; k < 32 * r; k++) - T[k] = X[k] ^ *pV++; - scryptBlockMix(X, T, r); - } - /* Convert output to little endian */ - for (i = 0, pB = B; i < 32 * r; i++) { - uint32_t xtmp = X[i]; - *pB++ = xtmp & 0xff; - *pB++ = (xtmp >> 8) & 0xff; - *pB++ = (xtmp >> 16) & 0xff; - *pB++ = (xtmp >> 24) & 0xff; - } -} - -#ifndef SIZE_MAX -# define SIZE_MAX ((size_t)-1) -#endif - -/* - * Maximum power of two that will fit in uint64_t: this should work on - * most (all?) platforms. - */ - -#define LOG2_UINT64_MAX (sizeof(uint64_t) * 8 - 1) - -/* - * Maximum value of p * r: - * p <= ((2^32-1) * hLen) / MFLen => - * p <= ((2^32-1) * 32) / (128 * r) => - * p * r <= (2^30-1) - * - */ - -#define SCRYPT_PR_MAX ((1 << 30) - 1) - -/* - * Maximum permitted memory allow this to be overridden with Configuration - * option: e.g. -DSCRYPT_MAX_MEM=0 for maximum possible. - */ - -#ifdef SCRYPT_MAX_MEM -# if SCRYPT_MAX_MEM == 0 -# undef SCRYPT_MAX_MEM -/* - * Although we could theoretically allocate SIZE_MAX memory that would leave - * no memory available for anything else so set limit as half that. - */ -# define SCRYPT_MAX_MEM (SIZE_MAX/2) -# endif -#else -/* Default memory limit: 32 MB */ -# define SCRYPT_MAX_MEM (1024 * 1024 * 32) -#endif - -int EVP_PBE_scrypt(const char *pass, size_t passlen, - const unsigned char *salt, size_t saltlen, - uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem, - unsigned char *key, size_t keylen) -{ - int rv = 0; - unsigned char *B; - uint32_t *X, *V, *T; - uint64_t i, Blen, Vlen; - size_t allocsize; - - /* Sanity check parameters */ - /* initial check, r,p must be non zero, N >= 2 and a power of 2 */ - if (r == 0 || p == 0 || N < 2 || (N & (N - 1))) - return 0; - /* Check p * r < SCRYPT_PR_MAX avoiding overflow */ - if (p > SCRYPT_PR_MAX / r) - return 0; - - /* - * Need to check N: if 2^(128 * r / 8) overflows limit this is - * automatically satisfied since N <= UINT64_MAX. - */ - - if (16 * r <= LOG2_UINT64_MAX) { - if (N >= (((uint64_t)1) << (16 * r))) - return 0; - } - - /* Memory checks: check total allocated buffer size fits in uint64_t */ - - /* - * B size in section 5 step 1.S - * Note: we know p * 128 * r < UINT64_MAX because we already checked - * p * r < SCRYPT_PR_MAX - */ - Blen = p * 128 * r; - - /* - * Check 32 * r * (N + 2) * sizeof(uint32_t) fits in - * uint64_t and also size_t (their sizes are unrelated). - * This is combined size V, X and T (section 4) - */ - i = UINT64_MAX / (32 * sizeof(uint32_t)); - if (N + 2 > i / r) - return 0; - Vlen = 32 * r * (N + 2) * sizeof(uint32_t); - - /* check total allocated size fits in uint64_t */ - if (Blen > UINT64_MAX - Vlen) - return 0; - /* check total allocated size fits in size_t */ - if (Blen > SIZE_MAX - Vlen) - return 0; - - allocsize = (size_t)(Blen + Vlen); - - if (maxmem == 0) - maxmem = SCRYPT_MAX_MEM; - - if (allocsize > maxmem) { - EVPerr(EVP_F_EVP_PBE_SCRYPT, EVP_R_MEMORY_LIMIT_EXCEEDED); - return 0; - } - - /* If no key return to indicate parameters are OK */ - if (key == NULL) - return 1; - - B = OPENSSL_malloc(allocsize); - if (B == NULL) - return 0; - X = (uint32_t *)(B + Blen); - T = X + 32 * r; - V = T + 32 * r; - if (PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, 1, EVP_sha256(), - Blen, B) == 0) - goto err; - - for (i = 0; i < p; i++) - scryptROMix(B + 128 * r * i, r, N, X, T, V); - - if (PKCS5_PBKDF2_HMAC(pass, passlen, B, Blen, 1, EVP_sha256(), - keylen, key) == 0) - goto err; - rv = 1; - err: - OPENSSL_clear_free(B, allocsize); - return rv; -} -#endif diff --git a/crypto/ex_data.c b/crypto/ex_data.c index 22c4d3d9..ed9820cf 100644 --- a/crypto/ex_data.c +++ b/crypto/ex_data.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -9,7 +9,6 @@ #include "internal/cryptlib_int.h" #include "internal/thread_once.h" -#include /* * Each structure type (sometimes called a class), that supports diff --git a/crypto/hmac/hm_ameth.c b/crypto/hmac/hm_ameth.c index 78ae0ea6..4d830b8d 100644 --- a/crypto/hmac/hm_ameth.c +++ b/crypto/hmac/hm_ameth.c @@ -12,8 +12,6 @@ #include #include "internal/asn1_int.h" -#define HMAC_TEST_PRIVATE_KEY_FORMAT - /* * HMAC "ASN1" method. This is just here to indicate the maximum HMAC output * length and to free up an HMAC key. @@ -51,53 +49,6 @@ static int hmac_pkey_public_cmp(const EVP_PKEY *a, const EVP_PKEY *b) return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b)); } -#ifdef HMAC_TEST_PRIVATE_KEY_FORMAT -/* - * A bogus private key format for test purposes. This is simply the HMAC key - * with "HMAC PRIVATE KEY" in the headers. When enabled the genpkey utility - * can be used to "generate" HMAC keys. - */ - -static int old_hmac_decode(EVP_PKEY *pkey, - const unsigned char **pder, int derlen) -{ - ASN1_OCTET_STRING *os; - os = ASN1_OCTET_STRING_new(); - if (os == NULL || !ASN1_OCTET_STRING_set(os, *pder, derlen)) - goto err; - if (!EVP_PKEY_assign(pkey, EVP_PKEY_HMAC, os)) - goto err; - return 1; - - err: - ASN1_OCTET_STRING_free(os); - return 0; -} - -static int old_hmac_encode(const EVP_PKEY *pkey, unsigned char **pder) -{ - int inc; - ASN1_OCTET_STRING *os = EVP_PKEY_get0(pkey); - if (pder) { - if (!*pder) { - *pder = OPENSSL_malloc(os->length); - if (*pder == NULL) - return -1; - inc = 0; - } else - inc = 1; - - memcpy(*pder, os->data, os->length); - - if (inc) - *pder += os->length; - } - - return os->length; -} - -#endif - const EVP_PKEY_ASN1_METHOD hmac_asn1_meth = { EVP_PKEY_HMAC, EVP_PKEY_HMAC, @@ -116,10 +67,5 @@ const EVP_PKEY_ASN1_METHOD hmac_asn1_meth = { hmac_key_free, hmac_pkey_ctrl, -#ifdef HMAC_TEST_PRIVATE_KEY_FORMAT - old_hmac_decode, - old_hmac_encode -#else 0, 0 -#endif }; diff --git a/crypto/hmac/hmac.c b/crypto/hmac/hmac.c index 3374105c..156725ea 100644 --- a/crypto/hmac/hmac.c +++ b/crypto/hmac/hmac.c @@ -37,7 +37,8 @@ int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int len, if (key != NULL) { reset = 1; j = EVP_MD_block_size(md); - OPENSSL_assert(j <= (int)sizeof(ctx->key)); + if (!ossl_assert(j <= (int)sizeof(ctx->key))) + goto err; if (j < len) { if (!EVP_DigestInit_ex(ctx->md_ctx, md, impl)) goto err; @@ -118,7 +119,9 @@ int HMAC_Final(HMAC_CTX *ctx, unsigned char *md, unsigned int *len) size_t HMAC_size(const HMAC_CTX *ctx) { - return EVP_MD_size((ctx)->md); + int size = EVP_MD_size((ctx)->md); + + return (size < 0) ? 0 : size; } HMAC_CTX *HMAC_CTX_new(void) @@ -155,31 +158,36 @@ void HMAC_CTX_free(HMAC_CTX *ctx) } } -int HMAC_CTX_reset(HMAC_CTX *ctx) +static int hmac_ctx_alloc_mds(HMAC_CTX *ctx) { - hmac_ctx_cleanup(ctx); if (ctx->i_ctx == NULL) ctx->i_ctx = EVP_MD_CTX_new(); if (ctx->i_ctx == NULL) - goto err; + return 0; if (ctx->o_ctx == NULL) ctx->o_ctx = EVP_MD_CTX_new(); if (ctx->o_ctx == NULL) - goto err; + return 0; if (ctx->md_ctx == NULL) ctx->md_ctx = EVP_MD_CTX_new(); if (ctx->md_ctx == NULL) - goto err; - ctx->md = NULL; + return 0; return 1; - err: +} + +int HMAC_CTX_reset(HMAC_CTX *ctx) +{ hmac_ctx_cleanup(ctx); - return 0; + if (!hmac_ctx_alloc_mds(ctx)) { + hmac_ctx_cleanup(ctx); + return 0; + } + return 1; } int HMAC_CTX_copy(HMAC_CTX *dctx, HMAC_CTX *sctx) { - if (!HMAC_CTX_reset(dctx)) + if (!hmac_ctx_alloc_mds(dctx)) goto err; if (!EVP_MD_CTX_copy_ex(dctx->i_ctx, sctx->i_ctx)) goto err; diff --git a/crypto/idea/i_ecb.c b/crypto/idea/i_ecb.c index 2208287e..058d0c14 100644 --- a/crypto/idea/i_ecb.c +++ b/crypto/idea/i_ecb.c @@ -13,7 +13,7 @@ const char *IDEA_options(void) { - return ("idea(int)"); + return "idea(int)"; } void IDEA_ecb_encrypt(const unsigned char *in, unsigned char *out, diff --git a/crypto/idea/i_skey.c b/crypto/idea/i_skey.c index 02853246..9d914558 100644 --- a/crypto/idea/i_skey.c +++ b/crypto/idea/i_skey.c @@ -108,5 +108,5 @@ static IDEA_INT inverse(unsigned int xin) } } while (r != 0); } - return ((IDEA_INT) b2); + return (IDEA_INT)b2; } diff --git a/crypto/idea/idea_lcl.h b/crypto/idea/idea_lcl.h index 825d0006..50f81dfd 100644 --- a/crypto/idea/idea_lcl.h +++ b/crypto/idea/idea_lcl.h @@ -7,11 +7,6 @@ * https://www.openssl.org/source/license.html */ -/* - * The new form of this macro (check if the a*b == 0) was suggested by Colin - * Plumb - */ -/* Removal of the inner if from from Wei Dai 24/4/96 */ #define idea_mul(r,a,b,ul) \ ul=(unsigned long)a*b; \ if (ul != 0) \ @@ -22,16 +17,6 @@ if (ul != 0) \ else \ r=(-(int)a-b+1); /* assuming a or b is 0 and in range */ -/* - * 7/12/95 - Many thanks to Rhys Weatherley for - * pointing out that I was assuming little endian byte order for all - * quantities what idea actually used bigendian. No where in the spec does - * it mention this, it is all in terms of 16 bit numbers and even the example - * does not use byte streams for the input example :-(. If you byte swap each - * pair of input, keys and iv, the functions would produce the output as the - * old version :-(. - */ - /* NOTE - c is not incremented as per n2l */ #define n2ln(c,l1,l2,n) { \ c+=n; \ diff --git a/crypto/include/internal/__DECC_INCLUDE_EPILOGUE.H b/crypto/include/internal/__DECC_INCLUDE_EPILOGUE.H new file mode 100644 index 00000000..c350018a --- /dev/null +++ b/crypto/include/internal/__DECC_INCLUDE_EPILOGUE.H @@ -0,0 +1,16 @@ +/* + * 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 + */ + +/* + * This file is only used by HP C on VMS, and is included automatically + * after each header file from this directory + */ + +/* restore state. Must correspond to the save in __decc_include_prologue.h */ +#pragma names restore diff --git a/crypto/include/internal/__DECC_INCLUDE_PROLOGUE.H b/crypto/include/internal/__DECC_INCLUDE_PROLOGUE.H new file mode 100644 index 00000000..9a9c777f --- /dev/null +++ b/crypto/include/internal/__DECC_INCLUDE_PROLOGUE.H @@ -0,0 +1,20 @@ +/* + * 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 + */ + +/* + * This file is only used by HP C on VMS, and is included automatically + * after each header file from this directory + */ + +/* save state */ +#pragma names save +/* have the compiler shorten symbols larger than 31 chars to 23 chars + * followed by a 8 hex char CRC + */ +#pragma names as_is,shortened diff --git a/crypto/include/internal/aria.h b/crypto/include/internal/aria.h new file mode 100644 index 00000000..07382718 --- /dev/null +++ b/crypto/include/internal/aria.h @@ -0,0 +1,58 @@ +/* + * Copyright 2006-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2017, Oracle and/or its affiliates. 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 + */ + + /* Copyright (c) 2017 National Security Research Institute. All rights reserved. */ + +#ifndef HEADER_ARIA_H +# define HEADER_ARIA_H + +# include + +# ifdef OPENSSL_NO_ARIA +# error ARIA is disabled. +# endif + +# define ARIA_ENCRYPT 1 +# define ARIA_DECRYPT 0 + +# define ARIA_BLOCK_SIZE 16 /* Size of each encryption/decryption block */ +# define ARIA_MAX_KEYS 17 /* Number of keys needed in the worst case */ + +# ifdef __cplusplus +extern "C" { +# endif + +typedef union { + unsigned char c[ARIA_BLOCK_SIZE]; + unsigned int u[ARIA_BLOCK_SIZE / sizeof(unsigned int)]; +} ARIA_u128; + +typedef unsigned char ARIA_c128[ARIA_BLOCK_SIZE]; + +struct aria_key_st { + ARIA_u128 rd_key[ARIA_MAX_KEYS]; + unsigned int rounds; +}; +typedef struct aria_key_st ARIA_KEY; + + +int aria_set_encrypt_key(const unsigned char *userKey, const int bits, + ARIA_KEY *key); +int aria_set_decrypt_key(const unsigned char *userKey, const int bits, + ARIA_KEY *key); + +void aria_encrypt(const unsigned char *in, unsigned char *out, + const ARIA_KEY *key); + +# ifdef __cplusplus +} +# endif + +#endif diff --git a/crypto/include/internal/asn1_int.h b/crypto/include/internal/asn1_int.h index f70e3b47..90d525aa 100644 --- a/crypto/include/internal/asn1_int.h +++ b/crypto/include/internal/asn1_int.h @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-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 @@ -52,6 +52,12 @@ struct evp_pkey_asn1_method_st { int (*item_sign) (EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *alg1, X509_ALGOR *alg2, ASN1_BIT_STRING *sig); + int (*siginf_set) (X509_SIG_INFO *siginf, const X509_ALGOR *alg, + const ASN1_STRING *sig); + /* Check */ + int (*pkey_check) (const EVP_PKEY *pk); + int (*pkey_public_check) (const EVP_PKEY *pk); + int (*pkey_param_check) (const EVP_PKEY *pk); } /* EVP_PKEY_ASN1_METHOD */ ; DEFINE_STACK_OF_CONST(EVP_PKEY_ASN1_METHOD) @@ -62,8 +68,13 @@ extern const EVP_PKEY_ASN1_METHOD dhx_asn1_meth; extern const EVP_PKEY_ASN1_METHOD dsa_asn1_meths[5]; extern const EVP_PKEY_ASN1_METHOD eckey_asn1_meth; extern const EVP_PKEY_ASN1_METHOD ecx25519_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD ed25519_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD poly1305_asn1_meth; + extern const EVP_PKEY_ASN1_METHOD hmac_asn1_meth; extern const EVP_PKEY_ASN1_METHOD rsa_asn1_meths[2]; +extern const EVP_PKEY_ASN1_METHOD rsa_pss_asn1_meth; +extern const EVP_PKEY_ASN1_METHOD siphash_asn1_meth; /* * These are used internally in the ASN1_OBJECT to keep track of whether the @@ -92,3 +103,4 @@ struct asn1_pctx_st { } /* ASN1_PCTX */ ; int asn1_valid_host(const ASN1_STRING *host); +int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb); diff --git a/crypto/include/internal/bn_dh.h b/crypto/include/internal/bn_dh.h index f49f0398..70ebca28 100644 --- a/crypto/include/internal/bn_dh.h +++ b/crypto/include/internal/bn_dh.h @@ -15,3 +15,10 @@ declare_dh_bn(1024_160) declare_dh_bn(2048_224) declare_dh_bn(2048_256) + +extern const BIGNUM _bignum_ffdhe2048_p; +extern const BIGNUM _bignum_ffdhe3072_p; +extern const BIGNUM _bignum_ffdhe4096_p; +extern const BIGNUM _bignum_ffdhe6144_p; +extern const BIGNUM _bignum_ffdhe8192_p; +extern const BIGNUM _bignum_const_2; diff --git a/crypto/include/internal/bn_int.h b/crypto/include/internal/bn_int.h index 9c984ba7..ac49d1ea 100644 --- a/crypto/include/internal/bn_int.h +++ b/crypto/include/internal/bn_int.h @@ -34,8 +34,6 @@ signed char *bn_compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len); int bn_get_top(const BIGNUM *a); -void bn_set_top(BIGNUM *a, int top); - int bn_get_dmax(const BIGNUM *a); /* Set all words to zero */ @@ -66,15 +64,6 @@ void bn_set_static_words(BIGNUM *a, BN_ULONG *words, int size); */ int bn_set_words(BIGNUM *a, BN_ULONG *words, int num_words); -size_t bn_sizeof_BIGNUM(void); - -/* - * Return element el from an array of BIGNUMs starting at base (required - * because callers do not know the size of BIGNUM at compilation time) - */ -BIGNUM *bn_array_el(BIGNUM *base, int el); - - #ifdef __cplusplus } #endif diff --git a/crypto/include/internal/cryptlib_int.h b/crypto/include/internal/cryptlib_int.h index 8e2a7199..3dddf082 100644 --- a/crypto/include/internal/cryptlib_int.h +++ b/crypto/include/internal/cryptlib_int.h @@ -7,7 +7,7 @@ * https://www.openssl.org/source/license.html */ -#include +#include "internal/cryptlib.h" /* This file is not scanned by mkdef.pl, whereas cryptlib.h is */ @@ -29,3 +29,4 @@ int ossl_init_thread_start(uint64_t opts); # define OPENSSL_INIT_THREAD_ASYNC 0x01 # define OPENSSL_INIT_THREAD_ERR_STATE 0x02 +void ossl_malloc_setup_failures(void); diff --git a/crypto/include/internal/ctype.h b/crypto/include/internal/ctype.h new file mode 100644 index 00000000..a35b12bf --- /dev/null +++ b/crypto/include/internal/ctype.h @@ -0,0 +1,80 @@ +/* + * 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 + */ + +/* + * This version of ctype.h provides a standardised and platform + * independent implementation that supports seven bit ASCII characters. + * The specific intent is to not pass extended ASCII characters (> 127) + * even if the host operating system would. + * + * There is EBCDIC support included for machines which use this. However, + * there are a number of concerns about how well EBCDIC is supported + * throughout the rest of the source code. Refer to issue #4154 for + * details. + */ +#ifndef INTERNAL_CTYPE_H +# define INTERNAL_CTYPE_H + +# define CTYPE_MASK_lower 0x1 +# define CTYPE_MASK_upper 0x2 +# define CTYPE_MASK_digit 0x4 +# define CTYPE_MASK_space 0x8 +# define CTYPE_MASK_xdigit 0x10 +# define CTYPE_MASK_blank 0x20 +# define CTYPE_MASK_cntrl 0x40 +# define CTYPE_MASK_graph 0x80 +# define CTYPE_MASK_print 0x100 +# define CTYPE_MASK_punct 0x200 +# define CTYPE_MASK_base64 0x400 +# define CTYPE_MASK_asn1print 0x800 + +# define CTYPE_MASK_alpha (CTYPE_MASK_lower | CTYPE_MASK_upper) +# define CTYPE_MASK_alnum (CTYPE_MASK_alpha | CTYPE_MASK_digit) + +/* + * The ascii mask assumes that any other classification implies that + * the character is ASCII and that there are no ASCII characters + * that aren't in any of the classifications. + * + * This assumption holds at the moment, but it might not in the future. + */ +# define CTYPE_MASK_ascii (~0) + +# ifdef CHARSET_EBCDIC +int ossl_toascii(int c); +int ossl_fromascii(int c); +# else +# define ossl_toascii(c) (c) +# define ossl_fromascii(c) (c) +# endif +int ossl_ctype_check(int c, unsigned int mask); +int ossl_tolower(int c); +int ossl_toupper(int c); + +# define ossl_isalnum(c) (ossl_ctype_check((c), CTYPE_MASK_alnum)) +# define ossl_isalpha(c) (ossl_ctype_check((c), CTYPE_MASK_alpha)) +# ifdef CHARSET_EBCDIC +# define ossl_isascii(c) (ossl_ctype_check((c), CTYPE_MASK_ascii)) +# else +# define ossl_isascii(c) (((c) & ~127) == 0) +# endif +# define ossl_isblank(c) (ossl_ctype_check((c), CTYPE_MASK_blank)) +# define ossl_iscntrl(c) (ossl_ctype_check((c), CTYPE_MASK_cntrl)) +# define ossl_isdigit(c) (ossl_ctype_check((c), CTYPE_MASK_digit)) +# define ossl_isgraph(c) (ossl_ctype_check((c), CTYPE_MASK_graph)) +# define ossl_islower(c) (ossl_ctype_check((c), CTYPE_MASK_lower)) +# define ossl_isprint(c) (ossl_ctype_check((c), CTYPE_MASK_print)) +# define ossl_ispunct(c) (ossl_ctype_check((c), CTYPE_MASK_punct)) +# define ossl_isspace(c) (ossl_ctype_check((c), CTYPE_MASK_space)) +# define ossl_isupper(c) (ossl_ctype_check((c), CTYPE_MASK_upper)) +# define ossl_isxdigit(c) (ossl_ctype_check((c), CTYPE_MASK_xdigit)) +# define ossl_isbase64(c) (ossl_ctype_check((c), CTYPE_MASK_base64)) +# define ossl_isasn1print(c) (ossl_ctype_check((c), CTYPE_MASK_asn1print)) + +#endif diff --git a/crypto/include/internal/engine.h b/crypto/include/internal/engine.h index 977cf06d..f80ae3ec 100644 --- a/crypto/include/internal/engine.h +++ b/crypto/include/internal/engine.h @@ -10,7 +10,7 @@ #include void engine_load_openssl_int(void); -void engine_load_cryptodev_int(void); +void engine_load_devcrypto_int(void); void engine_load_rdrand_int(void); void engine_load_dynamic_int(void); void engine_load_padlock_int(void); diff --git a/crypto/include/internal/evp_int.h b/crypto/include/internal/evp_int.h index f34699bf..a838a2a3 100644 --- a/crypto/include/internal/evp_int.h +++ b/crypto/include/internal/evp_int.h @@ -7,6 +7,8 @@ * https://www.openssl.org/source/license.html */ +#include "internal/refcount.h" + struct evp_pkey_ctx_st { /* Method associated with this operation */ const EVP_PKEY_METHOD *pmeth; @@ -68,6 +70,14 @@ struct evp_pkey_method_st { 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); + int (*digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen, + const unsigned char *tbs, size_t tbslen); + int (*digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig, + size_t siglen, const unsigned char *tbs, + size_t tbslen); + int (*check) (EVP_PKEY *pkey); + int (*public_check) (EVP_PKEY *pkey); + int (*param_check) (EVP_PKEY *pkey); } /* EVP_PKEY_METHOD */ ; DEFINE_STACK_OF_CONST(EVP_PKEY_METHOD) @@ -80,10 +90,15 @@ extern const EVP_PKEY_METHOD dhx_pkey_meth; extern const EVP_PKEY_METHOD dsa_pkey_meth; extern const EVP_PKEY_METHOD ec_pkey_meth; extern const EVP_PKEY_METHOD ecx25519_pkey_meth; +extern const EVP_PKEY_METHOD ed25519_pkey_meth; extern const EVP_PKEY_METHOD hmac_pkey_meth; extern const EVP_PKEY_METHOD rsa_pkey_meth; +extern const EVP_PKEY_METHOD rsa_pss_pkey_meth; +extern const EVP_PKEY_METHOD scrypt_pkey_meth; extern const EVP_PKEY_METHOD tls1_prf_pkey_meth; extern const EVP_PKEY_METHOD hkdf_pkey_meth; +extern const EVP_PKEY_METHOD poly1305_pkey_meth; +extern const EVP_PKEY_METHOD siphash_pkey_meth; struct evp_md_st { int type; @@ -353,7 +368,7 @@ const EVP_CIPHER *EVP_##cname##_ecb(void) { return &cname##_ecb; } struct evp_pkey_st { int type; int save_type; - int references; + CRYPTO_REF_COUNT references; const EVP_PKEY_ASN1_METHOD *ameth; ENGINE *engine; ENGINE *pmeth_engine; /* If not NULL public key ENGINE to use */ @@ -381,8 +396,9 @@ struct evp_pkey_st { void openssl_add_all_ciphers_int(void); void openssl_add_all_digests_int(void); void evp_cleanup_int(void); +void evp_app_cleanup_int(void); -/* Pulling defines out of C soure files */ +/* Pulling defines out of C source files */ #define EVP_RC4_KEY_SIZE 16 #ifndef TLS1_1_VERSION diff --git a/crypto/include/internal/md32_common.h b/crypto/include/internal/md32_common.h index 6e4ce14e..e498cf37 100644 --- a/crypto/include/internal/md32_common.h +++ b/crypto/include/internal/md32_common.h @@ -22,7 +22,7 @@ * HASH_CBLOCK * size of a unit chunk HASH_BLOCK operates on. * HASH_LONG - * has to be at lest 32 bit wide. + * has to be at least 32 bit wide. * HASH_CTX * context structure that at least contains following * members: @@ -48,7 +48,7 @@ * name of "block" function capable of treating *unaligned* input * message in original (data) byte order, implemented externally. * HASH_MAKE_STRING - * macro convering context variables to an ASCII hash string. + * macro converting context variables to an ASCII hash string. * * MD5 example: * @@ -61,8 +61,6 @@ * #define HASH_TRANSFORM MD5_Transform * #define HASH_FINAL MD5_Final * #define HASH_BLOCK_DATA_ORDER md5_block_data_order - * - * */ #include @@ -109,7 +107,6 @@ * Some GNU C inline assembler templates. Note that these are * rotates by *constant* number of bits! But that's exactly * what we need here... - * */ # if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__) # define ROTATE(a,n) ({ register unsigned int ret; \ @@ -243,7 +240,7 @@ #endif /* - * Time for some action:-) + * Time for some action :-) */ int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len) @@ -257,10 +254,6 @@ int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len) return 1; l = (c->Nl + (((HASH_LONG) len) << 3)) & 0xffffffffUL; - /* - * 95-05-24 eay Fixed a bug with the overflow handling, thanks to Wei Dai - * for pointing it out. - */ if (l < c->Nl) /* overflow */ c->Nh++; c->Nh += (HASH_LONG) (len >> 29); /* might cause compiler warning on @@ -368,7 +361,6 @@ int HASH_FINAL(unsigned char *md, HASH_CTX *c) * improvement under SPARC Solaris7/64 and 5% under AlphaLinux. * Well, to be honest it should say that this *prevents* * performance degradation. - * */ # else /* @@ -376,7 +368,6 @@ int HASH_FINAL(unsigned char *md, HASH_CTX *c) * generate better code if MD32_REG_T is defined int. The above * pre-processor condition reflects the circumstances under which * the conclusion was made and is subject to further extension. - * */ # define MD32_REG_T int # endif diff --git a/crypto/include/internal/poly1305.h b/crypto/include/internal/poly1305.h index 1bc8716f..5fef239d 100644 --- a/crypto/include/internal/poly1305.h +++ b/crypto/include/internal/poly1305.h @@ -9,7 +9,9 @@ #include -#define POLY1305_BLOCK_SIZE 16 +#define POLY1305_BLOCK_SIZE 16 +#define POLY1305_DIGEST_SIZE 16 +#define POLY1305_KEY_SIZE 32 typedef struct poly1305_context POLY1305; diff --git a/crypto/include/internal/rand.h b/crypto/include/internal/rand.h deleted file mode 100644 index 30887c4a..00000000 --- a/crypto/include/internal/rand.h +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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 - */ - -/* - * Licensed under the OpenSSL licenses, (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * https://www.openssl.org/source/license.html - * or in the file LICENSE in the source distribution. - */ - -#include - -void rand_cleanup_int(void); diff --git a/crypto/include/internal/rand_int.h b/crypto/include/internal/rand_int.h new file mode 100644 index 00000000..fc1abd97 --- /dev/null +++ b/crypto/include/internal/rand_int.h @@ -0,0 +1,22 @@ +/* + * 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 + */ + +/* + * Licensed under the OpenSSL licenses, (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * https://www.openssl.org/source/license.html + * or in the file LICENSE in the source distribution. + */ + +#include + +void rand_cleanup_int(void); +void rand_drbg_cleanup_int(void); +void rand_fork(void); diff --git a/crypto/include/internal/sha.h b/crypto/include/internal/sha.h new file mode 100644 index 00000000..458a75e8 --- /dev/null +++ b/crypto/include/internal/sha.h @@ -0,0 +1,19 @@ +/* + * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2018, Oracle and/or its affiliates. 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 + */ + +#ifndef HEADER_INTERNAL_SHA_H +# define HEADER_INTERNAL_SHA_H + +# include + +int sha512_224_init(SHA512_CTX *); +int sha512_256_init(SHA512_CTX *); + +#endif diff --git a/crypto/include/internal/siphash.h b/crypto/include/internal/siphash.h new file mode 100644 index 00000000..e0868596 --- /dev/null +++ b/crypto/include/internal/siphash.h @@ -0,0 +1,24 @@ +/* + * 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 + +#define SIPHASH_BLOCK_SIZE 8 +#define SIPHASH_KEY_SIZE 16 +#define SIPHASH_MIN_DIGEST_SIZE 8 +#define SIPHASH_MAX_DIGEST_SIZE 16 + +typedef struct siphash_st SIPHASH; + +size_t SipHash_ctx_size(void); +size_t SipHash_hash_size(SIPHASH *ctx); +int SipHash_Init(SIPHASH *ctx, const unsigned char *k, int hash_size, + int crounds, int drounds); +void SipHash_Update(SIPHASH *ctx, const unsigned char *in, size_t inlen); +int SipHash_Final(SIPHASH *ctx, unsigned char *out, size_t outlen); diff --git a/crypto/include/internal/sm3.h b/crypto/include/internal/sm3.h new file mode 100644 index 00000000..27eb471c --- /dev/null +++ b/crypto/include/internal/sm3.h @@ -0,0 +1,39 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 Ribose Inc. 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 + */ + +#ifndef HEADER_SM3_H +# define HEADER_SM3_H + +# include + +# ifdef OPENSSL_NO_SM3 +# error SM3 is disabled. +# endif + +# define SM3_DIGEST_LENGTH 32 +# define SM3_WORD unsigned int + +# define SM3_CBLOCK 64 +# define SM3_LBLOCK (SM3_CBLOCK/4) + +typedef struct SM3state_st { + SM3_WORD A, B, C, D, E, F, G, H; + SM3_WORD Nl, Nh; + SM3_WORD data[SM3_LBLOCK]; + unsigned int num; +} SM3_CTX; + +int sm3_init(SM3_CTX *c); +int sm3_update(SM3_CTX *c, const void *data, size_t len); +int sm3_final(unsigned char *md, SM3_CTX *c); + +void sm3_block_data_order(SM3_CTX *c, const void *p, size_t num); + +#endif diff --git a/crypto/include/internal/sm4.h b/crypto/include/internal/sm4.h new file mode 100644 index 00000000..f1f157ef --- /dev/null +++ b/crypto/include/internal/sm4.h @@ -0,0 +1,37 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 Ribose Inc. 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 + */ + +#ifndef HEADER_SM4_H +# define HEADER_SM4_H + +# include +# include + +# ifdef OPENSSL_NO_SM4 +# error SM4 is disabled. +# endif + +# define SM4_ENCRYPT 1 +# define SM4_DECRYPT 0 + +# define SM4_BLOCK_SIZE 16 +# define SM4_KEY_SCHEDULE 32 + +typedef struct SM4_KEY_st { + uint32_t rk[SM4_KEY_SCHEDULE]; +} SM4_KEY; + +int SM4_set_key(const uint8_t *key, SM4_KEY *ks); + +void SM4_encrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks); + +void SM4_decrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks); + +#endif diff --git a/crypto/include/internal/store.h b/crypto/include/internal/store.h new file mode 100644 index 00000000..f5013dc3 --- /dev/null +++ b/crypto/include/internal/store.h @@ -0,0 +1,10 @@ +/* + * 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 + */ + +void ossl_store_cleanup_int(void); diff --git a/crypto/include/internal/store_int.h b/crypto/include/internal/store_int.h new file mode 100644 index 00000000..9966aefa --- /dev/null +++ b/crypto/include/internal/store_int.h @@ -0,0 +1,33 @@ +/* + * 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 + */ + +#ifndef HEADER_STORE_INT_H +# define HEADER_STORE_INT_H + +# include +# include +# include + +# ifdef __cplusplus +extern "C" { +# endif + +/* + * Two functions to read PEM data off an already opened BIO. To be used + * instead of OSSLSTORE_open() and OSSLSTORE_close(). Everything is done + * as usual with OSSLSTORE_load() and OSSLSTORE_eof(). + */ +OSSL_STORE_CTX *ossl_store_attach_pem_bio(BIO *bp, const UI_METHOD *ui_method, + void *ui_data); +int ossl_store_detach_pem_bio(OSSL_STORE_CTX *ctx); + +# ifdef __cplusplus +} +# endif +#endif diff --git a/crypto/include/internal/x509_int.h b/crypto/include/internal/x509_int.h index 2845026d..124cc533 100644 --- a/crypto/include/internal/x509_int.h +++ b/crypto/include/internal/x509_int.h @@ -7,6 +7,8 @@ * https://www.openssl.org/source/license.html */ +#include "internal/refcount.h" + /* Internal X509 structures and functions: not for application use */ /* Note: unless otherwise stated a field pointer is mandatory and should @@ -35,6 +37,19 @@ struct X509_name_st { int canon_enclen; } /* X509_NAME */ ; +/* Signature info structure */ + +struct x509_sig_info_st { + /* NID of message digest */ + int mdnid; + /* NID of public key algorithm */ + int pknid; + /* Security bits */ + int secbits; + /* Various flags */ + uint32_t flags; +}; + /* PKCS#10 certificate request */ struct X509_req_info_st { @@ -54,7 +69,7 @@ struct X509_req_st { X509_REQ_INFO req_info; /* signed certificate request data */ X509_ALGOR sig_alg; /* signature algorithm */ ASN1_BIT_STRING *signature; /* signature */ - int references; + CRYPTO_REF_COUNT references; CRYPTO_RWLOCK *lock; }; @@ -73,7 +88,7 @@ struct X509_crl_st { X509_CRL_INFO crl; /* signed CRL data */ X509_ALGOR sig_alg; /* CRL signature algorithm */ ASN1_BIT_STRING signature; /* CRL signature */ - int references; + CRYPTO_REF_COUNT references; int flags; /* * Cached copies of decoded extension values, since extensions @@ -144,7 +159,8 @@ struct x509_st { X509_CINF cert_info; X509_ALGOR sig_alg; ASN1_BIT_STRING signature; - int references; + X509_SIG_INFO siginf; + CRYPTO_REF_COUNT references; CRYPTO_EX_DATA ex_data; /* These contain copies of various extension values */ long ex_pathlen; @@ -265,3 +281,5 @@ struct x509_object_st { int a2i_ipadd(unsigned char *ipout, const char *ipasc); int x509_set1_time(ASN1_TIME **ptm, const ASN1_TIME *tm); + +void x509_init_sig_info(X509 *x); diff --git a/crypto/init.c b/crypto/init.c index 173eac37..4a88e9cc 100644 --- a/crypto/init.c +++ b/crypto/init.c @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-2018 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 @@ -7,23 +7,25 @@ * https://www.openssl.org/source/license.html */ -#include +#include "e_os.h" +#include "internal/cryptlib_int.h" #include -#include -#include +#include "internal/rand_int.h" +#include "internal/bio.h" #include -#include -#include -#include -#include -#include -#include -#include -#include +#include "internal/evp_int.h" +#include "internal/conf.h" +#include "internal/async.h" +#include "internal/engine.h" +#include "internal/comp.h" +#include "internal/err.h" +#include "internal/err_int.h" +#include "internal/objects.h" #include #include -#include -#include +#include "internal/thread_once.h" +#include "internal/dso.h" +#include "internal/store.h" static int stopped = 0; @@ -70,6 +72,9 @@ DEFINE_RUN_ONCE_STATIC(ossl_init_base) { #ifdef OPENSSL_INIT_DEBUG fprintf(stderr, "OPENSSL_INIT: ossl_init_base: Setting up stop handlers\n"); +#endif +#ifndef OPENSSL_NO_CRYPTO_MDEBUG + ossl_malloc_setup_failures(); #endif /* * We use a dummy thread local key here. We use the destructor to detect @@ -145,7 +150,7 @@ DEFINE_RUN_ONCE_STATIC(ossl_init_load_crypto_strings) # endif ret = err_load_crypto_strings_int(); load_crypto_strings_inited = 1; -#endif +#endif return ret; } @@ -238,16 +243,15 @@ DEFINE_RUN_ONCE_STATIC(ossl_init_engine_openssl) engine_load_openssl_int(); return 1; } -# if !defined(OPENSSL_NO_HW) && \ - (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(HAVE_CRYPTODEV)) -static CRYPTO_ONCE engine_cryptodev = CRYPTO_ONCE_STATIC_INIT; -DEFINE_RUN_ONCE_STATIC(ossl_init_engine_cryptodev) +# ifndef OPENSSL_NO_DEVCRYPTOENG +static CRYPTO_ONCE engine_devcrypto = CRYPTO_ONCE_STATIC_INIT; +DEFINE_RUN_ONCE_STATIC(ossl_init_engine_devcrypto) { # ifdef OPENSSL_INIT_DEBUG - fprintf(stderr, "OPENSSL_INIT: ossl_init_engine_cryptodev: " - "engine_load_cryptodev_int()\n"); + fprintf(stderr, "OPENSSL_INIT: ossl_init_engine_devcrypto: " + "engine_load_devcrypto_int()\n"); # endif - engine_load_cryptodev_int(); + engine_load_devcrypto_int(); return 1; } # endif @@ -417,6 +421,7 @@ void OPENSSL_cleanup(void) stop_handlers = NULL; CRYPTO_THREAD_lock_free(init_lock); + init_lock = NULL; /* * We assume we are single-threaded for this function, i.e. no race @@ -485,16 +490,20 @@ void OPENSSL_cleanup(void) * obj_cleanup_int() must be called last */ rand_cleanup_int(); + rand_drbg_cleanup_int(); conf_modules_free_int(); #ifndef OPENSSL_NO_ENGINE engine_cleanup_int(); #endif + ossl_store_cleanup_int(); crypto_cleanup_all_ex_data_int(); bio_cleanup(); evp_cleanup_int(); obj_cleanup_int(); err_cleanup(); + CRYPTO_secure_malloc_done(); + base_inited = 0; } @@ -548,6 +557,10 @@ int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings) && !RUN_ONCE(&add_all_digests, ossl_init_add_all_digests)) return 0; + if ((opts & OPENSSL_INIT_ATFORK) + && !openssl_init_fork_handlers()) + return 0; + if ((opts & OPENSSL_INIT_NO_LOAD_CONFIG) && !RUN_ONCE(&config, ossl_init_no_config)) return 0; @@ -570,10 +583,9 @@ int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings) if ((opts & OPENSSL_INIT_ENGINE_OPENSSL) && !RUN_ONCE(&engine_openssl, ossl_init_engine_openssl)) return 0; -# if !defined(OPENSSL_NO_HW) && \ - (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(HAVE_CRYPTODEV)) +# if !defined(OPENSSL_NO_HW) && !defined(OPENSSL_NO_DEVCRYPTOENG) if ((opts & OPENSSL_INIT_ENGINE_CRYPTODEV) - && !RUN_ONCE(&engine_cryptodev, ossl_init_engine_cryptodev)) + && !RUN_ONCE(&engine_devcrypto, ossl_init_engine_devcrypto)) return 0; # endif # ifndef OPENSSL_NO_RDRAND @@ -674,3 +686,29 @@ int OPENSSL_atexit(void (*handler)(void)) return 1; } + +#ifdef OPENSSL_SYS_UNIX +/* + * The following three functions are for OpenSSL developers. This is + * where we set/reset state across fork (called via pthread_atfork when + * it exists, or manually by the application when it doesn't). + * + * WARNING! If you put code in either OPENSSL_fork_parent or + * OPENSSL_fork_child, you MUST MAKE SURE that they are async-signal- + * safe. See this link, for example: + * http://man7.org/linux/man-pages/man7/signal-safety.7.html + */ + +void OPENSSL_fork_prepare(void) +{ +} + +void OPENSSL_fork_parent(void) +{ +} + +void OPENSSL_fork_child(void) +{ + rand_fork(); +} +#endif diff --git a/crypto/kdf/build.info b/crypto/kdf/build.info index cbe2080e..c166399d 100644 --- a/crypto/kdf/build.info +++ b/crypto/kdf/build.info @@ -1,3 +1,3 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ - tls1_prf.c kdf_err.c hkdf.c + tls1_prf.c kdf_err.c hkdf.c scrypt.c diff --git a/crypto/kdf/hkdf.c b/crypto/kdf/hkdf.c index 00b95b5a..63c3523c 100644 --- a/crypto/kdf/hkdf.c +++ b/crypto/kdf/hkdf.c @@ -34,6 +34,7 @@ static unsigned char *HKDF_Expand(const EVP_MD *evp_md, unsigned char *okm, size_t okm_len); typedef struct { + int mode; const EVP_MD *md; unsigned char *salt; size_t salt_len; @@ -77,6 +78,10 @@ static int pkey_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) kctx->md = p2; return 1; + case EVP_PKEY_CTRL_HKDF_MODE: + kctx->mode = p1; + return 1; + case EVP_PKEY_CTRL_HKDF_SALT: if (p1 == 0 || p2 == NULL) return 1; @@ -128,8 +133,24 @@ static int pkey_hkdf_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) static int pkey_hkdf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { + if (strcmp(type, "mode") == 0) { + int mode; + + if (strcmp(value, "EXTRACT_AND_EXPAND") == 0) + mode = EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND; + else if (strcmp(value, "EXTRACT_ONLY") == 0) + mode = EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY; + else if (strcmp(value, "EXPAND_ONLY") == 0) + mode = EVP_PKEY_HKDEF_MODE_EXPAND_ONLY; + else + return 0; + + return EVP_PKEY_CTX_hkdf_mode(ctx, mode); + } + if (strcmp(type, "md") == 0) - return EVP_PKEY_CTX_set_hkdf_md(ctx, EVP_get_digestbyname(value)); + return EVP_PKEY_CTX_md(ctx, EVP_PKEY_OP_DERIVE, + EVP_PKEY_CTRL_HKDF_MD, value); if (strcmp(type, "salt") == 0) return EVP_PKEY_CTX_str2ctrl(ctx, EVP_PKEY_CTRL_HKDF_SALT, value); @@ -149,6 +170,7 @@ static int pkey_hkdf_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, if (strcmp(type, "hexinfo") == 0) return EVP_PKEY_CTX_hex2ctrl(ctx, EVP_PKEY_CTRL_HKDF_INFO, value); + KDFerr(KDF_F_PKEY_HKDF_CTRL_STR, KDF_R_UNKNOWN_PARAMETER_TYPE); return -2; } @@ -157,16 +179,36 @@ static int pkey_hkdf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, { HKDF_PKEY_CTX *kctx = ctx->data; - if (kctx->md == NULL || kctx->key == NULL) + if (kctx->md == NULL) { + KDFerr(KDF_F_PKEY_HKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST); return 0; - - if (HKDF(kctx->md, kctx->salt, kctx->salt_len, kctx->key, kctx->key_len, - kctx->info, kctx->info_len, key, *keylen) == NULL) - { + } + if (kctx->key == NULL) { + KDFerr(KDF_F_PKEY_HKDF_DERIVE, KDF_R_MISSING_KEY); return 0; } - return 1; + switch (kctx->mode) { + case EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND: + return HKDF(kctx->md, kctx->salt, kctx->salt_len, kctx->key, + kctx->key_len, kctx->info, kctx->info_len, key, + *keylen) != NULL; + + case EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY: + if (key == NULL) { + *keylen = EVP_MD_size(kctx->md); + return 1; + } + return HKDF_Extract(kctx->md, kctx->salt, kctx->salt_len, kctx->key, + kctx->key_len, key, keylen) != NULL; + + case EVP_PKEY_HKDEF_MODE_EXPAND_ONLY: + return HKDF_Expand(kctx->md, kctx->key, kctx->key_len, kctx->info, + kctx->info_len, key, *keylen) != NULL; + + default: + return 0; + } } const EVP_PKEY_METHOD hkdf_pkey_meth = { @@ -206,12 +248,16 @@ static unsigned char *HKDF(const EVP_MD *evp_md, unsigned char *okm, size_t okm_len) { unsigned char prk[EVP_MAX_MD_SIZE]; + unsigned char *ret; size_t prk_len; if (!HKDF_Extract(evp_md, salt, salt_len, key, key_len, prk, &prk_len)) return NULL; - return HKDF_Expand(evp_md, prk, prk_len, info, info_len, okm, okm_len); + ret = HKDF_Expand(evp_md, prk, prk_len, info, info_len, okm, okm_len); + OPENSSL_cleanse(prk, sizeof(prk)); + + return ret; } static unsigned char *HKDF_Extract(const EVP_MD *evp_md, @@ -245,7 +291,7 @@ static unsigned char *HKDF_Expand(const EVP_MD *evp_md, if (okm_len % dig_len) n++; - if (n > 255) + if (n > 255 || okm == NULL) return NULL; if ((hmac = HMAC_CTX_new()) == NULL) diff --git a/crypto/kdf/kdf_err.c b/crypto/kdf/kdf_err.c index d7d71b35..c7b84b0f 100644 --- a/crypto/kdf/kdf_err.c +++ b/crypto/kdf/kdf_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,26 +8,42 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_KDF,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_KDF,0,reason) - -static ERR_STRING_DATA KDF_str_functs[] = { - {ERR_FUNC(KDF_F_PKEY_TLS1_PRF_CTRL_STR), "pkey_tls1_prf_ctrl_str"}, - {ERR_FUNC(KDF_F_PKEY_TLS1_PRF_DERIVE), "pkey_tls1_prf_derive"}, +static const ERR_STRING_DATA KDF_str_functs[] = { + {ERR_PACK(ERR_LIB_KDF, KDF_F_PKEY_HKDF_CTRL_STR, 0), "pkey_hkdf_ctrl_str"}, + {ERR_PACK(ERR_LIB_KDF, KDF_F_PKEY_HKDF_DERIVE, 0), "pkey_hkdf_derive"}, + {ERR_PACK(ERR_LIB_KDF, KDF_F_PKEY_SCRYPT_CTRL_STR, 0), + "pkey_scrypt_ctrl_str"}, + {ERR_PACK(ERR_LIB_KDF, KDF_F_PKEY_SCRYPT_CTRL_UINT64, 0), + "pkey_scrypt_ctrl_uint64"}, + {ERR_PACK(ERR_LIB_KDF, KDF_F_PKEY_SCRYPT_DERIVE, 0), "pkey_scrypt_derive"}, + {ERR_PACK(ERR_LIB_KDF, KDF_F_PKEY_TLS1_PRF_CTRL_STR, 0), + "pkey_tls1_prf_ctrl_str"}, + {ERR_PACK(ERR_LIB_KDF, KDF_F_PKEY_TLS1_PRF_DERIVE, 0), + "pkey_tls1_prf_derive"}, {0, NULL} }; -static ERR_STRING_DATA KDF_str_reasons[] = { - {ERR_REASON(KDF_R_INVALID_DIGEST), "invalid digest"}, - {ERR_REASON(KDF_R_MISSING_PARAMETER), "missing parameter"}, - {ERR_REASON(KDF_R_VALUE_MISSING), "value missing"}, +static const ERR_STRING_DATA KDF_str_reasons[] = { + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_INVALID_DIGEST), "invalid digest"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_MISSING_ITERATION_COUNT), + "missing iteration count"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_MISSING_KEY), "missing key"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_MISSING_MESSAGE_DIGEST), + "missing message digest"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_MISSING_PARAMETER), "missing parameter"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_MISSING_PASS), "missing pass"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_MISSING_SALT), "missing salt"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_MISSING_SECRET), "missing secret"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_MISSING_SEED), "missing seed"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_UNKNOWN_PARAMETER_TYPE), + "unknown parameter type"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_VALUE_ERROR), "value error"}, + {ERR_PACK(ERR_LIB_KDF, 0, KDF_R_VALUE_MISSING), "value missing"}, {0, NULL} }; @@ -36,10 +52,9 @@ static ERR_STRING_DATA KDF_str_reasons[] = { int ERR_load_KDF_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(KDF_str_functs[0].error) == NULL) { - ERR_load_strings(0, KDF_str_functs); - ERR_load_strings(0, KDF_str_reasons); + ERR_load_strings_const(KDF_str_functs); + ERR_load_strings_const(KDF_str_reasons); } #endif return 1; diff --git a/crypto/kdf/scrypt.c b/crypto/kdf/scrypt.c new file mode 100644 index 00000000..3f4cf385 --- /dev/null +++ b/crypto/kdf/scrypt.c @@ -0,0 +1,262 @@ +/* + * 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 +#include +#include +#include +#include +#include "internal/cryptlib.h" +#include "internal/evp_int.h" + +#ifndef OPENSSL_NO_SCRYPT + +static int atou64(const char *nptr, uint64_t *result); + +typedef struct { + unsigned char *pass; + size_t pass_len; + unsigned char *salt; + size_t salt_len; + uint64_t N, r, p; + uint64_t maxmem_bytes; +} SCRYPT_PKEY_CTX; + +/* Custom uint64_t parser since we do not have strtoull */ +static int atou64(const char *nptr, uint64_t *result) +{ + uint64_t value = 0; + + while (*nptr) { + unsigned int digit; + uint64_t new_value; + + if ((*nptr < '0') || (*nptr > '9')) { + return 0; + } + digit = (unsigned int)(*nptr - '0'); + new_value = (value * 10) + digit; + if ((new_value < digit) || ((new_value - digit) / 10 != value)) { + /* Overflow */ + return 0; + } + value = new_value; + nptr++; + } + *result = value; + return 1; +} + +static int pkey_scrypt_init(EVP_PKEY_CTX *ctx) +{ + SCRYPT_PKEY_CTX *kctx; + + kctx = OPENSSL_zalloc(sizeof(*kctx)); + if (kctx == NULL) + return 0; + + /* Default values are the most conservative recommendation given in the + * original paper of C. Percival. Derivation uses roughly 1 GiB of memory + * for this parameter choice (approx. 128 * r * (N + p) bytes). + */ + kctx->N = 1 << 20; + kctx->r = 8; + kctx->p = 1; + kctx->maxmem_bytes = 1025 * 1024 * 1024; + + ctx->data = kctx; + + return 1; +} + +static void pkey_scrypt_cleanup(EVP_PKEY_CTX *ctx) +{ + SCRYPT_PKEY_CTX *kctx = ctx->data; + + OPENSSL_clear_free(kctx->salt, kctx->salt_len); + OPENSSL_clear_free(kctx->pass, kctx->pass_len); + OPENSSL_free(kctx); +} + +static int pkey_scrypt_set_membuf(unsigned char **buffer, size_t *buflen, + const unsigned char *new_buffer, + const int new_buflen) +{ + if (new_buffer == NULL) + return 1; + + if (new_buflen < 0) + return 0; + + if (*buffer != NULL) + OPENSSL_clear_free(*buffer, *buflen); + + if (new_buflen > 0) { + *buffer = OPENSSL_memdup(new_buffer, new_buflen); + } else { + *buffer = OPENSSL_malloc(1); + } + if (*buffer == NULL) + return 0; + + *buflen = new_buflen; + return 1; +} + +static int is_power_of_two(uint64_t value) +{ + return (value != 0) && ((value & (value - 1)) == 0); +} + +static int pkey_scrypt_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) +{ + SCRYPT_PKEY_CTX *kctx = ctx->data; + uint64_t u64_value; + + switch (type) { + case EVP_PKEY_CTRL_PASS: + return pkey_scrypt_set_membuf(&kctx->pass, &kctx->pass_len, p2, p1); + + case EVP_PKEY_CTRL_SCRYPT_SALT: + return pkey_scrypt_set_membuf(&kctx->salt, &kctx->salt_len, p2, p1); + + case EVP_PKEY_CTRL_SCRYPT_N: + u64_value = *((uint64_t *)p2); + if ((u64_value <= 1) || !is_power_of_two(u64_value)) + return 0; + kctx->N = u64_value; + return 1; + + case EVP_PKEY_CTRL_SCRYPT_R: + u64_value = *((uint64_t *)p2); + if (u64_value < 1) + return 0; + kctx->r = u64_value; + return 1; + + case EVP_PKEY_CTRL_SCRYPT_P: + u64_value = *((uint64_t *)p2); + if (u64_value < 1) + return 0; + kctx->p = u64_value; + return 1; + + case EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES: + u64_value = *((uint64_t *)p2); + if (u64_value < 1) + return 0; + kctx->maxmem_bytes = u64_value; + return 1; + + default: + return -2; + + } +} + +static int pkey_scrypt_ctrl_uint64(EVP_PKEY_CTX *ctx, int type, + const char *value) +{ + uint64_t int_value; + + if (!atou64(value, &int_value)) { + KDFerr(KDF_F_PKEY_SCRYPT_CTRL_UINT64, KDF_R_VALUE_ERROR); + return 0; + } + return pkey_scrypt_ctrl(ctx, type, 0, &int_value); +} + +static int pkey_scrypt_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, + const char *value) +{ + if (value == NULL) { + KDFerr(KDF_F_PKEY_SCRYPT_CTRL_STR, KDF_R_VALUE_MISSING); + return 0; + } + + if (strcmp(type, "pass") == 0) + return EVP_PKEY_CTX_str2ctrl(ctx, EVP_PKEY_CTRL_PASS, value); + + if (strcmp(type, "hexpass") == 0) + return EVP_PKEY_CTX_hex2ctrl(ctx, EVP_PKEY_CTRL_PASS, value); + + if (strcmp(type, "salt") == 0) + return EVP_PKEY_CTX_str2ctrl(ctx, EVP_PKEY_CTRL_SCRYPT_SALT, value); + + if (strcmp(type, "hexsalt") == 0) + return EVP_PKEY_CTX_hex2ctrl(ctx, EVP_PKEY_CTRL_SCRYPT_SALT, value); + + if (strcmp(type, "N") == 0) + return pkey_scrypt_ctrl_uint64(ctx, EVP_PKEY_CTRL_SCRYPT_N, value); + + if (strcmp(type, "r") == 0) + return pkey_scrypt_ctrl_uint64(ctx, EVP_PKEY_CTRL_SCRYPT_R, value); + + if (strcmp(type, "p") == 0) + return pkey_scrypt_ctrl_uint64(ctx, EVP_PKEY_CTRL_SCRYPT_P, value); + + if (strcmp(type, "maxmem_bytes") == 0) + return pkey_scrypt_ctrl_uint64(ctx, EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES, + value); + + KDFerr(KDF_F_PKEY_SCRYPT_CTRL_STR, KDF_R_UNKNOWN_PARAMETER_TYPE); + return -2; +} + +static int pkey_scrypt_derive(EVP_PKEY_CTX *ctx, unsigned char *key, + size_t *keylen) +{ + SCRYPT_PKEY_CTX *kctx = ctx->data; + + if (kctx->pass == NULL) { + KDFerr(KDF_F_PKEY_SCRYPT_DERIVE, KDF_R_MISSING_PASS); + return 0; + } + + if (kctx->salt == NULL) { + KDFerr(KDF_F_PKEY_SCRYPT_DERIVE, KDF_R_MISSING_SALT); + return 0; + } + + return EVP_PBE_scrypt((char *)kctx->pass, kctx->pass_len, kctx->salt, + kctx->salt_len, kctx->N, kctx->r, kctx->p, + kctx->maxmem_bytes, key, *keylen); +} + +const EVP_PKEY_METHOD scrypt_pkey_meth = { + EVP_PKEY_SCRYPT, + 0, + pkey_scrypt_init, + 0, + pkey_scrypt_cleanup, + + 0, 0, + 0, 0, + + 0, + 0, + + 0, + 0, + + 0, 0, + + 0, 0, 0, 0, + + 0, 0, + + 0, 0, + + 0, + pkey_scrypt_derive, + pkey_scrypt_ctrl, + pkey_scrypt_ctrl_str +}; + +#endif diff --git a/crypto/kdf/tls1_prf.c b/crypto/kdf/tls1_prf.c index fa13732b..339e10c1 100644 --- a/crypto/kdf/tls1_prf.c +++ b/crypto/kdf/tls1_prf.c @@ -115,6 +115,8 @@ static int pkey_tls1_prf_ctrl_str(EVP_PKEY_CTX *ctx, return EVP_PKEY_CTX_str2ctrl(ctx, EVP_PKEY_CTRL_TLS_SEED, value); if (strcmp(type, "hexseed") == 0) return EVP_PKEY_CTX_hex2ctrl(ctx, EVP_PKEY_CTRL_TLS_SEED, value); + + KDFerr(KDF_F_PKEY_TLS1_PRF_CTRL_STR, KDF_R_UNKNOWN_PARAMETER_TYPE); return -2; } @@ -122,8 +124,16 @@ static int pkey_tls1_prf_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen) { TLS1_PRF_PKEY_CTX *kctx = ctx->data; - if (kctx->md == NULL || kctx->sec == NULL || kctx->seedlen == 0) { - KDFerr(KDF_F_PKEY_TLS1_PRF_DERIVE, KDF_R_MISSING_PARAMETER); + if (kctx->md == NULL) { + KDFerr(KDF_F_PKEY_TLS1_PRF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST); + return 0; + } + if (kctx->sec == NULL) { + KDFerr(KDF_F_PKEY_TLS1_PRF_DERIVE, KDF_R_MISSING_SECRET); + return 0; + } + if (kctx->seedlen == 0) { + KDFerr(KDF_F_PKEY_TLS1_PRF_DERIVE, KDF_R_MISSING_SEED); return 0; } return tls1_prf_alg(kctx->md, kctx->sec, kctx->seclen, @@ -174,7 +184,8 @@ static int tls1_prf_P_hash(const EVP_MD *md, int ret = 0; chunk = EVP_MD_size(md); - OPENSSL_assert(chunk >= 0); + if (!ossl_assert(chunk > 0)) + goto err; ctx = EVP_MD_CTX_new(); ctx_tmp = EVP_MD_CTX_new(); diff --git a/crypto/lhash/lh_stats.c b/crypto/lhash/lh_stats.c index 5586afa0..65b91e1e 100644 --- a/crypto/lhash/lh_stats.c +++ b/crypto/lhash/lh_stats.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -61,35 +61,22 @@ void OPENSSL_LH_node_usage_stats(const OPENSSL_LHASH *lh, FILE *fp) void OPENSSL_LH_stats_bio(const OPENSSL_LHASH *lh, BIO *out) { - OPENSSL_LHASH *lh_mut = (OPENSSL_LHASH *) lh; - int ret; - BIO_printf(out, "num_items = %lu\n", lh->num_items); - BIO_printf(out, "num_nodes = %u\n", lh->num_nodes); - BIO_printf(out, "num_alloc_nodes = %u\n", lh->num_alloc_nodes); + BIO_printf(out, "num_nodes = %u\n", lh->num_nodes); + BIO_printf(out, "num_alloc_nodes = %u\n", lh->num_alloc_nodes); BIO_printf(out, "num_expands = %lu\n", lh->num_expands); BIO_printf(out, "num_expand_reallocs = %lu\n", lh->num_expand_reallocs); BIO_printf(out, "num_contracts = %lu\n", lh->num_contracts); - BIO_printf(out, "num_contract_reallocs = %lu\n", - lh->num_contract_reallocs); - CRYPTO_atomic_add(&lh_mut->num_hash_calls, 0, &ret, - lh->retrieve_stats_lock); - BIO_printf(out, "num_hash_calls = %d\n", ret); - CRYPTO_atomic_add(&lh_mut->num_comp_calls, 0, &ret, - lh->retrieve_stats_lock); - BIO_printf(out, "num_comp_calls = %d\n", ret); + BIO_printf(out, "num_contract_reallocs = %lu\n", lh->num_contract_reallocs); + BIO_printf(out, "num_hash_calls = %lu\n", lh->num_hash_calls); + BIO_printf(out, "num_comp_calls = %lu\n", lh->num_comp_calls); BIO_printf(out, "num_insert = %lu\n", lh->num_insert); BIO_printf(out, "num_replace = %lu\n", lh->num_replace); BIO_printf(out, "num_delete = %lu\n", lh->num_delete); BIO_printf(out, "num_no_delete = %lu\n", lh->num_no_delete); - CRYPTO_atomic_add(&lh_mut->num_retrieve, 0, &ret, lh->retrieve_stats_lock); - BIO_printf(out, "num_retrieve = %d\n", ret); - CRYPTO_atomic_add(&lh_mut->num_retrieve_miss, 0, &ret, - lh->retrieve_stats_lock); - BIO_printf(out, "num_retrieve_miss = %d\n", ret); - CRYPTO_atomic_add(&lh_mut->num_hash_comps, 0, &ret, - lh->retrieve_stats_lock); - BIO_printf(out, "num_hash_comps = %d\n", ret); + BIO_printf(out, "num_retrieve = %lu\n", lh->num_retrieve); + BIO_printf(out, "num_retrieve_miss = %lu\n", lh->num_retrieve_miss); + BIO_printf(out, "num_hash_comps = %lu\n", lh->num_hash_comps); } void OPENSSL_LH_node_stats_bio(const OPENSSL_LHASH *lh, BIO *out) diff --git a/crypto/lhash/lhash.c b/crypto/lhash/lhash.c index f4854117..38c084d1 100644 --- a/crypto/lhash/lhash.c +++ b/crypto/lhash/lhash.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -16,7 +16,7 @@ /* * A hashing implementation that appears to be based on the linear hashing - * algorithm: + * alogrithm: * https://en.wikipedia.org/wiki/Linear_hashing * * Litwin, Witold (1980), "Linear hashing: A new tool for file and table @@ -49,8 +49,6 @@ OPENSSL_LHASH *OPENSSL_LH_new(OPENSSL_LH_HASHFUNC h, OPENSSL_LH_COMPFUNC c) return NULL; if ((ret->b = OPENSSL_zalloc(sizeof(*ret->b) * MIN_NODES)) == NULL) goto err; - if ((ret->retrieve_stats_lock = CRYPTO_THREAD_lock_new()) == NULL) - goto err; ret->comp = ((c == NULL) ? (OPENSSL_LH_COMPFUNC)strcmp : c); ret->hash = ((h == NULL) ? (OPENSSL_LH_HASHFUNC)OPENSSL_LH_strhash : h); ret->num_nodes = MIN_NODES / 2; @@ -58,7 +56,7 @@ OPENSSL_LHASH *OPENSSL_LH_new(OPENSSL_LH_HASHFUNC h, OPENSSL_LH_COMPFUNC c) ret->pmax = MIN_NODES / 2; ret->up_load = UP_LOAD; ret->down_load = DOWN_LOAD; - return (ret); + return ret; err: OPENSSL_free(ret->b); @@ -82,7 +80,6 @@ void OPENSSL_LH_free(OPENSSL_LHASH *lh) n = nn; } } - CRYPTO_THREAD_lock_free(lh->retrieve_stats_lock); OPENSSL_free(lh->b); OPENSSL_free(lh); } @@ -102,7 +99,7 @@ void *OPENSSL_LH_insert(OPENSSL_LHASH *lh, void *data) if (*rn == NULL) { if ((nn = OPENSSL_malloc(sizeof(*nn))) == NULL) { lh->error++; - return (NULL); + return NULL; } nn->data = data; nn->next = NULL; @@ -112,12 +109,11 @@ void *OPENSSL_LH_insert(OPENSSL_LHASH *lh, void *data) lh->num_insert++; lh->num_items++; } else { /* replace same key */ - ret = (*rn)->data; (*rn)->data = data; lh->num_replace++; } - return (ret); + return ret; } void *OPENSSL_LH_delete(OPENSSL_LHASH *lh, const void *data) @@ -131,7 +127,7 @@ void *OPENSSL_LH_delete(OPENSSL_LHASH *lh, const void *data) if (*rn == NULL) { lh->num_no_delete++; - return (NULL); + return NULL; } else { nn = *rn; *rn = nn->next; @@ -145,7 +141,7 @@ void *OPENSSL_LH_delete(OPENSSL_LHASH *lh, const void *data) (lh->down_load >= (lh->num_items * LH_LOAD_MULT / lh->num_nodes))) contract(lh); - return (ret); + return ret; } void *OPENSSL_LH_retrieve(OPENSSL_LHASH *lh, const void *data) @@ -153,17 +149,16 @@ void *OPENSSL_LH_retrieve(OPENSSL_LHASH *lh, const void *data) unsigned long hash; OPENSSL_LH_NODE **rn; void *ret; - int scratch; lh->error = 0; rn = getrn(lh, data, &hash); if (*rn == NULL) { - CRYPTO_atomic_add(&lh->num_retrieve_miss, 1, &scratch, lh->retrieve_stats_lock); + lh->num_retrieve_miss++; return NULL; } else { ret = (*rn)->data; - CRYPTO_atomic_add(&lh->num_retrieve, 1, &scratch, lh->retrieve_stats_lock); + lh->num_retrieve++; } return ret; } @@ -292,10 +287,9 @@ static OPENSSL_LH_NODE **getrn(OPENSSL_LHASH *lh, OPENSSL_LH_NODE **ret, *n1; unsigned long hash, nn; OPENSSL_LH_COMPFUNC cf; - int scratch; hash = (*(lh->hash)) (data); - CRYPTO_atomic_add(&lh->num_hash_calls, 1, &scratch, lh->retrieve_stats_lock); + lh->num_hash_calls++; *rhash = hash; nn = hash % lh->pmax; @@ -305,17 +299,17 @@ static OPENSSL_LH_NODE **getrn(OPENSSL_LHASH *lh, cf = lh->comp; ret = &(lh->b[(int)nn]); for (n1 = *ret; n1 != NULL; n1 = n1->next) { - CRYPTO_atomic_add(&lh->num_hash_comps, 1, &scratch, lh->retrieve_stats_lock); + lh->num_hash_comps++; if (n1->hash != hash) { ret = &(n1->next); continue; } - CRYPTO_atomic_add(&lh->num_comp_calls, 1, &scratch, lh->retrieve_stats_lock); + lh->num_comp_calls++; if (cf(n1->data, data) == 0) break; ret = &(n1->next); } - return (ret); + return ret; } /* @@ -331,12 +325,7 @@ unsigned long OPENSSL_LH_strhash(const char *c) int r; if ((c == NULL) || (*c == '\0')) - return (ret); -/*- - unsigned char b[16]; - MD5(c,strlen(c),b); - return(b[0]|(b[1]<<8)|(b[2]<<16)|(b[3]<<24)); -*/ + return ret; n = 0x100; while (*c) { @@ -348,7 +337,7 @@ unsigned long OPENSSL_LH_strhash(const char *c) ret ^= v * v; c++; } - return ((ret >> 16) ^ ret); + return (ret >> 16) ^ ret; } unsigned long OPENSSL_LH_num_items(const OPENSSL_LHASH *lh) diff --git a/crypto/lhash/lhash_lcl.h b/crypto/lhash/lhash_lcl.h index 01d463fb..78691eb6 100644 --- a/crypto/lhash/lhash_lcl.h +++ b/crypto/lhash/lhash_lcl.h @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -18,13 +18,6 @@ struct lhash_st { OPENSSL_LH_NODE **b; OPENSSL_LH_COMPFUNC comp; OPENSSL_LH_HASHFUNC hash; - /* - * some stats are updated on lookup, which callers aren't expecting to have - * to take an exclusive lock around. This lock protects them on platforms - * without atomics, and their types are int rather than unsigned long below - * so they can be adjusted with CRYPTO_atomic_add. - */ - CRYPTO_RWLOCK *retrieve_stats_lock; unsigned int num_nodes; unsigned int num_alloc_nodes; unsigned int p; @@ -36,14 +29,14 @@ struct lhash_st { unsigned long num_expand_reallocs; unsigned long num_contracts; unsigned long num_contract_reallocs; - int num_hash_calls; - int num_comp_calls; + unsigned long num_hash_calls; + unsigned long num_comp_calls; unsigned long num_insert; unsigned long num_replace; unsigned long num_delete; unsigned long num_no_delete; - int num_retrieve; - int num_retrieve_miss; - int num_hash_comps; + unsigned long num_retrieve; + unsigned long num_retrieve_miss; + unsigned long num_hash_comps; int error; }; diff --git a/crypto/lhash/num.pl b/crypto/lhash/num.pl deleted file mode 100644 index 8a8c42c8..00000000 --- a/crypto/lhash/num.pl +++ /dev/null @@ -1,23 +0,0 @@ -#! /usr/bin/env perl -# Copyright 1995-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 - -#node 10 -> 4 - -while (<>) - { - next unless /^node/; - s|\R$||; # Better chomp - @a=split; - $num{$a[3]}++; - } - -@a=sort {$a <=> $b } keys %num; -foreach (0 .. $a[$#a]) - { - printf "%4d:%4d\n",$_,$num{$_}; - } diff --git a/crypto/md2/md2_dgst.c b/crypto/md2/md2_dgst.c index ff062fd4..faa9393f 100644 --- a/crypto/md2/md2_dgst.c +++ b/crypto/md2/md2_dgst.c @@ -63,9 +63,9 @@ static const MD2_INT S[256] = { const char *MD2_options(void) { if (sizeof(MD2_INT) == 1) - return ("md2(char)"); + return "md2(char)"; else - return ("md2(int)"); + return "md2(int)"; } int MD2_Init(MD2_CTX *c) diff --git a/crypto/md2/md2_one.c b/crypto/md2/md2_one.c index 460f96e4..5502b216 100644 --- a/crypto/md2/md2_one.c +++ b/crypto/md2/md2_one.c @@ -43,5 +43,5 @@ unsigned char *MD2(const unsigned char *d, size_t n, unsigned char *md) #endif MD2_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* Security consideration */ - return (md); + return md; } diff --git a/crypto/md4/md4_locl.h b/crypto/md4/md4_locl.h index 6aec5562..a6c4003f 100644 --- a/crypto/md4/md4_locl.h +++ b/crypto/md4/md4_locl.h @@ -39,9 +39,9 @@ void md4_block_data_order(MD4_CTX *c, const void *p, size_t num); */ /* - * As pointed out by Wei Dai , the above can be simplified - * to the code below. Wei attributes these optimizations to Peter Gutmann's - * SHS code, and he attributes it to Rich Schroeppel. + * As pointed out by Wei Dai, the above can be simplified to the code + * below. Wei attributes these optimizations to Peter Gutmann's SHS code, + * and he attributes it to Rich Schroeppel. */ #define F(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) #define G(b,c,d) (((b) & (c)) | ((b) & (d)) | ((c) & (d))) diff --git a/crypto/md4/md4_one.c b/crypto/md4/md4_one.c index 9f0989fa..9e52303c 100644 --- a/crypto/md4/md4_one.c +++ b/crypto/md4/md4_one.c @@ -43,5 +43,5 @@ unsigned char *MD4(const unsigned char *d, size_t n, unsigned char *md) #endif MD4_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* security consideration */ - return (md); + return md; } diff --git a/crypto/md5/asm/md5-586.pl b/crypto/md5/asm/md5-586.pl index 24f68af5..15e14864 100644 --- a/crypto/md5/asm/md5-586.pl +++ b/crypto/md5/asm/md5-586.pl @@ -21,7 +21,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],$0); +&asm_init($ARGV[0]); $A="eax"; $B="ebx"; @@ -57,7 +57,7 @@ sub R0 local($pos,$a,$b,$c,$d,$K,$ki,$s,$t)=@_; &mov($tmp1,$C) if $pos < 0; - &mov($tmp2,&DWP($xo[$ki]*4,$K,"",0)) if $pos < 0; # very first one + &mov($tmp2,&DWP($xo[$ki]*4,$K,"",0)) if $pos < 0; # very first one # body proper diff --git a/crypto/md5/asm/md5-ia64.S b/crypto/md5/asm/md5-ia64.S deleted file mode 100644 index c20467b4..00000000 --- a/crypto/md5/asm/md5-ia64.S +++ /dev/null @@ -1,1002 +0,0 @@ -/* - * - * Copyright 2005-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 - */ - -/* Copyright (c) 2005 Hewlett-Packard Development Company, L.P. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -// Common registers are assigned as follows: -// -// COMMON -// -// t0 Const Tbl Ptr TPtr -// t1 Round Constant TRound -// t4 Block residual LenResid -// t5 Residual Data DTmp -// -// {in,out}0 Block 0 Cycle RotateM0 -// {in,out}1 Block Value 12 M12 -// {in,out}2 Block Value 8 M8 -// {in,out}3 Block Value 4 M4 -// {in,out}4 Block Value 0 M0 -// {in,out}5 Block 1 Cycle RotateM1 -// {in,out}6 Block Value 13 M13 -// {in,out}7 Block Value 9 M9 -// {in,out}8 Block Value 5 M5 -// {in,out}9 Block Value 1 M1 -// {in,out}10 Block 2 Cycle RotateM2 -// {in,out}11 Block Value 14 M14 -// {in,out}12 Block Value 10 M10 -// {in,out}13 Block Value 6 M6 -// {in,out}14 Block Value 2 M2 -// {in,out}15 Block 3 Cycle RotateM3 -// {in,out}16 Block Value 15 M15 -// {in,out}17 Block Value 11 M11 -// {in,out}18 Block Value 7 M7 -// {in,out}19 Block Value 3 M3 -// {in,out}20 Scratch Z -// {in,out}21 Scratch Y -// {in,out}22 Scratch X -// {in,out}23 Scratch W -// {in,out}24 Digest A A -// {in,out}25 Digest B B -// {in,out}26 Digest C C -// {in,out}27 Digest D D -// {in,out}28 Active Data Ptr DPtr -// in28 Dummy Value - -// out28 Dummy Value - -// bt0 Coroutine Link QUICK_RTN -// -/// These predicates are used for computing the padding block(s) and -/// are shared between the driver and digest co-routines -// -// pt0 Extra Pad Block pExtra -// pt1 Load next word pLoad -// pt2 Skip next word pSkip -// pt3 Search for Pad pNoPad -// pt4 Pad Word 0 pPad0 -// pt5 Pad Word 1 pPad1 -// pt6 Pad Word 2 pPad2 -// pt7 Pad Word 3 pPad3 - -#define DTmp r19 -#define LenResid r18 -#define QUICK_RTN b6 -#define TPtr r14 -#define TRound r15 -#define pExtra p6 -#define pLoad p7 -#define pNoPad p9 -#define pPad0 p10 -#define pPad1 p11 -#define pPad2 p12 -#define pPad3 p13 -#define pSkip p8 - -#define A_ out24 -#define B_ out25 -#define C_ out26 -#define D_ out27 -#define DPtr_ out28 -#define M0_ out4 -#define M1_ out9 -#define M10_ out12 -#define M11_ out17 -#define M12_ out1 -#define M13_ out6 -#define M14_ out11 -#define M15_ out16 -#define M2_ out14 -#define M3_ out19 -#define M4_ out3 -#define M5_ out8 -#define M6_ out13 -#define M7_ out18 -#define M8_ out2 -#define M9_ out7 -#define RotateM0_ out0 -#define RotateM1_ out5 -#define RotateM2_ out10 -#define RotateM3_ out15 -#define W_ out23 -#define X_ out22 -#define Y_ out21 -#define Z_ out20 - -#define A in24 -#define B in25 -#define C in26 -#define D in27 -#define DPtr in28 -#define M0 in4 -#define M1 in9 -#define M10 in12 -#define M11 in17 -#define M12 in1 -#define M13 in6 -#define M14 in11 -#define M15 in16 -#define M2 in14 -#define M3 in19 -#define M4 in3 -#define M5 in8 -#define M6 in13 -#define M7 in18 -#define M8 in2 -#define M9 in7 -#define RotateM0 in0 -#define RotateM1 in5 -#define RotateM2 in10 -#define RotateM3 in15 -#define W in23 -#define X in22 -#define Y in21 -#define Z in20 - -/* register stack configuration for md5_block_asm_data_order(): */ -#define MD5_NINP 3 -#define MD5_NLOC 0 -#define MD5_NOUT 29 -#define MD5_NROT 0 - -/* register stack configuration for helpers: */ -#define _NINPUTS MD5_NOUT -#define _NLOCALS 0 -#define _NOUTPUT 0 -#define _NROTATE 24 /* this must be <= _NINPUTS */ - -#if defined(_HPUX_SOURCE) && !defined(_LP64) -#define ADDP addp4 -#else -#define ADDP add -#endif - -#if defined(_HPUX_SOURCE) || defined(B_ENDIAN) -#define HOST_IS_BIG_ENDIAN -#endif - -// Macros for getting the left and right portions of little-endian words - -#define GETLW(dst, src, align) dep.z dst = src, 32 - 8 * align, 8 * align -#define GETRW(dst, src, align) extr.u dst = src, 8 * align, 32 - 8 * align - -// MD5 driver -// -// Reads an input block, then calls the digest block -// subroutine and adds the results to the accumulated -// digest. It allocates 32 outs which the subroutine -// uses as it's inputs and rotating -// registers. Initializes the round constant pointer and -// takes care of saving/restoring ar.lc -// -/// INPUT -// -// in0 Context Ptr CtxPtr0 -// in1 Input Data Ptr DPtrIn -// in2 Integral Blocks BlockCount -// rp Return Address - -// -/// CODE -// -// v2 Input Align InAlign -// t0 Shared w/digest - -// t1 Shared w/digest - -// t2 Shared w/digest - -// t3 Shared w/digest - -// t4 Shared w/digest - -// t5 Shared w/digest - -// t6 PFS Save PFSSave -// t7 ar.lc Save LCSave -// t8 Saved PR PRSave -// t9 2nd CtxPtr CtxPtr1 -// t10 Table Base CTable -// t11 Table[0] CTable0 -// t13 Accumulator A AccumA -// t14 Accumulator B AccumB -// t15 Accumulator C AccumC -// t16 Accumulator D AccumD -// pt0 Shared w/digest - -// pt1 Shared w/digest - -// pt2 Shared w/digest - -// pt3 Shared w/digest - -// pt4 Shared w/digest - -// pt5 Shared w/digest - -// pt6 Shared w/digest - -// pt7 Shared w/digest - -// pt8 Not Aligned pOff -// pt8 Blocks Left pAgain - -#define AccumA r27 -#define AccumB r28 -#define AccumC r29 -#define AccumD r30 -#define CTable r24 -#define CTable0 r25 -#define CtxPtr0 in0 -#define CtxPtr1 r23 -#define DPtrIn in1 -#define BlockCount in2 -#define InAlign r10 -#define LCSave r21 -#define PFSSave r20 -#define PRSave r22 -#define pAgain p63 -#define pOff p63 - - .text - -/* md5_block_asm_data_order(MD5_CTX *c, const void *data, size_t num) - - where: - c: a pointer to a structure of this type: - - typedef struct MD5state_st - { - MD5_LONG A,B,C,D; - MD5_LONG Nl,Nh; - MD5_LONG data[MD5_LBLOCK]; - unsigned int num; - } - MD5_CTX; - - data: a pointer to the input data (may be misaligned) - num: the number of 16-byte blocks to hash (i.e., the length - of DATA is 16*NUM. - - */ - - .type md5_block_asm_data_order, @function - .global md5_block_asm_data_order - .align 32 - .proc md5_block_asm_data_order -md5_block_asm_data_order: -.md5_block: - .prologue -{ .mmi - .save ar.pfs, PFSSave - alloc PFSSave = ar.pfs, MD5_NINP, MD5_NLOC, MD5_NOUT, MD5_NROT - ADDP CtxPtr1 = 8, CtxPtr0 - mov CTable = ip -} -{ .mmi - ADDP DPtrIn = 0, DPtrIn - ADDP CtxPtr0 = 0, CtxPtr0 - .save ar.lc, LCSave - mov LCSave = ar.lc -} -;; -{ .mmi - add CTable = .md5_tbl_data_order#-.md5_block#, CTable - and InAlign = 0x3, DPtrIn -} - -{ .mmi - ld4 AccumA = [CtxPtr0], 4 - ld4 AccumC = [CtxPtr1], 4 - .save pr, PRSave - mov PRSave = pr - .body -} -;; -{ .mmi - ld4 AccumB = [CtxPtr0] - ld4 AccumD = [CtxPtr1] - dep DPtr_ = 0, DPtrIn, 0, 2 -} ;; -#ifdef HOST_IS_BIG_ENDIAN - rum psr.be;; // switch to little-endian -#endif -{ .mmb - ld4 CTable0 = [CTable], 4 - cmp.ne pOff, p0 = 0, InAlign -(pOff) br.cond.spnt.many .md5_unaligned -} ;; - -// The FF load/compute loop rotates values three times, so that -// loading into M12 here produces the M0 value, M13 -> M1, etc. - -.md5_block_loop0: -{ .mmi - ld4 M12_ = [DPtr_], 4 - mov TPtr = CTable - mov TRound = CTable0 -} ;; -{ .mmi - ld4 M13_ = [DPtr_], 4 - mov A_ = AccumA - mov B_ = AccumB -} ;; -{ .mmi - ld4 M14_ = [DPtr_], 4 - mov C_ = AccumC - mov D_ = AccumD -} ;; -{ .mmb - ld4 M15_ = [DPtr_], 4 - add BlockCount = -1, BlockCount - br.call.sptk.many QUICK_RTN = md5_digest_block0 -} ;; - -// Now, we add the new digest values and do some clean-up -// before checking if there's another full block to process - -{ .mmi - add AccumA = AccumA, A_ - add AccumB = AccumB, B_ - cmp.ne pAgain, p0 = 0, BlockCount -} -{ .mib - add AccumC = AccumC, C_ - add AccumD = AccumD, D_ -(pAgain) br.cond.dptk.many .md5_block_loop0 -} ;; - -.md5_exit: -#ifdef HOST_IS_BIG_ENDIAN - sum psr.be;; // switch back to big-endian mode -#endif -{ .mmi - st4 [CtxPtr0] = AccumB, -4 - st4 [CtxPtr1] = AccumD, -4 - mov pr = PRSave, 0x1ffff ;; -} -{ .mmi - st4 [CtxPtr0] = AccumA - st4 [CtxPtr1] = AccumC - mov ar.lc = LCSave -} ;; -{ .mib - mov ar.pfs = PFSSave - br.ret.sptk.few rp -} ;; - -#define MD5UNALIGNED(offset) \ -.md5_process##offset: \ -{ .mib ; \ - nop 0x0 ; \ - GETRW(DTmp, DTmp, offset) ; \ -} ;; \ -.md5_block_loop##offset: \ -{ .mmi ; \ - ld4 Y_ = [DPtr_], 4 ; \ - mov TPtr = CTable ; \ - mov TRound = CTable0 ; \ -} ;; \ -{ .mmi ; \ - ld4 M13_ = [DPtr_], 4 ; \ - mov A_ = AccumA ; \ - mov B_ = AccumB ; \ -} ;; \ -{ .mii ; \ - ld4 M14_ = [DPtr_], 4 ; \ - GETLW(W_, Y_, offset) ; \ - mov C_ = AccumC ; \ -} \ -{ .mmi ; \ - mov D_ = AccumD ;; \ - or M12_ = W_, DTmp ; \ - GETRW(DTmp, Y_, offset) ; \ -} \ -{ .mib ; \ - ld4 M15_ = [DPtr_], 4 ; \ - add BlockCount = -1, BlockCount ; \ - br.call.sptk.many QUICK_RTN = md5_digest_block##offset; \ -} ;; \ -{ .mmi ; \ - add AccumA = AccumA, A_ ; \ - add AccumB = AccumB, B_ ; \ - cmp.ne pAgain, p0 = 0, BlockCount ; \ -} \ -{ .mib ; \ - add AccumC = AccumC, C_ ; \ - add AccumD = AccumD, D_ ; \ -(pAgain) br.cond.dptk.many .md5_block_loop##offset ; \ -} ;; \ -{ .mib ; \ - nop 0x0 ; \ - nop 0x0 ; \ - br.cond.sptk.many .md5_exit ; \ -} ;; - - .align 32 -.md5_unaligned: -// -// Because variable shifts are expensive, we special case each of -// the four alignements. In practice, this won't hurt too much -// since only one working set of code will be loaded. -// -{ .mib - ld4 DTmp = [DPtr_], 4 - cmp.eq pOff, p0 = 1, InAlign -(pOff) br.cond.dpnt.many .md5_process1 -} ;; -{ .mib - cmp.eq pOff, p0 = 2, InAlign - nop 0x0 -(pOff) br.cond.dpnt.many .md5_process2 -} ;; - MD5UNALIGNED(3) - MD5UNALIGNED(1) - MD5UNALIGNED(2) - - .endp md5_block_asm_data_order - - -// MD5 Perform the F function and load -// -// Passed the first 4 words (M0 - M3) and initial (A, B, C, D) values, -// computes the FF() round of functions, then branches to the common -// digest code to finish up with GG(), HH, and II(). -// -// INPUT -// -// rp Return Address - -// -// CODE -// -// v0 PFS bit bucket PFS -// v1 Loop Trip Count LTrip -// pt0 Load next word pMore - -/* For F round: */ -#define LTrip r9 -#define PFS r8 -#define pMore p6 - -/* For GHI rounds: */ -#define T r9 -#define U r10 -#define V r11 - -#define COMPUTE(a, b, s, M, R) \ -{ \ - .mii ; \ - ld4 TRound = [TPtr], 4 ; \ - dep.z Y = Z, 32, 32 ;; \ - shrp Z = Z, Y, 64 - s ; \ -} ;; \ -{ \ - .mmi ; \ - add a = Z, b ; \ - mov R = M ; \ - nop 0x0 ; \ -} ;; - -#define LOOP(a, b, s, M, R, label) \ -{ .mii ; \ - ld4 TRound = [TPtr], 4 ; \ - dep.z Y = Z, 32, 32 ;; \ - shrp Z = Z, Y, 64 - s ; \ -} ;; \ -{ .mib ; \ - add a = Z, b ; \ - mov R = M ; \ - br.ctop.sptk.many label ; \ -} ;; - -// G(B, C, D) = (B & D) | (C & ~D) - -#define G(a, b, c, d, M) \ -{ .mmi ; \ - add Z = M, TRound ; \ - and Y = b, d ; \ - andcm X = c, d ; \ -} ;; \ -{ .mii ; \ - add Z = Z, a ; \ - or Y = Y, X ;; \ - add Z = Z, Y ; \ -} ;; - -// H(B, C, D) = B ^ C ^ D - -#define H(a, b, c, d, M) \ -{ .mmi ; \ - add Z = M, TRound ; \ - xor Y = b, c ; \ - nop 0x0 ; \ -} ;; \ -{ .mii ; \ - add Z = Z, a ; \ - xor Y = Y, d ;; \ - add Z = Z, Y ; \ -} ;; - -// I(B, C, D) = C ^ (B | ~D) -// -// However, since we have an andcm operator, we use the fact that -// -// Y ^ Z == ~Y ^ ~Z -// -// to rewrite the expression as -// -// I(B, C, D) = ~C ^ (~B & D) - -#define I(a, b, c, d, M) \ -{ .mmi ; \ - add Z = M, TRound ; \ - andcm Y = d, b ; \ - andcm X = -1, c ; \ -} ;; \ -{ .mii ; \ - add Z = Z, a ; \ - xor Y = Y, X ;; \ - add Z = Z, Y ; \ -} ;; - -#define GG4(label) \ - G(A, B, C, D, M0) \ - COMPUTE(A, B, 5, M0, RotateM0) \ - G(D, A, B, C, M1) \ - COMPUTE(D, A, 9, M1, RotateM1) \ - G(C, D, A, B, M2) \ - COMPUTE(C, D, 14, M2, RotateM2) \ - G(B, C, D, A, M3) \ - LOOP(B, C, 20, M3, RotateM3, label) - -#define HH4(label) \ - H(A, B, C, D, M0) \ - COMPUTE(A, B, 4, M0, RotateM0) \ - H(D, A, B, C, M1) \ - COMPUTE(D, A, 11, M1, RotateM1) \ - H(C, D, A, B, M2) \ - COMPUTE(C, D, 16, M2, RotateM2) \ - H(B, C, D, A, M3) \ - LOOP(B, C, 23, M3, RotateM3, label) - -#define II4(label) \ - I(A, B, C, D, M0) \ - COMPUTE(A, B, 6, M0, RotateM0) \ - I(D, A, B, C, M1) \ - COMPUTE(D, A, 10, M1, RotateM1) \ - I(C, D, A, B, M2) \ - COMPUTE(C, D, 15, M2, RotateM2) \ - I(B, C, D, A, M3) \ - LOOP(B, C, 21, M3, RotateM3, label) - -#define FFLOAD(a, b, c, d, M, N, s) \ -{ .mii ; \ -(pMore) ld4 N = [DPtr], 4 ; \ - add Z = M, TRound ; \ - and Y = c, b ; \ -} \ -{ .mmi ; \ - andcm X = d, b ;; \ - add Z = Z, a ; \ - or Y = Y, X ; \ -} ;; \ -{ .mii ; \ - ld4 TRound = [TPtr], 4 ; \ - add Z = Z, Y ;; \ - dep.z Y = Z, 32, 32 ; \ -} ;; \ -{ .mii ; \ - nop 0x0 ; \ - shrp Z = Z, Y, 64 - s ;; \ - add a = Z, b ; \ -} ;; - -#define FFLOOP(a, b, c, d, M, N, s, dest) \ -{ .mii ; \ -(pMore) ld4 N = [DPtr], 4 ; \ - add Z = M, TRound ; \ - and Y = c, b ; \ -} \ -{ .mmi ; \ - andcm X = d, b ;; \ - add Z = Z, a ; \ - or Y = Y, X ; \ -} ;; \ -{ .mii ; \ - ld4 TRound = [TPtr], 4 ; \ - add Z = Z, Y ;; \ - dep.z Y = Z, 32, 32 ; \ -} ;; \ -{ .mii ; \ - nop 0x0 ; \ - shrp Z = Z, Y, 64 - s ;; \ - add a = Z, b ; \ -} \ -{ .mib ; \ - cmp.ne pMore, p0 = 0, LTrip ; \ - add LTrip = -1, LTrip ; \ - br.ctop.dptk.many dest ; \ -} ;; - - .type md5_digest_block0, @function - .align 32 - - .proc md5_digest_block0 - .prologue -md5_digest_block0: - .altrp QUICK_RTN - .body -{ .mmi - alloc PFS = ar.pfs, _NINPUTS, _NLOCALS, _NOUTPUT, _NROTATE - mov LTrip = 2 - mov ar.lc = 3 -} ;; -{ .mii - cmp.eq pMore, p0 = r0, r0 - mov ar.ec = 0 - nop 0x0 -} ;; - -.md5_FF_round0: - FFLOAD(A, B, C, D, M12, RotateM0, 7) - FFLOAD(D, A, B, C, M13, RotateM1, 12) - FFLOAD(C, D, A, B, M14, RotateM2, 17) - FFLOOP(B, C, D, A, M15, RotateM3, 22, .md5_FF_round0) - // - // !!! Fall through to md5_digest_GHI - // - .endp md5_digest_block0 - - .type md5_digest_GHI, @function - .align 32 - - .proc md5_digest_GHI - .prologue - .regstk _NINPUTS, _NLOCALS, _NOUTPUT, _NROTATE -md5_digest_GHI: - .altrp QUICK_RTN - .body -// -// The following sequence shuffles the block counstants round for the -// next round: -// -// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -// 1 6 11 0 5 10 14 4 9 14 3 8 13 2 7 12 -// -{ .mmi - mov Z = M0 - mov Y = M15 - mov ar.lc = 3 -} -{ .mmi - mov X = M2 - mov W = M9 - mov V = M4 -} ;; - -{ .mmi - mov M0 = M1 - mov M15 = M12 - mov ar.ec = 1 -} -{ .mmi - mov M2 = M11 - mov M9 = M14 - mov M4 = M5 -} ;; - -{ .mmi - mov M1 = M6 - mov M12 = M13 - mov U = M3 -} -{ .mmi - mov M11 = M8 - mov M14 = M7 - mov M5 = M10 -} ;; - -{ .mmi - mov M6 = Y - mov M13 = X - mov M3 = Z -} -{ .mmi - mov M8 = W - mov M7 = V - mov M10 = U -} ;; - -.md5_GG_round: - GG4(.md5_GG_round) - -// The following sequence shuffles the block constants round for the -// next round: -// -// 1 6 11 0 5 10 14 4 9 14 3 8 13 2 7 12 -// 5 8 11 14 1 4 7 10 13 0 3 6 9 12 15 2 - -{ .mmi - mov Z = M0 - mov Y = M1 - mov ar.lc = 3 -} -{ .mmi - mov X = M3 - mov W = M5 - mov V = M6 -} ;; - -{ .mmi - mov M0 = M4 - mov M1 = M11 - mov ar.ec = 1 -} -{ .mmi - mov M3 = M9 - mov U = M8 - mov T = M13 -} ;; - -{ .mmi - mov M4 = Z - mov M11 = Y - mov M5 = M7 -} -{ .mmi - mov M6 = M14 - mov M8 = M12 - mov M13 = M15 -} ;; - -{ .mmi - mov M7 = W - mov M14 = V - nop 0x0 -} -{ .mmi - mov M9 = X - mov M12 = U - mov M15 = T -} ;; - -.md5_HH_round: - HH4(.md5_HH_round) - -// The following sequence shuffles the block constants round for the -// next round: -// -// 5 8 11 14 1 4 7 10 13 0 3 6 9 12 15 2 -// 0 7 14 5 12 3 10 1 8 15 6 13 4 11 2 9 - -{ .mmi - mov Z = M0 - mov Y = M15 - mov ar.lc = 3 -} -{ .mmi - mov X = M10 - mov W = M1 - mov V = M4 -} ;; - -{ .mmi - mov M0 = M9 - mov M15 = M12 - mov ar.ec = 1 -} -{ .mmi - mov M10 = M11 - mov M1 = M6 - mov M4 = M13 -} ;; - -{ .mmi - mov M9 = M14 - mov M12 = M5 - mov U = M3 -} -{ .mmi - mov M11 = M8 - mov M6 = M7 - mov M13 = M2 -} ;; - -{ .mmi - mov M14 = Y - mov M5 = X - mov M3 = Z -} -{ .mmi - mov M8 = W - mov M7 = V - mov M2 = U -} ;; - -.md5_II_round: - II4(.md5_II_round) - -{ .mib - nop 0x0 - nop 0x0 - br.ret.sptk.many QUICK_RTN -} ;; - - .endp md5_digest_GHI - -#define FFLOADU(a, b, c, d, M, P, N, s, offset) \ -{ .mii ; \ -(pMore) ld4 N = [DPtr], 4 ; \ - add Z = M, TRound ; \ - and Y = c, b ; \ -} \ -{ .mmi ; \ - andcm X = d, b ;; \ - add Z = Z, a ; \ - or Y = Y, X ; \ -} ;; \ -{ .mii ; \ - ld4 TRound = [TPtr], 4 ; \ - GETLW(W, P, offset) ; \ - add Z = Z, Y ; \ -} ;; \ -{ .mii ; \ - or W = W, DTmp ; \ - dep.z Y = Z, 32, 32 ;; \ - shrp Z = Z, Y, 64 - s ; \ -} ;; \ -{ .mii ; \ - add a = Z, b ; \ - GETRW(DTmp, P, offset) ; \ - mov P = W ; \ -} ;; - -#define FFLOOPU(a, b, c, d, M, P, N, s, offset) \ -{ .mii ; \ -(pMore) ld4 N = [DPtr], 4 ; \ - add Z = M, TRound ; \ - and Y = c, b ; \ -} \ -{ .mmi ; \ - andcm X = d, b ;; \ - add Z = Z, a ; \ - or Y = Y, X ; \ -} ;; \ -{ .mii ; \ - ld4 TRound = [TPtr], 4 ; \ -(pMore) GETLW(W, P, offset) ; \ - add Z = Z, Y ; \ -} ;; \ -{ .mii ; \ -(pMore) or W = W, DTmp ; \ - dep.z Y = Z, 32, 32 ;; \ - shrp Z = Z, Y, 64 - s ; \ -} ;; \ -{ .mii ; \ - add a = Z, b ; \ -(pMore) GETRW(DTmp, P, offset) ; \ -(pMore) mov P = W ; \ -} \ -{ .mib ; \ - cmp.ne pMore, p0 = 0, LTrip ; \ - add LTrip = -1, LTrip ; \ - br.ctop.sptk.many .md5_FF_round##offset ; \ -} ;; - -#define MD5FBLOCK(offset) \ - .type md5_digest_block##offset, @function ; \ - \ - .align 32 ; \ - .proc md5_digest_block##offset ; \ - .prologue ; \ - .altrp QUICK_RTN ; \ - .body ; \ -md5_digest_block##offset: \ -{ .mmi ; \ - alloc PFS = ar.pfs, _NINPUTS, _NLOCALS, _NOUTPUT, _NROTATE ; \ - mov LTrip = 2 ; \ - mov ar.lc = 3 ; \ -} ;; \ -{ .mii ; \ - cmp.eq pMore, p0 = r0, r0 ; \ - mov ar.ec = 0 ; \ - nop 0x0 ; \ -} ;; \ - \ - .pred.rel "mutex", pLoad, pSkip ; \ -.md5_FF_round##offset: \ - FFLOADU(A, B, C, D, M12, M13, RotateM0, 7, offset) \ - FFLOADU(D, A, B, C, M13, M14, RotateM1, 12, offset) \ - FFLOADU(C, D, A, B, M14, M15, RotateM2, 17, offset) \ - FFLOOPU(B, C, D, A, M15, RotateM0, RotateM3, 22, offset) \ - \ -{ .mib ; \ - nop 0x0 ; \ - nop 0x0 ; \ - br.cond.sptk.many md5_digest_GHI ; \ -} ;; \ - .endp md5_digest_block##offset - -MD5FBLOCK(1) -MD5FBLOCK(2) -MD5FBLOCK(3) - - .align 64 - .type md5_constants, @object -md5_constants: -.md5_tbl_data_order: // To ensure little-endian data - // order, code as bytes. - data1 0x78, 0xa4, 0x6a, 0xd7 // 0 - data1 0x56, 0xb7, 0xc7, 0xe8 // 1 - data1 0xdb, 0x70, 0x20, 0x24 // 2 - data1 0xee, 0xce, 0xbd, 0xc1 // 3 - data1 0xaf, 0x0f, 0x7c, 0xf5 // 4 - data1 0x2a, 0xc6, 0x87, 0x47 // 5 - data1 0x13, 0x46, 0x30, 0xa8 // 6 - data1 0x01, 0x95, 0x46, 0xfd // 7 - data1 0xd8, 0x98, 0x80, 0x69 // 8 - data1 0xaf, 0xf7, 0x44, 0x8b // 9 - data1 0xb1, 0x5b, 0xff, 0xff // 10 - data1 0xbe, 0xd7, 0x5c, 0x89 // 11 - data1 0x22, 0x11, 0x90, 0x6b // 12 - data1 0x93, 0x71, 0x98, 0xfd // 13 - data1 0x8e, 0x43, 0x79, 0xa6 // 14 - data1 0x21, 0x08, 0xb4, 0x49 // 15 - data1 0x62, 0x25, 0x1e, 0xf6 // 16 - data1 0x40, 0xb3, 0x40, 0xc0 // 17 - data1 0x51, 0x5a, 0x5e, 0x26 // 18 - data1 0xaa, 0xc7, 0xb6, 0xe9 // 19 - data1 0x5d, 0x10, 0x2f, 0xd6 // 20 - data1 0x53, 0x14, 0x44, 0x02 // 21 - data1 0x81, 0xe6, 0xa1, 0xd8 // 22 - data1 0xc8, 0xfb, 0xd3, 0xe7 // 23 - data1 0xe6, 0xcd, 0xe1, 0x21 // 24 - data1 0xd6, 0x07, 0x37, 0xc3 // 25 - data1 0x87, 0x0d, 0xd5, 0xf4 // 26 - data1 0xed, 0x14, 0x5a, 0x45 // 27 - data1 0x05, 0xe9, 0xe3, 0xa9 // 28 - data1 0xf8, 0xa3, 0xef, 0xfc // 29 - data1 0xd9, 0x02, 0x6f, 0x67 // 30 - data1 0x8a, 0x4c, 0x2a, 0x8d // 31 - data1 0x42, 0x39, 0xfa, 0xff // 32 - data1 0x81, 0xf6, 0x71, 0x87 // 33 - data1 0x22, 0x61, 0x9d, 0x6d // 34 - data1 0x0c, 0x38, 0xe5, 0xfd // 35 - data1 0x44, 0xea, 0xbe, 0xa4 // 36 - data1 0xa9, 0xcf, 0xde, 0x4b // 37 - data1 0x60, 0x4b, 0xbb, 0xf6 // 38 - data1 0x70, 0xbc, 0xbf, 0xbe // 39 - data1 0xc6, 0x7e, 0x9b, 0x28 // 40 - data1 0xfa, 0x27, 0xa1, 0xea // 41 - data1 0x85, 0x30, 0xef, 0xd4 // 42 - data1 0x05, 0x1d, 0x88, 0x04 // 43 - data1 0x39, 0xd0, 0xd4, 0xd9 // 44 - data1 0xe5, 0x99, 0xdb, 0xe6 // 45 - data1 0xf8, 0x7c, 0xa2, 0x1f // 46 - data1 0x65, 0x56, 0xac, 0xc4 // 47 - data1 0x44, 0x22, 0x29, 0xf4 // 48 - data1 0x97, 0xff, 0x2a, 0x43 // 49 - data1 0xa7, 0x23, 0x94, 0xab // 50 - data1 0x39, 0xa0, 0x93, 0xfc // 51 - data1 0xc3, 0x59, 0x5b, 0x65 // 52 - data1 0x92, 0xcc, 0x0c, 0x8f // 53 - data1 0x7d, 0xf4, 0xef, 0xff // 54 - data1 0xd1, 0x5d, 0x84, 0x85 // 55 - data1 0x4f, 0x7e, 0xa8, 0x6f // 56 - data1 0xe0, 0xe6, 0x2c, 0xfe // 57 - data1 0x14, 0x43, 0x01, 0xa3 // 58 - data1 0xa1, 0x11, 0x08, 0x4e // 59 - data1 0x82, 0x7e, 0x53, 0xf7 // 60 - data1 0x35, 0xf2, 0x3a, 0xbd // 61 - data1 0xbb, 0xd2, 0xd7, 0x2a // 62 - data1 0x91, 0xd3, 0x86, 0xeb // 63 -.size md5_constants#,64*4 diff --git a/crypto/md5/asm/md5-sparcv9.pl b/crypto/md5/asm/md5-sparcv9.pl index 09e6d713..6a62c625 100644 --- a/crypto/md5/asm/md5-sparcv9.pl +++ b/crypto/md5/asm/md5-sparcv9.pl @@ -13,7 +13,7 @@ # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. # -# Hardware SPARC T4 support by David S. Miller . +# Hardware SPARC T4 support by David S. Miller. # ==================================================================== # MD5 for SPARCv9, 6.9 cycles per byte on UltraSPARC, >40% faster than @@ -242,7 +242,7 @@ md5_block_asm_data_order: ldd [%o1 + 0x20], %f16 ldd [%o1 + 0x28], %f18 ldd [%o1 + 0x30], %f20 - subcc %o2, 1, %o2 ! done yet? + subcc %o2, 1, %o2 ! done yet? ldd [%o1 + 0x38], %f22 add %o1, 0x40, %o1 prefetch [%o1 + 63], 20 diff --git a/crypto/md5/asm/md5-x86_64.pl b/crypto/md5/asm/md5-x86_64.pl index 3f656dc0..386d8048 100755 --- a/crypto/md5/asm/md5-x86_64.pl +++ b/crypto/md5/asm/md5-x86_64.pl @@ -140,11 +140,17 @@ $code .= <D = D mov (%rsp),%r15 +.cfi_restore %r15 mov 8(%rsp),%r14 +.cfi_restore %r14 mov 16(%rsp),%r12 +.cfi_restore %r12 mov 24(%rsp),%rbx +.cfi_restore %rbx mov 32(%rsp),%rbp +.cfi_restore %rbp add \$40,%rsp +.cfi_adjust_cfa_offset -40 .Lepilogue: ret +.cfi_endproc .size md5_block_asm_data_order,.-md5_block_asm_data_order EOF diff --git a/crypto/md5/build.info b/crypto/md5/build.info index 38323a3f..e641fecd 100644 --- a/crypto/md5/build.info +++ b/crypto/md5/build.info @@ -2,21 +2,10 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ md5_dgst.c md5_one.c {- $target{md5_asm_src} -} -GENERATE[md5-586.s]=asm/md5-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) +GENERATE[md5-586.s]=asm/md5-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) GENERATE[md5-x86_64.s]=asm/md5-x86_64.pl $(PERLASM_SCHEME) GENERATE[md5-sparcv9.S]=asm/md5-sparcv9.pl $(PERLASM_SCHEME) INCLUDE[md5-sparcv9.o]=.. - -BEGINRAW[makefile(windows)] -{- $builddir -}\md5-ia64.asm: {- $sourcedir -}\asm\md5-ia64.S - $(CC) $(CFLAGS) -EP {- $sourcedir -}\asm\md5-ia64.S > $@.i && move /Y $@.i $@ -ENDRAW[makefile(windows)] - -BEGINRAW[Makefile] -{- $builddir -}/md5-ia64.s: {- $sourcedir -}/asm/md5-ia64.S - $(CC) $(CFLAGS) -E {- $sourcedir -}/asm/md5-ia64.S | \ - $(PERL) -ne 's/;\s+/;\n/g; print;' > $@ - -ENDRAW[Makefile] diff --git a/crypto/md5/md5_locl.h b/crypto/md5/md5_locl.h index 9c7aade8..4eb7e50e 100644 --- a/crypto/md5/md5_locl.h +++ b/crypto/md5/md5_locl.h @@ -50,8 +50,8 @@ void md5_block_data_order(MD5_CTX *c, const void *p, size_t num); */ /* - * As pointed out by Wei Dai , the above can be simplified - * to the code below. Wei attributes these optimizations to Peter Gutmann's + * As pointed out by Wei Dai, the above can be simplified to the code + * below. Wei attributes these optimizations to Peter Gutmann's * SHS code, and he attributes it to Rich Schroeppel. */ #define F(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) diff --git a/crypto/md5/md5_one.c b/crypto/md5/md5_one.c index becd87e4..c3bf2f88 100644 --- a/crypto/md5/md5_one.c +++ b/crypto/md5/md5_one.c @@ -43,5 +43,5 @@ unsigned char *MD5(const unsigned char *d, size_t n, unsigned char *md) #endif MD5_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* security consideration */ - return (md); + return md; } diff --git a/crypto/mdc2/mdc2_one.c b/crypto/mdc2/mdc2_one.c index 472a5ec2..58e1e0fd 100644 --- a/crypto/mdc2/mdc2_one.c +++ b/crypto/mdc2/mdc2_one.c @@ -23,5 +23,5 @@ unsigned char *MDC2(const unsigned char *d, size_t n, unsigned char *md) MDC2_Update(&c, d, n); MDC2_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* security consideration */ - return (md); + return md; } diff --git a/crypto/mdc2/mdc2dgst.c b/crypto/mdc2/mdc2dgst.c index 37d99f48..14233b9a 100644 --- a/crypto/mdc2/mdc2dgst.c +++ b/crypto/mdc2/mdc2dgst.c @@ -124,24 +124,3 @@ int MDC2_Final(unsigned char *md, MDC2_CTX *c) memcpy(&(md[MDC2_BLOCK]), (char *)c->hh, MDC2_BLOCK); return 1; } - -#undef TEST - -#ifdef TEST -main() -{ - unsigned char md[MDC2_DIGEST_LENGTH]; - int i; - MDC2_CTX c; - static char *text = "Now is the time for all "; - - MDC2_Init(&c); - MDC2_Update(&c, text, strlen(text)); - MDC2_Final(&(md[0]), &c); - - for (i = 0; i < MDC2_DIGEST_LENGTH; i++) - printf("%02X", md[i]); - printf("\n"); -} - -#endif diff --git a/crypto/mem.c b/crypto/mem.c index 72b04c82..b3f7a1fa 100644 --- a/crypto/mem.c +++ b/crypto/mem.c @@ -7,11 +7,16 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" +#include "internal/cryptlib.h" +#include "internal/cryptlib_int.h" #include #include #include #include -#include "internal/cryptlib.h" +#ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE +# include +#endif /* * the following pointers may be changed as long as 'allow_customize' is set @@ -26,9 +31,30 @@ static void (*free_impl)(void *, const char *, int) = CRYPTO_free; #ifndef OPENSSL_NO_CRYPTO_MDEBUG +static int malloc_count; +static int realloc_count; +static int free_count; +static int dummy; + +# define INCREMENT(x) CRYPTO_atomic_add(&x, 1, &dummy, memdbg_lock) +# define GET(ret, val) CRYPTO_atomic_read(&val, ret, memdbg_lock) + +static char *md_failstring; +static long md_count; +static int md_fail_percent = 0; +static int md_tracefd = -1; static int call_malloc_debug = 1; + +static void parseit(void); +static int shouldfail(void); + +# define FAILTEST() if (shouldfail()) return NULL + #else static int call_malloc_debug = 0; + +# define INCREMENT(x) /* empty */ +# define FAILTEST() /* empty */ #endif int CRYPTO_set_mem_functions( @@ -68,24 +94,114 @@ void CRYPTO_get_mem_functions( *f = free_impl; } +#ifndef OPENSSL_NO_CRYPTO_MDEBUG +void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount) +{ + if (mcount != NULL) + GET(mcount, malloc_count); + if (rcount != NULL) + GET(rcount, realloc_count); + if (fcount != NULL) + GET(fcount, free_count); +} + +/* + * Parse a "malloc failure spec" string. This likes like a set of fields + * separated by semicolons. Each field has a count and an optional failure + * percentage. For example: + * 100@0;100@25;0@0 + * or 100;100@25;0 + * This means 100 mallocs succeed, then next 100 fail 25% of the time, and + * all remaining (count is zero) succeed. + */ +static void parseit(void) +{ + char *semi = strchr(md_failstring, ';'); + char *atsign; + + if (semi != NULL) + *semi++ = '\0'; + + /* Get the count (atol will stop at the @ if there), and percentage */ + md_count = atol(md_failstring); + atsign = strchr(md_failstring, '@'); + md_fail_percent = atsign == NULL ? 0 : atoi(atsign + 1); + + if (semi != NULL) + md_failstring = semi; +} + +/* + * Windows doesn't have random(), but it has rand() + * Some rand() implementations aren't good, but we're not + * dealing with secure randomness here. + */ +# ifdef _WIN32 +# define random() rand() +# endif +/* + * See if the current malloc should fail. + */ +static int shouldfail(void) +{ + int roll = (int)(random() % 100); + int shoulditfail = roll < md_fail_percent; +# ifndef _WIN32 +/* suppressed on Windows as POSIX-like file descriptors are non-inheritable */ + int len; + char buff[80]; + + if (md_tracefd > 0) { + BIO_snprintf(buff, sizeof(buff), + "%c C%ld %%%d R%d\n", + shoulditfail ? '-' : '+', md_count, md_fail_percent, roll); + len = strlen(buff); + if (write(md_tracefd, buff, len) != len) + perror("shouldfail write failed"); +# ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE + if (shoulditfail) { + void *addrs[30]; + int num = backtrace(addrs, OSSL_NELEM(addrs)); + + backtrace_symbols_fd(addrs, num, md_tracefd); + } +# endif + } +# endif + + if (md_count) { + /* If we used up this one, go to the next. */ + if (--md_count == 0) + parseit(); + } + + return shoulditfail; +} + +void ossl_malloc_setup_failures(void) +{ + const char *cp = getenv("OPENSSL_MALLOC_FAILURES"); + + if (cp != NULL && (md_failstring = strdup(cp)) != NULL) + parseit(); + if ((cp = getenv("OPENSSL_MALLOC_FD")) != NULL) + md_tracefd = atoi(cp); +} +#endif + void *CRYPTO_malloc(size_t num, const char *file, int line) { void *ret = NULL; + INCREMENT(malloc_count); if (malloc_impl != NULL && malloc_impl != CRYPTO_malloc) return malloc_impl(num, file, line); if (num == 0) return NULL; - if (allow_customize) { - /* - * Disallow customization after the first allocation. We only set this - * if necessary to avoid a store to the same cache line on every - * allocation. - */ - allow_customize = 0; - } + FAILTEST(); + allow_customize = 0; #ifndef OPENSSL_NO_CRYPTO_MDEBUG if (call_malloc_debug) { CRYPTO_mem_debug_malloc(NULL, num, 0, file, line); @@ -95,7 +211,7 @@ void *CRYPTO_malloc(size_t num, const char *file, int line) ret = malloc(num); } #else - osslargused(file); osslargused(line); + (void)(file); (void)(line); ret = malloc(num); #endif @@ -106,6 +222,7 @@ void *CRYPTO_zalloc(size_t num, const char *file, int line) { void *ret = CRYPTO_malloc(num, file, line); + FAILTEST(); if (ret != NULL) memset(ret, 0, num); return ret; @@ -113,9 +230,11 @@ void *CRYPTO_zalloc(size_t num, const char *file, int line) void *CRYPTO_realloc(void *str, size_t num, const char *file, int line) { + INCREMENT(realloc_count); if (realloc_impl != NULL && realloc_impl != &CRYPTO_realloc) return realloc_impl(str, num, file, line); + FAILTEST(); if (str == NULL) return CRYPTO_malloc(num, file, line); @@ -124,6 +243,7 @@ void *CRYPTO_realloc(void *str, size_t num, const char *file, int line) return NULL; } + allow_customize = 0; #ifndef OPENSSL_NO_CRYPTO_MDEBUG if (call_malloc_debug) { void *ret; @@ -133,7 +253,7 @@ void *CRYPTO_realloc(void *str, size_t num, const char *file, int line) return ret; } #else - osslargused(file); osslargused(line); + (void)(file); (void)(line); #endif return realloc(str, num); @@ -168,6 +288,7 @@ void *CRYPTO_clear_realloc(void *str, size_t old_len, size_t num, void CRYPTO_free(void *str, const char *file, int line) { + INCREMENT(free_count); if (free_impl != NULL && free_impl != &CRYPTO_free) { free_impl(str, file, line); return; diff --git a/crypto/mem_dbg.c b/crypto/mem_dbg.c index c884078e..0489e97a 100644 --- a/crypto/mem_dbg.c +++ b/crypto/mem_dbg.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -56,8 +56,8 @@ struct app_mem_info_st { }; static CRYPTO_ONCE memdbg_init = CRYPTO_ONCE_STATIC_INIT; -static CRYPTO_RWLOCK *malloc_lock = NULL; -static CRYPTO_RWLOCK *long_malloc_lock = NULL; +CRYPTO_RWLOCK *memdbg_lock; +static CRYPTO_RWLOCK *long_memdbg_lock; static CRYPTO_THREAD_LOCAL appinfokey; /* memory-block description */ @@ -76,28 +76,31 @@ struct mem_st { #endif }; -static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as - * key); access requires MALLOC2 lock */ +/* + * hash-table of memory requests (address as * key); access requires + * long_memdbg_lock lock + */ +static LHASH_OF(MEM) *mh = NULL; /* num_disable > 0 iff mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */ static unsigned int num_disable = 0; /* - * Valid iff num_disable > 0. long_malloc_lock is locked exactly in this + * Valid iff num_disable > 0. long_memdbg_lock is locked exactly in this * case (by the thread named in disabling_thread). */ static CRYPTO_THREAD_ID disabling_threadid; DEFINE_RUN_ONCE_STATIC(do_memdbg_init) { - malloc_lock = CRYPTO_THREAD_lock_new(); - long_malloc_lock = CRYPTO_THREAD_lock_new(); - if (malloc_lock == NULL || long_malloc_lock == NULL + memdbg_lock = CRYPTO_THREAD_lock_new(); + long_memdbg_lock = CRYPTO_THREAD_lock_new(); + if (memdbg_lock == NULL || long_memdbg_lock == NULL || !CRYPTO_THREAD_init_local(&appinfokey, NULL)) { - CRYPTO_THREAD_lock_free(malloc_lock); - malloc_lock = NULL; - CRYPTO_THREAD_lock_free(long_malloc_lock); - long_malloc_lock = NULL; + CRYPTO_THREAD_lock_free(memdbg_lock); + memdbg_lock = NULL; + CRYPTO_THREAD_lock_free(long_memdbg_lock); + long_memdbg_lock = NULL; return 0; } return 1; @@ -105,7 +108,7 @@ DEFINE_RUN_ONCE_STATIC(do_memdbg_init) static void app_info_free(APP_INFO *inf) { - if (!inf) + if (inf == NULL) return; if (--(inf->references) <= 0) { app_info_free(inf->next); @@ -124,7 +127,7 @@ int CRYPTO_mem_ctrl(int mode) if (!RUN_ONCE(&memdbg_init, do_memdbg_init)) return -1; - CRYPTO_THREAD_write_lock(malloc_lock); + CRYPTO_THREAD_write_lock(memdbg_lock); switch (mode) { default: break; @@ -143,26 +146,26 @@ int CRYPTO_mem_ctrl(int mode) case CRYPTO_MEM_CHECK_DISABLE: if (mh_mode & CRYPTO_MEM_CHECK_ON) { CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id(); - /* see if we don't have long_malloc_lock already */ + /* see if we don't have long_memdbg_lock already */ if (!num_disable || !CRYPTO_THREAD_compare_id(disabling_threadid, cur)) { /* - * Long-time lock long_malloc_lock must not be claimed - * while we're holding malloc_lock, or we'll deadlock - * if somebody else holds long_malloc_lock (and cannot + * Long-time lock long_memdbg_lock must not be claimed + * while we're holding memdbg_lock, or we'll deadlock + * if somebody else holds long_memdbg_lock (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_THREAD_unlock(malloc_lock); + CRYPTO_THREAD_unlock(memdbg_lock); /* - * Note that after we have waited for long_malloc_lock and - * malloc_lock, we'll still be in the right "case" and + * Note that after we have waited for long_memdbg_lock and + * memdbg_lock, 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_THREAD_write_lock(long_malloc_lock); - CRYPTO_THREAD_write_lock(malloc_lock); + CRYPTO_THREAD_write_lock(long_memdbg_lock); + CRYPTO_THREAD_write_lock(memdbg_lock); mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE; disabling_threadid = cur; } @@ -176,14 +179,14 @@ int CRYPTO_mem_ctrl(int mode) num_disable--; if (num_disable == 0) { mh_mode |= CRYPTO_MEM_CHECK_ENABLE; - CRYPTO_THREAD_unlock(long_malloc_lock); + CRYPTO_THREAD_unlock(long_memdbg_lock); } } } break; } - CRYPTO_THREAD_unlock(malloc_lock); - return (ret); + CRYPTO_THREAD_unlock(memdbg_lock); + return ret; #endif } @@ -199,14 +202,14 @@ static int mem_check_on(void) return 0; cur = CRYPTO_THREAD_get_current_id(); - CRYPTO_THREAD_read_lock(malloc_lock); + CRYPTO_THREAD_read_lock(memdbg_lock); ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE) || !CRYPTO_THREAD_compare_id(disabling_threadid, cur); - CRYPTO_THREAD_unlock(malloc_lock); + CRYPTO_THREAD_unlock(memdbg_lock); } - return (ret); + return ret; } static int mem_cmp(const MEM *a, const MEM *b) @@ -231,7 +234,7 @@ static unsigned long mem_hash(const MEM *a) ret = (size_t)a->addr; ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251; - return (ret); + return ret; } /* returns 1 if there was an info to pop, 0 if the stack was empty. */ @@ -292,7 +295,7 @@ int CRYPTO_mem_debug_push(const char *info, const char *file, int line) CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE); } - return (ret); + return ret; } int CRYPTO_mem_debug_pop(void) @@ -304,7 +307,7 @@ int CRYPTO_mem_debug_pop(void) ret = pop_info(); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE); } - return (ret); + return ret; } static unsigned long break_order_num = 0; @@ -443,7 +446,8 @@ void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num, } typedef struct mem_leak_st { - BIO *bio; + int (*print_cb) (const char *str, size_t len, void *u); + void *print_cb_arg; int chunks; long bytes; } MEM_LEAK; @@ -452,8 +456,9 @@ static void print_leak(const MEM *m, MEM_LEAK *l) { char buf[1024]; char *bufp = buf; + size_t len = sizeof(buf), ami_cnt; APP_INFO *amip; - int ami_cnt; + int n; struct tm *lcl = NULL; /* * Convert between CRYPTO_THREAD_ID (which could be anything at all) and @@ -466,27 +471,38 @@ static void print_leak(const MEM *m, MEM_LEAK *l) } tid; CRYPTO_THREAD_ID ti; -#define BUF_REMAIN (sizeof(buf) - (size_t)(bufp - buf)) - lcl = localtime(&m->time); - BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ", - lcl->tm_hour, lcl->tm_min, lcl->tm_sec); - bufp += strlen(bufp); + n = BIO_snprintf(bufp, len, "[%02d:%02d:%02d] ", + lcl->tm_hour, lcl->tm_min, lcl->tm_sec); + if (n <= 0) { + bufp[0] = '\0'; + return; + } + bufp += n; + len -= n; - BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ", - m->order, m->file, m->line); - bufp += strlen(bufp); + n = BIO_snprintf(bufp, len, "%5lu file=%s, line=%d, ", + m->order, m->file, m->line); + if (n <= 0) + return; + bufp += n; + len -= n; tid.ltid = 0; tid.tid = m->threadid; - BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ", tid.ltid); - bufp += strlen(bufp); + n = BIO_snprintf(bufp, len, "thread=%lu, ", tid.ltid); + if (n <= 0) + return; + bufp += n; + len -= n; - BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n", - m->num, m->addr); - bufp += strlen(bufp); + n = BIO_snprintf(bufp, len, "number=%d, address=%p\n", m->num, m->addr); + if (n <= 0) + return; + bufp += n; + len -= n; - BIO_puts(l->bio, buf); + l->print_cb(buf, (size_t)(bufp - buf), l->print_cb_arg); l->chunks++; l->bytes += m->num; @@ -502,25 +518,34 @@ static void print_leak(const MEM *m, MEM_LEAK *l) int info_len; ami_cnt++; + if (ami_cnt >= sizeof(buf) - 1) + break; memset(buf, '>', ami_cnt); + buf[ami_cnt] = '\0'; tid.ltid = 0; tid.tid = amip->threadid; - BIO_snprintf(buf + ami_cnt, sizeof(buf) - ami_cnt, - " thread=%lu, file=%s, line=%d, info=\"", - tid.ltid, amip->file, - amip->line); - buf_len = strlen(buf); + n = BIO_snprintf(buf + ami_cnt, sizeof(buf) - ami_cnt, + " thread=%lu, file=%s, line=%d, info=\"", + tid.ltid, amip->file, amip->line); + if (n <= 0) + break; + buf_len = ami_cnt + n; 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 { - OPENSSL_strlcpy(buf + buf_len, amip->info, sizeof(buf) - buf_len); - buf_len = strlen(buf); + n = BIO_snprintf(buf + buf_len, sizeof(buf) - buf_len, "%s", + amip->info); + if (n < 0) + break; + buf_len += n; } - BIO_snprintf(buf + buf_len, sizeof(buf) - buf_len, "\"\n"); + n = BIO_snprintf(buf + buf_len, sizeof(buf) - buf_len, "\"\n"); + if (n <= 0) + break; - BIO_puts(l->bio, buf); + l->print_cb(buf, buf_len + n, l->print_cb_arg); amip = amip->next; } @@ -541,16 +566,11 @@ static void print_leak(const MEM *m, MEM_LEAK *l) IMPLEMENT_LHASH_DOALL_ARG_CONST(MEM, MEM_LEAK); -int CRYPTO_mem_leaks(BIO *b) +int CRYPTO_mem_leaks_cb(int (*cb) (const char *str, size_t len, void *u), + void *u) { MEM_LEAK ml; - /* - * OPENSSL_cleanup() will free the ex_data locks so we can't have any - * ex_data hanging around - */ - bio_free_ex_data(b); - /* Ensure all resources are released */ OPENSSL_cleanup(); @@ -559,14 +579,19 @@ int CRYPTO_mem_leaks(BIO *b) CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE); - ml.bio = b; + ml.print_cb = cb; + ml.print_cb_arg = u; ml.bytes = 0; ml.chunks = 0; if (mh != NULL) lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml); if (ml.chunks != 0) { - BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks); + char buf[256]; + + BIO_snprintf(buf, sizeof(buf), "%ld bytes leaked in %d chunks\n", + ml.bytes, ml.chunks); + cb(buf, strlen(buf), u); } else { /* * Make sure that, if we found no leaks, memory-leak debugging itself @@ -576,7 +601,7 @@ int CRYPTO_mem_leaks(BIO *b) */ int old_mh_mode; - CRYPTO_THREAD_write_lock(malloc_lock); + CRYPTO_THREAD_write_lock(memdbg_lock); /* * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses @@ -589,20 +614,36 @@ int CRYPTO_mem_leaks(BIO *b) mh = NULL; mh_mode = old_mh_mode; - CRYPTO_THREAD_unlock(malloc_lock); + CRYPTO_THREAD_unlock(memdbg_lock); } CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF); /* Clean up locks etc */ CRYPTO_THREAD_cleanup_local(&appinfokey); - CRYPTO_THREAD_lock_free(malloc_lock); - CRYPTO_THREAD_lock_free(long_malloc_lock); - malloc_lock = NULL; - long_malloc_lock = NULL; + CRYPTO_THREAD_lock_free(memdbg_lock); + CRYPTO_THREAD_lock_free(long_memdbg_lock); + memdbg_lock = NULL; + long_memdbg_lock = NULL; return ml.chunks == 0 ? 1 : 0; } +static int print_bio(const char *str, size_t len, void *b) +{ + return BIO_write((BIO *)b, str, len); +} + +int CRYPTO_mem_leaks(BIO *b) +{ + /* + * OPENSSL_cleanup() will free the ex_data locks so we can't have any + * ex_data hanging around + */ + bio_free_ex_data(b); + + return CRYPTO_mem_leaks_cb(print_bio, b); +} + # ifndef OPENSSL_NO_STDIO int CRYPTO_mem_leaks_fp(FILE *fp) { @@ -620,7 +661,7 @@ int CRYPTO_mem_leaks_fp(FILE *fp) if (b == NULL) return -1; BIO_set_fp(b, fp, BIO_NOCLOSE); - ret = CRYPTO_mem_leaks(b); + ret = CRYPTO_mem_leaks_cb(print_bio, b); BIO_free(b); return ret; } diff --git a/crypto/mem_sec.c b/crypto/mem_sec.c index 25cdb47d..77bf165f 100644 --- a/crypto/mem_sec.c +++ b/crypto/mem_sec.c @@ -1,5 +1,6 @@ /* * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2004-2014, Akamai Technologies. 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 @@ -7,11 +8,6 @@ * https://www.openssl.org/source/license.html */ -/* - * Copyright 2004-2014, Akamai Technologies. All Rights Reserved. - * This file is distributed under the terms of the OpenSSL license. - */ - /* * This file is in two halves. The first half implements the public API * to be used by external consumers, and to be used by OpenSSL to store @@ -19,8 +15,8 @@ * For details on that implementation, see below (look for uppercase * "SECURE HEAP IMPLEMENTATION"). */ +#include "e_os.h" #include -#include #include @@ -35,6 +31,11 @@ # include # include # include +# if defined(OPENSSL_SYS_LINUX) +# include +# include +# include +# endif # include # include # include @@ -44,9 +45,6 @@ #ifndef PAGE_SIZE # define PAGE_SIZE 4096 #endif -#if !defined(MAP_ANON) && defined(MAP_ANONYMOUS) -# define MAP_ANON MAP_ANONYMOUS -#endif #ifdef IMPLEMENTED static size_t secure_mem_used; @@ -59,8 +57,8 @@ static CRYPTO_RWLOCK *sec_malloc_lock = NULL; * These are the functions that must be implemented by a secure heap (sh). */ static int sh_init(size_t size, int minsize); -static char *sh_malloc(size_t size); -static void sh_free(char *ptr); +static void *sh_malloc(size_t size); +static void sh_free(void *ptr); static void sh_done(void); static size_t sh_actual_size(char *ptr); static int sh_allocated(const char *ptr); @@ -472,8 +470,19 @@ static int sh_init(size_t size, int minsize) if (mprotect(sh.map_result + aligned, pgsize, PROT_NONE) < 0) ret = 2; +#if defined(OPENSSL_SYS_LINUX) && defined(MLOCK_ONFAULT) && defined(SYS_mlock2) + if (syscall(SYS_mlock2, sh.arena, sh.arena_size, MLOCK_ONFAULT) < 0) { + if (errno == ENOSYS) { + if (mlock(sh.arena, sh.arena_size) < 0) + ret = 2; + } else { + ret = 2; + } + } +#else if (mlock(sh.arena, sh.arena_size) < 0) ret = 2; +#endif #ifdef MADV_DONTDUMP if (madvise(sh.arena, sh.arena_size, MADV_DONTDUMP) < 0) ret = 2; @@ -515,7 +524,7 @@ static char *sh_find_my_buddy(char *ptr, int list) return chunk; } -static char *sh_malloc(size_t size) +static void *sh_malloc(size_t size) { ossl_ssize_t list, slist; size_t i; @@ -577,10 +586,10 @@ static char *sh_malloc(size_t size) return chunk; } -static void sh_free(char *ptr) +static void sh_free(void *ptr) { size_t list; - char *buddy; + void *buddy; if (ptr == NULL) return; diff --git a/crypto/mips_arch.h b/crypto/mips_arch.h new file mode 100644 index 00000000..75043e79 --- /dev/null +++ b/crypto/mips_arch.h @@ -0,0 +1,40 @@ +/* + * Copyright 2011-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 + */ + +#ifndef __MIPS_ARCH_H__ +# define __MIPS_ARCH_H__ + +# if (defined(__mips_smartmips) || defined(_MIPS_ARCH_MIPS32R3) || \ + defined(_MIPS_ARCH_MIPS32R5) || defined(_MIPS_ARCH_MIPS32R6)) + && !defined(_MIPS_ARCH_MIPS32R2) +# define _MIPS_ARCH_MIPS32R2 +# endif + +# if (defined(_MIPS_ARCH_MIPS64R3) || defined(_MIPS_ARCH_MIPS64R5) || \ + defined(_MIPS_ARCH_MIPS64R6)) \ + && !defined(_MIPS_ARCH_MIPS64R2) +# define _MIPS_ARCH_MIPS64R2 +# endif + +# if defined(_MIPS_ARCH_MIPS64R6) +# define dmultu(rs,rt) +# define mflo(rd,rs,rt) dmulu rd,rs,rt +# define mfhi(rd,rs,rt) dmuhu rd,rs,rt +# elif defined(_MIPS_ARCH_MIPS32R6) +# define multu(rs,rt) +# define mflo(rd,rs,rt) mulu rd,rs,rt +# define mfhi(rd,rs,rt) muhu rd,rs,rt +# else +# define dmultu(rs,rt) dmultu rs,rt +# define multu(rs,rt) multu rs,rt +# define mflo(rd,rs,rt) mflo rd +# define mfhi(rd,rs,rt) mfhi rd +# endif + +#endif diff --git a/crypto/modes/asm/aesni-gcm-x86_64.pl b/crypto/modes/asm/aesni-gcm-x86_64.pl index 5ad62b39..b4201610 100644 --- a/crypto/modes/asm/aesni-gcm-x86_64.pl +++ b/crypto/modes/asm/aesni-gcm-x86_64.pl @@ -35,6 +35,8 @@ # Applications using the EVP interface will observe a few percent # worse performance.] # +# Knights Landing processes 1 byte in 1.25 cycles (measured with EVP). +# # [1] http://rt.openssl.org/Ticket/Display.html?id=2900&user=guest&pass=guest # [2] http://www.intel.com/content/dam/www/public/us/en/documents/software-support/enabling-high-performance-gcm.pdf @@ -116,23 +118,6 @@ _aesni_ctr32_ghash_6x: vpxor $rndkey,$inout3,$inout3 vmovups 0x10-0x80($key),$T2 # borrow $T2 for $rndkey vpclmulqdq \$0x01,$Hkey,$Z3,$Z2 - - # At this point, the current block of 96 (0x60) bytes has already been - # loaded into registers. Concurrently with processing it, we want to - # load the next 96 bytes of input for the next round. Obviously, we can - # only do this if there are at least 96 more bytes of input beyond the - # input we're currently processing, or else we'd read past the end of - # the input buffer. Here, we set |%r12| to 96 if there are at least 96 - # bytes of input beyond the 96 bytes we're already processing, and we - # set |%r12| to 0 otherwise. In the case where we set |%r12| to 96, - # we'll read in the next block so that it is in registers for the next - # loop iteration. In the case where we set |%r12| to 0, we'll re-read - # the current block and then ignore what we re-read. - # - # At this point, |$in0| points to the current (already read into - # registers) block, and |$end0| points to 2*96 bytes before the end of - # the input. Thus, |$in0| > |$end0| means that we do not have the next - # 96-byte block to read in, and |$in0| <= |$end0| means we do. xor %r12,%r12 cmp $in0,$end0 @@ -424,20 +409,25 @@ $code.=<<___; .type aesni_gcm_decrypt,\@function,6 .align 32 aesni_gcm_decrypt: +.cfi_startproc xor $ret,$ret - - # We call |_aesni_ctr32_ghash_6x|, which requires at least 96 (0x60) - # bytes of input. cmp \$0x60,$len # minimal accepted length jb .Lgcm_dec_abort lea (%rsp),%rax # save stack pointer +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -482,15 +472,7 @@ $code.=<<___; vmovdqu 0x50($inp),$Z3 # I[5] lea ($inp),$in0 vmovdqu 0x40($inp),$Z0 - - # |_aesni_ctr32_ghash_6x| requires |$end0| to point to 2*96 (0xc0) - # bytes before the end of the input. Note, in particular, that this is - # correct even if |$len| is not an even multiple of 96 or 16. XXX: This - # seems to require that |$inp| + |$len| >= 2*96 (0xc0); i.e. |$inp| must - # not be near the very beginning of the address space when |$len| < 2*96 - # (0xc0). lea -0xc0($inp,$len),$end0 - vmovdqu 0x30($inp),$Z1 shr \$4,$len xor $ret,$ret @@ -537,15 +519,23 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -48(%rax),%r15 +.cfi_restore %r15 mov -40(%rax),%r14 +.cfi_restore %r14 mov -32(%rax),%r13 +.cfi_restore %r13 mov -24(%rax),%r12 +.cfi_restore %r12 mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp # restore %rsp +.cfi_def_cfa_register %rsp .Lgcm_dec_abort: mov $ret,%rax # return value ret +.cfi_endproc .size aesni_gcm_decrypt,.-aesni_gcm_decrypt ___ @@ -645,21 +635,25 @@ _aesni_ctr32_6x: .type aesni_gcm_encrypt,\@function,6 .align 32 aesni_gcm_encrypt: +.cfi_startproc xor $ret,$ret - - # We call |_aesni_ctr32_6x| twice, each call consuming 96 bytes of - # input. Then we call |_aesni_ctr32_ghash_6x|, which requires at - # least 96 more bytes of input. cmp \$0x60*3,$len # minimal accepted length jb .Lgcm_enc_abort lea (%rsp),%rax # save stack pointer +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -699,16 +693,7 @@ $code.=<<___; .Lenc_no_key_aliasing: lea ($out),$in0 - - # |_aesni_ctr32_ghash_6x| requires |$end0| to point to 2*96 (0xc0) - # bytes before the end of the input. Note, in particular, that this is - # correct even if |$len| is not an even multiple of 96 or 16. Unlike in - # the decryption case, there's no caveat that |$out| must not be near - # the very beginning of the address space, because we know that - # |$len| >= 3*96 from the check above, and so we know - # |$out| + |$len| >= 2*96 (0xc0). lea -0xc0($out,$len),$end0 - shr \$4,$len call _aesni_ctr32_6x @@ -931,15 +916,23 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -48(%rax),%r15 +.cfi_restore %r15 mov -40(%rax),%r14 +.cfi_restore %r14 mov -32(%rax),%r13 +.cfi_restore %r13 mov -24(%rax),%r12 +.cfi_restore %r12 mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp # restore %rsp +.cfi_def_cfa_register %rsp .Lgcm_enc_abort: mov $ret,%rax # return value ret +.cfi_endproc .size aesni_gcm_encrypt,.-aesni_gcm_encrypt ___ diff --git a/crypto/modes/asm/ghash-armv4.pl b/crypto/modes/asm/ghash-armv4.pl index 7d880c94..9cc072e7 100644 --- a/crypto/modes/asm/ghash-armv4.pl +++ b/crypto/modes/asm/ghash-armv4.pl @@ -54,7 +54,7 @@ # # Câmara, D.; Gouvêa, C. P. L.; López, J. & Dahab, R.: Fast Software # Polynomial Multiplication on ARM Processors using the NEON Engine. -# +# # http://conradoplg.cryptoland.net/files/2010/12/mocrysen13.pdf # ==================================================================== @@ -528,7 +528,7 @@ $code.=<<___; #ifdef __ARMEL__ vrev64.8 $Xl,$Xl #endif - sub $Xi,#16 + sub $Xi,#16 vst1.64 $Xl#hi,[$Xi]! @ write out Xi vst1.64 $Xl#lo,[$Xi] diff --git a/crypto/modes/asm/ghash-ia64.pl b/crypto/modes/asm/ghash-ia64.pl index 81e75f71..eb9ded91 100755 --- a/crypto/modes/asm/ghash-ia64.pl +++ b/crypto/modes/asm/ghash-ia64.pl @@ -156,7 +156,7 @@ $code.=<<___; ___ ###################################################################### -# "528B" (well, "512B" actualy) streamed GHASH +# "528B" (well, "512B" actually) streamed GHASH # $Xip="in0"; $Htbl="in1"; diff --git a/crypto/modes/asm/ghash-parisc.pl b/crypto/modes/asm/ghash-parisc.pl index 1d625454..fef2db19 100644 --- a/crypto/modes/asm/ghash-parisc.pl +++ b/crypto/modes/asm/ghash-parisc.pl @@ -705,7 +705,7 @@ my $depd = sub { my ($mod,$args) = @_; my $orig = "depd$mod\t$args"; - # I only have ",z" completer, it's impicitly encoded... + # I only have ",z" completer, it's implicitly encoded... if ($args =~ /%r([0-9]+),([0-9]+),([0-9]+),%r([0-9]+)/) # format 16 { my $opcode=(0x3c<<26)|($4<<21)|($1<<16); my $cpos=63-$2; diff --git a/crypto/modes/asm/ghash-s390x.pl b/crypto/modes/asm/ghash-s390x.pl index 6e628d88..17dc3750 100644 --- a/crypto/modes/asm/ghash-s390x.pl +++ b/crypto/modes/asm/ghash-s390x.pl @@ -80,6 +80,8 @@ $rem_4bit="%r14"; $sp="%r15"; $code.=<<___; +#include "s390x_arch.h" + .text .globl gcm_gmult_4bit @@ -89,12 +91,13 @@ ___ $code.=<<___ if(!$softonly && 0); # hardware is slow for single block... larl %r1,OPENSSL_s390xcap_P lghi %r0,0 - lg %r1,24(%r1) # load second word of kimd capabilities vector + lg %r1,S390X_KIMD+8(%r1) # load second word of kimd capabilities + # vector tmhh %r1,0x4000 # check for function 65 jz .Lsoft_gmult stg %r0,16($sp) # arrange 16 bytes of zero input stg %r0,24($sp) - lghi %r0,65 # function 65 + lghi %r0,S390X_GHASH # function 65 la %r1,0($Xi) # H lies right after Xi in gcm128_context la $inp,16($sp) lghi $len,16 @@ -123,10 +126,11 @@ gcm_ghash_4bit: ___ $code.=<<___ if(!$softonly); larl %r1,OPENSSL_s390xcap_P - lg %r0,24(%r1) # load second word of kimd capabilities vector + lg %r0,S390X_KIMD+8(%r1) # load second word of kimd capabilities + # vector tmhh %r0,0x4000 # check for function 65 jz .Lsoft_ghash - lghi %r0,65 # function 65 + lghi %r0,S390X_GHASH # function 65 la %r1,0($Xi) # H lies right after Xi in gcm128_context .long 0xb93e0004 # kimd %r0,$inp brc 1,.-4 # pay attention to "partial completion" @@ -149,7 +153,7 @@ $code.=<<___; lg $Zhi,0+1($Xi) lghi $tmp,0 .Louter: - xg $Zhi,0($inp) # Xi ^= inp + xg $Zhi,0($inp) # Xi ^= inp xg $Zlo,8($inp) xgr $Zhi,$tmp stg $Zlo,8+1($Xi) diff --git a/crypto/modes/asm/ghash-x86.pl b/crypto/modes/asm/ghash-x86.pl index cd845825..bcbe6e39 100644 --- a/crypto/modes/asm/ghash-x86.pl +++ b/crypto/modes/asm/ghash-x86.pl @@ -103,14 +103,13 @@ # # Does it make sense to increase Naggr? To start with it's virtually # impossible in 32-bit mode, because of limited register bank -# capacity. Otherwise improvement has to be weighed agiainst slower +# capacity. Otherwise improvement has to be weighed against slower # setup, as well as code size and complexity increase. As even # optimistic estimate doesn't promise 30% performance improvement, # there are currently no plans to increase Naggr. # -# Special thanks to David Woodhouse for -# providing access to a Westmere-based system on behalf of Intel -# Open Source Technology Centre. +# Special thanks to David Woodhouse for providing access to a +# Westmere-based system on behalf of Intel Open Source Technology Centre. # January 2010 # @@ -139,7 +138,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"ghash-x86.pl",$x86only = $ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$x86only = $ARGV[$#ARGV] eq "386"); $sse2=0; for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } @@ -811,7 +810,7 @@ sub mmx_loop() { &bswap ($dat); &pshufw ($Zhi,$Zhi,0b00011011); # 76543210 &bswap ("ebx"); - + &cmp ("ecx",&DWP(528+16+8,"esp")); # are we done? &jne (&label("outer")); } @@ -915,7 +914,7 @@ my ($Xhi,$Xi) = @_; &psllq ($Xi,57); # &movdqa ($T1,$Xi); # &pslldq ($Xi,8); - &psrldq ($T1,8); # + &psrldq ($T1,8); # &pxor ($Xi,$T2); &pxor ($Xhi,$T1); # @@ -1085,7 +1084,7 @@ my ($Xhi,$Xi) = @_; &psllq ($Xi,57); # &movdqa ($T1,$Xi); # &pslldq ($Xi,8); - &psrldq ($T1,8); # + &psrldq ($T1,8); # &pxor ($Xi,$T2); &pxor ($Xhi,$T1); # &pshufd ($T1,$Xhn,0b01001110); diff --git a/crypto/modes/asm/ghash-x86_64.pl b/crypto/modes/asm/ghash-x86_64.pl index 387e3f85..afc30c3e 100644 --- a/crypto/modes/asm/ghash-x86_64.pl +++ b/crypto/modes/asm/ghash-x86_64.pl @@ -44,9 +44,8 @@ # See ghash-x86.pl for background information and details about coding # techniques. # -# Special thanks to David Woodhouse for -# providing access to a Westmere-based system on behalf of Intel -# Open Source Technology Centre. +# Special thanks to David Woodhouse for providing access to a +# Westmere-based system on behalf of Intel Open Source Technology Centre. # December 2012 # @@ -74,6 +73,7 @@ # Skylake 0.44(+110%)(if system doesn't support AVX) # Bulldozer 1.49(+27%) # Silvermont 2.88(+13%) +# Knights L 2.12(-) (if system doesn't support AVX) # Goldmont 1.08(+24%) # March 2013 @@ -86,6 +86,8 @@ # it performs in 0.41 cycles per byte on Haswell processor, in # 0.29 on Broadwell, and in 0.36 on Skylake. # +# Knights Landing achieves 1.09 cpb. +# # [1] http://rt.openssl.org/Ticket/Display.html?id=2900&user=guest&pass=guest $flavour = shift; @@ -236,9 +238,21 @@ $code=<<___; .type gcm_gmult_4bit,\@function,2 .align 16 gcm_gmult_4bit: +.cfi_startproc push %rbx - push %rbp # %rbp and %r12 are pushed exclusively in +.cfi_push %rbx + push %rbp # %rbp and others are pushed exclusively in +.cfi_push %rbp push %r12 # order to reuse Win64 exception handler... +.cfi_push %r12 + push %r13 +.cfi_push %r13 + push %r14 +.cfi_push %r14 + push %r15 +.cfi_push %r15 + sub \$280,%rsp +.cfi_adjust_cfa_offset 280 .Lgmult_prologue: movzb 15($Xi),$Zlo @@ -249,10 +263,15 @@ $code.=<<___; mov $Zlo,8($Xi) mov $Zhi,($Xi) - mov 16(%rsp),%rbx - lea 24(%rsp),%rsp + lea 280+48(%rsp),%rsi +.cfi_def_cfa %rsi,8 + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lgmult_epilogue: ret +.cfi_endproc .size gcm_gmult_4bit,.-gcm_gmult_4bit ___ @@ -266,13 +285,21 @@ $code.=<<___; .type gcm_ghash_4bit,\@function,4 .align 16 gcm_ghash_4bit: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 sub \$280,%rsp +.cfi_adjust_cfa_offset 280 .Lghash_prologue: mov $inp,%r14 # reassign couple of args mov $len,%r15 @@ -400,16 +427,25 @@ $code.=<<___; mov $Zlo,8($Xi) mov $Zhi,($Xi) - lea 280(%rsp),%rsi - mov 0(%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp + lea 280+48(%rsp),%rsi +.cfi_def_cfa %rsi,8 + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea 0(%rsi),%rsp +.cfi_def_cfa_register %rsp .Lghash_epilogue: ret +.cfi_endproc .size gcm_ghash_4bit,.-gcm_ghash_4bit ___ @@ -469,7 +505,7 @@ $code.=<<___; psllq \$57,$Xi # movdqa $Xi,$T1 # pslldq \$8,$Xi - psrldq \$8,$T1 # + psrldq \$8,$T1 # pxor $T2,$Xi pxor $T1,$Xhi # @@ -583,7 +619,7 @@ ___ &clmul64x64_T2 ($Xhi,$Xi,$Hkey,$T2); $code.=<<___ if (0 || (&reduction_alg9($Xhi,$Xi)&&0)); # experimental alternative. special thing about is that there - # no dependency between the two multiplications... + # no dependency between the two multiplications... mov \$`0xE1<<1`,%eax mov \$0xA040608020C0E000,%r10 # ((7..0)·0xE0)&0xff mov \$0x07,%r11d @@ -758,7 +794,7 @@ $code.=<<___; movdqa $T2,$T1 # pslldq \$8,$T2 pclmulqdq \$0x00,$Hkey2,$Xln - psrldq \$8,$T1 # + psrldq \$8,$T1 # pxor $T2,$Xi pxor $T1,$Xhi # movdqu 0($inp),$T1 @@ -894,7 +930,7 @@ $code.=<<___; psllq \$57,$Xi # movdqa $Xi,$T1 # pslldq \$8,$Xi - psrldq \$8,$T1 # + psrldq \$8,$T1 # pxor $T2,$Xi pshufd \$0b01001110,$Xhn,$Xmn pxor $T1,$Xhi # @@ -1648,14 +1684,20 @@ se_handler: cmp %r10,%rbx # context->Rip>=epilogue label jae .Lin_prologue - lea 24(%rax),%rax # adjust "rsp" + lea 48+280(%rax),%rax # adjust "rsp" mov -8(%rax),%rbx mov -16(%rax),%rbp mov -24(%rax),%r12 + mov -32(%rax),%r13 + mov -40(%rax),%r14 + mov -48(%rax),%r15 mov %rbx,144($context) # restore context->Rbx mov %rbp,160($context) # restore context->Rbp mov %r12,216($context) # restore context->R12 + mov %r13,224($context) # restore context->R13 + mov %r14,232($context) # restore context->R14 + mov %r15,240($context) # restore context->R15 .Lin_prologue: mov 8(%rax),%rdi diff --git a/crypto/modes/asm/ghashp8-ppc.pl b/crypto/modes/asm/ghashp8-ppc.pl index f0598cb2..45c64384 100755 --- a/crypto/modes/asm/ghashp8-ppc.pl +++ b/crypto/modes/asm/ghashp8-ppc.pl @@ -23,7 +23,7 @@ # Relative comparison is therefore more informative. This initial # version is ~2.1x slower than hardware-assisted AES-128-CTR, ~12x # faster than "4-bit" integer-only compiler-generated 64-bit code. -# "Initial version" means that there is room for futher improvement. +# "Initial version" means that there is room for further improvement. # May 2016 # diff --git a/crypto/modes/asm/ghashv8-armx.pl b/crypto/modes/asm/ghashv8-armx.pl index dcd5f595..7e572387 100644 --- a/crypto/modes/asm/ghashv8-armx.pl +++ b/crypto/modes/asm/ghashv8-armx.pl @@ -19,23 +19,29 @@ # June 2014 # # Initial version was developed in tight cooperation with Ard -# Biesheuvel from bits-n-pieces from -# other assembly modules. Just like aesv8-armx.pl this module -# supports both AArch32 and AArch64 execution modes. +# Biesheuvel of Linaro from bits-n-pieces from other assembly modules. +# Just like aesv8-armx.pl this module supports both AArch32 and +# AArch64 execution modes. # # July 2014 # # Implement 2x aggregated reduction [see ghash-x86.pl for background # information]. # +# November 2017 +# +# AArch64 register bank to "accommodate" 4x aggregated reduction and +# improve performance by 20-70% depending on processor. +# # Current performance in cycles per processed byte: # -# PMULL[2] 32-bit NEON(*) -# Apple A7 0.92 5.62 -# Cortex-A53 1.01 8.39 -# Cortex-A57 1.17 7.61 -# Denver 0.71 6.02 -# Mongoose 1.10 8.06 +# 64-bit PMULL 32-bit PMULL 32-bit NEON(*) +# Apple A7 0.58 0.92 5.62 +# Cortex-A53 0.85 1.01 8.39 +# Cortex-A57 0.73 1.17 7.61 +# Denver 0.51 0.65 6.02 +# Mongoose 0.65 1.10 8.06 +# Kryo 0.76 1.16 8.00 # # (*) presented for reference/comparison purposes; @@ -130,8 +136,56 @@ gcm_init_v8: vext.8 $t1,$H2,$H2,#8 @ Karatsuba pre-processing veor $t1,$t1,$H2 vext.8 $Hhl,$t0,$t1,#8 @ pack Karatsuba pre-processed - vst1.64 {$Hhl-$H2},[x0] @ store Htable[1..2] + vst1.64 {$Hhl-$H2},[x0],#32 @ store Htable[1..2] +___ +if ($flavour =~ /64/) { +my ($t3,$Yl,$Ym,$Yh) = map("q$_",(4..7)); +$code.=<<___; + @ calculate H^3 and H^4 + vpmull.p64 $Xl,$H, $H2 + vpmull.p64 $Yl,$H2,$H2 + vpmull2.p64 $Xh,$H, $H2 + vpmull2.p64 $Yh,$H2,$H2 + vpmull.p64 $Xm,$t0,$t1 + vpmull.p64 $Ym,$t1,$t1 + + vext.8 $t0,$Xl,$Xh,#8 @ Karatsuba post-processing + vext.8 $t1,$Yl,$Yh,#8 + veor $t2,$Xl,$Xh + veor $Xm,$Xm,$t0 + veor $t3,$Yl,$Yh + veor $Ym,$Ym,$t1 + veor $Xm,$Xm,$t2 + vpmull.p64 $t2,$Xl,$xC2 @ 1st phase + veor $Ym,$Ym,$t3 + vpmull.p64 $t3,$Yl,$xC2 + + vmov $Xh#lo,$Xm#hi @ Xh|Xm - 256-bit result + vmov $Yh#lo,$Ym#hi + vmov $Xm#hi,$Xl#lo @ Xm is rotated Xl + vmov $Ym#hi,$Yl#lo + veor $Xl,$Xm,$t2 + veor $Yl,$Ym,$t3 + + vext.8 $t2,$Xl,$Xl,#8 @ 2nd phase + vext.8 $t3,$Yl,$Yl,#8 + vpmull.p64 $Xl,$Xl,$xC2 + vpmull.p64 $Yl,$Yl,$xC2 + veor $t2,$t2,$Xh + veor $t3,$t3,$Yh + veor $H, $Xl,$t2 @ H^3 + veor $H2,$Yl,$t3 @ H^4 + + vext.8 $t0,$H, $H,#8 @ Karatsuba pre-processing + vext.8 $t1,$H2,$H2,#8 + veor $t0,$t0,$H + veor $t1,$t1,$H2 + vext.8 $Hhl,$t0,$t1,#8 @ pack Karatsuba pre-processed + vst1.64 {$H-$H2},[x0] @ store Htable[3..5] +___ +} +$code.=<<___; ret .size gcm_init_v8,.-gcm_init_v8 ___ @@ -200,6 +254,10 @@ $code.=<<___; .align 4 gcm_ghash_v8: ___ +$code.=<<___ if ($flavour =~ /64/); + cmp $len,#64 + b.hs .Lgcm_ghash_v8_4x +___ $code.=<<___ if ($flavour !~ /64/); vstmdb sp!,{d8-d15} @ 32-bit ABI says so ___ @@ -209,13 +267,13 @@ $code.=<<___; @ loaded value would have @ to be rotated in order to @ make it appear as in - @ alorithm specification + @ algorithm specification subs $len,$len,#32 @ see if $len is 32 or larger mov $inc,#16 @ $inc is used as post- @ increment for input pointer; @ as loop is modulo-scheduled @ $inc is zeroed just in time - @ to preclude oversteping + @ to preclude overstepping @ inp[len], which means that @ last block[s] are actually @ loaded twice, but last @@ -347,7 +405,297 @@ $code.=<<___; ret .size gcm_ghash_v8,.-gcm_ghash_v8 ___ + +if ($flavour =~ /64/) { # 4x subroutine +my ($I0,$j1,$j2,$j3, + $I1,$I2,$I3,$H3,$H34,$H4,$Yl,$Ym,$Yh) = map("q$_",(4..7,15..23)); + +$code.=<<___; +.type gcm_ghash_v8_4x,%function +.align 4 +gcm_ghash_v8_4x: +.Lgcm_ghash_v8_4x: + vld1.64 {$Xl},[$Xi] @ load [rotated] Xi + vld1.64 {$H-$H2},[$Htbl],#48 @ load twisted H, ..., H^2 + vmov.i8 $xC2,#0xe1 + vld1.64 {$H3-$H4},[$Htbl] @ load twisted H^3, ..., H^4 + vshl.u64 $xC2,$xC2,#57 @ compose 0xc2.0 constant + + vld1.64 {$I0-$j3},[$inp],#64 +#ifndef __ARMEB__ + vrev64.8 $Xl,$Xl + vrev64.8 $j1,$j1 + vrev64.8 $j2,$j2 + vrev64.8 $j3,$j3 + vrev64.8 $I0,$I0 +#endif + vext.8 $I3,$j3,$j3,#8 + vext.8 $I2,$j2,$j2,#8 + vext.8 $I1,$j1,$j1,#8 + + vpmull.p64 $Yl,$H,$I3 @ H·Ii+3 + veor $j3,$j3,$I3 + vpmull2.p64 $Yh,$H,$I3 + vpmull.p64 $Ym,$Hhl,$j3 + + vpmull.p64 $t0,$H2,$I2 @ H^2·Ii+2 + veor $j2,$j2,$I2 + vpmull2.p64 $I2,$H2,$I2 + vpmull2.p64 $j2,$Hhl,$j2 + + veor $Yl,$Yl,$t0 + veor $Yh,$Yh,$I2 + veor $Ym,$Ym,$j2 + + vpmull.p64 $j3,$H3,$I1 @ H^3·Ii+1 + veor $j1,$j1,$I1 + vpmull2.p64 $I1,$H3,$I1 + vpmull.p64 $j1,$H34,$j1 + + veor $Yl,$Yl,$j3 + veor $Yh,$Yh,$I1 + veor $Ym,$Ym,$j1 + + subs $len,$len,#128 + b.lo .Ltail4x + + b .Loop4x + +.align 4 +.Loop4x: + veor $t0,$I0,$Xl + vld1.64 {$I0-$j3},[$inp],#64 + vext.8 $IN,$t0,$t0,#8 +#ifndef __ARMEB__ + vrev64.8 $j1,$j1 + vrev64.8 $j2,$j2 + vrev64.8 $j3,$j3 + vrev64.8 $I0,$I0 +#endif + + vpmull.p64 $Xl,$H4,$IN @ H^4·(Xi+Ii) + veor $t0,$t0,$IN + vpmull2.p64 $Xh,$H4,$IN + vext.8 $I3,$j3,$j3,#8 + vpmull2.p64 $Xm,$H34,$t0 + + veor $Xl,$Xl,$Yl + veor $Xh,$Xh,$Yh + vext.8 $I2,$j2,$j2,#8 + veor $Xm,$Xm,$Ym + vext.8 $I1,$j1,$j1,#8 + + vext.8 $t1,$Xl,$Xh,#8 @ Karatsuba post-processing + veor $t2,$Xl,$Xh + vpmull.p64 $Yl,$H,$I3 @ H·Ii+3 + veor $j3,$j3,$I3 + veor $Xm,$Xm,$t1 + vpmull2.p64 $Yh,$H,$I3 + veor $Xm,$Xm,$t2 + vpmull.p64 $Ym,$Hhl,$j3 + + vpmull.p64 $t2,$Xl,$xC2 @ 1st phase of reduction + vmov $Xh#lo,$Xm#hi @ Xh|Xm - 256-bit result + vmov $Xm#hi,$Xl#lo @ Xm is rotated Xl + vpmull.p64 $t0,$H2,$I2 @ H^2·Ii+2 + veor $j2,$j2,$I2 + vpmull2.p64 $I2,$H2,$I2 + veor $Xl,$Xm,$t2 + vpmull2.p64 $j2,$Hhl,$j2 + + veor $Yl,$Yl,$t0 + veor $Yh,$Yh,$I2 + veor $Ym,$Ym,$j2 + + vext.8 $t2,$Xl,$Xl,#8 @ 2nd phase of reduction + vpmull.p64 $Xl,$Xl,$xC2 + vpmull.p64 $j3,$H3,$I1 @ H^3·Ii+1 + veor $j1,$j1,$I1 + veor $t2,$t2,$Xh + vpmull2.p64 $I1,$H3,$I1 + vpmull.p64 $j1,$H34,$j1 + + veor $Xl,$Xl,$t2 + veor $Yl,$Yl,$j3 + veor $Yh,$Yh,$I1 + vext.8 $Xl,$Xl,$Xl,#8 + veor $Ym,$Ym,$j1 + + subs $len,$len,#64 + b.hs .Loop4x + +.Ltail4x: + veor $t0,$I0,$Xl + vext.8 $IN,$t0,$t0,#8 + + vpmull.p64 $Xl,$H4,$IN @ H^4·(Xi+Ii) + veor $t0,$t0,$IN + vpmull2.p64 $Xh,$H4,$IN + vpmull2.p64 $Xm,$H34,$t0 + + veor $Xl,$Xl,$Yl + veor $Xh,$Xh,$Yh + veor $Xm,$Xm,$Ym + + adds $len,$len,#64 + b.eq .Ldone4x + + cmp $len,#32 + b.lo .Lone + b.eq .Ltwo +.Lthree: + vext.8 $t1,$Xl,$Xh,#8 @ Karatsuba post-processing + veor $t2,$Xl,$Xh + veor $Xm,$Xm,$t1 + vld1.64 {$I0-$j2},[$inp] + veor $Xm,$Xm,$t2 +#ifndef __ARMEB__ + vrev64.8 $j1,$j1 + vrev64.8 $j2,$j2 + vrev64.8 $I0,$I0 +#endif + + vpmull.p64 $t2,$Xl,$xC2 @ 1st phase of reduction + vmov $Xh#lo,$Xm#hi @ Xh|Xm - 256-bit result + vmov $Xm#hi,$Xl#lo @ Xm is rotated Xl + vext.8 $I2,$j2,$j2,#8 + vext.8 $I1,$j1,$j1,#8 + veor $Xl,$Xm,$t2 + + vpmull.p64 $Yl,$H,$I2 @ H·Ii+2 + veor $j2,$j2,$I2 + + vext.8 $t2,$Xl,$Xl,#8 @ 2nd phase of reduction + vpmull.p64 $Xl,$Xl,$xC2 + veor $t2,$t2,$Xh + vpmull2.p64 $Yh,$H,$I2 + vpmull.p64 $Ym,$Hhl,$j2 + veor $Xl,$Xl,$t2 + vpmull.p64 $j3,$H2,$I1 @ H^2·Ii+1 + veor $j1,$j1,$I1 + vext.8 $Xl,$Xl,$Xl,#8 + + vpmull2.p64 $I1,$H2,$I1 + veor $t0,$I0,$Xl + vpmull2.p64 $j1,$Hhl,$j1 + vext.8 $IN,$t0,$t0,#8 + + veor $Yl,$Yl,$j3 + veor $Yh,$Yh,$I1 + veor $Ym,$Ym,$j1 + + vpmull.p64 $Xl,$H3,$IN @ H^3·(Xi+Ii) + veor $t0,$t0,$IN + vpmull2.p64 $Xh,$H3,$IN + vpmull.p64 $Xm,$H34,$t0 + + veor $Xl,$Xl,$Yl + veor $Xh,$Xh,$Yh + veor $Xm,$Xm,$Ym + b .Ldone4x + +.align 4 +.Ltwo: + vext.8 $t1,$Xl,$Xh,#8 @ Karatsuba post-processing + veor $t2,$Xl,$Xh + veor $Xm,$Xm,$t1 + vld1.64 {$I0-$j1},[$inp] + veor $Xm,$Xm,$t2 +#ifndef __ARMEB__ + vrev64.8 $j1,$j1 + vrev64.8 $I0,$I0 +#endif + + vpmull.p64 $t2,$Xl,$xC2 @ 1st phase of reduction + vmov $Xh#lo,$Xm#hi @ Xh|Xm - 256-bit result + vmov $Xm#hi,$Xl#lo @ Xm is rotated Xl + vext.8 $I1,$j1,$j1,#8 + veor $Xl,$Xm,$t2 + + vext.8 $t2,$Xl,$Xl,#8 @ 2nd phase of reduction + vpmull.p64 $Xl,$Xl,$xC2 + veor $t2,$t2,$Xh + veor $Xl,$Xl,$t2 + vext.8 $Xl,$Xl,$Xl,#8 + + vpmull.p64 $Yl,$H,$I1 @ H·Ii+1 + veor $j1,$j1,$I1 + + veor $t0,$I0,$Xl + vext.8 $IN,$t0,$t0,#8 + + vpmull2.p64 $Yh,$H,$I1 + vpmull.p64 $Ym,$Hhl,$j1 + + vpmull.p64 $Xl,$H2,$IN @ H^2·(Xi+Ii) + veor $t0,$t0,$IN + vpmull2.p64 $Xh,$H2,$IN + vpmull2.p64 $Xm,$Hhl,$t0 + + veor $Xl,$Xl,$Yl + veor $Xh,$Xh,$Yh + veor $Xm,$Xm,$Ym + b .Ldone4x + +.align 4 +.Lone: + vext.8 $t1,$Xl,$Xh,#8 @ Karatsuba post-processing + veor $t2,$Xl,$Xh + veor $Xm,$Xm,$t1 + vld1.64 {$I0},[$inp] + veor $Xm,$Xm,$t2 +#ifndef __ARMEB__ + vrev64.8 $I0,$I0 +#endif + + vpmull.p64 $t2,$Xl,$xC2 @ 1st phase of reduction + vmov $Xh#lo,$Xm#hi @ Xh|Xm - 256-bit result + vmov $Xm#hi,$Xl#lo @ Xm is rotated Xl + veor $Xl,$Xm,$t2 + + vext.8 $t2,$Xl,$Xl,#8 @ 2nd phase of reduction + vpmull.p64 $Xl,$Xl,$xC2 + veor $t2,$t2,$Xh + veor $Xl,$Xl,$t2 + vext.8 $Xl,$Xl,$Xl,#8 + + veor $t0,$I0,$Xl + vext.8 $IN,$t0,$t0,#8 + + vpmull.p64 $Xl,$H,$IN + veor $t0,$t0,$IN + vpmull2.p64 $Xh,$H,$IN + vpmull.p64 $Xm,$Hhl,$t0 + +.Ldone4x: + vext.8 $t1,$Xl,$Xh,#8 @ Karatsuba post-processing + veor $t2,$Xl,$Xh + veor $Xm,$Xm,$t1 + veor $Xm,$Xm,$t2 + + vpmull.p64 $t2,$Xl,$xC2 @ 1st phase of reduction + vmov $Xh#lo,$Xm#hi @ Xh|Xm - 256-bit result + vmov $Xm#hi,$Xl#lo @ Xm is rotated Xl + veor $Xl,$Xm,$t2 + + vext.8 $t2,$Xl,$Xl,#8 @ 2nd phase of reduction + vpmull.p64 $Xl,$Xl,$xC2 + veor $t2,$t2,$Xh + veor $Xl,$Xl,$t2 + vext.8 $Xl,$Xl,$Xl,#8 + +#ifndef __ARMEB__ + vrev64.8 $Xl,$Xl +#endif + vst1.64 {$Xl},[$Xi] @ write out Xi + + ret +.size gcm_ghash_v8_4x,.-gcm_ghash_v8_4x +___ + } +} + $code.=<<___; .asciz "GHASH for ARMv8, CRYPTOGAMS by " .align 2 @@ -358,7 +706,8 @@ if ($flavour =~ /64/) { ######## 64-bit code my $arg=shift; $arg =~ m/q([0-9]+)#(lo|hi),\s*q([0-9]+)#(lo|hi)/o && - sprintf "ins v%d.d[%d],v%d.d[%d]",$1,($2 eq "lo")?0:1,$3,($4 eq "lo")?0:1; + sprintf "ins v%d.d[%d],v%d.d[%d]",$1<8?$1:$1+8,($2 eq "lo")?0:1, + $3<8?$3:$3+8,($4 eq "lo")?0:1; } foreach(split("\n",$code)) { s/cclr\s+([wx])([^,]+),\s*([a-z]+)/csel $1$2,$1zr,$1$2,$3/o or @@ -373,7 +722,7 @@ if ($flavour =~ /64/) { ######## 64-bit code s/\bq([0-9]+)\b/"v".($1<8?$1:$1+8).".16b"/geo; # old->new registers s/@\s/\/\//o; # old->new style commentary - # fix up remainig legacy suffixes + # fix up remaining legacy suffixes s/\.[ui]?8(\s)/$1/o; s/\.[uis]?32//o and s/\.16b/\.4s/go; m/\.p64/o and s/\.16b/\.1q/o; # 1st pmull argument @@ -413,7 +762,7 @@ if ($flavour =~ /64/) { ######## 64-bit code s/\bv([0-9])\.[12468]+[bsd]\b/q$1/go; # new->old registers s/\/\/\s?/@ /o; # new->old style commentary - # fix up remainig new-style suffixes + # fix up remaining new-style suffixes s/\],#[0-9]+/]!/o; s/cclr\s+([^,]+),\s*([a-z]+)/mov$2 $1,#0/o or diff --git a/crypto/modes/build.info b/crypto/modes/build.info index 38195c44..821340eb 100644 --- a/crypto/modes/build.info +++ b/crypto/modes/build.info @@ -6,8 +6,9 @@ SOURCE[../../libcrypto]=\ INCLUDE[gcm128.o]=.. -GENERATE[ghash-ia64.s]=asm/ghash-ia64.pl $(CFLAGS) $(LIB_CFLAGS) -GENERATE[ghash-x86.s]=asm/ghash-x86.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[ghash-ia64.s]=asm/ghash-ia64.pl $(LIB_CFLAGS) $(LIB_CPPFLAGS) +GENERATE[ghash-x86.s]=asm/ghash-x86.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) GENERATE[ghash-x86_64.s]=asm/ghash-x86_64.pl $(PERLASM_SCHEME) GENERATE[aesni-gcm-x86_64.s]=asm/aesni-gcm-x86_64.pl $(PERLASM_SCHEME) GENERATE[ghash-sparcv9.S]=asm/ghash-sparcv9.pl $(PERLASM_SCHEME) @@ -19,6 +20,8 @@ GENERATE[ghash-armv4.S]=asm/ghash-armv4.pl $(PERLASM_SCHEME) INCLUDE[ghash-armv4.o]=.. GENERATE[ghashv8-armx.S]=asm/ghashv8-armx.pl $(PERLASM_SCHEME) INCLUDE[ghashv8-armx.o]=.. +GENERATE[ghash-s390x.S]=asm/ghash-s390x.pl $(PERLASM_SCHEME) +INCLUDE[ghash-s390x.o]=.. BEGINRAW[Makefile] # GNU make "catch all" diff --git a/crypto/modes/cts128.c b/crypto/modes/cts128.c index 77ec994b..93826a1e 100644 --- a/crypto/modes/cts128.c +++ b/crypto/modes/cts128.c @@ -328,196 +328,3 @@ size_t CRYPTO_nistcts128_decrypt(const unsigned char *in, unsigned char *out, #endif return 16 + len + residue; } - -#if defined(SELFTEST) -# include -# include - -/* test vectors from RFC 3962 */ -static const unsigned char test_key[16] = "chicken teriyaki"; -static const unsigned char test_input[64] = - "I would like the" " General Gau's C" - "hicken, please, " "and wonton soup."; -static const unsigned char test_iv[16] = - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - -static const unsigned char vector_17[17] = { - 0xc6, 0x35, 0x35, 0x68, 0xf2, 0xbf, 0x8c, 0xb4, - 0xd8, 0xa5, 0x80, 0x36, 0x2d, 0xa7, 0xff, 0x7f, - 0x97 -}; - -static const unsigned char vector_31[31] = { - 0xfc, 0x00, 0x78, 0x3e, 0x0e, 0xfd, 0xb2, 0xc1, - 0xd4, 0x45, 0xd4, 0xc8, 0xef, 0xf7, 0xed, 0x22, - 0x97, 0x68, 0x72, 0x68, 0xd6, 0xec, 0xcc, 0xc0, - 0xc0, 0x7b, 0x25, 0xe2, 0x5e, 0xcf, 0xe5 -}; - -static const unsigned char vector_32[32] = { - 0x39, 0x31, 0x25, 0x23, 0xa7, 0x86, 0x62, 0xd5, - 0xbe, 0x7f, 0xcb, 0xcc, 0x98, 0xeb, 0xf5, 0xa8, - 0x97, 0x68, 0x72, 0x68, 0xd6, 0xec, 0xcc, 0xc0, - 0xc0, 0x7b, 0x25, 0xe2, 0x5e, 0xcf, 0xe5, 0x84 -}; - -static const unsigned char vector_47[47] = { - 0x97, 0x68, 0x72, 0x68, 0xd6, 0xec, 0xcc, 0xc0, - 0xc0, 0x7b, 0x25, 0xe2, 0x5e, 0xcf, 0xe5, 0x84, - 0xb3, 0xff, 0xfd, 0x94, 0x0c, 0x16, 0xa1, 0x8c, - 0x1b, 0x55, 0x49, 0xd2, 0xf8, 0x38, 0x02, 0x9e, - 0x39, 0x31, 0x25, 0x23, 0xa7, 0x86, 0x62, 0xd5, - 0xbe, 0x7f, 0xcb, 0xcc, 0x98, 0xeb, 0xf5 -}; - -static const unsigned char vector_48[48] = { - 0x97, 0x68, 0x72, 0x68, 0xd6, 0xec, 0xcc, 0xc0, - 0xc0, 0x7b, 0x25, 0xe2, 0x5e, 0xcf, 0xe5, 0x84, - 0x9d, 0xad, 0x8b, 0xbb, 0x96, 0xc4, 0xcd, 0xc0, - 0x3b, 0xc1, 0x03, 0xe1, 0xa1, 0x94, 0xbb, 0xd8, - 0x39, 0x31, 0x25, 0x23, 0xa7, 0x86, 0x62, 0xd5, - 0xbe, 0x7f, 0xcb, 0xcc, 0x98, 0xeb, 0xf5, 0xa8 -}; - -static const unsigned char vector_64[64] = { - 0x97, 0x68, 0x72, 0x68, 0xd6, 0xec, 0xcc, 0xc0, - 0xc0, 0x7b, 0x25, 0xe2, 0x5e, 0xcf, 0xe5, 0x84, - 0x39, 0x31, 0x25, 0x23, 0xa7, 0x86, 0x62, 0xd5, - 0xbe, 0x7f, 0xcb, 0xcc, 0x98, 0xeb, 0xf5, 0xa8, - 0x48, 0x07, 0xef, 0xe8, 0x36, 0xee, 0x89, 0xa5, - 0x26, 0x73, 0x0d, 0xbc, 0x2f, 0x7b, 0xc8, 0x40, - 0x9d, 0xad, 0x8b, 0xbb, 0x96, 0xc4, 0xcd, 0xc0, - 0x3b, 0xc1, 0x03, 0xe1, 0xa1, 0x94, 0xbb, 0xd8 -}; - -static AES_KEY encks, decks; - -void test_vector(const unsigned char *vector, size_t len) -{ - unsigned char iv[sizeof(test_iv)]; - unsigned char cleartext[64], ciphertext[64]; - size_t tail; - - printf("vector_%d\n", len); - fflush(stdout); - - if ((tail = len % 16) == 0) - tail = 16; - tail += 16; - - /* test block-based encryption */ - memcpy(iv, test_iv, sizeof(test_iv)); - CRYPTO_cts128_encrypt_block(test_input, ciphertext, len, &encks, iv, - (block128_f) AES_encrypt); - if (memcmp(ciphertext, vector, len)) - fprintf(stderr, "output_%d mismatch\n", len), exit(1); - if (memcmp(iv, vector + len - tail, sizeof(iv))) - fprintf(stderr, "iv_%d mismatch\n", len), exit(1); - - /* test block-based decryption */ - memcpy(iv, test_iv, sizeof(test_iv)); - CRYPTO_cts128_decrypt_block(ciphertext, cleartext, len, &decks, iv, - (block128_f) AES_decrypt); - if (memcmp(cleartext, test_input, len)) - fprintf(stderr, "input_%d mismatch\n", len), exit(2); - if (memcmp(iv, vector + len - tail, sizeof(iv))) - fprintf(stderr, "iv_%d mismatch\n", len), exit(2); - - /* test streamed encryption */ - memcpy(iv, test_iv, sizeof(test_iv)); - CRYPTO_cts128_encrypt(test_input, ciphertext, len, &encks, iv, - (cbc128_f) AES_cbc_encrypt); - if (memcmp(ciphertext, vector, len)) - fprintf(stderr, "output_%d mismatch\n", len), exit(3); - if (memcmp(iv, vector + len - tail, sizeof(iv))) - fprintf(stderr, "iv_%d mismatch\n", len), exit(3); - - /* test streamed decryption */ - memcpy(iv, test_iv, sizeof(test_iv)); - CRYPTO_cts128_decrypt(ciphertext, cleartext, len, &decks, iv, - (cbc128_f) AES_cbc_encrypt); - if (memcmp(cleartext, test_input, len)) - fprintf(stderr, "input_%d mismatch\n", len), exit(4); - if (memcmp(iv, vector + len - tail, sizeof(iv))) - fprintf(stderr, "iv_%d mismatch\n", len), exit(4); -} - -void test_nistvector(const unsigned char *vector, size_t len) -{ - unsigned char iv[sizeof(test_iv)]; - unsigned char cleartext[64], ciphertext[64], nistvector[64]; - size_t tail; - - printf("nistvector_%d\n", len); - fflush(stdout); - - if ((tail = len % 16) == 0) - tail = 16; - - len -= 16 + tail; - memcpy(nistvector, vector, len); - /* flip two last blocks */ - memcpy(nistvector + len, vector + len + 16, tail); - memcpy(nistvector + len + tail, vector + len, 16); - len += 16 + tail; - tail = 16; - - /* test block-based encryption */ - memcpy(iv, test_iv, sizeof(test_iv)); - CRYPTO_nistcts128_encrypt_block(test_input, ciphertext, len, &encks, iv, - (block128_f) AES_encrypt); - if (memcmp(ciphertext, nistvector, len)) - fprintf(stderr, "output_%d mismatch\n", len), exit(1); - if (memcmp(iv, nistvector + len - tail, sizeof(iv))) - fprintf(stderr, "iv_%d mismatch\n", len), exit(1); - - /* test block-based decryption */ - memcpy(iv, test_iv, sizeof(test_iv)); - CRYPTO_nistcts128_decrypt_block(ciphertext, cleartext, len, &decks, iv, - (block128_f) AES_decrypt); - if (memcmp(cleartext, test_input, len)) - fprintf(stderr, "input_%d mismatch\n", len), exit(2); - if (memcmp(iv, nistvector + len - tail, sizeof(iv))) - fprintf(stderr, "iv_%d mismatch\n", len), exit(2); - - /* test streamed encryption */ - memcpy(iv, test_iv, sizeof(test_iv)); - CRYPTO_nistcts128_encrypt(test_input, ciphertext, len, &encks, iv, - (cbc128_f) AES_cbc_encrypt); - if (memcmp(ciphertext, nistvector, len)) - fprintf(stderr, "output_%d mismatch\n", len), exit(3); - if (memcmp(iv, nistvector + len - tail, sizeof(iv))) - fprintf(stderr, "iv_%d mismatch\n", len), exit(3); - - /* test streamed decryption */ - memcpy(iv, test_iv, sizeof(test_iv)); - CRYPTO_nistcts128_decrypt(ciphertext, cleartext, len, &decks, iv, - (cbc128_f) AES_cbc_encrypt); - if (memcmp(cleartext, test_input, len)) - fprintf(stderr, "input_%d mismatch\n", len), exit(4); - if (memcmp(iv, nistvector + len - tail, sizeof(iv))) - fprintf(stderr, "iv_%d mismatch\n", len), exit(4); -} - -int main() -{ - AES_set_encrypt_key(test_key, 128, &encks); - AES_set_decrypt_key(test_key, 128, &decks); - - test_vector(vector_17, sizeof(vector_17)); - test_vector(vector_31, sizeof(vector_31)); - test_vector(vector_32, sizeof(vector_32)); - test_vector(vector_47, sizeof(vector_47)); - test_vector(vector_48, sizeof(vector_48)); - test_vector(vector_64, sizeof(vector_64)); - - test_nistvector(vector_17, sizeof(vector_17)); - test_nistvector(vector_31, sizeof(vector_31)); - test_nistvector(vector_32, sizeof(vector_32)); - test_nistvector(vector_47, sizeof(vector_47)); - test_nistvector(vector_48, sizeof(vector_48)); - test_nistvector(vector_64, sizeof(vector_64)); - - return 0; -} -#endif diff --git a/crypto/modes/gcm128.c b/crypto/modes/gcm128.c index a2b05c4d..4c8ae910 100644 --- a/crypto/modes/gcm128.c +++ b/crypto/modes/gcm128.c @@ -209,7 +209,7 @@ static void gcm_gmult_8bit(u64 Xi[2], const u128 Htable[256]) } } -# define GCM_MUL(ctx,Xi) gcm_gmult_8bit(ctx->Xi.u,ctx->Htable) +# define GCM_MUL(ctx) gcm_gmult_8bit(ctx->Xi.u,ctx->Htable) #elif TABLE_BITS==4 @@ -550,7 +550,7 @@ void gcm_ghash_4bit(u64 Xi[2], const u128 Htable[16], const u8 *inp, size_t len); # endif -# define GCM_MUL(ctx,Xi) gcm_gmult_4bit(ctx->Xi.u,ctx->Htable) +# define GCM_MUL(ctx) gcm_gmult_4bit(ctx->Xi.u,ctx->Htable) # if defined(GHASH_ASM) || !defined(OPENSSL_SMALL_FOOTPRINT) # define GHASH(ctx,in,len) gcm_ghash_4bit((ctx)->Xi.u,(ctx)->Htable,in,len) /* @@ -624,7 +624,7 @@ static void gcm_gmult_1bit(u64 Xi[2], const u64 H[2]) } } -# define GCM_MUL(ctx,Xi) gcm_gmult_1bit(ctx->Xi.u,ctx->H.u) +# define GCM_MUL(ctx) gcm_gmult_1bit(ctx->Xi.u,ctx->H.u) #endif @@ -703,7 +703,7 @@ void gcm_ghash_p8(u64 Xi[2], const u128 Htable[16], const u8 *inp, #ifdef GCM_FUNCREF_4BIT # undef GCM_MUL -# define GCM_MUL(ctx,Xi) (*gcm_gmult_p)(ctx->Xi.u,ctx->Htable) +# define GCM_MUL(ctx) (*gcm_gmult_p)(ctx->Xi.u,ctx->Htable) # ifdef GHASH # undef GHASH # define GHASH(ctx,in,len) (*gcm_ghash_p)(ctx->Xi.u,ctx->Htable,in,len) @@ -836,10 +836,6 @@ void CRYPTO_gcm128_setiv(GCM128_CONTEXT *ctx, const unsigned char *iv, void (*gcm_gmult_p) (u64 Xi[2], const u128 Htable[16]) = ctx->gmult; #endif - ctx->Yi.u[0] = 0; - ctx->Yi.u[1] = 0; - ctx->Xi.u[0] = 0; - ctx->Xi.u[1] = 0; ctx->len.u[0] = 0; /* AAD length */ ctx->len.u[1] = 0; /* message length */ ctx->ares = 0; @@ -847,53 +843,68 @@ void CRYPTO_gcm128_setiv(GCM128_CONTEXT *ctx, const unsigned char *iv, if (len == 12) { memcpy(ctx->Yi.c, iv, 12); + ctx->Yi.c[12] = 0; + ctx->Yi.c[13] = 0; + ctx->Yi.c[14] = 0; ctx->Yi.c[15] = 1; ctr = 1; } else { size_t i; u64 len0 = len; + /* Borrow ctx->Xi to calculate initial Yi */ + ctx->Xi.u[0] = 0; + ctx->Xi.u[1] = 0; + while (len >= 16) { for (i = 0; i < 16; ++i) - ctx->Yi.c[i] ^= iv[i]; - GCM_MUL(ctx, Yi); + ctx->Xi.c[i] ^= iv[i]; + GCM_MUL(ctx); iv += 16; len -= 16; } if (len) { for (i = 0; i < len; ++i) - ctx->Yi.c[i] ^= iv[i]; - GCM_MUL(ctx, Yi); + ctx->Xi.c[i] ^= iv[i]; + GCM_MUL(ctx); } len0 <<= 3; if (is_endian.little) { #ifdef BSWAP8 - ctx->Yi.u[1] ^= BSWAP8(len0); + ctx->Xi.u[1] ^= BSWAP8(len0); #else - ctx->Yi.c[8] ^= (u8)(len0 >> 56); - ctx->Yi.c[9] ^= (u8)(len0 >> 48); - ctx->Yi.c[10] ^= (u8)(len0 >> 40); - ctx->Yi.c[11] ^= (u8)(len0 >> 32); - ctx->Yi.c[12] ^= (u8)(len0 >> 24); - ctx->Yi.c[13] ^= (u8)(len0 >> 16); - ctx->Yi.c[14] ^= (u8)(len0 >> 8); - ctx->Yi.c[15] ^= (u8)(len0); + ctx->Xi.c[8] ^= (u8)(len0 >> 56); + ctx->Xi.c[9] ^= (u8)(len0 >> 48); + ctx->Xi.c[10] ^= (u8)(len0 >> 40); + ctx->Xi.c[11] ^= (u8)(len0 >> 32); + ctx->Xi.c[12] ^= (u8)(len0 >> 24); + ctx->Xi.c[13] ^= (u8)(len0 >> 16); + ctx->Xi.c[14] ^= (u8)(len0 >> 8); + ctx->Xi.c[15] ^= (u8)(len0); #endif - } else - ctx->Yi.u[1] ^= len0; + } else { + ctx->Xi.u[1] ^= len0; + } - GCM_MUL(ctx, Yi); + GCM_MUL(ctx); if (is_endian.little) #ifdef BSWAP4 - ctr = BSWAP4(ctx->Yi.d[3]); + ctr = BSWAP4(ctx->Xi.d[3]); #else - ctr = GETU32(ctx->Yi.c + 12); + ctr = GETU32(ctx->Xi.c + 12); #endif else - ctr = ctx->Yi.d[3]; + ctr = ctx->Xi.d[3]; + + /* Copy borrowed Xi to Yi */ + ctx->Yi.u[0] = ctx->Xi.u[0]; + ctx->Yi.u[1] = ctx->Xi.u[1]; } + ctx->Xi.u[0] = 0; + ctx->Xi.u[1] = 0; + (*ctx->block) (ctx->Yi.c, ctx->EK0.c, ctx->key); ++ctr; if (is_endian.little) @@ -936,7 +947,7 @@ int CRYPTO_gcm128_aad(GCM128_CONTEXT *ctx, const unsigned char *aad, n = (n + 1) % 16; } if (n == 0) - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); else { ctx->ares = n; return 0; @@ -952,7 +963,7 @@ int CRYPTO_gcm128_aad(GCM128_CONTEXT *ctx, const unsigned char *aad, while (len >= 16) { for (i = 0; i < 16; ++i) ctx->Xi.c[i] ^= aad[i]; - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); aad += 16; len -= 16; } @@ -995,7 +1006,7 @@ int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, if (ctx->ares) { /* First call to encrypt finalizes GHASH(AAD) */ - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); ctx->ares = 0; } @@ -1019,7 +1030,7 @@ int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, n = (n + 1) % 16; } if (n == 0) - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); else { ctx->mres = n; return 0; @@ -1100,7 +1111,7 @@ int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, ctx->Yi.d[3] = ctr; for (i = 0; i < 16 / sizeof(size_t); ++i) ctx->Xi.t[i] ^= out_t[i] = in_t[i] ^ ctx->EKi.t[i]; - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); out += 16; in += 16; len -= 16; @@ -1144,7 +1155,7 @@ int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx, ctx->Xi.c[n] ^= out[i] = in[i] ^ ctx->EKi.c[n]; n = (n + 1) % 16; if (n == 0) - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); } ctx->mres = n; @@ -1179,7 +1190,7 @@ int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, if (ctx->ares) { /* First call to decrypt finalizes GHASH(AAD) */ - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); ctx->ares = 0; } @@ -1205,7 +1216,7 @@ int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, n = (n + 1) % 16; } if (n == 0) - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); else { ctx->mres = n; return 0; @@ -1287,7 +1298,7 @@ int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, out[i] = c ^ ctx->EKi.t[i]; ctx->Xi.t[i] ^= c; } - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); out += 16; in += 16; len -= 16; @@ -1336,7 +1347,7 @@ int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx, ctx->Xi.c[n] ^= c; n = (n + 1) % 16; if (n == 0) - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); } ctx->mres = n; @@ -1373,7 +1384,7 @@ int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx, if (ctx->ares) { /* First call to encrypt finalizes GHASH(AAD) */ - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); ctx->ares = 0; } @@ -1394,7 +1405,7 @@ int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx, n = (n + 1) % 16; } if (n == 0) - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); else { ctx->mres = n; return 0; @@ -1440,7 +1451,7 @@ int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx, while (j--) { for (i = 0; i < 16; ++i) ctx->Xi.c[i] ^= out[i]; - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); out += 16; } # endif @@ -1497,7 +1508,7 @@ int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx, if (ctx->ares) { /* First call to decrypt finalizes GHASH(AAD) */ - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); ctx->ares = 0; } @@ -1520,7 +1531,7 @@ int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx, n = (n + 1) % 16; } if (n == 0) - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); else { ctx->mres = n; return 0; @@ -1554,7 +1565,7 @@ int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx, size_t k; for (k = 0; k < 16; ++k) ctx->Xi.c[k] ^= in[k]; - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); in += 16; } j = i / 16; @@ -1612,7 +1623,7 @@ int CRYPTO_gcm128_finish(GCM128_CONTEXT *ctx, const unsigned char *tag, #endif if (ctx->mres || ctx->ares) - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); if (is_endian.little) { #ifdef BSWAP8 @@ -1631,7 +1642,7 @@ int CRYPTO_gcm128_finish(GCM128_CONTEXT *ctx, const unsigned char *tag, ctx->Xi.u[0] ^= alen; ctx->Xi.u[1] ^= clen; - GCM_MUL(ctx, Xi); + GCM_MUL(ctx); ctx->Xi.u[0] ^= ctx->EK0.u[0]; ctx->Xi.u[1] ^= ctx->EK0.u[1]; @@ -1663,639 +1674,3 @@ void CRYPTO_gcm128_release(GCM128_CONTEXT *ctx) { OPENSSL_clear_free(ctx, sizeof(*ctx)); } - -#if defined(SELFTEST) -# include -# include - -/* Test Case 1 */ -static const u8 K1[16], *P1 = NULL, *A1 = NULL, IV1[12], *C1 = NULL; -static const u8 T1[] = { - 0x58, 0xe2, 0xfc, 0xce, 0xfa, 0x7e, 0x30, 0x61, - 0x36, 0x7f, 0x1d, 0x57, 0xa4, 0xe7, 0x45, 0x5a -}; - -/* Test Case 2 */ -# define K2 K1 -# define A2 A1 -# define IV2 IV1 -static const u8 P2[16]; -static const u8 C2[] = { - 0x03, 0x88, 0xda, 0xce, 0x60, 0xb6, 0xa3, 0x92, - 0xf3, 0x28, 0xc2, 0xb9, 0x71, 0xb2, 0xfe, 0x78 -}; - -static const u8 T2[] = { - 0xab, 0x6e, 0x47, 0xd4, 0x2c, 0xec, 0x13, 0xbd, - 0xf5, 0x3a, 0x67, 0xb2, 0x12, 0x57, 0xbd, 0xdf -}; - -/* Test Case 3 */ -# define A3 A2 -static const u8 K3[] = { - 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, - 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08 -}; - -static const u8 P3[] = { - 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, - 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, - 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, - 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, - 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, - 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, - 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, - 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55 -}; - -static const u8 IV3[] = { - 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, - 0xde, 0xca, 0xf8, 0x88 -}; - -static const u8 C3[] = { - 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24, - 0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c, - 0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0, - 0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e, - 0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c, - 0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05, - 0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97, - 0x3d, 0x58, 0xe0, 0x91, 0x47, 0x3f, 0x59, 0x85 -}; - -static const u8 T3[] = { - 0x4d, 0x5c, 0x2a, 0xf3, 0x27, 0xcd, 0x64, 0xa6, - 0x2c, 0xf3, 0x5a, 0xbd, 0x2b, 0xa6, 0xfa, 0xb4 -}; - -/* Test Case 4 */ -# define K4 K3 -# define IV4 IV3 -static const u8 P4[] = { - 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, - 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, - 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, - 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, - 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, - 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, - 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, - 0xba, 0x63, 0x7b, 0x39 -}; - -static const u8 A4[] = { - 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, - 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, - 0xab, 0xad, 0xda, 0xd2 -}; - -static const u8 C4[] = { - 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24, - 0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c, - 0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0, - 0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e, - 0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c, - 0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05, - 0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97, - 0x3d, 0x58, 0xe0, 0x91 -}; - -static const u8 T4[] = { - 0x5b, 0xc9, 0x4f, 0xbc, 0x32, 0x21, 0xa5, 0xdb, - 0x94, 0xfa, 0xe9, 0x5a, 0xe7, 0x12, 0x1a, 0x47 -}; - -/* Test Case 5 */ -# define K5 K4 -# define P5 P4 -# define A5 A4 -static const u8 IV5[] = { - 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad -}; - -static const u8 C5[] = { - 0x61, 0x35, 0x3b, 0x4c, 0x28, 0x06, 0x93, 0x4a, - 0x77, 0x7f, 0xf5, 0x1f, 0xa2, 0x2a, 0x47, 0x55, - 0x69, 0x9b, 0x2a, 0x71, 0x4f, 0xcd, 0xc6, 0xf8, - 0x37, 0x66, 0xe5, 0xf9, 0x7b, 0x6c, 0x74, 0x23, - 0x73, 0x80, 0x69, 0x00, 0xe4, 0x9f, 0x24, 0xb2, - 0x2b, 0x09, 0x75, 0x44, 0xd4, 0x89, 0x6b, 0x42, - 0x49, 0x89, 0xb5, 0xe1, 0xeb, 0xac, 0x0f, 0x07, - 0xc2, 0x3f, 0x45, 0x98 -}; - -static const u8 T5[] = { - 0x36, 0x12, 0xd2, 0xe7, 0x9e, 0x3b, 0x07, 0x85, - 0x56, 0x1b, 0xe1, 0x4a, 0xac, 0xa2, 0xfc, 0xcb -}; - -/* Test Case 6 */ -# define K6 K5 -# define P6 P5 -# define A6 A5 -static const u8 IV6[] = { - 0x93, 0x13, 0x22, 0x5d, 0xf8, 0x84, 0x06, 0xe5, - 0x55, 0x90, 0x9c, 0x5a, 0xff, 0x52, 0x69, 0xaa, - 0x6a, 0x7a, 0x95, 0x38, 0x53, 0x4f, 0x7d, 0xa1, - 0xe4, 0xc3, 0x03, 0xd2, 0xa3, 0x18, 0xa7, 0x28, - 0xc3, 0xc0, 0xc9, 0x51, 0x56, 0x80, 0x95, 0x39, - 0xfc, 0xf0, 0xe2, 0x42, 0x9a, 0x6b, 0x52, 0x54, - 0x16, 0xae, 0xdb, 0xf5, 0xa0, 0xde, 0x6a, 0x57, - 0xa6, 0x37, 0xb3, 0x9b -}; - -static const u8 C6[] = { - 0x8c, 0xe2, 0x49, 0x98, 0x62, 0x56, 0x15, 0xb6, - 0x03, 0xa0, 0x33, 0xac, 0xa1, 0x3f, 0xb8, 0x94, - 0xbe, 0x91, 0x12, 0xa5, 0xc3, 0xa2, 0x11, 0xa8, - 0xba, 0x26, 0x2a, 0x3c, 0xca, 0x7e, 0x2c, 0xa7, - 0x01, 0xe4, 0xa9, 0xa4, 0xfb, 0xa4, 0x3c, 0x90, - 0xcc, 0xdc, 0xb2, 0x81, 0xd4, 0x8c, 0x7c, 0x6f, - 0xd6, 0x28, 0x75, 0xd2, 0xac, 0xa4, 0x17, 0x03, - 0x4c, 0x34, 0xae, 0xe5 -}; - -static const u8 T6[] = { - 0x61, 0x9c, 0xc5, 0xae, 0xff, 0xfe, 0x0b, 0xfa, - 0x46, 0x2a, 0xf4, 0x3c, 0x16, 0x99, 0xd0, 0x50 -}; - -/* Test Case 7 */ -static const u8 K7[24], *P7 = NULL, *A7 = NULL, IV7[12], *C7 = NULL; -static const u8 T7[] = { - 0xcd, 0x33, 0xb2, 0x8a, 0xc7, 0x73, 0xf7, 0x4b, - 0xa0, 0x0e, 0xd1, 0xf3, 0x12, 0x57, 0x24, 0x35 -}; - -/* Test Case 8 */ -# define K8 K7 -# define IV8 IV7 -# define A8 A7 -static const u8 P8[16]; -static const u8 C8[] = { - 0x98, 0xe7, 0x24, 0x7c, 0x07, 0xf0, 0xfe, 0x41, - 0x1c, 0x26, 0x7e, 0x43, 0x84, 0xb0, 0xf6, 0x00 -}; - -static const u8 T8[] = { - 0x2f, 0xf5, 0x8d, 0x80, 0x03, 0x39, 0x27, 0xab, - 0x8e, 0xf4, 0xd4, 0x58, 0x75, 0x14, 0xf0, 0xfb -}; - -/* Test Case 9 */ -# define A9 A8 -static const u8 K9[] = { - 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, - 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08, - 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c -}; - -static const u8 P9[] = { - 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, - 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, - 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, - 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, - 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, - 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, - 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, - 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55 -}; - -static const u8 IV9[] = { - 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, - 0xde, 0xca, 0xf8, 0x88 -}; - -static const u8 C9[] = { - 0x39, 0x80, 0xca, 0x0b, 0x3c, 0x00, 0xe8, 0x41, - 0xeb, 0x06, 0xfa, 0xc4, 0x87, 0x2a, 0x27, 0x57, - 0x85, 0x9e, 0x1c, 0xea, 0xa6, 0xef, 0xd9, 0x84, - 0x62, 0x85, 0x93, 0xb4, 0x0c, 0xa1, 0xe1, 0x9c, - 0x7d, 0x77, 0x3d, 0x00, 0xc1, 0x44, 0xc5, 0x25, - 0xac, 0x61, 0x9d, 0x18, 0xc8, 0x4a, 0x3f, 0x47, - 0x18, 0xe2, 0x44, 0x8b, 0x2f, 0xe3, 0x24, 0xd9, - 0xcc, 0xda, 0x27, 0x10, 0xac, 0xad, 0xe2, 0x56 -}; - -static const u8 T9[] = { - 0x99, 0x24, 0xa7, 0xc8, 0x58, 0x73, 0x36, 0xbf, - 0xb1, 0x18, 0x02, 0x4d, 0xb8, 0x67, 0x4a, 0x14 -}; - -/* Test Case 10 */ -# define K10 K9 -# define IV10 IV9 -static const u8 P10[] = { - 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, - 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, - 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, - 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, - 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, - 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, - 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, - 0xba, 0x63, 0x7b, 0x39 -}; - -static const u8 A10[] = { - 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, - 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, - 0xab, 0xad, 0xda, 0xd2 -}; - -static const u8 C10[] = { - 0x39, 0x80, 0xca, 0x0b, 0x3c, 0x00, 0xe8, 0x41, - 0xeb, 0x06, 0xfa, 0xc4, 0x87, 0x2a, 0x27, 0x57, - 0x85, 0x9e, 0x1c, 0xea, 0xa6, 0xef, 0xd9, 0x84, - 0x62, 0x85, 0x93, 0xb4, 0x0c, 0xa1, 0xe1, 0x9c, - 0x7d, 0x77, 0x3d, 0x00, 0xc1, 0x44, 0xc5, 0x25, - 0xac, 0x61, 0x9d, 0x18, 0xc8, 0x4a, 0x3f, 0x47, - 0x18, 0xe2, 0x44, 0x8b, 0x2f, 0xe3, 0x24, 0xd9, - 0xcc, 0xda, 0x27, 0x10 -}; - -static const u8 T10[] = { - 0x25, 0x19, 0x49, 0x8e, 0x80, 0xf1, 0x47, 0x8f, - 0x37, 0xba, 0x55, 0xbd, 0x6d, 0x27, 0x61, 0x8c -}; - -/* Test Case 11 */ -# define K11 K10 -# define P11 P10 -# define A11 A10 -static const u8 IV11[] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad }; - -static const u8 C11[] = { - 0x0f, 0x10, 0xf5, 0x99, 0xae, 0x14, 0xa1, 0x54, - 0xed, 0x24, 0xb3, 0x6e, 0x25, 0x32, 0x4d, 0xb8, - 0xc5, 0x66, 0x63, 0x2e, 0xf2, 0xbb, 0xb3, 0x4f, - 0x83, 0x47, 0x28, 0x0f, 0xc4, 0x50, 0x70, 0x57, - 0xfd, 0xdc, 0x29, 0xdf, 0x9a, 0x47, 0x1f, 0x75, - 0xc6, 0x65, 0x41, 0xd4, 0xd4, 0xda, 0xd1, 0xc9, - 0xe9, 0x3a, 0x19, 0xa5, 0x8e, 0x8b, 0x47, 0x3f, - 0xa0, 0xf0, 0x62, 0xf7 -}; - -static const u8 T11[] = { - 0x65, 0xdc, 0xc5, 0x7f, 0xcf, 0x62, 0x3a, 0x24, - 0x09, 0x4f, 0xcc, 0xa4, 0x0d, 0x35, 0x33, 0xf8 -}; - -/* Test Case 12 */ -# define K12 K11 -# define P12 P11 -# define A12 A11 -static const u8 IV12[] = { - 0x93, 0x13, 0x22, 0x5d, 0xf8, 0x84, 0x06, 0xe5, - 0x55, 0x90, 0x9c, 0x5a, 0xff, 0x52, 0x69, 0xaa, - 0x6a, 0x7a, 0x95, 0x38, 0x53, 0x4f, 0x7d, 0xa1, - 0xe4, 0xc3, 0x03, 0xd2, 0xa3, 0x18, 0xa7, 0x28, - 0xc3, 0xc0, 0xc9, 0x51, 0x56, 0x80, 0x95, 0x39, - 0xfc, 0xf0, 0xe2, 0x42, 0x9a, 0x6b, 0x52, 0x54, - 0x16, 0xae, 0xdb, 0xf5, 0xa0, 0xde, 0x6a, 0x57, - 0xa6, 0x37, 0xb3, 0x9b -}; - -static const u8 C12[] = { - 0xd2, 0x7e, 0x88, 0x68, 0x1c, 0xe3, 0x24, 0x3c, - 0x48, 0x30, 0x16, 0x5a, 0x8f, 0xdc, 0xf9, 0xff, - 0x1d, 0xe9, 0xa1, 0xd8, 0xe6, 0xb4, 0x47, 0xef, - 0x6e, 0xf7, 0xb7, 0x98, 0x28, 0x66, 0x6e, 0x45, - 0x81, 0xe7, 0x90, 0x12, 0xaf, 0x34, 0xdd, 0xd9, - 0xe2, 0xf0, 0x37, 0x58, 0x9b, 0x29, 0x2d, 0xb3, - 0xe6, 0x7c, 0x03, 0x67, 0x45, 0xfa, 0x22, 0xe7, - 0xe9, 0xb7, 0x37, 0x3b -}; - -static const u8 T12[] = { - 0xdc, 0xf5, 0x66, 0xff, 0x29, 0x1c, 0x25, 0xbb, - 0xb8, 0x56, 0x8f, 0xc3, 0xd3, 0x76, 0xa6, 0xd9 -}; - -/* Test Case 13 */ -static const u8 K13[32], *P13 = NULL, *A13 = NULL, IV13[12], *C13 = NULL; -static const u8 T13[] = { - 0x53, 0x0f, 0x8a, 0xfb, 0xc7, 0x45, 0x36, 0xb9, - 0xa9, 0x63, 0xb4, 0xf1, 0xc4, 0xcb, 0x73, 0x8b -}; - -/* Test Case 14 */ -# define K14 K13 -# define A14 A13 -static const u8 P14[16], IV14[12]; -static const u8 C14[] = { - 0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e, - 0x07, 0x4e, 0xc5, 0xd3, 0xba, 0xf3, 0x9d, 0x18 -}; - -static const u8 T14[] = { - 0xd0, 0xd1, 0xc8, 0xa7, 0x99, 0x99, 0x6b, 0xf0, - 0x26, 0x5b, 0x98, 0xb5, 0xd4, 0x8a, 0xb9, 0x19 -}; - -/* Test Case 15 */ -# define A15 A14 -static const u8 K15[] = { - 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, - 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08, - 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, - 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08 -}; - -static const u8 P15[] = { - 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, - 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, - 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, - 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, - 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, - 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, - 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, - 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55 -}; - -static const u8 IV15[] = { - 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, - 0xde, 0xca, 0xf8, 0x88 -}; - -static const u8 C15[] = { - 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, - 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d, - 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, - 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, - 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, - 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, - 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, - 0xbc, 0xc9, 0xf6, 0x62, 0x89, 0x80, 0x15, 0xad -}; - -static const u8 T15[] = { - 0xb0, 0x94, 0xda, 0xc5, 0xd9, 0x34, 0x71, 0xbd, - 0xec, 0x1a, 0x50, 0x22, 0x70, 0xe3, 0xcc, 0x6c -}; - -/* Test Case 16 */ -# define K16 K15 -# define IV16 IV15 -static const u8 P16[] = { - 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, - 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, - 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, - 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, - 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, - 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, - 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, - 0xba, 0x63, 0x7b, 0x39 -}; - -static const u8 A16[] = { - 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, - 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, - 0xab, 0xad, 0xda, 0xd2 -}; - -static const u8 C16[] = { - 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, - 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d, - 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, - 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, - 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, - 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, - 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, - 0xbc, 0xc9, 0xf6, 0x62 -}; - -static const u8 T16[] = { - 0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68, - 0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b -}; - -/* Test Case 17 */ -# define K17 K16 -# define P17 P16 -# define A17 A16 -static const u8 IV17[] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad }; - -static const u8 C17[] = { - 0xc3, 0x76, 0x2d, 0xf1, 0xca, 0x78, 0x7d, 0x32, - 0xae, 0x47, 0xc1, 0x3b, 0xf1, 0x98, 0x44, 0xcb, - 0xaf, 0x1a, 0xe1, 0x4d, 0x0b, 0x97, 0x6a, 0xfa, - 0xc5, 0x2f, 0xf7, 0xd7, 0x9b, 0xba, 0x9d, 0xe0, - 0xfe, 0xb5, 0x82, 0xd3, 0x39, 0x34, 0xa4, 0xf0, - 0x95, 0x4c, 0xc2, 0x36, 0x3b, 0xc7, 0x3f, 0x78, - 0x62, 0xac, 0x43, 0x0e, 0x64, 0xab, 0xe4, 0x99, - 0xf4, 0x7c, 0x9b, 0x1f -}; - -static const u8 T17[] = { - 0x3a, 0x33, 0x7d, 0xbf, 0x46, 0xa7, 0x92, 0xc4, - 0x5e, 0x45, 0x49, 0x13, 0xfe, 0x2e, 0xa8, 0xf2 -}; - -/* Test Case 18 */ -# define K18 K17 -# define P18 P17 -# define A18 A17 -static const u8 IV18[] = { - 0x93, 0x13, 0x22, 0x5d, 0xf8, 0x84, 0x06, 0xe5, - 0x55, 0x90, 0x9c, 0x5a, 0xff, 0x52, 0x69, 0xaa, - 0x6a, 0x7a, 0x95, 0x38, 0x53, 0x4f, 0x7d, 0xa1, - 0xe4, 0xc3, 0x03, 0xd2, 0xa3, 0x18, 0xa7, 0x28, - 0xc3, 0xc0, 0xc9, 0x51, 0x56, 0x80, 0x95, 0x39, - 0xfc, 0xf0, 0xe2, 0x42, 0x9a, 0x6b, 0x52, 0x54, - 0x16, 0xae, 0xdb, 0xf5, 0xa0, 0xde, 0x6a, 0x57, - 0xa6, 0x37, 0xb3, 0x9b -}; - -static const u8 C18[] = { - 0x5a, 0x8d, 0xef, 0x2f, 0x0c, 0x9e, 0x53, 0xf1, - 0xf7, 0x5d, 0x78, 0x53, 0x65, 0x9e, 0x2a, 0x20, - 0xee, 0xb2, 0xb2, 0x2a, 0xaf, 0xde, 0x64, 0x19, - 0xa0, 0x58, 0xab, 0x4f, 0x6f, 0x74, 0x6b, 0xf4, - 0x0f, 0xc0, 0xc3, 0xb7, 0x80, 0xf2, 0x44, 0x45, - 0x2d, 0xa3, 0xeb, 0xf1, 0xc5, 0xd8, 0x2c, 0xde, - 0xa2, 0x41, 0x89, 0x97, 0x20, 0x0e, 0xf8, 0x2e, - 0x44, 0xae, 0x7e, 0x3f -}; - -static const u8 T18[] = { - 0xa4, 0x4a, 0x82, 0x66, 0xee, 0x1c, 0x8e, 0xb0, - 0xc8, 0xb5, 0xd4, 0xcf, 0x5a, 0xe9, 0xf1, 0x9a -}; - -/* Test Case 19 */ -# define K19 K1 -# define P19 P1 -# define IV19 IV1 -# define C19 C1 -static const u8 A19[] = { - 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, - 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, - 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, - 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, - 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, - 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, - 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, - 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55, - 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, - 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d, - 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, - 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, - 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, - 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, - 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, - 0xbc, 0xc9, 0xf6, 0x62, 0x89, 0x80, 0x15, 0xad -}; - -static const u8 T19[] = { - 0x5f, 0xea, 0x79, 0x3a, 0x2d, 0x6f, 0x97, 0x4d, - 0x37, 0xe6, 0x8e, 0x0c, 0xb8, 0xff, 0x94, 0x92 -}; - -/* Test Case 20 */ -# define K20 K1 -# define A20 A1 -/* this results in 0xff in counter LSB */ -static const u8 IV20[64] = { 0xff, 0xff, 0xff, 0xff }; - -static const u8 P20[288]; -static const u8 C20[] = { - 0x56, 0xb3, 0x37, 0x3c, 0xa9, 0xef, 0x6e, 0x4a, - 0x2b, 0x64, 0xfe, 0x1e, 0x9a, 0x17, 0xb6, 0x14, - 0x25, 0xf1, 0x0d, 0x47, 0xa7, 0x5a, 0x5f, 0xce, - 0x13, 0xef, 0xc6, 0xbc, 0x78, 0x4a, 0xf2, 0x4f, - 0x41, 0x41, 0xbd, 0xd4, 0x8c, 0xf7, 0xc7, 0x70, - 0x88, 0x7a, 0xfd, 0x57, 0x3c, 0xca, 0x54, 0x18, - 0xa9, 0xae, 0xff, 0xcd, 0x7c, 0x5c, 0xed, 0xdf, - 0xc6, 0xa7, 0x83, 0x97, 0xb9, 0xa8, 0x5b, 0x49, - 0x9d, 0xa5, 0x58, 0x25, 0x72, 0x67, 0xca, 0xab, - 0x2a, 0xd0, 0xb2, 0x3c, 0xa4, 0x76, 0xa5, 0x3c, - 0xb1, 0x7f, 0xb4, 0x1c, 0x4b, 0x8b, 0x47, 0x5c, - 0xb4, 0xf3, 0xf7, 0x16, 0x50, 0x94, 0xc2, 0x29, - 0xc9, 0xe8, 0xc4, 0xdc, 0x0a, 0x2a, 0x5f, 0xf1, - 0x90, 0x3e, 0x50, 0x15, 0x11, 0x22, 0x13, 0x76, - 0xa1, 0xcd, 0xb8, 0x36, 0x4c, 0x50, 0x61, 0xa2, - 0x0c, 0xae, 0x74, 0xbc, 0x4a, 0xcd, 0x76, 0xce, - 0xb0, 0xab, 0xc9, 0xfd, 0x32, 0x17, 0xef, 0x9f, - 0x8c, 0x90, 0xbe, 0x40, 0x2d, 0xdf, 0x6d, 0x86, - 0x97, 0xf4, 0xf8, 0x80, 0xdf, 0xf1, 0x5b, 0xfb, - 0x7a, 0x6b, 0x28, 0x24, 0x1e, 0xc8, 0xfe, 0x18, - 0x3c, 0x2d, 0x59, 0xe3, 0xf9, 0xdf, 0xff, 0x65, - 0x3c, 0x71, 0x26, 0xf0, 0xac, 0xb9, 0xe6, 0x42, - 0x11, 0xf4, 0x2b, 0xae, 0x12, 0xaf, 0x46, 0x2b, - 0x10, 0x70, 0xbe, 0xf1, 0xab, 0x5e, 0x36, 0x06, - 0x87, 0x2c, 0xa1, 0x0d, 0xee, 0x15, 0xb3, 0x24, - 0x9b, 0x1a, 0x1b, 0x95, 0x8f, 0x23, 0x13, 0x4c, - 0x4b, 0xcc, 0xb7, 0xd0, 0x32, 0x00, 0xbc, 0xe4, - 0x20, 0xa2, 0xf8, 0xeb, 0x66, 0xdc, 0xf3, 0x64, - 0x4d, 0x14, 0x23, 0xc1, 0xb5, 0x69, 0x90, 0x03, - 0xc1, 0x3e, 0xce, 0xf4, 0xbf, 0x38, 0xa3, 0xb6, - 0x0e, 0xed, 0xc3, 0x40, 0x33, 0xba, 0xc1, 0x90, - 0x27, 0x83, 0xdc, 0x6d, 0x89, 0xe2, 0xe7, 0x74, - 0x18, 0x8a, 0x43, 0x9c, 0x7e, 0xbc, 0xc0, 0x67, - 0x2d, 0xbd, 0xa4, 0xdd, 0xcf, 0xb2, 0x79, 0x46, - 0x13, 0xb0, 0xbe, 0x41, 0x31, 0x5e, 0xf7, 0x78, - 0x70, 0x8a, 0x70, 0xee, 0x7d, 0x75, 0x16, 0x5c -}; - -static const u8 T20[] = { - 0x8b, 0x30, 0x7f, 0x6b, 0x33, 0x28, 0x6d, 0x0a, - 0xb0, 0x26, 0xa9, 0xed, 0x3f, 0xe1, 0xe8, 0x5f -}; - -# define TEST_CASE(n) do { \ - u8 out[sizeof(P##n)]; \ - AES_set_encrypt_key(K##n,sizeof(K##n)*8,&key); \ - CRYPTO_gcm128_init(&ctx,&key,(block128_f)AES_encrypt); \ - CRYPTO_gcm128_setiv(&ctx,IV##n,sizeof(IV##n)); \ - memset(out,0,sizeof(out)); \ - if (A##n) CRYPTO_gcm128_aad(&ctx,A##n,sizeof(A##n)); \ - if (P##n) CRYPTO_gcm128_encrypt(&ctx,P##n,out,sizeof(out)); \ - if (CRYPTO_gcm128_finish(&ctx,T##n,16) || \ - (C##n && memcmp(out,C##n,sizeof(out)))) \ - ret++, printf ("encrypt test#%d failed.\n",n); \ - CRYPTO_gcm128_setiv(&ctx,IV##n,sizeof(IV##n)); \ - memset(out,0,sizeof(out)); \ - if (A##n) CRYPTO_gcm128_aad(&ctx,A##n,sizeof(A##n)); \ - if (C##n) CRYPTO_gcm128_decrypt(&ctx,C##n,out,sizeof(out)); \ - if (CRYPTO_gcm128_finish(&ctx,T##n,16) || \ - (P##n && memcmp(out,P##n,sizeof(out)))) \ - ret++, printf ("decrypt test#%d failed.\n",n); \ - } while(0) - -int main() -{ - GCM128_CONTEXT ctx; - AES_KEY key; - int ret = 0; - - TEST_CASE(1); - TEST_CASE(2); - TEST_CASE(3); - TEST_CASE(4); - TEST_CASE(5); - TEST_CASE(6); - TEST_CASE(7); - TEST_CASE(8); - TEST_CASE(9); - TEST_CASE(10); - TEST_CASE(11); - TEST_CASE(12); - TEST_CASE(13); - TEST_CASE(14); - TEST_CASE(15); - TEST_CASE(16); - TEST_CASE(17); - TEST_CASE(18); - TEST_CASE(19); - TEST_CASE(20); - -# ifdef OPENSSL_CPUID_OBJ - { - size_t start, stop, gcm_t, ctr_t, OPENSSL_rdtsc(); - union { - u64 u; - u8 c[1024]; - } buf; - int i; - - AES_set_encrypt_key(K1, sizeof(K1) * 8, &key); - CRYPTO_gcm128_init(&ctx, &key, (block128_f) AES_encrypt); - CRYPTO_gcm128_setiv(&ctx, IV1, sizeof(IV1)); - - CRYPTO_gcm128_encrypt(&ctx, buf.c, buf.c, sizeof(buf)); - start = OPENSSL_rdtsc(); - CRYPTO_gcm128_encrypt(&ctx, buf.c, buf.c, sizeof(buf)); - gcm_t = OPENSSL_rdtsc() - start; - - CRYPTO_ctr128_encrypt(buf.c, buf.c, sizeof(buf), - &key, ctx.Yi.c, ctx.EKi.c, &ctx.mres, - (block128_f) AES_encrypt); - start = OPENSSL_rdtsc(); - CRYPTO_ctr128_encrypt(buf.c, buf.c, sizeof(buf), - &key, ctx.Yi.c, ctx.EKi.c, &ctx.mres, - (block128_f) AES_encrypt); - ctr_t = OPENSSL_rdtsc() - start; - - printf("%.2f-%.2f=%.2f\n", - gcm_t / (double)sizeof(buf), - ctr_t / (double)sizeof(buf), - (gcm_t - ctr_t) / (double)sizeof(buf)); -# ifdef GHASH - { - void (*gcm_ghash_p) (u64 Xi[2], const u128 Htable[16], - const u8 *inp, size_t len) = ctx.ghash; - - GHASH((&ctx), buf.c, sizeof(buf)); - start = OPENSSL_rdtsc(); - for (i = 0; i < 100; ++i) - GHASH((&ctx), buf.c, sizeof(buf)); - gcm_t = OPENSSL_rdtsc() - start; - printf("%.2f\n", gcm_t / (double)sizeof(buf) / (double)i); - } -# endif - } -# endif - - return ret; -} -#endif diff --git a/crypto/modes/modes_lcl.h b/crypto/modes/modes_lcl.h index 7a1603bf..16dcf4e1 100644 --- a/crypto/modes/modes_lcl.h +++ b/crypto/modes/modes_lcl.h @@ -1,5 +1,5 @@ /* - * Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2010-2018 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 @@ -73,6 +73,7 @@ typedef unsigned char u8; # endif # elif defined(_MSC_VER) # if _MSC_VER>=1300 +# include # pragma intrinsic(_byteswap_uint64,_byteswap_ulong) # define BSWAP8(x) _byteswap_uint64((u64)(x)) # define BSWAP4(x) _byteswap_ulong((u32)(x)) diff --git a/crypto/o_dir.c b/crypto/o_dir.c index 7019383d..fca9c75e 100644 --- a/crypto/o_dir.c +++ b/crypto/o_dir.c @@ -7,8 +7,8 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" #include -#include /* * The routines really come from the Levitte Programming, so to make life diff --git a/crypto/o_fips.c b/crypto/o_fips.c index bf6db65f..050ea9c2 100644 --- a/crypto/o_fips.c +++ b/crypto/o_fips.c @@ -8,27 +8,17 @@ */ #include "internal/cryptlib.h" -#ifdef OPENSSL_FIPS -# include -#endif int FIPS_mode(void) { -#ifdef OPENSSL_FIPS - return FIPS_module_mode(); -#else + /* This version of the library does not support FIPS mode. */ return 0; -#endif } int FIPS_mode_set(int r) { -#ifdef OPENSSL_FIPS - return FIPS_module_mode_set(r); -#else if (r == 0) return 1; CRYPTOerr(CRYPTO_F_FIPS_MODE_SET, CRYPTO_R_FIPS_MODE_NOT_SUPPORTED); return 0; -#endif } diff --git a/crypto/o_init.c b/crypto/o_init.c index 2e0c1260..ed6b1303 100644 --- a/crypto/o_init.c +++ b/crypto/o_init.c @@ -7,28 +7,15 @@ * https://www.openssl.org/source/license.html */ -#include +#include "e_os.h" #include -#ifdef OPENSSL_FIPS -# include -# include -#endif /* - * Perform any essential OpenSSL initialization operations. Currently only - * sets FIPS callbacks + * Perform any essential OpenSSL initialization operations. Currently does + * nothing. */ 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); - FIPS_set_error_callbacks(ERR_put_error, ERR_add_error_vdata); - FIPS_set_malloc_callbacks(CRYPTO_malloc, CRYPTO_free); - RAND_init_fips(); -#endif + return; } diff --git a/crypto/o_str.c b/crypto/o_str.c index 528655aa..a8357691 100644 --- a/crypto/o_str.c +++ b/crypto/o_str.c @@ -1,5 +1,5 @@ /* - * Copyright 2003-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2003-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 @@ -7,9 +7,8 @@ * https://www.openssl.org/source/license.html */ -#include +#include "e_os.h" #include -#include #include #include "internal/cryptlib.h" #include "internal/o_str.h" @@ -28,14 +27,12 @@ int OPENSSL_memcmp(const void *v1, const void *v2, size_t n) char *CRYPTO_strdup(const char *str, const char* file, int line) { char *ret; - size_t size; if (str == NULL) return NULL; - size = strlen(str) + 1; - ret = CRYPTO_malloc(size, file, line); + ret = CRYPTO_malloc(strlen(str) + 1, file, line); if (ret != NULL) - memcpy(ret, str, size); + strcpy(ret, str); return ret; } diff --git a/crypto/objects/README b/crypto/objects/README index cb1d216c..700f9c5e 100644 --- a/crypto/objects/README +++ b/crypto/objects/README @@ -16,7 +16,7 @@ The basic syntax for adding an object is as follows: create the C macros SN_base, LN_base, NID_base and OBJ_base. Note that if the base name contains spaces, dashes or periods, - those will be converte to underscore. + those will be converted to underscore. Then there are some extra commands: diff --git a/crypto/objects/o_names.c b/crypto/objects/o_names.c index 15fe653d..8f7bc793 100644 --- a/crypto/objects/o_names.c +++ b/crypto/objects/o_names.c @@ -1,5 +1,5 @@ /* - * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1998-2018 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 @@ -16,7 +16,7 @@ #include #include #include -#include +#include "internal/thread_once.h" #include "obj_lcl.h" /* @@ -45,7 +45,7 @@ static int obj_strcmp(const char *a, const char *b) */ static LHASH_OF(OBJ_NAME) *names_lh = NULL; static int names_type_num = OBJ_NAME_TYPE_NUM; -static CRYPTO_RWLOCK *lock = NULL; +static CRYPTO_RWLOCK *obj_lock = NULL; struct name_funcs_st { unsigned long (*hash_func) (const char *name); @@ -69,9 +69,9 @@ DEFINE_RUN_ONCE_STATIC(o_names_init) { CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE); names_lh = lh_OBJ_NAME_new(obj_name_hash, obj_name_cmp); - lock = CRYPTO_THREAD_lock_new(); + obj_lock = CRYPTO_THREAD_lock_new(); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE); - return names_lh != NULL && lock != NULL; + return names_lh != NULL && obj_lock != NULL; } int OBJ_NAME_init(void) @@ -89,7 +89,7 @@ int OBJ_NAME_new_index(unsigned long (*hash_func) (const char *), if (!OBJ_NAME_init()) return 0; - CRYPTO_THREAD_write_lock(lock); + CRYPTO_THREAD_write_lock(obj_lock); if (name_funcs_stack == NULL) { CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE); @@ -134,7 +134,7 @@ int OBJ_NAME_new_index(unsigned long (*hash_func) (const char *), name_funcs->free_func = free_func; out: - CRYPTO_THREAD_unlock(lock); + CRYPTO_THREAD_unlock(obj_lock); return ret; } @@ -180,7 +180,7 @@ const char *OBJ_NAME_get(const char *name, int type) return NULL; if (!OBJ_NAME_init()) return NULL; - CRYPTO_THREAD_read_lock(lock); + CRYPTO_THREAD_read_lock(obj_lock); alias = type & OBJ_NAME_ALIAS; type &= ~OBJ_NAME_ALIAS; @@ -202,7 +202,7 @@ const char *OBJ_NAME_get(const char *name, int type) } } - CRYPTO_THREAD_unlock(lock); + CRYPTO_THREAD_unlock(obj_lock); return value; } @@ -212,9 +212,9 @@ int OBJ_NAME_add(const char *name, int type, const char *data) int alias, ok = 0; if (!OBJ_NAME_init()) - return 0; + return 0; - CRYPTO_THREAD_write_lock(lock); + CRYPTO_THREAD_write_lock(obj_lock); alias = type & OBJ_NAME_ALIAS; type &= ~OBJ_NAME_ALIAS; @@ -255,7 +255,7 @@ int OBJ_NAME_add(const char *name, int type, const char *data) ok = 1; unlock: - CRYPTO_THREAD_unlock(lock); + CRYPTO_THREAD_unlock(obj_lock); return ok; } @@ -267,7 +267,7 @@ int OBJ_NAME_remove(const char *name, int type) if (!OBJ_NAME_init()) return 0; - CRYPTO_THREAD_write_lock(lock); + CRYPTO_THREAD_write_lock(obj_lock); type &= ~OBJ_NAME_ALIAS; on.name = name; @@ -289,7 +289,7 @@ int OBJ_NAME_remove(const char *name, int type) ok = 1; } - CRYPTO_THREAD_unlock(lock); + CRYPTO_THREAD_unlock(obj_lock); return ok; } @@ -398,10 +398,10 @@ void OBJ_NAME_cleanup(int type) if (type < 0) { lh_OBJ_NAME_free(names_lh); sk_NAME_FUNCS_pop_free(name_funcs_stack, name_funcs_free); - CRYPTO_THREAD_lock_free(lock); + CRYPTO_THREAD_lock_free(obj_lock); names_lh = NULL; name_funcs_stack = NULL; - lock = NULL; + obj_lock = NULL; } else lh_OBJ_NAME_set_down_load(names_lh, down_load); } diff --git a/crypto/objects/obj_dat.c b/crypto/objects/obj_dat.c index 21a1f05b..06a3fb34 100644 --- a/crypto/objects/obj_dat.c +++ b/crypto/objects/obj_dat.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,7 +8,7 @@ */ #include -#include +#include "internal/ctype.h" #include #include "internal/cryptlib.h" #include @@ -40,14 +40,14 @@ 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)); + 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)); + return strcmp((*a)->ln, nid_objs[*b].ln); } IMPLEMENT_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, ln); @@ -82,7 +82,7 @@ static unsigned long added_obj_hash(const ADDED_OBJ *ca) } ret &= 0x3fffffffL; ret |= ((unsigned long)ca->type) << 30L; - return (ret); + return ret; } static int added_obj_cmp(const ADDED_OBJ *ca, const ADDED_OBJ *cb) @@ -92,31 +92,31 @@ static int added_obj_cmp(const ADDED_OBJ *ca, const ADDED_OBJ *cb) i = ca->type - cb->type; if (i) - return (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)); + return i; + return memcmp(a->data, b->data, (size_t)a->length); case ADDED_SNAME: if (a->sn == NULL) - return (-1); + return -1; else if (b->sn == NULL) - return (1); + return 1; else - return (strcmp(a->sn, b->sn)); + return strcmp(a->sn, b->sn); case ADDED_LNAME: if (a->ln == NULL) - return (-1); + return -1; else if (b->ln == NULL) - return (1); + return 1; else - return (strcmp(a->ln, b->ln)); + return strcmp(a->ln, b->ln); case ADDED_NID: - return (a->nid - b->nid); + return a->nid - b->nid; default: /* abort(); */ return 0; @@ -126,9 +126,9 @@ static int added_obj_cmp(const ADDED_OBJ *ca, const ADDED_OBJ *cb) static int init_added(void) { if (added != NULL) - return (1); + return 1; added = lh_ADDED_OBJ_new(added_obj_hash, added_obj_cmp); - return (added != NULL); + return added != NULL; } static void cleanup1_doall(ADDED_OBJ *a) @@ -168,7 +168,7 @@ int OBJ_new_nid(int num) i = new_nid; new_nid += num; - return (i); + return i; } int OBJ_add_object(const ASN1_OBJECT *obj) @@ -179,7 +179,7 @@ int OBJ_add_object(const ASN1_OBJECT *obj) if (added == NULL) if (!init_added()) - return (0); + return 0; if ((o = OBJ_dup(obj)) == NULL) goto err; if ((ao[ADDED_NID] = OPENSSL_malloc(sizeof(*ao[0]))) == NULL) @@ -207,13 +207,13 @@ int OBJ_add_object(const ASN1_OBJECT *obj) ~(ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS | ASN1_OBJECT_FLAG_DYNAMIC_DATA); - return (o->nid); + return o->nid; err2: OBJerr(OBJ_F_OBJ_ADD_OBJECT, ERR_R_MALLOC_FAILURE); err: for (i = ADDED_DATA; i <= ADDED_NID; i++) OPENSSL_free(ao[i]); - ASN1_OBJECT_free(o); + OPENSSL_free(o); return NID_undef; } @@ -225,21 +225,21 @@ ASN1_OBJECT *OBJ_nid2obj(int n) 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 NULL; } - return ((ASN1_OBJECT *)&(nid_objs[n])); + return (ASN1_OBJECT *)&(nid_objs[n]); } else if (added == NULL) - return (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); + return adp->obj; else { OBJerr(OBJ_F_OBJ_NID2OBJ, OBJ_R_UNKNOWN_NID); - return (NULL); + return NULL; } } } @@ -252,21 +252,21 @@ const char *OBJ_nid2sn(int n) 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 NULL; } - return (nid_objs[n].sn); + return nid_objs[n].sn; } else if (added == NULL) - return (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); + return adp->obj->sn; else { OBJerr(OBJ_F_OBJ_NID2SN, OBJ_R_UNKNOWN_NID); - return (NULL); + return NULL; } } } @@ -279,21 +279,21 @@ const char *OBJ_nid2ln(int n) 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 NULL; } - return (nid_objs[n].ln); + return nid_objs[n].ln; } else if (added == NULL) - return (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); + return adp->obj->ln; else { OBJerr(OBJ_F_OBJ_NID2LN, OBJ_R_UNKNOWN_NID); - return (NULL); + return NULL; } } } @@ -306,10 +306,10 @@ static int obj_cmp(const ASN1_OBJECT *const *ap, const unsigned int *bp) j = (a->length - b->length); if (j) - return (j); + return j; if (a->length == 0) return 0; - return (memcmp(a->data, b->data, a->length)); + return memcmp(a->data, b->data, a->length); } IMPLEMENT_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, obj); @@ -320,9 +320,9 @@ int OBJ_obj2nid(const ASN1_OBJECT *a) ADDED_OBJ ad, *adp; if (a == NULL) - return (NID_undef); + return NID_undef; if (a->nid != 0) - return (a->nid); + return a->nid; if (a->length == 0) return NID_undef; @@ -332,12 +332,12 @@ int OBJ_obj2nid(const ASN1_OBJECT *a) ad.obj = (ASN1_OBJECT *)a; /* XXX: ugly but harmless */ adp = lh_ADDED_OBJ_retrieve(added, &ad); if (adp != NULL) - return (adp->obj->nid); + return adp->obj->nid; } op = OBJ_bsearch_obj(&a, obj_objs, NUM_OBJ); if (op == NULL) - return (NID_undef); - return (nid_objs[*op].nid); + return NID_undef; + return nid_objs[*op].nid; } /* @@ -404,7 +404,7 @@ int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name) buf[0] = '\0'; if ((a == NULL) || (a->data == NULL)) - return (0); + return 0; if (!no_name && (nid = OBJ_obj2nid(a)) != NID_undef) { const char *s; @@ -548,12 +548,12 @@ int OBJ_ln2nid(const char *s) ad.obj = &o; adp = lh_ADDED_OBJ_retrieve(added, &ad); if (adp != NULL) - return (adp->obj->nid); + return adp->obj->nid; } op = OBJ_bsearch_ln(&oo, ln_objs, NUM_LN); if (op == NULL) - return (NID_undef); - return (nid_objs[*op].nid); + return NID_undef; + return nid_objs[*op].nid; } int OBJ_sn2nid(const char *s) @@ -569,12 +569,12 @@ int OBJ_sn2nid(const char *s) ad.obj = &o; adp = lh_ADDED_OBJ_retrieve(added, &ad); if (adp != NULL) - return (adp->obj->nid); + return adp->obj->nid; } op = OBJ_bsearch_sn(&oo, sn_objs, NUM_SN); if (op == NULL) - return (NID_undef); - return (nid_objs[*op].nid); + return NID_undef; + return nid_objs[*op].nid; } const void *OBJ_bsearch_(const void *key, const void *base, int num, int size, @@ -593,7 +593,7 @@ const void *OBJ_bsearch_ex_(const void *key, const void *base_, int num, const char *p = NULL; if (num == 0) - return (NULL); + return NULL; l = 0; h = num; while (l < h) { @@ -629,7 +629,7 @@ const void *OBJ_bsearch_ex_(const void *key, const void *base_, int num, i--; p = &(base[i * size]); } - return (p); + return p; } /* @@ -646,26 +646,26 @@ int OBJ_create_objects(BIO *in) s = o = NULL; i = BIO_gets(in, buf, 512); if (i <= 0) - return (num); + return num; buf[i - 1] = '\0'; - if (!isalnum((unsigned char)buf[0])) - return (num); + if (!ossl_isalnum(buf[0])) + return num; o = s = buf; - while (isdigit((unsigned char)*s) || (*s == '.')) + while (ossl_isdigit(*s) || *s == '.') s++; if (*s != '\0') { *(s++) = '\0'; - while (isspace((unsigned char)*s)) + while (ossl_isspace(*s)) s++; if (*s == '\0') { s = NULL; } else { l = s; - while ((*l != '\0') && !isspace((unsigned char)*l)) + while (*l != '\0' && !ossl_isspace(*l)) l++; if (*l != '\0') { *(l++) = '\0'; - while (isspace((unsigned char)*l)) + while (ossl_isspace(*l)) l++; if (*l == '\0') { l = NULL; @@ -680,10 +680,9 @@ int OBJ_create_objects(BIO *in) if (*o == '\0') return num; if (!OBJ_create(o, s, l)) - return (num); + return num; num++; } - /* return(num); */ } int OBJ_create(const char *oid, const char *sn, const char *ln) diff --git a/crypto/objects/obj_dat.h b/crypto/objects/obj_dat.h index e1fc64f7..61b12bf0 100644 --- a/crypto/objects/obj_dat.h +++ b/crypto/objects/obj_dat.h @@ -2,7 +2,7 @@ * WARNING: do not edit! * Generated by crypto/objects/obj_dat.pl * - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -10,7 +10,7 @@ */ /* Serialized OID's */ -static const unsigned char so[6765] = { +static const unsigned char so[7342] = { 0x2A,0x86,0x48,0x86,0xF7,0x0D, /* [ 0] OBJ_rsadsi */ 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01, /* [ 6] OBJ_pkcs */ 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x02,0x02, /* [ 13] OBJ_md2 */ @@ -961,9 +961,80 @@ static const unsigned char so[6765] = { 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x09,0x10,0x01,0x13, /* [ 6731] OBJ_id_smime_ct_contentCollection */ 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x09,0x10,0x01,0x17, /* [ 6742] OBJ_id_smime_ct_authEnvelopedData */ 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x09,0x10,0x01,0x1C, /* [ 6753] OBJ_id_ct_xml */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x01, /* [ 6764] OBJ_aria_128_ecb */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x02, /* [ 6773] OBJ_aria_128_cbc */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x03, /* [ 6782] OBJ_aria_128_cfb128 */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x04, /* [ 6791] OBJ_aria_128_ofb128 */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x05, /* [ 6800] OBJ_aria_128_ctr */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x06, /* [ 6809] OBJ_aria_192_ecb */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x07, /* [ 6818] OBJ_aria_192_cbc */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x08, /* [ 6827] OBJ_aria_192_cfb128 */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x09, /* [ 6836] OBJ_aria_192_ofb128 */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x0A, /* [ 6845] OBJ_aria_192_ctr */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x0B, /* [ 6854] OBJ_aria_256_ecb */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x0C, /* [ 6863] OBJ_aria_256_cbc */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x0D, /* [ 6872] OBJ_aria_256_cfb128 */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x0E, /* [ 6881] OBJ_aria_256_ofb128 */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x0F, /* [ 6890] OBJ_aria_256_ctr */ + 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x09,0x10,0x02,0x2F, /* [ 6899] OBJ_id_smime_aa_signingCertificateV2 */ + 0x2B,0x65,0x70, /* [ 6910] OBJ_ED25519 */ + 0x2B,0x65,0x71, /* [ 6913] OBJ_ED448 */ + 0x55,0x04,0x61, /* [ 6916] OBJ_organizationIdentifier */ + 0x55,0x04,0x62, /* [ 6919] OBJ_countryCode3c */ + 0x55,0x04,0x63, /* [ 6922] OBJ_countryCode3n */ + 0x55,0x04,0x64, /* [ 6925] OBJ_dnsName */ + 0x2B,0x24,0x08,0x03,0x03, /* [ 6928] OBJ_x509ExtAdmission */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x05, /* [ 6933] OBJ_sha512_224 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x06, /* [ 6942] OBJ_sha512_256 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x07, /* [ 6951] OBJ_sha3_224 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x08, /* [ 6960] OBJ_sha3_256 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x09, /* [ 6969] OBJ_sha3_384 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0A, /* [ 6978] OBJ_sha3_512 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0B, /* [ 6987] OBJ_shake128 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0C, /* [ 6996] OBJ_shake256 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0D, /* [ 7005] OBJ_hmac_sha3_224 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0E, /* [ 7014] OBJ_hmac_sha3_256 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x0F, /* [ 7023] OBJ_hmac_sha3_384 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x02,0x10, /* [ 7032] OBJ_hmac_sha3_512 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x03, /* [ 7041] OBJ_dsa_with_SHA384 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x04, /* [ 7050] OBJ_dsa_with_SHA512 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x05, /* [ 7059] OBJ_dsa_with_SHA3_224 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x06, /* [ 7068] OBJ_dsa_with_SHA3_256 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x07, /* [ 7077] OBJ_dsa_with_SHA3_384 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x08, /* [ 7086] OBJ_dsa_with_SHA3_512 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x09, /* [ 7095] OBJ_ecdsa_with_SHA3_224 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0A, /* [ 7104] OBJ_ecdsa_with_SHA3_256 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0B, /* [ 7113] OBJ_ecdsa_with_SHA3_384 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0C, /* [ 7122] OBJ_ecdsa_with_SHA3_512 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0D, /* [ 7131] OBJ_RSA_SHA3_224 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0E, /* [ 7140] OBJ_RSA_SHA3_256 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x0F, /* [ 7149] OBJ_RSA_SHA3_384 */ + 0x60,0x86,0x48,0x01,0x65,0x03,0x04,0x03,0x10, /* [ 7158] OBJ_RSA_SHA3_512 */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x25, /* [ 7167] OBJ_aria_128_ccm */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x26, /* [ 7176] OBJ_aria_192_ccm */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x27, /* [ 7185] OBJ_aria_256_ccm */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x22, /* [ 7194] OBJ_aria_128_gcm */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x23, /* [ 7203] OBJ_aria_192_gcm */ + 0x2A,0x83,0x1A,0x8C,0x9A,0x6E,0x01,0x01,0x24, /* [ 7212] OBJ_aria_256_gcm */ + 0x2B,0x06,0x01,0x05,0x05,0x07,0x03,0x1B, /* [ 7221] OBJ_cmcCA */ + 0x2B,0x06,0x01,0x05,0x05,0x07,0x03,0x1C, /* [ 7229] OBJ_cmcRA */ + 0x2A,0x81,0x1C,0xCF,0x55,0x01,0x68,0x01, /* [ 7237] OBJ_sm4_ecb */ + 0x2A,0x81,0x1C,0xCF,0x55,0x01,0x68,0x02, /* [ 7245] OBJ_sm4_cbc */ + 0x2A,0x81,0x1C,0xCF,0x55,0x01,0x68,0x03, /* [ 7253] OBJ_sm4_ofb128 */ + 0x2A,0x81,0x1C,0xCF,0x55,0x01,0x68,0x05, /* [ 7261] OBJ_sm4_cfb1 */ + 0x2A,0x81,0x1C,0xCF,0x55,0x01,0x68,0x04, /* [ 7269] OBJ_sm4_cfb128 */ + 0x2A,0x81,0x1C,0xCF,0x55,0x01,0x68,0x06, /* [ 7277] OBJ_sm4_cfb8 */ + 0x2A,0x81,0x1C,0xCF,0x55,0x01,0x68,0x07, /* [ 7285] OBJ_sm4_ctr */ + 0x2A,0x81,0x1C, /* [ 7293] OBJ_ISO_CN */ + 0x2A,0x81,0x1C,0xCF,0x55, /* [ 7296] OBJ_oscca */ + 0x2A,0x81,0x1C,0xCF,0x55,0x01, /* [ 7301] OBJ_sm_scheme */ + 0x2A,0x81,0x1C,0xCF,0x55,0x01,0x83,0x11, /* [ 7307] OBJ_sm3 */ + 0x2A,0x81,0x1C,0xCF,0x55,0x01,0x83,0x78, /* [ 7315] OBJ_sm3WithRSAEncryption */ + 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0F, /* [ 7323] OBJ_sha512_224WithRSAEncryption */ + 0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x10, /* [ 7332] OBJ_sha512_256WithRSAEncryption */ }; -#define NUM_NID 1061 +#define NUM_NID 1147 static const ASN1_OBJECT nid_objs[NUM_NID] = { {"UNDEF", "undefined", NID_undef}, {"rsadsi", "RSA Data Security, Inc.", NID_rsadsi, 6, &so[0]}, @@ -1938,7 +2009,7 @@ static const ASN1_OBJECT nid_objs[NUM_NID] = { {"CAMELLIA-256-CCM", "camellia-256-ccm", NID_camellia_256_ccm, 8, &so[6330]}, {"CAMELLIA-256-CTR", "camellia-256-ctr", NID_camellia_256_ctr, 8, &so[6338]}, {"CAMELLIA-256-CMAC", "camellia-256-cmac", NID_camellia_256_cmac, 8, &so[6346]}, - {"id-scrypt", "id-scrypt", NID_id_scrypt, 9, &so[6354]}, + {"id-scrypt", "scrypt", NID_id_scrypt, 9, &so[6354]}, {"id-tc26", "id-tc26", NID_id_tc26, 5, &so[6363]}, {"gost89-cnt-12", "gost89-cnt-12", NID_gost89_cnt_12}, {"gost-mac-12", "gost-mac-12", NID_gost_mac_12}, @@ -2026,9 +2097,95 @@ static const ASN1_OBJECT nid_objs[NUM_NID] = { {"id-smime-ct-contentCollection", "id-smime-ct-contentCollection", NID_id_smime_ct_contentCollection, 11, &so[6731]}, {"id-smime-ct-authEnvelopedData", "id-smime-ct-authEnvelopedData", NID_id_smime_ct_authEnvelopedData, 11, &so[6742]}, {"id-ct-xml", "id-ct-xml", NID_id_ct_xml, 11, &so[6753]}, + {"Poly1305", "poly1305", NID_poly1305}, + {"SipHash", "siphash", NID_siphash}, + {"KxANY", "kx-any", NID_kx_any}, + {"AuthANY", "auth-any", NID_auth_any}, + {"ARIA-128-ECB", "aria-128-ecb", NID_aria_128_ecb, 9, &so[6764]}, + {"ARIA-128-CBC", "aria-128-cbc", NID_aria_128_cbc, 9, &so[6773]}, + {"ARIA-128-CFB", "aria-128-cfb", NID_aria_128_cfb128, 9, &so[6782]}, + {"ARIA-128-OFB", "aria-128-ofb", NID_aria_128_ofb128, 9, &so[6791]}, + {"ARIA-128-CTR", "aria-128-ctr", NID_aria_128_ctr, 9, &so[6800]}, + {"ARIA-192-ECB", "aria-192-ecb", NID_aria_192_ecb, 9, &so[6809]}, + {"ARIA-192-CBC", "aria-192-cbc", NID_aria_192_cbc, 9, &so[6818]}, + {"ARIA-192-CFB", "aria-192-cfb", NID_aria_192_cfb128, 9, &so[6827]}, + {"ARIA-192-OFB", "aria-192-ofb", NID_aria_192_ofb128, 9, &so[6836]}, + {"ARIA-192-CTR", "aria-192-ctr", NID_aria_192_ctr, 9, &so[6845]}, + {"ARIA-256-ECB", "aria-256-ecb", NID_aria_256_ecb, 9, &so[6854]}, + {"ARIA-256-CBC", "aria-256-cbc", NID_aria_256_cbc, 9, &so[6863]}, + {"ARIA-256-CFB", "aria-256-cfb", NID_aria_256_cfb128, 9, &so[6872]}, + {"ARIA-256-OFB", "aria-256-ofb", NID_aria_256_ofb128, 9, &so[6881]}, + {"ARIA-256-CTR", "aria-256-ctr", NID_aria_256_ctr, 9, &so[6890]}, + {"ARIA-128-CFB1", "aria-128-cfb1", NID_aria_128_cfb1}, + {"ARIA-192-CFB1", "aria-192-cfb1", NID_aria_192_cfb1}, + {"ARIA-256-CFB1", "aria-256-cfb1", NID_aria_256_cfb1}, + {"ARIA-128-CFB8", "aria-128-cfb8", NID_aria_128_cfb8}, + {"ARIA-192-CFB8", "aria-192-cfb8", NID_aria_192_cfb8}, + {"ARIA-256-CFB8", "aria-256-cfb8", NID_aria_256_cfb8}, + {"id-smime-aa-signingCertificateV2", "id-smime-aa-signingCertificateV2", NID_id_smime_aa_signingCertificateV2, 11, &so[6899]}, + {"ED25519", "ED25519", NID_ED25519, 3, &so[6910]}, + {"ED448", "ED448", NID_ED448, 3, &so[6913]}, + {"organizationIdentifier", "organizationIdentifier", NID_organizationIdentifier, 3, &so[6916]}, + {"c3", "countryCode3c", NID_countryCode3c, 3, &so[6919]}, + {"n3", "countryCode3n", NID_countryCode3n, 3, &so[6922]}, + {"dnsName", "dnsName", NID_dnsName, 3, &so[6925]}, + {"x509ExtAdmission", "Professional Information or basis for Admission", NID_x509ExtAdmission, 5, &so[6928]}, + {"SHA512-224", "sha512-224", NID_sha512_224, 9, &so[6933]}, + {"SHA512-256", "sha512-256", NID_sha512_256, 9, &so[6942]}, + {"SHA3-224", "sha3-224", NID_sha3_224, 9, &so[6951]}, + {"SHA3-256", "sha3-256", NID_sha3_256, 9, &so[6960]}, + {"SHA3-384", "sha3-384", NID_sha3_384, 9, &so[6969]}, + {"SHA3-512", "sha3-512", NID_sha3_512, 9, &so[6978]}, + {"SHAKE128", "shake128", NID_shake128, 9, &so[6987]}, + {"SHAKE256", "shake256", NID_shake256, 9, &so[6996]}, + {"id-hmacWithSHA3-224", "hmac-sha3-224", NID_hmac_sha3_224, 9, &so[7005]}, + {"id-hmacWithSHA3-256", "hmac-sha3-256", NID_hmac_sha3_256, 9, &so[7014]}, + {"id-hmacWithSHA3-384", "hmac-sha3-384", NID_hmac_sha3_384, 9, &so[7023]}, + {"id-hmacWithSHA3-512", "hmac-sha3-512", NID_hmac_sha3_512, 9, &so[7032]}, + {"id-dsa-with-sha384", "dsa_with_SHA384", NID_dsa_with_SHA384, 9, &so[7041]}, + {"id-dsa-with-sha512", "dsa_with_SHA512", NID_dsa_with_SHA512, 9, &so[7050]}, + {"id-dsa-with-sha3-224", "dsa_with_SHA3-224", NID_dsa_with_SHA3_224, 9, &so[7059]}, + {"id-dsa-with-sha3-256", "dsa_with_SHA3-256", NID_dsa_with_SHA3_256, 9, &so[7068]}, + {"id-dsa-with-sha3-384", "dsa_with_SHA3-384", NID_dsa_with_SHA3_384, 9, &so[7077]}, + {"id-dsa-with-sha3-512", "dsa_with_SHA3-512", NID_dsa_with_SHA3_512, 9, &so[7086]}, + {"id-ecdsa-with-sha3-224", "ecdsa_with_SHA3-224", NID_ecdsa_with_SHA3_224, 9, &so[7095]}, + {"id-ecdsa-with-sha3-256", "ecdsa_with_SHA3-256", NID_ecdsa_with_SHA3_256, 9, &so[7104]}, + {"id-ecdsa-with-sha3-384", "ecdsa_with_SHA3-384", NID_ecdsa_with_SHA3_384, 9, &so[7113]}, + {"id-ecdsa-with-sha3-512", "ecdsa_with_SHA3-512", NID_ecdsa_with_SHA3_512, 9, &so[7122]}, + {"id-rsassa-pkcs1-v1_5-with-sha3-224", "RSA-SHA3-224", NID_RSA_SHA3_224, 9, &so[7131]}, + {"id-rsassa-pkcs1-v1_5-with-sha3-256", "RSA-SHA3-256", NID_RSA_SHA3_256, 9, &so[7140]}, + {"id-rsassa-pkcs1-v1_5-with-sha3-384", "RSA-SHA3-384", NID_RSA_SHA3_384, 9, &so[7149]}, + {"id-rsassa-pkcs1-v1_5-with-sha3-512", "RSA-SHA3-512", NID_RSA_SHA3_512, 9, &so[7158]}, + {"ARIA-128-CCM", "aria-128-ccm", NID_aria_128_ccm, 9, &so[7167]}, + {"ARIA-192-CCM", "aria-192-ccm", NID_aria_192_ccm, 9, &so[7176]}, + {"ARIA-256-CCM", "aria-256-ccm", NID_aria_256_ccm, 9, &so[7185]}, + {"ARIA-128-GCM", "aria-128-gcm", NID_aria_128_gcm, 9, &so[7194]}, + {"ARIA-192-GCM", "aria-192-gcm", NID_aria_192_gcm, 9, &so[7203]}, + {"ARIA-256-GCM", "aria-256-gcm", NID_aria_256_gcm, 9, &so[7212]}, + {"ffdhe2048", "ffdhe2048", NID_ffdhe2048}, + {"ffdhe3072", "ffdhe3072", NID_ffdhe3072}, + {"ffdhe4096", "ffdhe4096", NID_ffdhe4096}, + {"ffdhe6144", "ffdhe6144", NID_ffdhe6144}, + {"ffdhe8192", "ffdhe8192", NID_ffdhe8192}, + {"cmcCA", "CMC Certificate Authority", NID_cmcCA, 8, &so[7221]}, + {"cmcRA", "CMC Registration Authority", NID_cmcRA, 8, &so[7229]}, + {"SM4-ECB", "sm4-ecb", NID_sm4_ecb, 8, &so[7237]}, + {"SM4-CBC", "sm4-cbc", NID_sm4_cbc, 8, &so[7245]}, + {"SM4-OFB", "sm4-ofb", NID_sm4_ofb128, 8, &so[7253]}, + {"SM4-CFB1", "sm4-cfb1", NID_sm4_cfb1, 8, &so[7261]}, + {"SM4-CFB", "sm4-cfb", NID_sm4_cfb128, 8, &so[7269]}, + {"SM4-CFB8", "sm4-cfb8", NID_sm4_cfb8, 8, &so[7277]}, + {"SM4-CTR", "sm4-ctr", NID_sm4_ctr, 8, &so[7285]}, + {"ISO-CN", "ISO CN Member Body", NID_ISO_CN, 3, &so[7293]}, + {"oscca", "oscca", NID_oscca, 5, &so[7296]}, + {"sm-scheme", "sm-scheme", NID_sm_scheme, 6, &so[7301]}, + {"SM3", "sm3", NID_sm3, 8, &so[7307]}, + {"RSA-SM3", "sm3WithRSAEncryption", NID_sm3WithRSAEncryption, 8, &so[7315]}, + {"RSA-SHA512/224", "sha512-224WithRSAEncryption", NID_sha512_224WithRSAEncryption, 9, &so[7323]}, + {"RSA-SHA512/256", "sha512-256WithRSAEncryption", NID_sha512_256WithRSAEncryption, 9, &so[7332]}, }; -#define NUM_SN 1052 +#define NUM_SN 1138 static const unsigned int sn_objs[NUM_SN] = { 364, /* "AD_DVCS" */ 419, /* "AES-128-CBC" */ @@ -2063,6 +2220,34 @@ static const unsigned int sn_objs[NUM_SN] = { 960, /* "AES-256-OCB" */ 428, /* "AES-256-OFB" */ 914, /* "AES-256-XTS" */ + 1066, /* "ARIA-128-CBC" */ + 1120, /* "ARIA-128-CCM" */ + 1067, /* "ARIA-128-CFB" */ + 1080, /* "ARIA-128-CFB1" */ + 1083, /* "ARIA-128-CFB8" */ + 1069, /* "ARIA-128-CTR" */ + 1065, /* "ARIA-128-ECB" */ + 1123, /* "ARIA-128-GCM" */ + 1068, /* "ARIA-128-OFB" */ + 1071, /* "ARIA-192-CBC" */ + 1121, /* "ARIA-192-CCM" */ + 1072, /* "ARIA-192-CFB" */ + 1081, /* "ARIA-192-CFB1" */ + 1084, /* "ARIA-192-CFB8" */ + 1074, /* "ARIA-192-CTR" */ + 1070, /* "ARIA-192-ECB" */ + 1124, /* "ARIA-192-GCM" */ + 1073, /* "ARIA-192-OFB" */ + 1076, /* "ARIA-256-CBC" */ + 1122, /* "ARIA-256-CCM" */ + 1077, /* "ARIA-256-CFB" */ + 1082, /* "ARIA-256-CFB1" */ + 1085, /* "ARIA-256-CFB8" */ + 1079, /* "ARIA-256-CTR" */ + 1075, /* "ARIA-256-ECB" */ + 1125, /* "ARIA-256-GCM" */ + 1078, /* "ARIA-256-OFB" */ + 1064, /* "AuthANY" */ 1049, /* "AuthDSS" */ 1047, /* "AuthECDSA" */ 1050, /* "AuthGOST01" */ @@ -2145,6 +2330,8 @@ static const unsigned int sn_objs[NUM_SN] = { 70, /* "DSA-SHA1-old" */ 67, /* "DSA-old" */ 297, /* "DVCS" */ + 1087, /* "ED25519" */ + 1088, /* "ED448" */ 99, /* "GN" */ 1036, /* "HKDF" */ 855, /* "HMAC" */ @@ -2157,10 +2344,12 @@ static const unsigned int sn_objs[NUM_SN] = { 46, /* "IDEA-OFB" */ 1004, /* "INN" */ 181, /* "ISO" */ + 1140, /* "ISO-CN" */ 183, /* "ISO-US" */ 645, /* "ITU-T" */ 646, /* "JOINT-ISO-ITU-T" */ 773, /* "KISA" */ + 1063, /* "KxANY" */ 1039, /* "KxDHE" */ 1041, /* "KxDHE-PSK" */ 1038, /* "KxECDHE" */ @@ -2208,6 +2397,7 @@ static const unsigned int sn_objs[NUM_SN] = { 162, /* "PBMAC1" */ 127, /* "PKIX" */ 935, /* "PSPECIFIED" */ + 1061, /* "Poly1305" */ 98, /* "RC2-40-CBC" */ 166, /* "RC2-64-CBC" */ 37, /* "RC2-CBC" */ @@ -2236,6 +2426,9 @@ static const unsigned int sn_objs[NUM_SN] = { 668, /* "RSA-SHA256" */ 669, /* "RSA-SHA384" */ 670, /* "RSA-SHA512" */ + 1145, /* "RSA-SHA512/224" */ + 1146, /* "RSA-SHA512/256" */ + 1144, /* "RSA-SM3" */ 919, /* "RSAES-OAEP" */ 912, /* "RSASSA-PSS" */ 777, /* "SEED-CBC" */ @@ -2246,14 +2439,31 @@ static const unsigned int sn_objs[NUM_SN] = { 64, /* "SHA1" */ 675, /* "SHA224" */ 672, /* "SHA256" */ + 1096, /* "SHA3-224" */ + 1097, /* "SHA3-256" */ + 1098, /* "SHA3-384" */ + 1099, /* "SHA3-512" */ 673, /* "SHA384" */ 674, /* "SHA512" */ + 1094, /* "SHA512-224" */ + 1095, /* "SHA512-256" */ + 1100, /* "SHAKE128" */ + 1101, /* "SHAKE256" */ + 1143, /* "SM3" */ + 1134, /* "SM4-CBC" */ + 1137, /* "SM4-CFB" */ + 1136, /* "SM4-CFB1" */ + 1138, /* "SM4-CFB8" */ + 1139, /* "SM4-CTR" */ + 1133, /* "SM4-ECB" */ + 1135, /* "SM4-OFB" */ 188, /* "SMIME" */ 167, /* "SMIME-CAPS" */ 100, /* "SN" */ 1006, /* "SNILS" */ 16, /* "ST" */ 143, /* "SXNetID" */ + 1062, /* "SipHash" */ 1021, /* "TLS1-PRF" */ 458, /* "UID" */ 0, /* "UNDEF" */ @@ -2323,6 +2533,7 @@ static const unsigned int sn_objs[NUM_SN] = { 696, /* "c2tnb239v3" */ 701, /* "c2tnb359v1" */ 703, /* "c2tnb431r1" */ + 1090, /* "c3" */ 881, /* "cACertificate" */ 483, /* "cNAMERecord" */ 179, /* "caIssuers" */ @@ -2339,6 +2550,8 @@ static const unsigned int sn_objs[NUM_SN] = { 407, /* "characteristic-two-field" */ 395, /* "clearance" */ 130, /* "clientAuth" */ + 1131, /* "cmcCA" */ + 1132, /* "cmcRA" */ 131, /* "codeSigning" */ 50, /* "contentType" */ 53, /* "countersignature" */ @@ -2379,6 +2592,7 @@ static const unsigned int sn_objs[NUM_SN] = { 887, /* "distinguishedName" */ 892, /* "dmdName" */ 174, /* "dnQualifier" */ + 1092, /* "dnsName" */ 447, /* "document" */ 471, /* "documentAuthor" */ 468, /* "documentIdentifier" */ @@ -2409,6 +2623,11 @@ static const unsigned int sn_objs[NUM_SN] = { 372, /* "extendedStatus" */ 867, /* "facsimileTelephoneNumber" */ 462, /* "favouriteDrink" */ + 1126, /* "ffdhe2048" */ + 1127, /* "ffdhe3072" */ + 1128, /* "ffdhe4096" */ + 1129, /* "ffdhe6144" */ + 1130, /* "ffdhe8192" */ 857, /* "freshestCRL" */ 453, /* "friendlyCountry" */ 490, /* "friendlyCountryName" */ @@ -2548,9 +2767,23 @@ static const unsigned int sn_objs[NUM_SN] = { 331, /* "id-cmc-transactionId" */ 787, /* "id-ct-asciiTextWithCRLF" */ 1060, /* "id-ct-xml" */ + 1108, /* "id-dsa-with-sha3-224" */ + 1109, /* "id-dsa-with-sha3-256" */ + 1110, /* "id-dsa-with-sha3-384" */ + 1111, /* "id-dsa-with-sha3-512" */ + 1106, /* "id-dsa-with-sha384" */ + 1107, /* "id-dsa-with-sha512" */ 408, /* "id-ecPublicKey" */ + 1112, /* "id-ecdsa-with-sha3-224" */ + 1113, /* "id-ecdsa-with-sha3-256" */ + 1114, /* "id-ecdsa-with-sha3-384" */ + 1115, /* "id-ecdsa-with-sha3-512" */ 508, /* "id-hex-multipart-message" */ 507, /* "id-hex-partial-message" */ + 1102, /* "id-hmacWithSHA3-224" */ + 1103, /* "id-hmacWithSHA3-256" */ + 1104, /* "id-hmacWithSHA3-384" */ + 1105, /* "id-hmacWithSHA3-512" */ 260, /* "id-it" */ 302, /* "id-it-caKeyUpdateInfo" */ 298, /* "id-it-caProtEncCert" */ @@ -2617,6 +2850,10 @@ static const unsigned int sn_objs[NUM_SN] = { 314, /* "id-regInfo" */ 322, /* "id-regInfo-certReq" */ 321, /* "id-regInfo-utf8Pairs" */ + 1116, /* "id-rsassa-pkcs1-v1_5-with-sha3-224" */ + 1117, /* "id-rsassa-pkcs1-v1_5-with-sha3-256" */ + 1118, /* "id-rsassa-pkcs1-v1_5-with-sha3-384" */ + 1119, /* "id-rsassa-pkcs1-v1_5-with-sha3-512" */ 973, /* "id-scrypt" */ 512, /* "id-set" */ 191, /* "id-smime-aa" */ @@ -2647,6 +2884,7 @@ static const unsigned int sn_objs[NUM_SN] = { 213, /* "id-smime-aa-securityLabel" */ 239, /* "id-smime-aa-signatureType" */ 223, /* "id-smime-aa-signingCertificate" */ + 1086, /* "id-smime-aa-signingCertificateV2" */ 224, /* "id-smime-aa-smimeEncryptCerts" */ 225, /* "id-smime-aa-timeStampToken" */ 192, /* "id-smime-alg" */ @@ -2760,6 +2998,7 @@ static const unsigned int sn_objs[NUM_SN] = { 137, /* "msSGC" */ 648, /* "msSmartcardLogin" */ 649, /* "msUPN" */ + 1091, /* "n3" */ 481, /* "nSRecord" */ 173, /* "name" */ 666, /* "nameConstraints" */ @@ -2778,7 +3017,9 @@ static const unsigned int sn_objs[NUM_SN] = { 139, /* "nsSGC" */ 77, /* "nsSslServerName" */ 681, /* "onBasis" */ + 1089, /* "organizationIdentifier" */ 491, /* "organizationalStatus" */ + 1141, /* "oscca" */ 475, /* "otherMailbox" */ 876, /* "owner" */ 489, /* "pagerTelephoneNumber" */ @@ -3033,6 +3274,7 @@ static const unsigned int sn_objs[NUM_SN] = { 52, /* "signingTime" */ 454, /* "simpleSecurityObject" */ 496, /* "singleLevelQuality" */ + 1142, /* "sm-scheme" */ 387, /* "snmpv2" */ 660, /* "street" */ 85, /* "subjectAltName" */ @@ -3082,9 +3324,10 @@ static const unsigned int sn_objs[NUM_SN] = { 503, /* "x500UniqueIdentifier" */ 158, /* "x509Certificate" */ 160, /* "x509Crl" */ + 1093, /* "x509ExtAdmission" */ }; -#define NUM_LN 1052 +#define NUM_LN 1138 static const unsigned int ln_objs[NUM_LN] = { 363, /* "AD Time Stamping" */ 405, /* "ANSI X9.62" */ @@ -3096,6 +3339,8 @@ static const unsigned int ln_objs[NUM_LN] = { 285, /* "Biometric Info" */ 179, /* "CA Issuers" */ 785, /* "CA Repository" */ + 1131, /* "CMC Certificate Authority" */ + 1132, /* "CMC Registration Authority" */ 954, /* "CT Certificate SCTs" */ 952, /* "CT Precertificate Poison" */ 951, /* "CT Precertificate SCTs" */ @@ -3107,6 +3352,8 @@ static const unsigned int ln_objs[NUM_LN] = { 382, /* "Directory" */ 392, /* "Domain" */ 132, /* "E-mail Protection" */ + 1087, /* "ED25519" */ + 1088, /* "ED448" */ 389, /* "Enterprises" */ 384, /* "Experimental" */ 372, /* "Extended OCSP Status" */ @@ -3149,6 +3396,7 @@ static const unsigned int ln_objs[NUM_LN] = { 294, /* "IPSec End System" */ 295, /* "IPSec Tunnel" */ 296, /* "IPSec User" */ + 1140, /* "ISO CN Member Body" */ 182, /* "ISO Member Body" */ 183, /* "ISO US Member Body" */ 667, /* "Independent" */ @@ -3200,9 +3448,14 @@ static const unsigned int ln_objs[NUM_LN] = { 164, /* "Policy Qualifier CPS" */ 165, /* "Policy Qualifier User Notice" */ 385, /* "Private" */ + 1093, /* "Professional Information or basis for Admission" */ 663, /* "Proxy Certificate Information" */ 1, /* "RSA Data Security, Inc." */ 2, /* "RSA Data Security, Inc. PKCS" */ + 1116, /* "RSA-SHA3-224" */ + 1117, /* "RSA-SHA3-256" */ + 1118, /* "RSA-SHA3-384" */ + 1119, /* "RSA-SHA3-512" */ 188, /* "S/MIME" */ 167, /* "S/MIME Capabilities" */ 1006, /* "SNILS" */ @@ -3303,9 +3556,37 @@ static const unsigned int ln_objs[NUM_LN] = { 428, /* "aes-256-ofb" */ 914, /* "aes-256-xts" */ 376, /* "algorithm" */ + 1066, /* "aria-128-cbc" */ + 1120, /* "aria-128-ccm" */ + 1067, /* "aria-128-cfb" */ + 1080, /* "aria-128-cfb1" */ + 1083, /* "aria-128-cfb8" */ + 1069, /* "aria-128-ctr" */ + 1065, /* "aria-128-ecb" */ + 1123, /* "aria-128-gcm" */ + 1068, /* "aria-128-ofb" */ + 1071, /* "aria-192-cbc" */ + 1121, /* "aria-192-ccm" */ + 1072, /* "aria-192-cfb" */ + 1081, /* "aria-192-cfb1" */ + 1084, /* "aria-192-cfb8" */ + 1074, /* "aria-192-ctr" */ + 1070, /* "aria-192-ecb" */ + 1124, /* "aria-192-gcm" */ + 1073, /* "aria-192-ofb" */ + 1076, /* "aria-256-cbc" */ + 1122, /* "aria-256-ccm" */ + 1077, /* "aria-256-cfb" */ + 1082, /* "aria-256-cfb1" */ + 1085, /* "aria-256-cfb8" */ + 1079, /* "aria-256-ctr" */ + 1075, /* "aria-256-ecb" */ + 1125, /* "aria-256-gcm" */ + 1078, /* "aria-256-ofb" */ 484, /* "associatedDomain" */ 485, /* "associatedName" */ 501, /* "audio" */ + 1064, /* "auth-any" */ 1049, /* "auth-dss" */ 1047, /* "auth-ecdsa" */ 1050, /* "auth-gost01" */ @@ -3409,6 +3690,8 @@ static const unsigned int ln_objs[NUM_LN] = { 513, /* "content types" */ 50, /* "contentType" */ 53, /* "countersignature" */ + 1090, /* "countryCode3c" */ + 1091, /* "countryCode3n" */ 14, /* "countryName" */ 153, /* "crlBag" */ 884, /* "crossCertificatePair" */ @@ -3458,6 +3741,7 @@ static const unsigned int ln_objs[NUM_LN] = { 887, /* "distinguishedName" */ 892, /* "dmdName" */ 174, /* "dnQualifier" */ + 1092, /* "dnsName" */ 447, /* "document" */ 471, /* "documentAuthor" */ 468, /* "documentIdentifier" */ @@ -3476,6 +3760,12 @@ static const unsigned int ln_objs[NUM_LN] = { 70, /* "dsaWithSHA1-old" */ 802, /* "dsa_with_SHA224" */ 803, /* "dsa_with_SHA256" */ + 1108, /* "dsa_with_SHA3-224" */ + 1109, /* "dsa_with_SHA3-256" */ + 1110, /* "dsa_with_SHA3-384" */ + 1111, /* "dsa_with_SHA3-512" */ + 1106, /* "dsa_with_SHA384" */ + 1107, /* "dsa_with_SHA512" */ 297, /* "dvcs" */ 791, /* "ecdsa-with-Recommended" */ 416, /* "ecdsa-with-SHA1" */ @@ -3484,12 +3774,21 @@ static const unsigned int ln_objs[NUM_LN] = { 795, /* "ecdsa-with-SHA384" */ 796, /* "ecdsa-with-SHA512" */ 792, /* "ecdsa-with-Specified" */ + 1112, /* "ecdsa_with_SHA3-224" */ + 1113, /* "ecdsa_with_SHA3-256" */ + 1114, /* "ecdsa_with_SHA3-384" */ + 1115, /* "ecdsa_with_SHA3-512" */ 48, /* "emailAddress" */ 632, /* "encrypted track 2" */ 885, /* "enhancedSearchGuide" */ 56, /* "extendedCertificateAttributes" */ 867, /* "facsimileTelephoneNumber" */ 462, /* "favouriteDrink" */ + 1126, /* "ffdhe2048" */ + 1127, /* "ffdhe3072" */ + 1128, /* "ffdhe4096" */ + 1129, /* "ffdhe6144" */ + 1130, /* "ffdhe8192" */ 453, /* "friendlyCountry" */ 490, /* "friendlyCountryName" */ 156, /* "friendlyName" */ @@ -3513,6 +3812,10 @@ static const unsigned int ln_objs[NUM_LN] = { 855, /* "hmac" */ 780, /* "hmac-md5" */ 781, /* "hmac-sha1" */ + 1102, /* "hmac-sha3-224" */ + 1103, /* "hmac-sha3-256" */ + 1104, /* "hmac-sha3-384" */ + 1105, /* "hmac-sha3-512" */ 797, /* "hmacWithMD5" */ 163, /* "hmacWithSHA1" */ 798, /* "hmacWithSHA224" */ @@ -3670,7 +3973,6 @@ static const unsigned int ln_objs[NUM_LN] = { 314, /* "id-regInfo" */ 322, /* "id-regInfo-certReq" */ 321, /* "id-regInfo-utf8Pairs" */ - 973, /* "id-scrypt" */ 191, /* "id-smime-aa" */ 215, /* "id-smime-aa-contentHint" */ 218, /* "id-smime-aa-contentIdentifier" */ @@ -3699,6 +4001,7 @@ static const unsigned int ln_objs[NUM_LN] = { 213, /* "id-smime-aa-securityLabel" */ 239, /* "id-smime-aa-signatureType" */ 223, /* "id-smime-aa-signingCertificate" */ + 1086, /* "id-smime-aa-signingCertificateV2" */ 224, /* "id-smime-aa-smimeEncryptCerts" */ 225, /* "id-smime-aa-timeStampToken" */ 192, /* "id-smime-alg" */ @@ -3779,6 +4082,7 @@ static const unsigned int ln_objs[NUM_LN] = { 956, /* "jurisdictionStateOrProvinceName" */ 150, /* "keyBag" */ 773, /* "kisa" */ + 1063, /* "kx-any" */ 1039, /* "kx-dhe" */ 1041, /* "kx-dhe-psk" */ 1038, /* "kx-ecdhe" */ @@ -3817,9 +4121,11 @@ static const unsigned int ln_objs[NUM_LN] = { 173, /* "name" */ 681, /* "onBasis" */ 379, /* "org" */ + 1089, /* "organizationIdentifier" */ 17, /* "organizationName" */ 491, /* "organizationalStatus" */ 18, /* "organizationalUnitName" */ + 1141, /* "oscca" */ 475, /* "otherMailbox" */ 876, /* "owner" */ 935, /* "pSpecified" */ @@ -3866,6 +4172,7 @@ static const unsigned int ln_objs[NUM_LN] = { 22, /* "pkcs7-signedData" */ 151, /* "pkcs8ShroudedKeyBag" */ 47, /* "pkcs9" */ + 1061, /* "poly1305" */ 862, /* "postOfficeBox" */ 861, /* "postalAddress" */ 661, /* "postalCode" */ @@ -3918,6 +4225,7 @@ static const unsigned int ln_objs[NUM_LN] = { 291, /* "sbgp-autonomousSysNum" */ 290, /* "sbgp-ipAddrBlock" */ 292, /* "sbgp-routerIdentifier" */ + 973, /* "scrypt" */ 159, /* "sdsiCertificate" */ 859, /* "searchGuide" */ 704, /* "secp112r1" */ @@ -4085,14 +4393,35 @@ static const unsigned int ln_objs[NUM_LN] = { 671, /* "sha224WithRSAEncryption" */ 672, /* "sha256" */ 668, /* "sha256WithRSAEncryption" */ + 1096, /* "sha3-224" */ + 1097, /* "sha3-256" */ + 1098, /* "sha3-384" */ + 1099, /* "sha3-512" */ 673, /* "sha384" */ 669, /* "sha384WithRSAEncryption" */ 674, /* "sha512" */ + 1094, /* "sha512-224" */ + 1145, /* "sha512-224WithRSAEncryption" */ + 1095, /* "sha512-256" */ + 1146, /* "sha512-256WithRSAEncryption" */ 670, /* "sha512WithRSAEncryption" */ 42, /* "shaWithRSAEncryption" */ + 1100, /* "shake128" */ + 1101, /* "shake256" */ 52, /* "signingTime" */ 454, /* "simpleSecurityObject" */ 496, /* "singleLevelQuality" */ + 1062, /* "siphash" */ + 1142, /* "sm-scheme" */ + 1143, /* "sm3" */ + 1144, /* "sm3WithRSAEncryption" */ + 1134, /* "sm4-cbc" */ + 1137, /* "sm4-cfb" */ + 1136, /* "sm4-cfb1" */ + 1138, /* "sm4-cfb8" */ + 1139, /* "sm4-ctr" */ + 1133, /* "sm4-ecb" */ + 1135, /* "sm4-ofb" */ 16, /* "stateOrProvinceName" */ 660, /* "streetAddress" */ 498, /* "subtreeMaximumQuality" */ @@ -4140,7 +4469,7 @@ static const unsigned int ln_objs[NUM_LN] = { 125, /* "zlib compression" */ }; -#define NUM_OBJ 956 +#define NUM_OBJ 1027 static const unsigned int obj_objs[NUM_OBJ] = { 0, /* OBJ_undef 0 */ 181, /* OBJ_iso 1 */ @@ -4161,10 +4490,13 @@ static const unsigned int obj_objs[NUM_OBJ] = { 512, /* OBJ_id_set 2 23 42 */ 678, /* OBJ_wap 2 23 43 */ 435, /* OBJ_pss 0 9 2342 */ + 1140, /* OBJ_ISO_CN 1 2 156 */ 183, /* OBJ_ISO_US 1 2 840 */ 381, /* OBJ_iana 1 3 6 1 */ 1034, /* OBJ_X25519 1 3 101 110 */ 1035, /* OBJ_X448 1 3 101 111 */ + 1087, /* OBJ_ED25519 1 3 101 112 */ + 1088, /* OBJ_ED448 1 3 101 113 */ 677, /* OBJ_certicom_arc 1 3 132 */ 394, /* OBJ_selected_attribute_types 2 5 1 5 */ 13, /* OBJ_commonName 2 5 4 3 */ @@ -4221,6 +4553,10 @@ static const unsigned int obj_objs[NUM_OBJ] = { 892, /* OBJ_dmdName 2 5 4 54 */ 510, /* OBJ_pseudonym 2 5 4 65 */ 400, /* OBJ_role 2 5 4 72 */ + 1089, /* OBJ_organizationIdentifier 2 5 4 97 */ + 1090, /* OBJ_countryCode3c 2 5 4 98 */ + 1091, /* OBJ_countryCode3n 2 5 4 99 */ + 1092, /* OBJ_dnsName 2 5 4 100 */ 769, /* OBJ_subject_directory_attributes 2 5 29 9 */ 82, /* OBJ_subject_key_identifier 2 5 29 14 */ 83, /* OBJ_key_usage 2 5 29 15 */ @@ -4378,6 +4714,7 @@ static const unsigned int obj_objs[NUM_OBJ] = { 637, /* OBJ_set_brand_Diners 2 23 42 8 30 */ 638, /* OBJ_set_brand_AmericanExpress 2 23 42 8 34 */ 639, /* OBJ_set_brand_JCB 2 23 42 8 35 */ + 1141, /* OBJ_oscca 1 2 156 10197 */ 805, /* OBJ_cryptopro 1 2 643 2 2 */ 806, /* OBJ_cryptocom 1 2 643 2 9 */ 974, /* OBJ_id_tc26 1 2 643 7 1 */ @@ -4404,6 +4741,7 @@ static const unsigned int obj_objs[NUM_OBJ] = { 70, /* OBJ_dsaWithSHA1_2 1 3 14 3 2 27 */ 115, /* OBJ_sha1WithRSA 1 3 14 3 2 29 */ 117, /* OBJ_ripemd160 1 3 36 3 2 1 */ + 1093, /* OBJ_x509ExtAdmission 1 3 36 8 3 3 */ 143, /* OBJ_sxnet 1 3 101 1 4 1 */ 721, /* OBJ_sect163k1 1 3 132 0 1 */ 722, /* OBJ_sect163r1 1 3 132 0 2 */ @@ -4456,6 +4794,7 @@ static const unsigned int obj_objs[NUM_OBJ] = { 744, /* OBJ_wap_wsg_idm_ecid_wtls11 2 23 43 1 4 11 */ 745, /* OBJ_wap_wsg_idm_ecid_wtls12 2 23 43 1 4 12 */ 804, /* OBJ_whirlpool 1 0 10118 3 0 55 */ + 1142, /* OBJ_sm_scheme 1 2 156 10197 1 */ 773, /* OBJ_kisa 1 2 410 200004 */ 807, /* OBJ_id_GostR3411_94_with_GostR3410_2001 1 2 643 2 2 3 */ 808, /* OBJ_id_GostR3411_94_with_GostR3410_94 1 2 643 2 2 4 */ @@ -4585,6 +4924,15 @@ static const unsigned int obj_objs[NUM_OBJ] = { 971, /* OBJ_camellia_256_ctr 0 3 4401 5 3 1 9 49 */ 972, /* OBJ_camellia_256_cmac 0 3 4401 5 3 1 9 50 */ 437, /* OBJ_pilot 0 9 2342 19200300 100 */ + 1133, /* OBJ_sm4_ecb 1 2 156 10197 1 104 1 */ + 1134, /* OBJ_sm4_cbc 1 2 156 10197 1 104 2 */ + 1135, /* OBJ_sm4_ofb128 1 2 156 10197 1 104 3 */ + 1137, /* OBJ_sm4_cfb128 1 2 156 10197 1 104 4 */ + 1136, /* OBJ_sm4_cfb1 1 2 156 10197 1 104 5 */ + 1138, /* OBJ_sm4_cfb8 1 2 156 10197 1 104 6 */ + 1139, /* OBJ_sm4_ctr 1 2 156 10197 1 104 7 */ + 1143, /* OBJ_sm3 1 2 156 10197 1 401 */ + 1144, /* OBJ_sm3WithRSAEncryption 1 2 156 10197 1 504 */ 776, /* OBJ_seed_ecb 1 2 410 200004 1 3 */ 777, /* OBJ_seed_cbc 1 2 410 200004 1 4 */ 779, /* OBJ_seed_cfb128 1 2 410 200004 1 5 */ @@ -4710,6 +5058,8 @@ static const unsigned int obj_objs[NUM_OBJ] = { 1028, /* OBJ_sendProxiedRouter 1 3 6 1 5 5 7 3 24 */ 1029, /* OBJ_sendOwner 1 3 6 1 5 5 7 3 25 */ 1030, /* OBJ_sendProxiedOwner 1 3 6 1 5 5 7 3 26 */ + 1131, /* OBJ_cmcCA 1 3 6 1 5 5 7 3 27 */ + 1132, /* OBJ_cmcRA 1 3 6 1 5 5 7 3 28 */ 298, /* OBJ_id_it_caProtEncCert 1 3 6 1 5 5 7 4 1 */ 299, /* OBJ_id_it_signKeyPairTypes 1 3 6 1 5 5 7 4 2 */ 300, /* OBJ_id_it_encKeyPairTypes 1 3 6 1 5 5 7 4 3 */ @@ -4785,6 +5135,27 @@ static const unsigned int obj_objs[NUM_OBJ] = { 439, /* OBJ_pilotAttributeSyntax 0 9 2342 19200300 100 3 */ 440, /* OBJ_pilotObjectClass 0 9 2342 19200300 100 4 */ 441, /* OBJ_pilotGroups 0 9 2342 19200300 100 10 */ + 1065, /* OBJ_aria_128_ecb 1 2 410 200046 1 1 1 */ + 1066, /* OBJ_aria_128_cbc 1 2 410 200046 1 1 2 */ + 1067, /* OBJ_aria_128_cfb128 1 2 410 200046 1 1 3 */ + 1068, /* OBJ_aria_128_ofb128 1 2 410 200046 1 1 4 */ + 1069, /* OBJ_aria_128_ctr 1 2 410 200046 1 1 5 */ + 1070, /* OBJ_aria_192_ecb 1 2 410 200046 1 1 6 */ + 1071, /* OBJ_aria_192_cbc 1 2 410 200046 1 1 7 */ + 1072, /* OBJ_aria_192_cfb128 1 2 410 200046 1 1 8 */ + 1073, /* OBJ_aria_192_ofb128 1 2 410 200046 1 1 9 */ + 1074, /* OBJ_aria_192_ctr 1 2 410 200046 1 1 10 */ + 1075, /* OBJ_aria_256_ecb 1 2 410 200046 1 1 11 */ + 1076, /* OBJ_aria_256_cbc 1 2 410 200046 1 1 12 */ + 1077, /* OBJ_aria_256_cfb128 1 2 410 200046 1 1 13 */ + 1078, /* OBJ_aria_256_ofb128 1 2 410 200046 1 1 14 */ + 1079, /* OBJ_aria_256_ctr 1 2 410 200046 1 1 15 */ + 1123, /* OBJ_aria_128_gcm 1 2 410 200046 1 1 34 */ + 1124, /* OBJ_aria_192_gcm 1 2 410 200046 1 1 35 */ + 1125, /* OBJ_aria_256_gcm 1 2 410 200046 1 1 36 */ + 1120, /* OBJ_aria_128_ccm 1 2 410 200046 1 1 37 */ + 1121, /* OBJ_aria_192_ccm 1 2 410 200046 1 1 38 */ + 1122, /* OBJ_aria_256_ccm 1 2 410 200046 1 1 39 */ 997, /* OBJ_id_tc26_gost_3410_2012_512_paramSetTest 1 2 643 7 1 2 1 2 0 */ 998, /* OBJ_id_tc26_gost_3410_2012_512_paramSetA 1 2 643 7 1 2 1 2 1 */ 999, /* OBJ_id_tc26_gost_3410_2012_512_paramSetB 1 2 643 7 1 2 1 2 2 */ @@ -4807,6 +5178,8 @@ static const unsigned int obj_objs[NUM_OBJ] = { 669, /* OBJ_sha384WithRSAEncryption 1 2 840 113549 1 1 12 */ 670, /* OBJ_sha512WithRSAEncryption 1 2 840 113549 1 1 13 */ 671, /* OBJ_sha224WithRSAEncryption 1 2 840 113549 1 1 14 */ + 1145, /* OBJ_sha512_224WithRSAEncryption 1 2 840 113549 1 1 15 */ + 1146, /* OBJ_sha512_256WithRSAEncryption 1 2 840 113549 1 1 16 */ 28, /* OBJ_dhKeyAgreement 1 2 840 113549 1 3 1 */ 9, /* OBJ_pbeWithMD2AndDES_CBC 1 2 840 113549 1 5 1 */ 10, /* OBJ_pbeWithMD5AndDES_CBC 1 2 840 113549 1 5 3 */ @@ -4908,8 +5281,34 @@ static const unsigned int obj_objs[NUM_OBJ] = { 673, /* OBJ_sha384 2 16 840 1 101 3 4 2 2 */ 674, /* OBJ_sha512 2 16 840 1 101 3 4 2 3 */ 675, /* OBJ_sha224 2 16 840 1 101 3 4 2 4 */ + 1094, /* OBJ_sha512_224 2 16 840 1 101 3 4 2 5 */ + 1095, /* OBJ_sha512_256 2 16 840 1 101 3 4 2 6 */ + 1096, /* OBJ_sha3_224 2 16 840 1 101 3 4 2 7 */ + 1097, /* OBJ_sha3_256 2 16 840 1 101 3 4 2 8 */ + 1098, /* OBJ_sha3_384 2 16 840 1 101 3 4 2 9 */ + 1099, /* OBJ_sha3_512 2 16 840 1 101 3 4 2 10 */ + 1100, /* OBJ_shake128 2 16 840 1 101 3 4 2 11 */ + 1101, /* OBJ_shake256 2 16 840 1 101 3 4 2 12 */ + 1102, /* OBJ_hmac_sha3_224 2 16 840 1 101 3 4 2 13 */ + 1103, /* OBJ_hmac_sha3_256 2 16 840 1 101 3 4 2 14 */ + 1104, /* OBJ_hmac_sha3_384 2 16 840 1 101 3 4 2 15 */ + 1105, /* OBJ_hmac_sha3_512 2 16 840 1 101 3 4 2 16 */ 802, /* OBJ_dsa_with_SHA224 2 16 840 1 101 3 4 3 1 */ 803, /* OBJ_dsa_with_SHA256 2 16 840 1 101 3 4 3 2 */ + 1106, /* OBJ_dsa_with_SHA384 2 16 840 1 101 3 4 3 3 */ + 1107, /* OBJ_dsa_with_SHA512 2 16 840 1 101 3 4 3 4 */ + 1108, /* OBJ_dsa_with_SHA3_224 2 16 840 1 101 3 4 3 5 */ + 1109, /* OBJ_dsa_with_SHA3_256 2 16 840 1 101 3 4 3 6 */ + 1110, /* OBJ_dsa_with_SHA3_384 2 16 840 1 101 3 4 3 7 */ + 1111, /* OBJ_dsa_with_SHA3_512 2 16 840 1 101 3 4 3 8 */ + 1112, /* OBJ_ecdsa_with_SHA3_224 2 16 840 1 101 3 4 3 9 */ + 1113, /* OBJ_ecdsa_with_SHA3_256 2 16 840 1 101 3 4 3 10 */ + 1114, /* OBJ_ecdsa_with_SHA3_384 2 16 840 1 101 3 4 3 11 */ + 1115, /* OBJ_ecdsa_with_SHA3_512 2 16 840 1 101 3 4 3 12 */ + 1116, /* OBJ_RSA_SHA3_224 2 16 840 1 101 3 4 3 13 */ + 1117, /* OBJ_RSA_SHA3_256 2 16 840 1 101 3 4 3 14 */ + 1118, /* OBJ_RSA_SHA3_384 2 16 840 1 101 3 4 3 15 */ + 1119, /* OBJ_RSA_SHA3_512 2 16 840 1 101 3 4 3 16 */ 71, /* OBJ_netscape_cert_type 2 16 840 1 113730 1 1 */ 72, /* OBJ_netscape_base_url 2 16 840 1 113730 1 2 */ 73, /* OBJ_netscape_revocation_url 2 16 840 1 113730 1 3 */ @@ -5068,6 +5467,7 @@ static const unsigned int obj_objs[NUM_OBJ] = { 238, /* OBJ_id_smime_aa_ets_archiveTimeStamp 1 2 840 113549 1 9 16 2 27 */ 239, /* OBJ_id_smime_aa_signatureType 1 2 840 113549 1 9 16 2 28 */ 240, /* OBJ_id_smime_aa_dvcs_dvc 1 2 840 113549 1 9 16 2 29 */ + 1086, /* OBJ_id_smime_aa_signingCertificateV2 1 2 840 113549 1 9 16 2 47 */ 241, /* OBJ_id_smime_alg_ESDHwith3DES 1 2 840 113549 1 9 16 3 1 */ 242, /* OBJ_id_smime_alg_ESDHwithRC2 1 2 840 113549 1 9 16 3 2 */ 243, /* OBJ_id_smime_alg_3DESwrap 1 2 840 113549 1 9 16 3 3 */ diff --git a/crypto/objects/obj_dat.pl b/crypto/objects/obj_dat.pl index 1cb3d1c9..392617c0 100644 --- a/crypto/objects/obj_dat.pl +++ b/crypto/objects/obj_dat.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 1995-2018 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 @@ -36,6 +36,10 @@ sub der_it return $ret; } +# Output year depends on the year of the script and the input file. +my $YEAR = [localtime([stat($0)]->[9])]->[5] + 1900; +my $iYEAR = [localtime([stat($ARGV[0])]->[9])]->[5] + 1900; +$YEAR = $iYEAR if $iYEAR > $YEAR; # Read input, parse all #define's into OID name and value. # Populate %ln and %sn with long and short names (%dupln and %dupsn) @@ -149,12 +153,12 @@ for (my $i = 0; $i < $n; $i++) { # Finally ready to generate the output. open(OUT, ">$ARGV[1]") || die "Can't open output file $ARGV[1], $!"; -print OUT <<'EOF'; +print OUT <<"EOF"; /* * WARNING: do not edit! * Generated by crypto/objects/obj_dat.pl * - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-$YEAR 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 diff --git a/crypto/objects/obj_err.c b/crypto/objects/obj_err.c index 4677b673..ef36313c 100644 --- a/crypto/objects/obj_err.c +++ b/crypto/objects/obj_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,30 +8,25 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_OBJ,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_OBJ,0,reason) - -static ERR_STRING_DATA OBJ_str_functs[] = { - {ERR_FUNC(OBJ_F_OBJ_ADD_OBJECT), "OBJ_add_object"}, - {ERR_FUNC(OBJ_F_OBJ_CREATE), "OBJ_create"}, - {ERR_FUNC(OBJ_F_OBJ_DUP), "OBJ_dup"}, - {ERR_FUNC(OBJ_F_OBJ_NAME_NEW_INDEX), "OBJ_NAME_new_index"}, - {ERR_FUNC(OBJ_F_OBJ_NID2LN), "OBJ_nid2ln"}, - {ERR_FUNC(OBJ_F_OBJ_NID2OBJ), "OBJ_nid2obj"}, - {ERR_FUNC(OBJ_F_OBJ_NID2SN), "OBJ_nid2sn"}, +static const ERR_STRING_DATA OBJ_str_functs[] = { + {ERR_PACK(ERR_LIB_OBJ, OBJ_F_OBJ_ADD_OBJECT, 0), "OBJ_add_object"}, + {ERR_PACK(ERR_LIB_OBJ, OBJ_F_OBJ_CREATE, 0), "OBJ_create"}, + {ERR_PACK(ERR_LIB_OBJ, OBJ_F_OBJ_DUP, 0), "OBJ_dup"}, + {ERR_PACK(ERR_LIB_OBJ, OBJ_F_OBJ_NAME_NEW_INDEX, 0), "OBJ_NAME_new_index"}, + {ERR_PACK(ERR_LIB_OBJ, OBJ_F_OBJ_NID2LN, 0), "OBJ_nid2ln"}, + {ERR_PACK(ERR_LIB_OBJ, OBJ_F_OBJ_NID2OBJ, 0), "OBJ_nid2obj"}, + {ERR_PACK(ERR_LIB_OBJ, OBJ_F_OBJ_NID2SN, 0), "OBJ_nid2sn"}, {0, NULL} }; -static ERR_STRING_DATA OBJ_str_reasons[] = { - {ERR_REASON(OBJ_R_OID_EXISTS), "oid exists"}, - {ERR_REASON(OBJ_R_UNKNOWN_NID), "unknown nid"}, +static const ERR_STRING_DATA OBJ_str_reasons[] = { + {ERR_PACK(ERR_LIB_OBJ, 0, OBJ_R_OID_EXISTS), "oid exists"}, + {ERR_PACK(ERR_LIB_OBJ, 0, OBJ_R_UNKNOWN_NID), "unknown nid"}, {0, NULL} }; @@ -40,10 +35,9 @@ static ERR_STRING_DATA OBJ_str_reasons[] = { int ERR_load_OBJ_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(OBJ_str_functs[0].error) == NULL) { - ERR_load_strings(0, OBJ_str_functs); - ERR_load_strings(0, OBJ_str_reasons); + ERR_load_strings_const(OBJ_str_functs); + ERR_load_strings_const(OBJ_str_reasons); } #endif return 1; diff --git a/crypto/objects/obj_lib.c b/crypto/objects/obj_lib.c index 33075e64..acbdeec2 100644 --- a/crypto/objects/obj_lib.c +++ b/crypto/objects/obj_lib.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,7 +9,6 @@ #include #include "internal/cryptlib.h" -#include #include #include #include "internal/asn1_int.h" @@ -22,12 +21,12 @@ ASN1_OBJECT *OBJ_dup(const ASN1_OBJECT *o) return NULL; /* If object isn't dynamic it's an internal OID which is never freed */ if (!(o->flags & ASN1_OBJECT_FLAG_DYNAMIC)) - return ((ASN1_OBJECT *)o); + return (ASN1_OBJECT *)o; r = ASN1_OBJECT_new(); if (r == NULL) { OBJerr(OBJ_F_OBJ_DUP, ERR_R_ASN1_LIB); - return (NULL); + return NULL; } /* Set dynamic flags so everything gets freed up on error */ @@ -61,6 +60,6 @@ int OBJ_cmp(const ASN1_OBJECT *a, const ASN1_OBJECT *b) ret = (a->length - b->length); if (ret) - return (ret); - return (memcmp(a->data, b->data, a->length)); + return ret; + return memcmp(a->data, b->data, a->length); } diff --git a/crypto/objects/obj_mac.num b/crypto/objects/obj_mac.num index a5995a51..bef6050a 100644 --- a/crypto/objects/obj_mac.num +++ b/crypto/objects/obj_mac.num @@ -1058,3 +1058,89 @@ blake2s256 1057 id_smime_ct_contentCollection 1058 id_smime_ct_authEnvelopedData 1059 id_ct_xml 1060 +poly1305 1061 +siphash 1062 +kx_any 1063 +auth_any 1064 +aria_128_ecb 1065 +aria_128_cbc 1066 +aria_128_cfb128 1067 +aria_128_ofb128 1068 +aria_128_ctr 1069 +aria_192_ecb 1070 +aria_192_cbc 1071 +aria_192_cfb128 1072 +aria_192_ofb128 1073 +aria_192_ctr 1074 +aria_256_ecb 1075 +aria_256_cbc 1076 +aria_256_cfb128 1077 +aria_256_ofb128 1078 +aria_256_ctr 1079 +aria_128_cfb1 1080 +aria_192_cfb1 1081 +aria_256_cfb1 1082 +aria_128_cfb8 1083 +aria_192_cfb8 1084 +aria_256_cfb8 1085 +id_smime_aa_signingCertificateV2 1086 +ED25519 1087 +ED448 1088 +organizationIdentifier 1089 +countryCode3c 1090 +countryCode3n 1091 +dnsName 1092 +x509ExtAdmission 1093 +sha512_224 1094 +sha512_256 1095 +sha3_224 1096 +sha3_256 1097 +sha3_384 1098 +sha3_512 1099 +shake128 1100 +shake256 1101 +hmac_sha3_224 1102 +hmac_sha3_256 1103 +hmac_sha3_384 1104 +hmac_sha3_512 1105 +dsa_with_SHA384 1106 +dsa_with_SHA512 1107 +dsa_with_SHA3_224 1108 +dsa_with_SHA3_256 1109 +dsa_with_SHA3_384 1110 +dsa_with_SHA3_512 1111 +ecdsa_with_SHA3_224 1112 +ecdsa_with_SHA3_256 1113 +ecdsa_with_SHA3_384 1114 +ecdsa_with_SHA3_512 1115 +RSA_SHA3_224 1116 +RSA_SHA3_256 1117 +RSA_SHA3_384 1118 +RSA_SHA3_512 1119 +aria_128_ccm 1120 +aria_192_ccm 1121 +aria_256_ccm 1122 +aria_128_gcm 1123 +aria_192_gcm 1124 +aria_256_gcm 1125 +ffdhe2048 1126 +ffdhe3072 1127 +ffdhe4096 1128 +ffdhe6144 1129 +ffdhe8192 1130 +cmcCA 1131 +cmcRA 1132 +sm4_ecb 1133 +sm4_cbc 1134 +sm4_ofb128 1135 +sm4_cfb1 1136 +sm4_cfb128 1137 +sm4_cfb8 1138 +sm4_ctr 1139 +ISO_CN 1140 +oscca 1141 +sm_scheme 1142 +sm3 1143 +sm3WithRSAEncryption 1144 +sha512_224WithRSAEncryption 1145 +sha512_256WithRSAEncryption 1146 diff --git a/crypto/objects/obj_xref.c b/crypto/objects/obj_xref.c index 627f5bca..05a5c862 100644 --- a/crypto/objects/obj_xref.c +++ b/crypto/objects/obj_xref.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-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 @@ -9,7 +9,7 @@ #include #include "obj_xref.h" -#include "e_os.h" +#include "internal/nelem.h" static STACK_OF(nid_triple) *sig_app, *sigx_app; @@ -136,30 +136,3 @@ void OBJ_sigid_free(void) sk_nid_triple_free(sigx_app); sigx_app = NULL; } - -#ifdef OBJ_XREF_TEST - -main() -{ - int n1, n2, n3; - - int i, rv; -# ifdef OBJ_XREF_TEST2 - for (i = 0; i < OSSL_NELEM(sigoid_srt); i++) { - OBJ_add_sigid(sigoid_srt[i][0], sigoid_srt[i][1], sigoid_srt[i][2]); - } -# endif - - for (i = 0; i < OSSL_NELEM(sigoid_srt); i++) { - n1 = sigoid_srt[i][0]; - rv = OBJ_find_sigid_algs(n1, &n2, &n3); - printf("Forward: %d, %s %s %s\n", rv, - OBJ_nid2ln(n1), OBJ_nid2ln(n2), OBJ_nid2ln(n3)); - n1 = 0; - rv = OBJ_find_sigid_by_algs(&n1, n2, n3); - printf("Reverse: %d, %s %s %s\n", rv, - OBJ_nid2ln(n1), OBJ_nid2ln(n2), OBJ_nid2ln(n3)); - } -} - -#endif diff --git a/crypto/objects/obj_xref.h b/crypto/objects/obj_xref.h index d09aa71f..ebd5bf5a 100644 --- a/crypto/objects/obj_xref.h +++ b/crypto/objects/obj_xref.h @@ -2,7 +2,7 @@ * WARNING: do not edit! * Generated by objxref.pl * - * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1998-2018 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 @@ -73,6 +73,11 @@ static const nid_triple sigoid_srt[] = { NID_id_GostR3410_2012_256}, {NID_id_tc26_signwithdigest_gost3410_2012_512, NID_id_GostR3411_2012_512, NID_id_GostR3410_2012_512}, + {NID_ED25519, NID_undef, NID_ED25519}, + {NID_RSA_SHA3_224, NID_sha3_224, NID_rsaEncryption}, + {NID_RSA_SHA3_256, NID_sha3_256, NID_rsaEncryption}, + {NID_RSA_SHA3_384, NID_sha3_384, NID_rsaEncryption}, + {NID_RSA_SHA3_512, NID_sha3_512, NID_rsaEncryption}, }; static const nid_triple *const sigoid_srt_xref[] = { @@ -115,4 +120,8 @@ static const nid_triple *const sigoid_srt_xref[] = { &sigoid_srt[28], &sigoid_srt[40], &sigoid_srt[41], + &sigoid_srt[43], + &sigoid_srt[44], + &sigoid_srt[45], + &sigoid_srt[46], }; diff --git a/crypto/objects/obj_xref.txt b/crypto/objects/obj_xref.txt index 981103b3..c8dee7b8 100644 --- a/crypto/objects/obj_xref.txt +++ b/crypto/objects/obj_xref.txt @@ -13,10 +13,15 @@ sha512WithRSAEncryption sha512 rsaEncryption sha224WithRSAEncryption sha224 rsaEncryption mdc2WithRSA mdc2 rsaEncryption ripemd160WithRSA ripemd160 rsaEncryption +RSA_SHA3_224 sha3_224 rsaEncryption +RSA_SHA3_256 sha3_256 rsaEncryption +RSA_SHA3_384 sha3_384 rsaEncryption +RSA_SHA3_512 sha3_512 rsaEncryption # For PSS the digest algorithm can vary and depends on the included # AlgorithmIdentifier. The digest "undef" indicates the public key # method should handle this explicitly. rsassaPss undef rsaEncryption +ED25519 undef ED25519 # Alternative deprecated OIDs. By using the older "rsa" OID this # type will be recognized by not normally used. diff --git a/crypto/objects/objects.pl b/crypto/objects/objects.pl index 3b40277a..20f726d4 100644 --- a/crypto/objects/objects.pl +++ b/crypto/objects/objects.pl @@ -1,11 +1,18 @@ #! /usr/bin/env perl -# Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2000-2018 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 +# Output year depends on the year of the script and the input files. +my $YEAR = [localtime([stat($0)]->[9])]->[5] + 1900; +my $iYEAR = [localtime([stat($ARGV[0])]->[9])]->[5] + 1900; +$YEAR = $iYEAR if $iYEAR > $YEAR; +$iYEAR = [localtime([stat($ARGV[1])]->[9])]->[5] + 1900; +$YEAR = $iYEAR if $iYEAR > $YEAR; + open (NUMIN,"$ARGV[1]") || die "Can't open number file $ARGV[1]"; $max_nid=0; $o=0; @@ -124,12 +131,12 @@ foreach (sort { $a <=> $b } keys %nidn) close NUMOUT; open (OUT,">$ARGV[2]") || die "Can't open output file $ARGV[2]"; -print OUT <<'EOF'; +print OUT <<"EOF"; /* * WARNING: do not edit! * Generated by crypto/objects/objects.pl * - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-$YEAR 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 diff --git a/crypto/objects/objects.txt b/crypto/objects/objects.txt index fc0781d1..74550be2 100644 --- a/crypto/objects/objects.txt +++ b/crypto/objects/objects.txt @@ -15,6 +15,9 @@ iso 3 : identified-organization identified-organization 6 1 5 5 8 1 1 : HMAC-MD5 : hmac-md5 identified-organization 6 1 5 5 8 1 2 : HMAC-SHA1 : hmac-sha1 +# "1.3.36.8.3.3" +identified-organization 36 8 3 3 : x509ExtAdmission : Professional Information or basis for Admission + identified-organization 132 : certicom-arc joint-iso-itu-t 23 : international-organizations : International Organizations @@ -175,6 +178,8 @@ pkcs1 11 : RSA-SHA256 : sha256WithRSAEncryption pkcs1 12 : RSA-SHA384 : sha384WithRSAEncryption pkcs1 13 : RSA-SHA512 : sha512WithRSAEncryption pkcs1 14 : RSA-SHA224 : sha224WithRSAEncryption +pkcs1 15 : RSA-SHA512/224 : sha512-224WithRSAEncryption +pkcs1 16 : RSA-SHA512/256 : sha512-256WithRSAEncryption pkcs 3 : pkcs3 pkcs3 1 : : dhKeyAgreement @@ -294,6 +299,7 @@ id-smime-aa 26 : id-smime-aa-ets-certCRLTimestamp id-smime-aa 27 : id-smime-aa-ets-archiveTimeStamp id-smime-aa 28 : id-smime-aa-signatureType id-smime-aa 29 : id-smime-aa-dvcs-dvc +id-smime-aa 47 : id-smime-aa-signingCertificateV2 # S/MIME Algorithm Identifiers # obsolete @@ -367,6 +373,9 @@ rsadsi 2 5 : MD5 : md5 rsadsi 2 6 : : hmacWithMD5 rsadsi 2 7 : : hmacWithSHA1 +member-body 156 10197 1 401 : SM3 : sm3 +member-body 156 10197 1 504 : RSA-SM3 : sm3WithRSAEncryption + # From RFC4231 rsadsi 2 8 : : hmacWithSHA224 rsadsi 2 9 : : hmacWithSHA256 @@ -512,6 +521,8 @@ id-kp 23 : sendRouter : Send Router id-kp 24 : sendProxiedRouter : Send Proxied Router id-kp 25 : sendOwner : Send Owner id-kp 26 : sendProxiedOwner : Send Proxied Owner +id-kp 27 : cmcCA : CMC Certificate Authority +id-kp 28 : cmcRA : CMC Registration Authority # CMP information types id-it 1 : id-it-caProtEncCert @@ -575,7 +586,7 @@ id-cmc 19 : id-cmc-responseInfo id-cmc 21 : id-cmc-queryPending id-cmc 22 : id-cmc-popLinkRandom id-cmc 23 : id-cmc-popLinkWitness -id-cmc 24 : id-cmc-confirmCertAcceptance +id-cmc 24 : id-cmc-confirmCertAcceptance # other names id-on 1 : id-on-personalData @@ -737,6 +748,11 @@ X509 53 : : deltaRevocationList X509 54 : dmdName : X509 65 : : pseudonym X509 72 : role : role +X509 97 : : organizationIdentifier +X509 98 : c3 : countryCode3c +X509 99 : n3 : countryCode3n +X509 100 : : dnsName + X500 8 : X500algorithms : directory services - algorithms X500algorithms 1 1 : RSA : rsa @@ -841,7 +857,7 @@ internet 6 : snmpv2 : SNMPv2 # Documents refer to "internet 7" as "mail". This however leads to ambiguities # with RFC2798, Section 9.1.3, where "mail" is defined as the short name for # rfc822Mailbox. The short name is therefore here left out for a reason. -# Subclasses of "mail", e.g. "MIME MHS" don't consitute a problem, as +# Subclasses of "mail", e.g. "MIME MHS" don't constitute a problem, as # references are realized via long name "Mail" (with capital M). internet 7 : : Mail @@ -921,17 +937,52 @@ aes 48 : id-aes256-wrap-pad : DES-EDE3-CFB1 : des-ede3-cfb1 : DES-EDE3-CFB8 : des-ede3-cfb8 -# OIDs for SHA224, SHA256, SHA385 and SHA512, according to x9.84. +# OIDs for SHA224, SHA256, SHA385 and SHA512, according to x9.84 and +# http://csrc.nist.gov/groups/ST/crypto_apps_infra/csor/algorithms.html +# "Middle" names are specified to be id-sha256, id-sha384, etc., but +# we adhere to unprefixed capitals for backward compatibility... !Alias nist_hashalgs nistAlgorithms 2 nist_hashalgs 1 : SHA256 : sha256 nist_hashalgs 2 : SHA384 : sha384 nist_hashalgs 3 : SHA512 : sha512 nist_hashalgs 4 : SHA224 : sha224 +nist_hashalgs 5 : SHA512-224 : sha512-224 +nist_hashalgs 6 : SHA512-256 : sha512-256 +nist_hashalgs 7 : SHA3-224 : sha3-224 +nist_hashalgs 8 : SHA3-256 : sha3-256 +nist_hashalgs 9 : SHA3-384 : sha3-384 +nist_hashalgs 10 : SHA3-512 : sha3-512 +nist_hashalgs 11 : SHAKE128 : shake128 +nist_hashalgs 12 : SHAKE256 : shake256 +nist_hashalgs 13 : id-hmacWithSHA3-224 : hmac-sha3-224 +nist_hashalgs 14 : id-hmacWithSHA3-256 : hmac-sha3-256 +nist_hashalgs 15 : id-hmacWithSHA3-384 : hmac-sha3-384 +nist_hashalgs 16 : id-hmacWithSHA3-512 : hmac-sha3-512 +# Below two are incomplete OIDs, to be uncommented when we figure out +# how to handle them... +# nist_hashalgs 17 : id-shake128-len : shake128-len +# nist_hashalgs 18 : id-shake256-len : shake256-len # OIDs for dsa-with-sha224 and dsa-with-sha256 !Alias dsa_with_sha2 nistAlgorithms 3 dsa_with_sha2 1 : dsa_with_SHA224 dsa_with_sha2 2 : dsa_with_SHA256 +# Above two belong below, but kept as they are for backward compatibility +!Alias sigAlgs nistAlgorithms 3 +sigAlgs 3 : id-dsa-with-sha384 : dsa_with_SHA384 +sigAlgs 4 : id-dsa-with-sha512 : dsa_with_SHA512 +sigAlgs 5 : id-dsa-with-sha3-224 : dsa_with_SHA3-224 +sigAlgs 6 : id-dsa-with-sha3-256 : dsa_with_SHA3-256 +sigAlgs 7 : id-dsa-with-sha3-384 : dsa_with_SHA3-384 +sigAlgs 8 : id-dsa-with-sha3-512 : dsa_with_SHA3-512 +sigAlgs 9 : id-ecdsa-with-sha3-224 : ecdsa_with_SHA3-224 +sigAlgs 10 : id-ecdsa-with-sha3-256 : ecdsa_with_SHA3-256 +sigAlgs 11 : id-ecdsa-with-sha3-384 : ecdsa_with_SHA3-384 +sigAlgs 12 : id-ecdsa-with-sha3-512 : ecdsa_with_SHA3-512 +sigAlgs 13 : id-rsassa-pkcs1-v1_5-with-sha3-224 : RSA-SHA3-224 +sigAlgs 14 : id-rsassa-pkcs1-v1_5-with-sha3-256 : RSA-SHA3-256 +sigAlgs 15 : id-rsassa-pkcs1-v1_5-with-sha3-384 : RSA-SHA3-384 +sigAlgs 16 : id-rsassa-pkcs1-v1_5-with-sha3-512 : RSA-SHA3-512 # Hold instruction CRL entry extension !Cname hold-instruction-code @@ -1322,7 +1373,7 @@ member-body 643 100 112 : issuerSignTool : Signing Tool of Issuer # Definitions for Camellia cipher - ECB, CFB, OFB MODE !Alias ntt-ds 0 3 4401 5 -!Alias camellia ntt-ds 3 1 9 +!Alias camellia ntt-ds 3 1 9 camellia 1 : CAMELLIA-128-ECB : camellia-128-ecb !Cname camellia-128-ofb128 @@ -1363,6 +1414,48 @@ camellia 50 : CAMELLIA-256-CMAC : camellia-256-cmac : CAMELLIA-192-CFB8 : camellia-192-cfb8 : CAMELLIA-256-CFB8 : camellia-256-cfb8 +# Definitions for ARIA cipher + +!Alias aria 1 2 410 200046 1 1 +aria 1 : ARIA-128-ECB : aria-128-ecb +aria 2 : ARIA-128-CBC : aria-128-cbc +!Cname aria-128-cfb128 +aria 3 : ARIA-128-CFB : aria-128-cfb +!Cname aria-128-ofb128 +aria 4 : ARIA-128-OFB : aria-128-ofb +aria 5 : ARIA-128-CTR : aria-128-ctr + +aria 6 : ARIA-192-ECB : aria-192-ecb +aria 7 : ARIA-192-CBC : aria-192-cbc +!Cname aria-192-cfb128 +aria 8 : ARIA-192-CFB : aria-192-cfb +!Cname aria-192-ofb128 +aria 9 : ARIA-192-OFB : aria-192-ofb +aria 10 : ARIA-192-CTR : aria-192-ctr + +aria 11 : ARIA-256-ECB : aria-256-ecb +aria 12 : ARIA-256-CBC : aria-256-cbc +!Cname aria-256-cfb128 +aria 13 : ARIA-256-CFB : aria-256-cfb +!Cname aria-256-ofb128 +aria 14 : ARIA-256-OFB : aria-256-ofb +aria 15 : ARIA-256-CTR : aria-256-ctr + +# There are no OIDs for these ARIA modes... + : ARIA-128-CFB1 : aria-128-cfb1 + : ARIA-192-CFB1 : aria-192-cfb1 + : ARIA-256-CFB1 : aria-256-cfb1 + : ARIA-128-CFB8 : aria-128-cfb8 + : ARIA-192-CFB8 : aria-192-cfb8 + : ARIA-256-CFB8 : aria-256-cfb8 + +aria 37 : ARIA-128-CCM : aria-128-ccm +aria 38 : ARIA-192-CCM : aria-192-ccm +aria 39 : ARIA-256-CCM : aria-256-ccm +aria 34 : ARIA-128-GCM : aria-128-gcm +aria 35 : ARIA-192-GCM : aria-192-gcm +aria 36 : ARIA-256-GCM : aria-256-gcm + # Definitions for SEED cipher - ECB, CBC, OFB mode member-body 410 200004 : KISA : kisa @@ -1373,6 +1466,23 @@ kisa 1 5 : SEED-CFB : seed-cfb !Cname seed-ofb128 kisa 1 6 : SEED-OFB : seed-ofb + +# Definitions for SM4 cipher + +member-body 156 : ISO-CN : ISO CN Member Body +ISO-CN 10197 : oscca +oscca 1 : sm-scheme + +sm-scheme 104 1 : SM4-ECB : sm4-ecb +sm-scheme 104 2 : SM4-CBC : sm4-cbc +!Cname sm4-ofb128 +sm-scheme 104 3 : SM4-OFB : sm4-ofb +!Cname sm4-cfb128 +sm-scheme 104 4 : SM4-CFB : sm4-cfb +sm-scheme 104 5 : SM4-CFB1 : sm4-cfb1 +sm-scheme 104 6 : SM4-CFB8 : sm4-cfb8 +sm-scheme 104 7 : SM4-CTR : sm4-ctr + # There is no OID that just denotes "HMAC" oddly enough... : HMAC : hmac @@ -1394,7 +1504,7 @@ ISO-US 10046 2 1 : dhpublicnumber : X9.42 DH # RFC 5639 curve OIDs (see http://www.ietf.org/rfc/rfc5639.txt) # versionOne OBJECT IDENTIFIER ::= { -# iso(1) identifified-organization(3) teletrust(36) algorithm(3) +# iso(1) identified-organization(3) teletrust(36) algorithm(3) # signature-algorithm(3) ecSign(2) ecStdCurvesAndGeneration(8) # ellipticCurve(1) 1 } 1 3 36 3 3 2 8 1 1 1 : brainpoolP160r1 @@ -1410,7 +1520,7 @@ ISO-US 10046 2 1 : dhpublicnumber : X9.42 DH 1 3 36 3 3 2 8 1 1 11 : brainpoolP384r1 1 3 36 3 3 2 8 1 1 12 : brainpoolP384t1 1 3 36 3 3 2 8 1 1 13 : brainpoolP512r1 -1 3 36 3 3 2 8 1 1 14 : brainpoolP512t1 +1 3 36 3 3 2 8 1 1 14 : brainpoolP512t1 # ECDH schemes from RFC5753 !Alias x9-63-scheme 1 3 133 16 840 63 0 @@ -1445,7 +1555,8 @@ secg-scheme 14 3 : dhSinglePass-cofactorDH-sha512kdf-scheme 1 3 6 1 4 1 311 60 2 1 3 : jurisdictionC : jurisdictionCountryName # SCRYPT algorithm -1 3 6 1 4 1 11591 4 11 : id-scrypt +!Cname id-scrypt +1 3 6 1 4 1 11591 4 11 : id-scrypt : scrypt # NID for TLS1 PRF : TLS1-PRF : tls1-prf @@ -1458,9 +1569,12 @@ secg-scheme 14 3 : dhSinglePass-cofactorDH-sha512kdf-scheme id-pkinit 4 : pkInitClientAuth : PKINIT Client Auth id-pkinit 5 : pkInitKDC : Signing KDC Response -# New curves from draft-ietf-curdle-pkix-00 +# New algorithms from draft-ietf-curdle-pkix-04 1 3 101 110 : X25519 1 3 101 111 : X448 +1 3 101 112 : ED25519 +1 3 101 113 : ED448 + # NIDs for cipher key exchange : KxRSA : kx-rsa @@ -1472,6 +1586,7 @@ id-pkinit 5 : pkInitKDC : Signing KDC Response : KxPSK : kx-psk : KxSRP : kx-srp : KxGOST : kx-gost + : KxANY : kx-any # NIDs for cipher authentication : AuthRSA : auth-rsa @@ -1482,4 +1597,15 @@ id-pkinit 5 : pkInitKDC : Signing KDC Response : AuthGOST12 : auth-gost12 : AuthSRP : auth-srp : AuthNULL : auth-null + : AuthANY : auth-any +# NID for Poly1305 + : Poly1305 : poly1305 +# NID for SipHash + : SipHash : siphash +# NIDs for RFC7919 DH parameters + : ffdhe2048 + : ffdhe3072 + : ffdhe4096 + : ffdhe6144 + : ffdhe8192 diff --git a/crypto/objects/objxref.pl b/crypto/objects/objxref.pl index 53f9bd60..0ec63f06 100644 --- a/crypto/objects/objxref.pl +++ b/crypto/objects/objxref.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 1998-2018 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 @@ -14,6 +14,13 @@ my %oid_tbl; my ($mac_file, $xref_file) = @ARGV; +# Output year depends on the year of the script and the input file. +my $YEAR = [localtime([stat($0)]->[9])]->[5] + 1900; +my $iYEAR = [localtime([stat($mac_file)]->[9])]->[5] + 1900; +$YEAR = $iYEAR if $iYEAR > $YEAR; +$iYEAR = [localtime([stat($xref_file)]->[9])]->[5] + 1900; +$YEAR = $iYEAR if $iYEAR > $YEAR; + open(IN, $mac_file) || die "Can't open $mac_file, $!\n"; # Read in OID nid values for a lookup table. @@ -71,7 +78,7 @@ print < #include #include "internal/cryptlib.h" +#include #include #include #include @@ -199,9 +200,9 @@ const STACK_OF(X509) *OCSP_resp_get0_certs(const OCSP_BASICRESP *bs) int OCSP_resp_get0_id(const OCSP_BASICRESP *bs, const ASN1_OCTET_STRING **pid, const X509_NAME **pname) - { const OCSP_RESPID *rid = &bs->tbsResponseData.responderId; + if (rid->type == V_OCSP_RESPID_NAME) { *pname = rid->value.byName; *pid = NULL; @@ -214,6 +215,26 @@ int OCSP_resp_get0_id(const OCSP_BASICRESP *bs, return 1; } +int OCSP_resp_get1_id(const OCSP_BASICRESP *bs, + ASN1_OCTET_STRING **pid, + X509_NAME **pname) +{ + const OCSP_RESPID *rid = &bs->tbsResponseData.responderId; + + if (rid->type == V_OCSP_RESPID_NAME) { + *pname = X509_NAME_dup(rid->value.byName); + *pid = NULL; + } else if (rid->type == V_OCSP_RESPID_KEY) { + *pid = ASN1_OCTET_STRING_dup(rid->value.byKey); + *pname = NULL; + } else { + return 0; + } + if (*pname == NULL && *pid == NULL) + return 0; + return 1; +} + /* Look single response matching a given certificate ID */ int OCSP_resp_find(OCSP_BASICRESP *bs, OCSP_CERTID *id, int last) diff --git a/crypto/ocsp/ocsp_err.c b/crypto/ocsp/ocsp_err.c index a2d96e9c..660e1936 100644 --- a/crypto/ocsp/ocsp_err.c +++ b/crypto/ocsp/ocsp_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -8,71 +8,82 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_OCSP,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_OCSP,0,reason) - -static ERR_STRING_DATA OCSP_str_functs[] = { - {ERR_FUNC(OCSP_F_D2I_OCSP_NONCE), "d2i_ocsp_nonce"}, - {ERR_FUNC(OCSP_F_OCSP_BASIC_ADD1_STATUS), "OCSP_basic_add1_status"}, - {ERR_FUNC(OCSP_F_OCSP_BASIC_SIGN), "OCSP_basic_sign"}, - {ERR_FUNC(OCSP_F_OCSP_BASIC_VERIFY), "OCSP_basic_verify"}, - {ERR_FUNC(OCSP_F_OCSP_CERT_ID_NEW), "OCSP_cert_id_new"}, - {ERR_FUNC(OCSP_F_OCSP_CHECK_DELEGATED), "ocsp_check_delegated"}, - {ERR_FUNC(OCSP_F_OCSP_CHECK_IDS), "ocsp_check_ids"}, - {ERR_FUNC(OCSP_F_OCSP_CHECK_ISSUER), "ocsp_check_issuer"}, - {ERR_FUNC(OCSP_F_OCSP_CHECK_VALIDITY), "OCSP_check_validity"}, - {ERR_FUNC(OCSP_F_OCSP_MATCH_ISSUERID), "ocsp_match_issuerid"}, - {ERR_FUNC(OCSP_F_OCSP_PARSE_URL), "OCSP_parse_url"}, - {ERR_FUNC(OCSP_F_OCSP_REQUEST_SIGN), "OCSP_request_sign"}, - {ERR_FUNC(OCSP_F_OCSP_REQUEST_VERIFY), "OCSP_request_verify"}, - {ERR_FUNC(OCSP_F_OCSP_RESPONSE_GET1_BASIC), "OCSP_response_get1_basic"}, - {ERR_FUNC(OCSP_F_PARSE_HTTP_LINE1), "parse_http_line1"}, +static const ERR_STRING_DATA OCSP_str_functs[] = { + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_D2I_OCSP_NONCE, 0), "d2i_ocsp_nonce"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_BASIC_ADD1_STATUS, 0), + "OCSP_basic_add1_status"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_BASIC_SIGN, 0), "OCSP_basic_sign"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_BASIC_SIGN_CTX, 0), + "OCSP_basic_sign_ctx"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_BASIC_VERIFY, 0), "OCSP_basic_verify"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_CERT_ID_NEW, 0), "OCSP_cert_id_new"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_CHECK_DELEGATED, 0), + "ocsp_check_delegated"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_CHECK_IDS, 0), "ocsp_check_ids"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_CHECK_ISSUER, 0), "ocsp_check_issuer"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_CHECK_VALIDITY, 0), + "OCSP_check_validity"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_MATCH_ISSUERID, 0), + "ocsp_match_issuerid"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_PARSE_URL, 0), "OCSP_parse_url"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_REQUEST_SIGN, 0), "OCSP_request_sign"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_REQUEST_VERIFY, 0), + "OCSP_request_verify"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_OCSP_RESPONSE_GET1_BASIC, 0), + "OCSP_response_get1_basic"}, + {ERR_PACK(ERR_LIB_OCSP, OCSP_F_PARSE_HTTP_LINE1, 0), "parse_http_line1"}, {0, NULL} }; -static ERR_STRING_DATA OCSP_str_reasons[] = { - {ERR_REASON(OCSP_R_CERTIFICATE_VERIFY_ERROR), "certificate verify error"}, - {ERR_REASON(OCSP_R_DIGEST_ERR), "digest err"}, - {ERR_REASON(OCSP_R_ERROR_IN_NEXTUPDATE_FIELD), - "error in nextupdate field"}, - {ERR_REASON(OCSP_R_ERROR_IN_THISUPDATE_FIELD), - "error in thisupdate field"}, - {ERR_REASON(OCSP_R_ERROR_PARSING_URL), "error parsing url"}, - {ERR_REASON(OCSP_R_MISSING_OCSPSIGNING_USAGE), - "missing ocspsigning usage"}, - {ERR_REASON(OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE), - "nextupdate before thisupdate"}, - {ERR_REASON(OCSP_R_NOT_BASIC_RESPONSE), "not basic response"}, - {ERR_REASON(OCSP_R_NO_CERTIFICATES_IN_CHAIN), "no certificates in chain"}, - {ERR_REASON(OCSP_R_NO_RESPONSE_DATA), "no response data"}, - {ERR_REASON(OCSP_R_NO_REVOKED_TIME), "no revoked time"}, - {ERR_REASON(OCSP_R_NO_SIGNER_KEY), "no signer key"}, - {ERR_REASON(OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), - "private key does not match certificate"}, - {ERR_REASON(OCSP_R_REQUEST_NOT_SIGNED), "request not signed"}, - {ERR_REASON(OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA), - "response contains no revocation data"}, - {ERR_REASON(OCSP_R_ROOT_CA_NOT_TRUSTED), "root ca not trusted"}, - {ERR_REASON(OCSP_R_SERVER_RESPONSE_ERROR), "server response error"}, - {ERR_REASON(OCSP_R_SERVER_RESPONSE_PARSE_ERROR), - "server response parse error"}, - {ERR_REASON(OCSP_R_SIGNATURE_FAILURE), "signature failure"}, - {ERR_REASON(OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND), - "signer certificate not found"}, - {ERR_REASON(OCSP_R_STATUS_EXPIRED), "status expired"}, - {ERR_REASON(OCSP_R_STATUS_NOT_YET_VALID), "status not yet valid"}, - {ERR_REASON(OCSP_R_STATUS_TOO_OLD), "status too old"}, - {ERR_REASON(OCSP_R_UNKNOWN_MESSAGE_DIGEST), "unknown message digest"}, - {ERR_REASON(OCSP_R_UNKNOWN_NID), "unknown nid"}, - {ERR_REASON(OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE), - "unsupported requestorname type"}, +static const ERR_STRING_DATA OCSP_str_reasons[] = { + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_CERTIFICATE_VERIFY_ERROR), + "certificate verify error"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_DIGEST_ERR), "digest err"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_ERROR_IN_NEXTUPDATE_FIELD), + "error in nextupdate field"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_ERROR_IN_THISUPDATE_FIELD), + "error in thisupdate field"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_ERROR_PARSING_URL), "error parsing url"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_MISSING_OCSPSIGNING_USAGE), + "missing ocspsigning usage"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE), + "nextupdate before thisupdate"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NOT_BASIC_RESPONSE), + "not basic response"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_CERTIFICATES_IN_CHAIN), + "no certificates in chain"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_RESPONSE_DATA), "no response data"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_REVOKED_TIME), "no revoked time"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_SIGNER_KEY), "no signer key"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), + "private key does not match certificate"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_REQUEST_NOT_SIGNED), + "request not signed"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA), + "response contains no revocation data"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_ROOT_CA_NOT_TRUSTED), + "root ca not trusted"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_SERVER_RESPONSE_ERROR), + "server response error"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_SERVER_RESPONSE_PARSE_ERROR), + "server response parse error"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_SIGNATURE_FAILURE), "signature failure"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND), + "signer certificate not found"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_STATUS_EXPIRED), "status expired"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_STATUS_NOT_YET_VALID), + "status not yet valid"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_STATUS_TOO_OLD), "status too old"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_UNKNOWN_MESSAGE_DIGEST), + "unknown message digest"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_UNKNOWN_NID), "unknown nid"}, + {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE), + "unsupported requestorname type"}, {0, NULL} }; @@ -81,10 +92,9 @@ static ERR_STRING_DATA OCSP_str_reasons[] = { int ERR_load_OCSP_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(OCSP_str_functs[0].error) == NULL) { - ERR_load_strings(0, OCSP_str_functs); - ERR_load_strings(0, OCSP_str_reasons); + ERR_load_strings_const(OCSP_str_functs); + ERR_load_strings_const(OCSP_str_reasons); } #endif return 1; diff --git a/crypto/ocsp/ocsp_ext.c b/crypto/ocsp/ocsp_ext.c index b829b2e4..27ee2124 100644 --- a/crypto/ocsp/ocsp_ext.c +++ b/crypto/ocsp/ocsp_ext.c @@ -22,7 +22,7 @@ int OCSP_REQUEST_get_ext_count(OCSP_REQUEST *x) { - return (X509v3_get_ext_count(x->tbsRequest.requestExtensions)); + return X509v3_get_ext_count(x->tbsRequest.requestExtensions); } int OCSP_REQUEST_get_ext_by_NID(OCSP_REQUEST *x, int nid, int lastpos) @@ -46,12 +46,12 @@ int OCSP_REQUEST_get_ext_by_critical(OCSP_REQUEST *x, int crit, int lastpos) X509_EXTENSION *OCSP_REQUEST_get_ext(OCSP_REQUEST *x, int loc) { - return (X509v3_get_ext(x->tbsRequest.requestExtensions, loc)); + return X509v3_get_ext(x->tbsRequest.requestExtensions, loc); } X509_EXTENSION *OCSP_REQUEST_delete_ext(OCSP_REQUEST *x, int loc) { - return (X509v3_delete_ext(x->tbsRequest.requestExtensions, loc)); + return X509v3_delete_ext(x->tbsRequest.requestExtensions, loc); } void *OCSP_REQUEST_get1_ext_d2i(OCSP_REQUEST *x, int nid, int *crit, int *idx) @@ -76,18 +76,18 @@ int OCSP_REQUEST_add_ext(OCSP_REQUEST *x, X509_EXTENSION *ex, int loc) int OCSP_ONEREQ_get_ext_count(OCSP_ONEREQ *x) { - return (X509v3_get_ext_count(x->singleRequestExtensions)); + return X509v3_get_ext_count(x->singleRequestExtensions); } int OCSP_ONEREQ_get_ext_by_NID(OCSP_ONEREQ *x, int nid, int lastpos) { - return (X509v3_get_ext_by_NID(x->singleRequestExtensions, nid, lastpos)); + return X509v3_get_ext_by_NID(x->singleRequestExtensions, nid, lastpos); } int OCSP_ONEREQ_get_ext_by_OBJ(OCSP_ONEREQ *x, const ASN1_OBJECT *obj, int lastpos) { - return (X509v3_get_ext_by_OBJ(x->singleRequestExtensions, obj, lastpos)); + return X509v3_get_ext_by_OBJ(x->singleRequestExtensions, obj, lastpos); } int OCSP_ONEREQ_get_ext_by_critical(OCSP_ONEREQ *x, int crit, int lastpos) @@ -98,12 +98,12 @@ int OCSP_ONEREQ_get_ext_by_critical(OCSP_ONEREQ *x, int crit, int lastpos) X509_EXTENSION *OCSP_ONEREQ_get_ext(OCSP_ONEREQ *x, int loc) { - return (X509v3_get_ext(x->singleRequestExtensions, loc)); + return X509v3_get_ext(x->singleRequestExtensions, loc); } X509_EXTENSION *OCSP_ONEREQ_delete_ext(OCSP_ONEREQ *x, int loc) { - return (X509v3_delete_ext(x->singleRequestExtensions, loc)); + return X509v3_delete_ext(x->singleRequestExtensions, loc); } void *OCSP_ONEREQ_get1_ext_d2i(OCSP_ONEREQ *x, int nid, int *crit, int *idx) @@ -127,7 +127,7 @@ int OCSP_ONEREQ_add_ext(OCSP_ONEREQ *x, X509_EXTENSION *ex, int loc) int OCSP_BASICRESP_get_ext_count(OCSP_BASICRESP *x) { - return (X509v3_get_ext_count(x->tbsResponseData.responseExtensions)); + return X509v3_get_ext_count(x->tbsResponseData.responseExtensions); } int OCSP_BASICRESP_get_ext_by_NID(OCSP_BASICRESP *x, int nid, int lastpos) @@ -152,12 +152,12 @@ int OCSP_BASICRESP_get_ext_by_critical(OCSP_BASICRESP *x, int crit, X509_EXTENSION *OCSP_BASICRESP_get_ext(OCSP_BASICRESP *x, int loc) { - return (X509v3_get_ext(x->tbsResponseData.responseExtensions, loc)); + return X509v3_get_ext(x->tbsResponseData.responseExtensions, loc); } X509_EXTENSION *OCSP_BASICRESP_delete_ext(OCSP_BASICRESP *x, int loc) { - return (X509v3_delete_ext(x->tbsResponseData.responseExtensions, loc)); + return X509v3_delete_ext(x->tbsResponseData.responseExtensions, loc); } void *OCSP_BASICRESP_get1_ext_d2i(OCSP_BASICRESP *x, int nid, int *crit, @@ -184,34 +184,34 @@ int OCSP_BASICRESP_add_ext(OCSP_BASICRESP *x, X509_EXTENSION *ex, int loc) int OCSP_SINGLERESP_get_ext_count(OCSP_SINGLERESP *x) { - return (X509v3_get_ext_count(x->singleExtensions)); + return X509v3_get_ext_count(x->singleExtensions); } int OCSP_SINGLERESP_get_ext_by_NID(OCSP_SINGLERESP *x, int nid, int lastpos) { - return (X509v3_get_ext_by_NID(x->singleExtensions, nid, lastpos)); + return X509v3_get_ext_by_NID(x->singleExtensions, nid, lastpos); } int OCSP_SINGLERESP_get_ext_by_OBJ(OCSP_SINGLERESP *x, const ASN1_OBJECT *obj, int lastpos) { - return (X509v3_get_ext_by_OBJ(x->singleExtensions, obj, lastpos)); + return X509v3_get_ext_by_OBJ(x->singleExtensions, obj, lastpos); } int OCSP_SINGLERESP_get_ext_by_critical(OCSP_SINGLERESP *x, int crit, int lastpos) { - return (X509v3_get_ext_by_critical(x->singleExtensions, crit, lastpos)); + return X509v3_get_ext_by_critical(x->singleExtensions, crit, lastpos); } X509_EXTENSION *OCSP_SINGLERESP_get_ext(OCSP_SINGLERESP *x, int loc) { - return (X509v3_get_ext(x->singleExtensions, loc)); + return X509v3_get_ext(x->singleExtensions, loc); } X509_EXTENSION *OCSP_SINGLERESP_delete_ext(OCSP_SINGLERESP *x, int loc) { - return (X509v3_delete_ext(x->singleExtensions, loc)); + return X509v3_delete_ext(x->singleExtensions, loc); } void *OCSP_SINGLERESP_get1_ext_d2i(OCSP_SINGLERESP *x, int nid, int *crit, diff --git a/crypto/ocsp/ocsp_ht.c b/crypto/ocsp/ocsp_ht.c index d8796ca6..42c36864 100644 --- a/crypto/ocsp/ocsp_ht.c +++ b/crypto/ocsp/ocsp_ht.c @@ -1,5 +1,5 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-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 @@ -7,11 +7,11 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" #include #include -#include +#include "internal/ctype.h" #include -#include "e_os.h" #include #include #include @@ -209,7 +209,7 @@ static int parse_http_line1(char *line) char *p, *q, *r; /* Skip to first white space (passed protocol info) */ - for (p = line; *p && !isspace((unsigned char)*p); p++) + for (p = line; *p && !ossl_isspace(*p); p++) continue; if (!*p) { OCSPerr(OCSP_F_PARSE_HTTP_LINE1, OCSP_R_SERVER_RESPONSE_PARSE_ERROR); @@ -217,7 +217,7 @@ static int parse_http_line1(char *line) } /* Skip past white space to start of response code */ - while (*p && isspace((unsigned char)*p)) + while (*p && ossl_isspace(*p)) p++; if (!*p) { @@ -226,7 +226,7 @@ static int parse_http_line1(char *line) } /* Find end of response code: first whitespace after start of code */ - for (q = p; *q && !isspace((unsigned char)*q); q++) + for (q = p; *q && !ossl_isspace(*q); q++) continue; if (!*q) { @@ -244,7 +244,7 @@ static int parse_http_line1(char *line) return 0; /* Skip over any leading white space in message */ - while (*q && isspace((unsigned char)*q)) + while (*q && ossl_isspace(*q)) q++; if (*q) { @@ -253,7 +253,7 @@ static int parse_http_line1(char *line) */ /* We know q has a non white space character so this is OK */ - for (r = q + strlen(q) - 1; isspace((unsigned char)*r); r--) + for (r = q + strlen(q) - 1; ossl_isspace(*r); r--) *r = 0; } if (retcode != 200) { diff --git a/crypto/ocsp/ocsp_lcl.h b/crypto/ocsp/ocsp_lcl.h index d1cf1583..36646fdf 100644 --- a/crypto/ocsp/ocsp_lcl.h +++ b/crypto/ocsp/ocsp_lcl.h @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2018 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 @@ -224,6 +224,10 @@ struct ocsp_service_locator_st { ASN1_item_sign(ASN1_ITEM_rptr(OCSP_RESPDATA),&(o)->signatureAlgorithm,\ NULL,(o)->signature,&(o)->tbsResponseData,pkey,md) +# define OCSP_BASICRESP_sign_ctx(o,ctx,d) \ + ASN1_item_sign_ctx(ASN1_ITEM_rptr(OCSP_RESPDATA),&(o)->signatureAlgorithm,\ + NULL,(o)->signature,&(o)->tbsResponseData,ctx) + # define OCSP_REQUEST_verify(a,r) ASN1_item_verify(ASN1_ITEM_rptr(OCSP_REQINFO),\ &(a)->optionalSignature->signatureAlgorithm,\ (a)->optionalSignature->signature,&(a)->tbsRequest,r) diff --git a/crypto/ocsp/ocsp_srv.c b/crypto/ocsp/ocsp_srv.c index 46a4bf78..eff6ddbd 100644 --- a/crypto/ocsp/ocsp_srv.c +++ b/crypto/ocsp/ocsp_srv.c @@ -1,5 +1,5 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-2018 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 @@ -168,15 +168,28 @@ int OCSP_basic_add1_cert(OCSP_BASICRESP *resp, X509 *cert) return 1; } -int OCSP_basic_sign(OCSP_BASICRESP *brsp, - X509 *signer, EVP_PKEY *key, const EVP_MD *dgst, +/* + * Sign an OCSP response using the parameters contained in the digest context, + * set the responderID to the subject name in the signer's certificate, and + * include one or more optional certificates in the response. + */ + +int OCSP_basic_sign_ctx(OCSP_BASICRESP *brsp, + X509 *signer, EVP_MD_CTX *ctx, STACK_OF(X509) *certs, unsigned long flags) { int i; OCSP_RESPID *rid; + EVP_PKEY *pkey; - if (!X509_check_private_key(signer, key)) { - OCSPerr(OCSP_F_OCSP_BASIC_SIGN, + if (ctx == NULL || EVP_MD_CTX_pkey_ctx(ctx) == NULL) { + OCSPerr(OCSP_F_OCSP_BASIC_SIGN_CTX, OCSP_R_NO_SIGNER_KEY); + goto err; + } + + pkey = EVP_PKEY_CTX_get0_pkey(EVP_MD_CTX_pkey_ctx(ctx)); + if (pkey == NULL || !X509_check_private_key(signer, pkey)) { + OCSPerr(OCSP_F_OCSP_BASIC_SIGN_CTX, OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE); goto err; } @@ -208,7 +221,7 @@ int OCSP_basic_sign(OCSP_BASICRESP *brsp, * -- Richard Levitte */ - if (!OCSP_BASICRESP_sign(brsp, key, dgst, 0)) + if (!OCSP_BASICRESP_sign_ctx(brsp, ctx, 0)) goto err; return 1; @@ -216,6 +229,23 @@ int OCSP_basic_sign(OCSP_BASICRESP *brsp, return 0; } +int OCSP_basic_sign(OCSP_BASICRESP *brsp, + X509 *signer, EVP_PKEY *key, const EVP_MD *dgst, + STACK_OF(X509) *certs, unsigned long flags) +{ + EVP_MD_CTX *ctx = EVP_MD_CTX_new(); + EVP_PKEY_CTX *pkctx = NULL; + int i; + + if (!EVP_DigestSignInit(ctx, &pkctx, dgst, NULL, key)) { + EVP_MD_CTX_free(ctx); + return 0; + } + i = OCSP_basic_sign_ctx(brsp, signer, ctx, certs, flags); + EVP_MD_CTX_free(ctx); + return i; +} + int OCSP_RESPID_set_by_name(OCSP_RESPID *respid, X509 *cert) { if (!X509_NAME_set(&respid->value.byName, X509_get_subject_name(cert))) @@ -265,7 +295,7 @@ int OCSP_RESPID_match(OCSP_RESPID *respid, X509 *cert) return (ASN1_STRING_length(respid->value.byKey) == SHA_DIGEST_LENGTH) && (memcmp(ASN1_STRING_get0_data(respid->value.byKey), md, SHA_DIGEST_LENGTH) == 0); - } else if(respid->type == V_OCSP_RESPID_NAME) { + } else if (respid->type == V_OCSP_RESPID_NAME) { if (respid->value.byName == NULL) return 0; diff --git a/crypto/pariscid.pl b/crypto/pariscid.pl index 3d4a5f8a..f82e27ac 100644 --- a/crypto/pariscid.pl +++ b/crypto/pariscid.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 2009-2018 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2009-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 @@ -160,7 +160,7 @@ L\$oop_cmp or %r29,$rv,$rv sub %r0,$rv,%r29 - extru %r29,0,1,$rv + extru %r29,31,1,$rv L\$no_data bv ($rp) .EXIT diff --git a/crypto/pem/pem_err.c b/crypto/pem/pem_err.c index f36d8932..c4c09e4c 100644 --- a/crypto/pem/pem_err.c +++ b/crypto/pem/pem_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,95 +8,106 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_PEM,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_PEM,0,reason) - -static ERR_STRING_DATA PEM_str_functs[] = { - {ERR_FUNC(PEM_F_B2I_DSS), "b2i_dss"}, - {ERR_FUNC(PEM_F_B2I_PVK_BIO), "b2i_PVK_bio"}, - {ERR_FUNC(PEM_F_B2I_RSA), "b2i_rsa"}, - {ERR_FUNC(PEM_F_CHECK_BITLEN_DSA), "check_bitlen_dsa"}, - {ERR_FUNC(PEM_F_CHECK_BITLEN_RSA), "check_bitlen_rsa"}, - {ERR_FUNC(PEM_F_D2I_PKCS8PRIVATEKEY_BIO), "d2i_PKCS8PrivateKey_bio"}, - {ERR_FUNC(PEM_F_D2I_PKCS8PRIVATEKEY_FP), "d2i_PKCS8PrivateKey_fp"}, - {ERR_FUNC(PEM_F_DO_B2I), "do_b2i"}, - {ERR_FUNC(PEM_F_DO_B2I_BIO), "do_b2i_bio"}, - {ERR_FUNC(PEM_F_DO_BLOB_HEADER), "do_blob_header"}, - {ERR_FUNC(PEM_F_DO_PK8PKEY), "do_pk8pkey"}, - {ERR_FUNC(PEM_F_DO_PK8PKEY_FP), "do_pk8pkey_fp"}, - {ERR_FUNC(PEM_F_DO_PVK_BODY), "do_PVK_body"}, - {ERR_FUNC(PEM_F_DO_PVK_HEADER), "do_PVK_header"}, - {ERR_FUNC(PEM_F_I2B_PVK), "i2b_PVK"}, - {ERR_FUNC(PEM_F_I2B_PVK_BIO), "i2b_PVK_bio"}, - {ERR_FUNC(PEM_F_LOAD_IV), "load_iv"}, - {ERR_FUNC(PEM_F_PEM_ASN1_READ), "PEM_ASN1_read"}, - {ERR_FUNC(PEM_F_PEM_ASN1_READ_BIO), "PEM_ASN1_read_bio"}, - {ERR_FUNC(PEM_F_PEM_ASN1_WRITE), "PEM_ASN1_write"}, - {ERR_FUNC(PEM_F_PEM_ASN1_WRITE_BIO), "PEM_ASN1_write_bio"}, - {ERR_FUNC(PEM_F_PEM_DEF_CALLBACK), "PEM_def_callback"}, - {ERR_FUNC(PEM_F_PEM_DO_HEADER), "PEM_do_header"}, - {ERR_FUNC(PEM_F_PEM_GET_EVP_CIPHER_INFO), "PEM_get_EVP_CIPHER_INFO"}, - {ERR_FUNC(PEM_F_PEM_READ), "PEM_read"}, - {ERR_FUNC(PEM_F_PEM_READ_BIO), "PEM_read_bio"}, - {ERR_FUNC(PEM_F_PEM_READ_BIO_DHPARAMS), "PEM_read_bio_DHparams"}, - {ERR_FUNC(PEM_F_PEM_READ_BIO_PARAMETERS), "PEM_read_bio_Parameters"}, - {ERR_FUNC(PEM_F_PEM_READ_BIO_PRIVATEKEY), "PEM_read_bio_PrivateKey"}, - {ERR_FUNC(PEM_F_PEM_READ_DHPARAMS), "PEM_read_DHparams"}, - {ERR_FUNC(PEM_F_PEM_READ_PRIVATEKEY), "PEM_read_PrivateKey"}, - {ERR_FUNC(PEM_F_PEM_SIGNFINAL), "PEM_SignFinal"}, - {ERR_FUNC(PEM_F_PEM_WRITE), "PEM_write"}, - {ERR_FUNC(PEM_F_PEM_WRITE_BIO), "PEM_write_bio"}, - {ERR_FUNC(PEM_F_PEM_WRITE_PRIVATEKEY), "PEM_write_PrivateKey"}, - {ERR_FUNC(PEM_F_PEM_X509_INFO_READ), "PEM_X509_INFO_read"}, - {ERR_FUNC(PEM_F_PEM_X509_INFO_READ_BIO), "PEM_X509_INFO_read_bio"}, - {ERR_FUNC(PEM_F_PEM_X509_INFO_WRITE_BIO), "PEM_X509_INFO_write_bio"}, +static const ERR_STRING_DATA PEM_str_functs[] = { + {ERR_PACK(ERR_LIB_PEM, PEM_F_B2I_DSS, 0), "b2i_dss"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_B2I_PVK_BIO, 0), "b2i_PVK_bio"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_B2I_RSA, 0), "b2i_rsa"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_CHECK_BITLEN_DSA, 0), "check_bitlen_dsa"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_CHECK_BITLEN_RSA, 0), "check_bitlen_rsa"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_D2I_PKCS8PRIVATEKEY_BIO, 0), + "d2i_PKCS8PrivateKey_bio"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_D2I_PKCS8PRIVATEKEY_FP, 0), + "d2i_PKCS8PrivateKey_fp"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_DO_B2I, 0), "do_b2i"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_DO_B2I_BIO, 0), "do_b2i_bio"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_DO_BLOB_HEADER, 0), "do_blob_header"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_DO_PK8PKEY, 0), "do_pk8pkey"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_DO_PK8PKEY_FP, 0), "do_pk8pkey_fp"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_DO_PVK_BODY, 0), "do_PVK_body"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_DO_PVK_HEADER, 0), "do_PVK_header"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_GET_HEADER_AND_DATA, 0), + "get_header_and_data"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_GET_NAME, 0), "get_name"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_I2B_PVK, 0), "i2b_PVK"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_I2B_PVK_BIO, 0), "i2b_PVK_bio"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_LOAD_IV, 0), "load_iv"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_ASN1_READ, 0), "PEM_ASN1_read"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_ASN1_READ_BIO, 0), "PEM_ASN1_read_bio"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_ASN1_WRITE, 0), "PEM_ASN1_write"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_ASN1_WRITE_BIO, 0), "PEM_ASN1_write_bio"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_DEF_CALLBACK, 0), "PEM_def_callback"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_DO_HEADER, 0), "PEM_do_header"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_GET_EVP_CIPHER_INFO, 0), + "PEM_get_EVP_CIPHER_INFO"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_READ, 0), "PEM_read"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_READ_BIO, 0), "PEM_read_bio"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_READ_BIO_DHPARAMS, 0), + "PEM_read_bio_DHparams"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_READ_BIO_EX, 0), "PEM_read_bio_ex"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_READ_BIO_PARAMETERS, 0), + "PEM_read_bio_Parameters"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_READ_BIO_PRIVATEKEY, 0), + "PEM_read_bio_PrivateKey"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_READ_DHPARAMS, 0), "PEM_read_DHparams"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_READ_PRIVATEKEY, 0), + "PEM_read_PrivateKey"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_SIGNFINAL, 0), "PEM_SignFinal"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_WRITE, 0), "PEM_write"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_WRITE_BIO, 0), "PEM_write_bio"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_WRITE_PRIVATEKEY, 0), + "PEM_write_PrivateKey"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_X509_INFO_READ, 0), "PEM_X509_INFO_read"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_X509_INFO_READ_BIO, 0), + "PEM_X509_INFO_read_bio"}, + {ERR_PACK(ERR_LIB_PEM, PEM_F_PEM_X509_INFO_WRITE_BIO, 0), + "PEM_X509_INFO_write_bio"}, {0, NULL} }; -static ERR_STRING_DATA PEM_str_reasons[] = { - {ERR_REASON(PEM_R_BAD_BASE64_DECODE), "bad base64 decode"}, - {ERR_REASON(PEM_R_BAD_DECRYPT), "bad decrypt"}, - {ERR_REASON(PEM_R_BAD_END_LINE), "bad end line"}, - {ERR_REASON(PEM_R_BAD_IV_CHARS), "bad iv chars"}, - {ERR_REASON(PEM_R_BAD_MAGIC_NUMBER), "bad magic number"}, - {ERR_REASON(PEM_R_BAD_PASSWORD_READ), "bad password read"}, - {ERR_REASON(PEM_R_BAD_VERSION_NUMBER), "bad version number"}, - {ERR_REASON(PEM_R_BIO_WRITE_FAILURE), "bio write failure"}, - {ERR_REASON(PEM_R_CIPHER_IS_NULL), "cipher is null"}, - {ERR_REASON(PEM_R_ERROR_CONVERTING_PRIVATE_KEY), - "error converting private key"}, - {ERR_REASON(PEM_R_EXPECTING_PRIVATE_KEY_BLOB), - "expecting private key blob"}, - {ERR_REASON(PEM_R_EXPECTING_PUBLIC_KEY_BLOB), - "expecting public key blob"}, - {ERR_REASON(PEM_R_HEADER_TOO_LONG), "header too long"}, - {ERR_REASON(PEM_R_INCONSISTENT_HEADER), "inconsistent header"}, - {ERR_REASON(PEM_R_KEYBLOB_HEADER_PARSE_ERROR), - "keyblob header parse error"}, - {ERR_REASON(PEM_R_KEYBLOB_TOO_SHORT), "keyblob too short"}, - {ERR_REASON(PEM_R_MISSING_DEK_IV), "missing dek iv"}, - {ERR_REASON(PEM_R_NOT_DEK_INFO), "not dek info"}, - {ERR_REASON(PEM_R_NOT_ENCRYPTED), "not encrypted"}, - {ERR_REASON(PEM_R_NOT_PROC_TYPE), "not proc type"}, - {ERR_REASON(PEM_R_NO_START_LINE), "no start line"}, - {ERR_REASON(PEM_R_PROBLEMS_GETTING_PASSWORD), - "problems getting password"}, - {ERR_REASON(PEM_R_PVK_DATA_TOO_SHORT), "pvk data too short"}, - {ERR_REASON(PEM_R_PVK_TOO_SHORT), "pvk too short"}, - {ERR_REASON(PEM_R_READ_KEY), "read key"}, - {ERR_REASON(PEM_R_SHORT_HEADER), "short header"}, - {ERR_REASON(PEM_R_UNEXPECTED_DEK_IV), "unexpected dek iv"}, - {ERR_REASON(PEM_R_UNSUPPORTED_CIPHER), "unsupported cipher"}, - {ERR_REASON(PEM_R_UNSUPPORTED_ENCRYPTION), "unsupported encryption"}, - {ERR_REASON(PEM_R_UNSUPPORTED_KEY_COMPONENTS), - "unsupported key components"}, +static const ERR_STRING_DATA PEM_str_reasons[] = { + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_BASE64_DECODE), "bad base64 decode"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_DECRYPT), "bad decrypt"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_END_LINE), "bad end line"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_IV_CHARS), "bad iv chars"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_MAGIC_NUMBER), "bad magic number"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_PASSWORD_READ), "bad password read"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_VERSION_NUMBER), "bad version number"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BIO_WRITE_FAILURE), "bio write failure"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_CIPHER_IS_NULL), "cipher is null"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_ERROR_CONVERTING_PRIVATE_KEY), + "error converting private key"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_EXPECTING_PRIVATE_KEY_BLOB), + "expecting private key blob"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_EXPECTING_PUBLIC_KEY_BLOB), + "expecting public key blob"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_HEADER_TOO_LONG), "header too long"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_INCONSISTENT_HEADER), + "inconsistent header"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_KEYBLOB_HEADER_PARSE_ERROR), + "keyblob header parse error"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_KEYBLOB_TOO_SHORT), "keyblob too short"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_MISSING_DEK_IV), "missing dek iv"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_NOT_DEK_INFO), "not dek info"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_NOT_ENCRYPTED), "not encrypted"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_NOT_PROC_TYPE), "not proc type"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_NO_START_LINE), "no start line"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_PROBLEMS_GETTING_PASSWORD), + "problems getting password"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_PVK_DATA_TOO_SHORT), "pvk data too short"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_PVK_TOO_SHORT), "pvk too short"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_READ_KEY), "read key"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_SHORT_HEADER), "short header"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_UNEXPECTED_DEK_IV), "unexpected dek iv"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_UNSUPPORTED_CIPHER), "unsupported cipher"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_UNSUPPORTED_ENCRYPTION), + "unsupported encryption"}, + {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_UNSUPPORTED_KEY_COMPONENTS), + "unsupported key components"}, {0, NULL} }; @@ -105,10 +116,9 @@ static ERR_STRING_DATA PEM_str_reasons[] = { int ERR_load_PEM_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(PEM_str_functs[0].error) == NULL) { - ERR_load_strings(0, PEM_str_functs); - ERR_load_strings(0, PEM_str_reasons); + ERR_load_strings_const(PEM_str_functs); + ERR_load_strings_const(PEM_str_reasons); } #endif return 1; diff --git a/crypto/pem/pem_info.c b/crypto/pem/pem_info.c index 78d4476a..a45fe830 100644 --- a/crypto/pem/pem_info.c +++ b/crypto/pem/pem_info.c @@ -26,12 +26,12 @@ STACK_OF(X509_INFO) *PEM_X509_INFO_read(FILE *fp, STACK_OF(X509_INFO) *sk, if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_X509_INFO_READ, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_X509_INFO_read_bio(b, sk, cb, u); BIO_free(b); - return (ret); + return ret; } #endif @@ -240,7 +240,7 @@ STACK_OF(X509_INFO) *PEM_X509_INFO_read_bio(BIO *bp, STACK_OF(X509_INFO) *sk, OPENSSL_free(name); OPENSSL_free(header); OPENSSL_free(data); - return (ret); + return ret; } /* A TJH addition */ @@ -256,7 +256,13 @@ int PEM_X509_INFO_write_bio(BIO *bp, X509_INFO *xi, EVP_CIPHER *enc, if (enc != NULL) { objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc)); - if (objstr == NULL) { + if (objstr == NULL + /* + * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n" + * fits into buf + */ + || (strlen(objstr) + 23 + 2 * EVP_CIPHER_iv_length(enc) + 13) + > sizeof(buf)) { PEMerr(PEM_F_PEM_X509_INFO_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER); goto err; } @@ -291,10 +297,7 @@ int PEM_X509_INFO_write_bio(BIO *bp, X509_INFO *xi, EVP_CIPHER *enc, goto err; } - /* create the right magic header stuff */ - OPENSSL_assert(strlen(objstr) + 23 - + 2 * EVP_CIPHER_iv_length(enc) + 13 <= - sizeof(buf)); + /* Create the right magic header stuff */ buf[0] = '\0'; PEM_proc_type(buf, PEM_TYPE_ENCRYPTED); PEM_dek_info(buf, objstr, EVP_CIPHER_iv_length(enc), @@ -330,5 +333,5 @@ int PEM_X509_INFO_write_bio(BIO *bp, X509_INFO *xi, EVP_CIPHER *enc, err: OPENSSL_cleanse(buf, PEM_BUFSIZE); - return (ret); + return ret; } diff --git a/crypto/pem/pem_lib.c b/crypto/pem/pem_lib.c index e9202f44..97b8a0d7 100644 --- a/crypto/pem/pem_lib.c +++ b/crypto/pem/pem_lib.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,7 +8,7 @@ */ #include -#include +#include "internal/ctype.h" #include #include "internal/cryptlib.h" #include @@ -30,12 +30,8 @@ int pem_check_suffix(const char *pem_str, const char *suffix); int PEM_def_callback(char *buf, int num, int w, void *key) { -#if defined(OPENSSL_NO_STDIO) || defined(OPENSSL_NO_UI) - int i; -#else int i, j; const char *prompt; -#endif if (key) { i = strlen(key); @@ -44,10 +40,6 @@ int PEM_def_callback(char *buf, int num, int w, void *key) return i; } -#if defined(OPENSSL_NO_STDIO) || defined(OPENSSL_NO_UI) - PEMerr(PEM_F_PEM_DEF_CALLBACK, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); - return -1; -#else prompt = EVP_get_pw_prompt(); if (prompt == NULL) prompt = "Enter PEM pass phrase:"; @@ -74,12 +66,12 @@ int PEM_def_callback(char *buf, int num, int w, void *key) break; } return j; -#endif } void PEM_proc_type(char *buf, int type) { const char *str; + char *p = buf + strlen(buf); if (type == PEM_TYPE_ENCRYPTED) str = "ENCRYPTED"; @@ -90,29 +82,29 @@ void PEM_proc_type(char *buf, int type) else str = "BAD-TYPE"; - OPENSSL_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE); - OPENSSL_strlcat(buf, str, PEM_BUFSIZE); - OPENSSL_strlcat(buf, "\n", PEM_BUFSIZE); + BIO_snprintf(p, PEM_BUFSIZE - (size_t)(p - buf), "Proc-Type: 4,%s\n", str); } void PEM_dek_info(char *buf, const char *type, int len, char *str) { - static const unsigned char map[17] = "0123456789ABCDEF"; long i; - int j; + char *p = buf + strlen(buf); + int j = PEM_BUFSIZE - (size_t)(p - buf), n; - OPENSSL_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE); - OPENSSL_strlcat(buf, type, PEM_BUFSIZE); - OPENSSL_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]; + n = BIO_snprintf(p, j, "DEK-Info: %s,", type); + if (n > 0) { + j -= n; + p += n; + for (i = 0; i < len; i++) { + n = BIO_snprintf(p, j, "%02X", 0xff & str[i]); + if (n <= 0) + return; + j -= n; + p += n; + } + if (j > 1) + strcpy(p, "\n"); } - buf[j + i * 2] = '\n'; - buf[j + i * 2 + 1] = '\0'; } #ifndef OPENSSL_NO_STDIO @@ -124,12 +116,12 @@ void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x, if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB); - return (0); + 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); + return ret; } #endif @@ -228,28 +220,41 @@ static int check_pem(const char *nm, const char *name) 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) +static void pem_free(void *p, unsigned int flags, size_t num) +{ + if (flags & PEM_FLAG_SECURE) + OPENSSL_secure_clear_free(p, num); + else + OPENSSL_free(p); +} + +static void *pem_malloc(int num, unsigned int flags) +{ + return (flags & PEM_FLAG_SECURE) ? OPENSSL_secure_malloc(num) + : OPENSSL_malloc(num); +} + +static int pem_bytes_read_bio_flags(unsigned char **pdata, long *plen, + char **pnm, const char *name, BIO *bp, + pem_password_cb *cb, void *u, + unsigned int flags) { EVP_CIPHER_INFO cipher; char *nm = NULL, *header = NULL; unsigned char *data = NULL; - long len; + long len = 0; int ret = 0; - for (;;) { - if (!PEM_read_bio(bp, &nm, &header, &data, &len)) { + do { + pem_free(nm, flags, 0); + pem_free(header, flags, 0); + pem_free(data, flags, len); + if (!PEM_read_bio_ex(bp, &nm, &header, &data, &len, flags)) { 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); - } + } while (!check_pem(nm, name)); if (!PEM_get_EVP_CIPHER_INFO(header, &cipher)) goto err; if (!PEM_do_header(&cipher, data, &len, cb, u)) @@ -258,20 +263,34 @@ int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm, *pdata = data; *plen = len; - if (pnm) + if (pnm != NULL) *pnm = nm; ret = 1; err: - if (!ret || !pnm) - OPENSSL_free(nm); - OPENSSL_free(header); + if (!ret || pnm == NULL) + pem_free(nm, flags, 0); + pem_free(header, flags, 0); if (!ret) - OPENSSL_free(data); + pem_free(data, flags, len); return ret; } +int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm, + const char *name, BIO *bp, pem_password_cb *cb, + void *u) { + return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u, + PEM_FLAG_EAY_COMPATIBLE); +} + +int PEM_bytes_read_bio_secmem(unsigned char **pdata, long *plen, char **pnm, + const char *name, BIO *bp, pem_password_cb *cb, + void *u) { + return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u, + PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE); +} + #ifndef OPENSSL_NO_STDIO int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp, void *x, const EVP_CIPHER *enc, unsigned char *kstr, @@ -282,12 +301,12 @@ int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp, if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB); - return (0); + 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); + return ret; } #endif @@ -305,7 +324,14 @@ int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, if (enc != NULL) { objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc)); - if (objstr == NULL || EVP_CIPHER_iv_length(enc) == 0) { + if (objstr == NULL || EVP_CIPHER_iv_length(enc) == 0 + || EVP_CIPHER_iv_length(enc) > (int)sizeof(iv) + /* + * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n" + * fits into buf + */ + || (strlen(objstr) + 23 + 2 * EVP_CIPHER_iv_length(enc) + 13) + > sizeof(buf)) { PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER); goto err; } @@ -342,8 +368,6 @@ int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, #endif kstr = (unsigned char *)buf; } - RAND_add(data, i, 0); /* put in the RSA key. */ - OPENSSL_assert(EVP_CIPHER_iv_length(enc) <= (int)sizeof(iv)); if (RAND_bytes(iv, EVP_CIPHER_iv_length(enc)) <= 0) /* Generate a salt */ goto err; /* @@ -356,9 +380,6 @@ int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, if (kstr == (unsigned char *)buf) OPENSSL_cleanse(buf, PEM_BUFSIZE); - OPENSSL_assert(strlen(objstr) + 23 + 2 * EVP_CIPHER_iv_length(enc) + 13 - <= sizeof(buf)); - buf[0] = '\0'; PEM_proc_type(buf, PEM_TYPE_ENCRYPTED); PEM_dek_info(buf, objstr, EVP_CIPHER_iv_length(enc), (char *)iv); @@ -386,7 +407,7 @@ int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, EVP_CIPHER_CTX_free(ctx); OPENSSL_cleanse(buf, PEM_BUFSIZE); OPENSSL_clear_free(data, (unsigned int)dsize); - return (ret); + return ret; } int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen, @@ -554,14 +575,14 @@ static int load_iv(char **fromp, unsigned char *to, int num) v = OPENSSL_hexchar2int(*from); if (v < 0) { PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS); - return (0); + return 0; } from++; to[i / 2] |= v << (long)((!(i & 1)) * 4); } *fromp = from; - return (1); + return 1; } #ifndef OPENSSL_NO_STDIO @@ -573,12 +594,12 @@ int PEM_write(FILE *fp, const char *name, const char *header, if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_write_bio(b, name, header, data, len); BIO_free(b); - return (ret); + return ret; } #endif @@ -635,12 +656,12 @@ int PEM_write_bio(BIO *bp, const char *name, const char *header, goto err; OPENSSL_clear_free(buf, PEM_BUFSIZE * 8); EVP_ENCODE_CTX_free(ctx); - return (i + outl); + return i + outl; err: OPENSSL_clear_free(buf, PEM_BUFSIZE * 8); EVP_ENCODE_CTX_free(ctx); PEMerr(PEM_F_PEM_WRITE_BIO, reason); - return (0); + return 0; } #ifndef OPENSSL_NO_STDIO @@ -652,186 +673,300 @@ int PEM_read(FILE *fp, char **name, char **header, unsigned char **data, if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio(b, name, header, data, len); BIO_free(b); - return (ret); + return ret; } #endif +/* Some helpers for PEM_read_bio_ex(). */ +static int sanitize_line(char *linebuf, int len, unsigned int flags) +{ + int i; + + if (flags & PEM_FLAG_EAY_COMPATIBLE) { + /* Strip trailing whitespace */ + while ((len >= 0) && (linebuf[len] <= ' ')) + len--; + /* Go back to whitespace before applying uniform line ending. */ + len++; + } else if (flags & PEM_FLAG_ONLY_B64) { + for (i = 0; i < len; ++i) { + if (!ossl_isbase64(linebuf[i]) || linebuf[i] == '\n' + || linebuf[i] == '\r') + break; + } + len = i; + } else { + /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip + * control characters in-place and let everything through. */ + for (i = 0; i < len; ++i) { + if (linebuf[i] == '\n' || linebuf[i] == '\r') + break; + if (ossl_iscntrl(linebuf[i])) + linebuf[i] = ' '; + } + len = i; + } + /* The caller allocated LINESIZE+1, so this is safe. */ + linebuf[len++] = '\n'; + linebuf[len] = '\0'; + return len; +} + +#define LINESIZE 255 +/* Note trailing spaces for begin and end. */ +static const char beginstr[] = "-----BEGIN "; +static const char endstr[] = "-----END "; +static const char tailstr[] = "-----\n"; +#define BEGINLEN (sizeof(beginstr) - 1) +#define ENDLEN (sizeof(endstr) - 1) +#define TAILLEN (sizeof(tailstr) - 1) +static int get_name(BIO *bp, char **name, unsigned int flags) +{ + char *linebuf; + int ret = 0; + size_t len; + + /* + * Need to hold trailing NUL (accounted for by BIO_gets() and the newline + * that will be added by sanitize_line() (the extra '1'). + */ + linebuf = pem_malloc(LINESIZE + 1, flags); + if (linebuf == NULL) { + PEMerr(PEM_F_GET_NAME, ERR_R_MALLOC_FAILURE); + return 0; + } + + do { + len = BIO_gets(bp, linebuf, LINESIZE); + + if (len <= 0) { + PEMerr(PEM_F_GET_NAME, PEM_R_NO_START_LINE); + goto err; + } + + /* Strip trailing garbage and standardize ending. */ + len = sanitize_line(linebuf, len, flags & ~PEM_FLAG_ONLY_B64); + + /* Allow leading empty or non-matching lines. */ + } while (strncmp(linebuf, beginstr, BEGINLEN) != 0 + || len < TAILLEN + || strncmp(linebuf + len - TAILLEN, tailstr, TAILLEN) != 0); + linebuf[len - TAILLEN] = '\0'; + len = len - BEGINLEN - TAILLEN + 1; + *name = pem_malloc(len, flags); + if (*name == NULL) { + PEMerr(PEM_F_GET_NAME, ERR_R_MALLOC_FAILURE); + goto err; + } + memcpy(*name, linebuf + BEGINLEN, len); + ret = 1; + +err: + pem_free(linebuf, flags, LINESIZE + 1); + return ret; +} + +/* Keep track of how much of a header we've seen. */ +enum header_status { + MAYBE_HEADER, + IN_HEADER, + POST_HEADER +}; + +/** + * Extract the optional PEM header, with details on the type of content and + * any encryption used on the contents, and the bulk of the data from the bio. + * The end of the header is marked by a blank line; if the end-of-input marker + * is reached prior to a blank line, there is no header. + * + * The header and data arguments are BIO** since we may have to swap them + * if there is no header, for efficiency. + * + * We need the name of the PEM-encoded type to verify the end string. + */ +static int get_header_and_data(BIO *bp, BIO **header, BIO **data, char *name, + unsigned int flags) +{ + BIO *tmp = *header; + char *linebuf, *p; + int len, line, ret = 0, end = 0; + /* 0 if not seen (yet), 1 if reading header, 2 if finished header */ + enum header_status got_header = MAYBE_HEADER; + unsigned int flags_mask; + size_t namelen; + + /* Need to hold trailing NUL (accounted for by BIO_gets() and the newline + * that will be added by sanitize_line() (the extra '1'). */ + linebuf = pem_malloc(LINESIZE + 1, flags); + if (linebuf == NULL) { + PEMerr(PEM_F_GET_HEADER_AND_DATA, ERR_R_MALLOC_FAILURE); + return 0; + } + + for (line = 0; ; line++) { + flags_mask = ~0u; + len = BIO_gets(bp, linebuf, LINESIZE); + if (len <= 0) { + PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_SHORT_HEADER); + goto err; + } + + if (got_header == MAYBE_HEADER) { + if (memchr(linebuf, ':', len) != NULL) + got_header = IN_HEADER; + } + if (!strncmp(linebuf, endstr, ENDLEN) || got_header == IN_HEADER) + flags_mask &= ~PEM_FLAG_ONLY_B64; + len = sanitize_line(linebuf, len, flags & flags_mask); + + /* Check for end of header. */ + if (linebuf[0] == '\n') { + if (got_header == POST_HEADER) { + /* Another blank line is an error. */ + PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE); + goto err; + } + got_header = POST_HEADER; + tmp = *data; + continue; + } + + /* Check for end of stream (which means there is no header). */ + if (strncmp(linebuf, endstr, ENDLEN) == 0) { + p = linebuf + ENDLEN; + namelen = strlen(name); + if (strncmp(p, name, namelen) != 0 || + strncmp(p + namelen, tailstr, TAILLEN) != 0) { + PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE); + goto err; + } + if (got_header == MAYBE_HEADER) { + *header = *data; + *data = tmp; + } + break; + } else if (end) { + /* Malformed input; short line not at end of data. */ + PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE); + goto err; + } + /* + * Else, a line of text -- could be header or data; we don't + * know yet. Just pass it through. + */ + if (BIO_puts(tmp, linebuf) < 0) + goto err; + /* + * Only encrypted files need the line length check applied. + */ + if (got_header == POST_HEADER) { + /* 65 includes the trailing newline */ + if (len > 65) + goto err; + if (len < 65) + end = 1; + } + } + + ret = 1; +err: + pem_free(linebuf, flags, LINESIZE + 1); + return ret; +} + +/** + * Read in PEM-formatted data from the given BIO. + * + * By nature of the PEM format, all content must be printable ASCII (except + * for line endings). Other characters, or lines that are longer than 80 + * characters, are malformed input and will be rejected. + */ +int PEM_read_bio_ex(BIO *bp, char **name_out, char **header, + unsigned char **data, long *len_out, unsigned int flags) +{ + EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new(); + const BIO_METHOD *bmeth; + BIO *headerB = NULL, *dataB = NULL; + char *name = NULL; + int len, taillen, headerlen, ret = 0; + BUF_MEM * buf_mem; + + if (ctx == NULL) { + PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE); + return 0; + } + + *len_out = 0; + *name_out = *header = NULL; + *data = NULL; + if ((flags & PEM_FLAG_EAY_COMPATIBLE) && (flags & PEM_FLAG_ONLY_B64)) { + /* These two are mutually incompatible; bail out. */ + PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_PASSED_INVALID_ARGUMENT); + goto end; + } + bmeth = (flags & PEM_FLAG_SECURE) ? BIO_s_secmem() : BIO_s_mem(); + + headerB = BIO_new(bmeth); + dataB = BIO_new(bmeth); + if (headerB == NULL || dataB == NULL) { + PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE); + goto end; + } + + if (!get_name(bp, &name, flags)) + goto end; + if (!get_header_and_data(bp, &headerB, &dataB, name, flags)) + goto end; + + EVP_DecodeInit(ctx); + BIO_get_mem_ptr(dataB, &buf_mem); + len = buf_mem->length; + if (EVP_DecodeUpdate(ctx, (unsigned char*)buf_mem->data, &len, + (unsigned char*)buf_mem->data, len) < 0 + || EVP_DecodeFinal(ctx, (unsigned char*)&(buf_mem->data[len]), + &taillen) < 0) { + PEMerr(PEM_F_PEM_READ_BIO_EX, PEM_R_BAD_BASE64_DECODE); + goto end; + } + len += taillen; + buf_mem->length = len; + + /* There was no data in the PEM file; avoid malloc(0). */ + if (len == 0) + goto end; + headerlen = BIO_get_mem_data(headerB, NULL); + *header = pem_malloc(headerlen + 1, flags); + *data = pem_malloc(len, flags); + if (*header == NULL || *data == NULL) { + pem_free(*header, flags, 0); + pem_free(*data, flags, 0); + goto end; + } + BIO_read(headerB, *header, headerlen); + (*header)[headerlen] = '\0'; + BIO_read(dataB, *data, len); + *len_out = len; + *name_out = name; + name = NULL; + ret = 1; + +end: + EVP_ENCODE_CTX_free(ctx); + pem_free(name, flags, 0); + BIO_free(headerB); + BIO_free(dataB); + return ret; +} + int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data, long *len) { - EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new(); - int end = 0, i, k, bl = 0, hl = 0, nohead = 0; - char buf[256]; - BUF_MEM *nameB; - BUF_MEM *headerB; - BUF_MEM *dataB, *tmpB; - - if (ctx == NULL) { - PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE); - return (0); - } - - nameB = BUF_MEM_new(); - headerB = BUF_MEM_new(); - dataB = BUF_MEM_new(); - if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) { - goto err; - } - - 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); - EVP_ENCODE_CTX_free(ctx); - return (1); - err: - BUF_MEM_free(nameB); - BUF_MEM_free(headerB); - BUF_MEM_free(dataB); - EVP_ENCODE_CTX_free(ctx); - return (0); + return PEM_read_bio_ex(bp, name, header, data, len, PEM_FLAG_EAY_COMPATIBLE); } /* diff --git a/crypto/pem/pem_oth.c b/crypto/pem/pem_oth.c index cc7a8dbe..56620533 100644 --- a/crypto/pem/pem_oth.c +++ b/crypto/pem/pem_oth.c @@ -32,5 +32,5 @@ void *PEM_ASN1_read_bio(d2i_of_void *d2i, const char *name, BIO *bp, void **x, if (ret == NULL) PEMerr(PEM_F_PEM_ASN1_READ_BIO, ERR_R_ASN1_LIB); OPENSSL_free(data); - return (ret); + return ret; } diff --git a/crypto/pem/pem_pk8.c b/crypto/pem/pem_pk8.c index 5caad9fa..e2c0f3de 100644 --- a/crypto/pem/pem_pk8.c +++ b/crypto/pem/pem_pk8.c @@ -183,7 +183,7 @@ static int do_pk8pkey_fp(FILE *fp, EVP_PKEY *x, int isder, int nid, if ((bp = BIO_new_fp(fp, BIO_NOCLOSE)) == NULL) { PEMerr(PEM_F_DO_PK8PKEY_FP, ERR_R_BUF_LIB); - return (0); + return 0; } ret = do_pk8pkey(bp, x, isder, nid, enc, kstr, klen, cb, u); BIO_free(bp); diff --git a/crypto/pem/pem_pkey.c b/crypto/pem/pem_pkey.c index 671b374f..62eb91c4 100644 --- a/crypto/pem/pem_pkey.c +++ b/crypto/pem/pem_pkey.c @@ -32,7 +32,8 @@ EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, int slen; EVP_PKEY *ret = NULL; - if (!PEM_bytes_read_bio(&data, &len, &nm, PEM_STRING_EVP_PKEY, bp, cb, u)) + if (!PEM_bytes_read_bio_secmem(&data, &len, &nm, PEM_STRING_EVP_PKEY, bp, + cb, u)) return NULL; p = data; @@ -86,9 +87,9 @@ EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, if (ret == NULL) PEMerr(PEM_F_PEM_READ_BIO_PRIVATEKEY, ERR_R_ASN1_LIB); err: - OPENSSL_free(nm); - OPENSSL_clear_free(data, len); - return (ret); + OPENSSL_secure_free(nm); + OPENSSL_secure_clear_free(data, len); + return ret; } int PEM_write_bio_PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, @@ -147,7 +148,7 @@ EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x) PEMerr(PEM_F_PEM_READ_BIO_PARAMETERS, ERR_R_ASN1_LIB); OPENSSL_free(nm); OPENSSL_free(data); - return (ret); + return ret; } int PEM_write_bio_Parameters(BIO *bp, EVP_PKEY *x) @@ -170,12 +171,12 @@ EVP_PKEY *PEM_read_PrivateKey(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_READ_PRIVATEKEY, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio_PrivateKey(b, x, cb, u); BIO_free(b); - return (ret); + return ret; } int PEM_write_PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, @@ -232,12 +233,12 @@ DH *PEM_read_DHparams(FILE *fp, DH **x, pem_password_cb *cb, void *u) if ((b = BIO_new(BIO_s_file())) == NULL) { PEMerr(PEM_F_PEM_READ_DHPARAMS, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio_DHparams(b, x, cb, u); BIO_free(b); - return (ret); + return ret; } # endif diff --git a/crypto/pem/pem_sign.c b/crypto/pem/pem_sign.c index 12ad9745..9662eb14 100644 --- a/crypto/pem/pem_sign.c +++ b/crypto/pem/pem_sign.c @@ -46,5 +46,5 @@ int PEM_SignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, err: /* ctx has been zeroed by EVP_SignFinal() */ OPENSSL_free(m); - return (ret); + return ret; } diff --git a/crypto/pem/pvkfmt.c b/crypto/pem/pvkfmt.c index d0a42395..ebd6913c 100644 --- a/crypto/pem/pvkfmt.c +++ b/crypto/pem/pvkfmt.c @@ -1,5 +1,5 @@ /* - * Copyright 2005-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2005-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 @@ -285,17 +285,14 @@ static EVP_PKEY *b2i_dss(const unsigned char **in, goto memerr; BN_CTX_free(ctx); - ctx = NULL; } if (!DSA_set0_pqg(dsa, pbn, qbn, gbn)) goto memerr; pbn = qbn = gbn = NULL; if (!DSA_set0_key(dsa, pub_key, priv_key)) goto memerr; - pub_key = priv_key = NULL; - if (!EVP_PKEY_set1_DSA(ret, dsa)) - goto memerr; + EVP_PKEY_set1_DSA(ret, dsa); DSA_free(dsa); *in = p; return ret; @@ -348,19 +345,12 @@ static EVP_PKEY *b2i_rsa(const unsigned char **in, goto memerr; if (!read_lebn(&pin, nbyte, &d)) goto memerr; - if (!RSA_set0_factors(rsa, p, q)) - goto memerr; - p = q = NULL; - if (!RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp)) - goto memerr; - dmp1 = dmq1 = iqmp = NULL; + RSA_set0_factors(rsa, p, q); + RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp); } - if (!RSA_set0_key(rsa, n, e, d)) - goto memerr; - n = e = d = NULL; + RSA_set0_key(rsa, n, e, d); - if (!EVP_PKEY_set1_RSA(ret, rsa)) - goto memerr; + EVP_PKEY_set1_RSA(ret, rsa); RSA_free(rsa); *in = pin; return ret; diff --git a/crypto/perlasm/README b/crypto/perlasm/README index e90bd8e0..3177c371 100644 --- a/crypto/perlasm/README +++ b/crypto/perlasm/README @@ -9,7 +9,7 @@ require "x86asm.pl"; The first thing we do is setup the file and type of assembler -&asm_init($ARGV[0],$0); +&asm_init($ARGV[0]); The first argument is the 'type'. Currently 'cpp', 'sol', 'a.out', 'elf' or 'win32'. @@ -62,7 +62,7 @@ So a very simple version of this function could be coded as push(@INC,"perlasm","../../perlasm"); require "x86asm.pl"; - &asm_init($ARGV[0],"cacl.pl"); + &asm_init($ARGV[0]); &external_label("other"); diff --git a/crypto/perlasm/cbc.pl b/crypto/perlasm/cbc.pl index ad79b240..01bafe45 100644 --- a/crypto/perlasm/cbc.pl +++ b/crypto/perlasm/cbc.pl @@ -15,7 +15,7 @@ # des_cblock (*ivec); # int enc; # -# calls +# calls # des_encrypt((DES_LONG *)tin,schedule,DES_ENCRYPT); # @@ -36,7 +36,7 @@ sub cbc # name is the function name # enc_func and dec_func and the functions to call for encrypt/decrypt # swap is true if byte order needs to be reversed - # iv_off is parameter number for the iv + # iv_off is parameter number for the iv # enc_off is parameter number for the encrypt/decrypt flag # p1,p2,p3 are the offsets for parameters to be passed to the # underlying calls. @@ -114,7 +114,7 @@ sub cbc ############################################################# &set_label("encrypt_loop"); - # encrypt start + # encrypt start # "eax" and "ebx" hold iv (or the last cipher text) &mov("ecx", &DWP(0,$in,"",0)); # load first 4 bytes @@ -208,7 +208,7 @@ sub cbc ############################################################# ############################################################# &set_label("decrypt",1); - # decrypt start + # decrypt start &and($count,0xfffffff8); # The next 2 instructions are only for if the jz is taken &mov("eax", &DWP($data_off+8,"esp","",0)); # get iv[0] @@ -350,7 +350,7 @@ sub cbc &align(64); &function_end_B($name); - + } 1; diff --git a/crypto/perlasm/ppc-xlate.pl b/crypto/perlasm/ppc-xlate.pl index 2d46e244..ba2842fb 100755 --- a/crypto/perlasm/ppc-xlate.pl +++ b/crypto/perlasm/ppc-xlate.pl @@ -11,40 +11,65 @@ my $output = shift; open STDOUT,">$output" || die "can't open $output: $!"; my %GLOBALS; +my %TYPES; my $dotinlocallabels=($flavour=~/linux/)?1:0; ################################################################ # directives which need special treatment on different platforms ################################################################ +my $type = sub { + my ($dir,$name,$type) = @_; + + $TYPES{$name} = $type; + if ($flavour =~ /linux/) { + $name =~ s|^\.||; + ".type $name,$type"; + } else { + ""; + } +}; my $globl = sub { my $junk = shift; my $name = shift; my $global = \$GLOBALS{$name}; + my $type = \$TYPES{$name}; my $ret; - $name =~ s|^[\.\_]||; - + $name =~ s|^\.||; + SWITCH: for ($flavour) { - /aix/ && do { $name = ".$name"; + /aix/ && do { if (!$$type) { + $$type = "\@function"; + } + if ($$type =~ /function/) { + $name = ".$name"; + } last; }; /osx/ && do { $name = "_$name"; last; }; /linux.*(32|64le)/ - && do { $ret .= ".globl $name\n"; - $ret .= ".type $name,\@function"; + && do { $ret .= ".globl $name"; + if (!$$type) { + $ret .= "\n.type $name,\@function"; + $$type = "\@function"; + } last; }; - /linux.*64/ && do { $ret .= ".globl $name\n"; - $ret .= ".type $name,\@function\n"; - $ret .= ".section \".opd\",\"aw\"\n"; - $ret .= ".align 3\n"; - $ret .= "$name:\n"; - $ret .= ".quad .$name,.TOC.\@tocbase,0\n"; - $ret .= ".previous\n"; - - $name = ".$name"; + /linux.*64/ && do { $ret .= ".globl $name"; + if (!$$type) { + $ret .= "\n.type $name,\@function"; + $$type = "\@function"; + } + if ($$type =~ /function/) { + $ret .= "\n.section \".opd\",\"aw\""; + $ret .= "\n.align 3"; + $ret .= "\n$name:"; + $ret .= "\n.quad .$name,.TOC.\@tocbase,0"; + $ret .= "\n.previous"; + $name = ".$name"; + } last; }; } @@ -70,9 +95,13 @@ my $machine = sub { my $size = sub { if ($flavour =~ /linux/) { shift; - my $name = shift; $name =~ s|^[\.\_]||; - my $ret = ".size $name,.-".($flavour=~/64$/?".":"").$name; - $ret .= "\n.size .$name,.-.$name" if ($flavour=~/64$/); + my $name = shift; + my $real = $GLOBALS{$name} ? \$GLOBALS{$name} : \$name; + my $ret = ".size $$real,.-$$real"; + $name =~ s|^\.||; + if ($$real ne $name) { + $ret .= "\n.size $name,.-$$real"; + } $ret; } else @@ -187,6 +216,12 @@ my $lvdx_u = sub { vsxmem_op(@_, 588); }; # lxsdx my $stvdx_u = sub { vsxmem_op(@_, 716); }; # stxsdx my $lvx_4w = sub { vsxmem_op(@_, 780); }; # lxvw4x my $stvx_4w = sub { vsxmem_op(@_, 908); }; # stxvw4x +my $lvx_splt = sub { vsxmem_op(@_, 332); }; # lxvdsx +my $vpermdi = sub { # xxpermdi + my ($f, $vrt, $vra, $vrb, $dm) = @_; + $dm = oct($dm) if ($dm =~ /^0/); + " .long ".sprintf "0x%X",(60<<26)|($vrt<<21)|($vra<<16)|($vrb<<11)|($dm<<8)|(10<<3)|7; +}; # PowerISA 2.07 stuff sub vcrypto_op { @@ -204,7 +239,14 @@ my $vpmsumb = sub { vcrypto_op(@_, 1032); }; my $vpmsumd = sub { vcrypto_op(@_, 1224); }; my $vpmsubh = sub { vcrypto_op(@_, 1096); }; my $vpmsumw = sub { vcrypto_op(@_, 1160); }; +# These are not really crypto, but one can use vcrypto_op my $vaddudm = sub { vcrypto_op(@_, 192); }; +my $vadduqm = sub { vcrypto_op(@_, 256); }; +my $vmuleuw = sub { vcrypto_op(@_, 648); }; +my $vmulouw = sub { vcrypto_op(@_, 136); }; +my $vrld = sub { vcrypto_op(@_, 196); }; +my $vsld = sub { vcrypto_op(@_, 1476); }; +my $vsrd = sub { vcrypto_op(@_, 1732); }; my $mtsle = sub { my ($f, $arg) = @_; @@ -220,11 +262,24 @@ my $maddld = sub { my ($f, $rt, $ra, $rb, $rc) = @_; " .long ".sprintf "0x%X",(4<<26)|($rt<<21)|($ra<<16)|($rb<<11)|($rc<<6)|51; }; - my $darn = sub { my ($f, $rt, $l) = @_; " .long ".sprintf "0x%X",(31<<26)|($rt<<21)|($l<<16)|(755<<1); }; +my $iseleq = sub { + my ($f, $rt, $ra, $rb) = @_; + " .long ".sprintf "0x%X",(31<<26)|($rt<<21)|($ra<<16)|($rb<<11)|(2<<6)|30; +}; + +# PowerISA 3.0B stuff +my $addex = sub { + my ($f, $rt, $ra, $rb, $cy) = @_; # only cy==0 is specified in 3.0B + " .long ".sprintf "0x%X",(31<<26)|($rt<<21)|($ra<<16)|($rb<<11)|($cy<<9)|(170<<1); +}; +my $vmsumudm = sub { + my ($f, $vrt, $vra, $vrb, $vrc) = @_; + " .long ".sprintf "0x%X",(4<<26)|($vrt<<21)|($vra<<16)|($vrb<<11)|($vrc<<6)|35; +}; while($line=<>) { @@ -234,7 +289,7 @@ while($line=<>) { $line =~ s|\s+$||; # ... and at the end { - $line =~ s|\b\.L(\w+)|L$1|g; # common denominator for Locallabel + $line =~ s|\.L(\w+)|L$1|g; # common denominator for Locallabel $line =~ s|\bL(\w+)|\.L$1|g if ($dotinlocallabels); } @@ -242,8 +297,13 @@ while($line=<>) { $line =~ s|(^[\.\w]+)\:\s*||; my $label = $1; if ($label) { - printf "%s:",($GLOBALS{$label} or $label); - printf "\n.localentry\t$GLOBALS{$label},0" if ($GLOBALS{$label} && $flavour =~ /linux.*64le/); + my $xlated = ($GLOBALS{$label} or $label); + print "$xlated:"; + if ($flavour =~ /linux.*64le/) { + if ($TYPES{$label} =~ /function/) { + printf "\n.localentry %s,0\n",$xlated; + } + } } } @@ -254,7 +314,7 @@ while($line=<>) { my $f = $3; my $opcode = eval("\$$mnemonic"); $line =~ s/\b(c?[rf]|v|vs)([0-9]+)\b/$2/g if ($c ne "." and $flavour !~ /osx/); - if (ref($opcode) eq 'CODE') { $line = &$opcode($f,split(',',$line)); } + if (ref($opcode) eq 'CODE') { $line = &$opcode($f,split(/,\s*/,$line)); } elsif ($mnemonic) { $line = $c.$mnemonic.$f."\t".$line; } } diff --git a/crypto/perlasm/sparcv9_modes.pl b/crypto/perlasm/sparcv9_modes.pl index bfdada85..b9922e03 100644 --- a/crypto/perlasm/sparcv9_modes.pl +++ b/crypto/perlasm/sparcv9_modes.pl @@ -117,7 +117,7 @@ $::code.=<<___; brnz,pn $ooff, 2f sub $len, 1, $len - + std %f0, [$out + 0] std %f2, [$out + 8] brnz,pt $len, .L${bits}_cbc_enc_loop @@ -224,7 +224,7 @@ $::code.=<<___; call _${alg}${bits}_encrypt_1x add $inp, 16, $inp sub $len, 1, $len - + stda %f0, [$out]0xe2 ! ASI_BLK_INIT, T4-specific add $out, 8, $out stda %f2, [$out]0xe2 ! ASI_BLK_INIT, T4-specific @@ -339,7 +339,7 @@ $::code.=<<___; brnz,pn $ooff, 2f sub $len, 1, $len - + std %f0, [$out + 0] std %f2, [$out + 8] brnz,pt $len, .L${bits}_cbc_dec_loop2x @@ -445,7 +445,7 @@ $::code.=<<___; brnz,pn $ooff, 2f sub $len, 2, $len - + std %f0, [$out + 0] std %f2, [$out + 8] std %f4, [$out + 16] @@ -702,7 +702,7 @@ $::code.=<<___; brnz,pn $ooff, 2f sub $len, 1, $len - + std %f0, [$out + 0] std %f2, [$out + 8] brnz,pt $len, .L${bits}_ctr32_loop2x @@ -791,7 +791,7 @@ $::code.=<<___; brnz,pn $ooff, 2f sub $len, 2, $len - + std %f0, [$out + 0] std %f2, [$out + 8] std %f4, [$out + 16] @@ -1024,7 +1024,7 @@ $code.=<<___; brnz,pn $ooff, 2f sub $len, 1, $len - + std %f0, [$out + 0] std %f2, [$out + 8] brnz,pt $len, .L${bits}_xts_${dir}loop2x @@ -1135,7 +1135,7 @@ $code.=<<___; brnz,pn $ooff, 2f sub $len, 2, $len - + std %f0, [$out + 0] std %f2, [$out + 8] std %f4, [$out + 16] diff --git a/crypto/perlasm/x86_64-xlate.pl b/crypto/perlasm/x86_64-xlate.pl index c4607dd9..eac21c1c 100755 --- a/crypto/perlasm/x86_64-xlate.pl +++ b/crypto/perlasm/x86_64-xlate.pl @@ -1430,4 +1430,3 @@ close STDOUT; # Unix. "Unlike" refers to the fact that on Unix signal handler # will always be invoked, core dumped and appropriate exit code # returned to parent (for user notification). - diff --git a/crypto/perlasm/x86asm.pl b/crypto/perlasm/x86asm.pl index 1ff46c92..29dc1a2c 100644 --- a/crypto/perlasm/x86asm.pl +++ b/crypto/perlasm/x86asm.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 1995-2018 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 @@ -8,7 +8,7 @@ # require 'x86asm.pl'; -# &asm_init(,"des-586.pl"[,$i386only]); +# &asm_init([,$i386only]); # &function_begin("foo"); # ... # &function_end("foo"); @@ -259,12 +259,11 @@ sub ::asm_finish } sub ::asm_init -{ my ($type,$fn,$cpu)=@_; +{ my ($type,$cpu)=@_; - $filename=$fn; $i386=$cpu; - $elf=$cpp=$coff=$aout=$macosx=$win32=$netware=$mwerks=$android=0; + $elf=$cpp=$coff=$aout=$macosx=$win32=$mwerks=$android=0; if (($type eq "elf")) { $elf=1; require "x86gas.pl"; } elsif (($type eq "elf-1")) @@ -275,10 +274,6 @@ sub ::asm_init { $coff=1; require "x86gas.pl"; } elsif (($type eq "win32n")) { $win32=1; require "x86nasm.pl"; } - elsif (($type eq "nw-nasm")) - { $netware=1; require "x86nasm.pl"; } - #elsif (($type eq "nw-mwasm")) - #{ $netware=1; $mwerks=1; require "x86nasm.pl"; } elsif (($type eq "win32")) { $win32=1; require "x86masm.pl"; } elsif (($type eq "macosx")) @@ -292,7 +287,6 @@ Pick one target type from a.out - DJGPP, elder OpenBSD, etc. coff - GAS/COFF such as Win32 targets win32n - Windows 95/Windows NT NASM format - nw-nasm - NetWare NASM format macosx - Mac OS X EOF exit(1); @@ -301,8 +295,7 @@ EOF $pic=0; for (@ARGV) { $pic=1 if (/\-[fK]PIC/i); } - $filename =~ s/\.pl$//; - &file($filename); + &file(); } sub ::hidden {} diff --git a/crypto/perlasm/x86gas.pl b/crypto/perlasm/x86gas.pl index 2c8fce07..5c7ea388 100644 --- a/crypto/perlasm/x86gas.pl +++ b/crypto/perlasm/x86gas.pl @@ -104,7 +104,7 @@ sub ::BC { @_; } sub ::DWC { @_; } sub ::file -{ push(@out,".file\t\"$_[0].s\"\n.text\n"); } +{ push(@out,".text\n"); } sub ::function_begin_B { my $func=shift; diff --git a/crypto/perlasm/x86masm.pl b/crypto/perlasm/x86masm.pl index d352f470..dffee762 100644 --- a/crypto/perlasm/x86masm.pl +++ b/crypto/perlasm/x86masm.pl @@ -85,7 +85,6 @@ sub ::DWC { "@_"; } sub ::file { my $tmp=<<___; -TITLE $_[0].asm IF \@Version LT 800 ECHO MASM version 8.00 or later is strongly recommended. ENDIF diff --git a/crypto/perlasm/x86nasm.pl b/crypto/perlasm/x86nasm.pl index 4b664a87..4e64dad9 100644 --- a/crypto/perlasm/x86nasm.pl +++ b/crypto/perlasm/x86nasm.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 1999-2018 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 @@ -12,7 +12,7 @@ package x86nasm; *out=\@::out; $::lbdecor="L\$"; # local label decoration -$nmdecor=$::netware?"":"_"; # external name decoration +$nmdecor="_"; # external name decoration $drdecor=$::mwerks?".":""; # directive decoration $initseg=""; @@ -132,7 +132,7 @@ ___ grep {s/(^extern\s+${nmdecor}OPENSSL_ia32cap_P)/\;$1/} @out; push (@out,$comm) } - push (@out,$initseg) if ($initseg); + push (@out,$initseg) if ($initseg); } sub ::comment { foreach (@_) { push(@out,"\t; $_\n"); } } diff --git a/crypto/pkcs12/p12_key.c b/crypto/pkcs12/p12_key.c index 9c13a451..ab31a612 100644 --- a/crypto/pkcs12/p12_key.c +++ b/crypto/pkcs12/p12_key.c @@ -78,10 +78,9 @@ int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt, unsigned char *out, const EVP_MD *md_type) { unsigned char *B = NULL, *D = NULL, *I = NULL, *p = NULL, *Ai = NULL; - int Slen, Plen, Ilen, Ijlen; + int Slen, Plen, Ilen; int i, j, u, v; int ret = 0; - BIGNUM *Ij = NULL, *Bpl1 = NULL; /* These hold Ij and B + 1 */ EVP_MD_CTX *ctx = NULL; #ifdef OPENSSL_DEBUG_KEYGEN unsigned char *tmpout = out; @@ -114,10 +113,7 @@ int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt, Plen = 0; Ilen = Slen + Plen; I = OPENSSL_malloc(Ilen); - Ij = BN_new(); - Bpl1 = BN_new(); - if (D == NULL || Ai == NULL || B == NULL || I == NULL || Ij == NULL - || Bpl1 == NULL) + if (D == NULL || Ai == NULL || B == NULL || I == NULL) goto err; for (i = 0; i < v; i++) D[i] = id; @@ -151,33 +147,17 @@ int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt, out += u; for (j = 0; j < v; j++) B[j] = Ai[j % u]; - /* Work out B + 1 first then can use B as tmp space */ - if (!BN_bin2bn(B, v, Bpl1)) - goto err; - if (!BN_add_word(Bpl1, 1)) - goto err; for (j = 0; j < Ilen; j += v) { - if (!BN_bin2bn(I + j, v, Ij)) - goto err; - if (!BN_add(Ij, Ij, Bpl1)) - goto err; - if (!BN_bn2bin(Ij, B)) - goto err; - Ijlen = BN_num_bytes(Ij); - /* If more than 2^(v*8) - 1 cut off MSB */ - if (Ijlen > v) { - if (!BN_bn2bin(Ij, B)) - goto err; - memcpy(I + j, B + 1, v); -#ifndef PKCS12_BROKEN_KEYGEN - /* If less than v bytes pad with zeroes */ - } else if (Ijlen < v) { - memset(I + j, 0, v - Ijlen); - if (!BN_bn2bin(Ij, I + j + v - Ijlen)) - goto err; -#endif - } else if (!BN_bn2bin(Ij, I + j)) - goto err; + int k; + unsigned char *Ij = I + j; + uint16_t c = 1; + + /* Work out Ij = Ij + B + 1 */ + for (k = v - 1; k >= 0; k--) { + c += Ij[k] + B[k]; + Ij[k] = (unsigned char)c; + c >>= 8; + } } } @@ -189,8 +169,6 @@ int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt, OPENSSL_free(B); OPENSSL_free(D); OPENSSL_free(I); - BN_free(Ij); - BN_free(Bpl1); EVP_MD_CTX_free(ctx); return ret; } diff --git a/crypto/pkcs12/pk12err.c b/crypto/pkcs12/pk12err.c index f705084a..38e7c66e 100644 --- a/crypto/pkcs12/pk12err.c +++ b/crypto/pkcs12/pk12err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,75 +8,92 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_PKCS12,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_PKCS12,0,reason) - -static ERR_STRING_DATA PKCS12_str_functs[] = { - {ERR_FUNC(PKCS12_F_PKCS12_CREATE), "PKCS12_create"}, - {ERR_FUNC(PKCS12_F_PKCS12_GEN_MAC), "PKCS12_gen_mac"}, - {ERR_FUNC(PKCS12_F_PKCS12_INIT), "PKCS12_init"}, - {ERR_FUNC(PKCS12_F_PKCS12_ITEM_DECRYPT_D2I), "PKCS12_item_decrypt_d2i"}, - {ERR_FUNC(PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT), "PKCS12_item_i2d_encrypt"}, - {ERR_FUNC(PKCS12_F_PKCS12_ITEM_PACK_SAFEBAG), "PKCS12_item_pack_safebag"}, - {ERR_FUNC(PKCS12_F_PKCS12_KEY_GEN_ASC), "PKCS12_key_gen_asc"}, - {ERR_FUNC(PKCS12_F_PKCS12_KEY_GEN_UNI), "PKCS12_key_gen_uni"}, - {ERR_FUNC(PKCS12_F_PKCS12_KEY_GEN_UTF8), "PKCS12_key_gen_utf8"}, - {ERR_FUNC(PKCS12_F_PKCS12_NEWPASS), "PKCS12_newpass"}, - {ERR_FUNC(PKCS12_F_PKCS12_PACK_P7DATA), "PKCS12_pack_p7data"}, - {ERR_FUNC(PKCS12_F_PKCS12_PACK_P7ENCDATA), "PKCS12_pack_p7encdata"}, - {ERR_FUNC(PKCS12_F_PKCS12_PARSE), "PKCS12_parse"}, - {ERR_FUNC(PKCS12_F_PKCS12_PBE_CRYPT), "PKCS12_pbe_crypt"}, - {ERR_FUNC(PKCS12_F_PKCS12_PBE_KEYIVGEN), "PKCS12_PBE_keyivgen"}, - {ERR_FUNC(PKCS12_F_PKCS12_SAFEBAG_CREATE0_P8INF), +static const ERR_STRING_DATA PKCS12_str_functs[] = { + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_CREATE, 0), "PKCS12_create"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_GEN_MAC, 0), "PKCS12_gen_mac"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_INIT, 0), "PKCS12_init"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_ITEM_DECRYPT_D2I, 0), + "PKCS12_item_decrypt_d2i"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT, 0), + "PKCS12_item_i2d_encrypt"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_ITEM_PACK_SAFEBAG, 0), + "PKCS12_item_pack_safebag"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_KEY_GEN_ASC, 0), + "PKCS12_key_gen_asc"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_KEY_GEN_UNI, 0), + "PKCS12_key_gen_uni"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_KEY_GEN_UTF8, 0), + "PKCS12_key_gen_utf8"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_NEWPASS, 0), "PKCS12_newpass"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_PACK_P7DATA, 0), + "PKCS12_pack_p7data"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_PACK_P7ENCDATA, 0), + "PKCS12_pack_p7encdata"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_PARSE, 0), "PKCS12_parse"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_PBE_CRYPT, 0), + "PKCS12_pbe_crypt"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_PBE_KEYIVGEN, 0), + "PKCS12_PBE_keyivgen"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_SAFEBAG_CREATE0_P8INF, 0), "PKCS12_SAFEBAG_create0_p8inf"}, - {ERR_FUNC(PKCS12_F_PKCS12_SAFEBAG_CREATE0_PKCS8), + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_SAFEBAG_CREATE0_PKCS8, 0), "PKCS12_SAFEBAG_create0_pkcs8"}, - {ERR_FUNC(PKCS12_F_PKCS12_SAFEBAG_CREATE_PKCS8_ENCRYPT), + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_SAFEBAG_CREATE_PKCS8_ENCRYPT, 0), "PKCS12_SAFEBAG_create_pkcs8_encrypt"}, - {ERR_FUNC(PKCS12_F_PKCS12_SETUP_MAC), "PKCS12_setup_mac"}, - {ERR_FUNC(PKCS12_F_PKCS12_SET_MAC), "PKCS12_set_mac"}, - {ERR_FUNC(PKCS12_F_PKCS12_UNPACK_AUTHSAFES), "PKCS12_unpack_authsafes"}, - {ERR_FUNC(PKCS12_F_PKCS12_UNPACK_P7DATA), "PKCS12_unpack_p7data"}, - {ERR_FUNC(PKCS12_F_PKCS12_VERIFY_MAC), "PKCS12_verify_mac"}, - {ERR_FUNC(PKCS12_F_PKCS8_ENCRYPT), "PKCS8_encrypt"}, - {ERR_FUNC(PKCS12_F_PKCS8_SET0_PBE), "PKCS8_set0_pbe"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_SETUP_MAC, 0), + "PKCS12_setup_mac"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_SET_MAC, 0), "PKCS12_set_mac"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_UNPACK_AUTHSAFES, 0), + "PKCS12_unpack_authsafes"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_UNPACK_P7DATA, 0), + "PKCS12_unpack_p7data"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS12_VERIFY_MAC, 0), + "PKCS12_verify_mac"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS8_ENCRYPT, 0), "PKCS8_encrypt"}, + {ERR_PACK(ERR_LIB_PKCS12, PKCS12_F_PKCS8_SET0_PBE, 0), "PKCS8_set0_pbe"}, {0, NULL} }; -static ERR_STRING_DATA PKCS12_str_reasons[] = { - {ERR_REASON(PKCS12_R_CANT_PACK_STRUCTURE), "cant pack structure"}, - {ERR_REASON(PKCS12_R_CONTENT_TYPE_NOT_DATA), "content type not data"}, - {ERR_REASON(PKCS12_R_DECODE_ERROR), "decode error"}, - {ERR_REASON(PKCS12_R_ENCODE_ERROR), "encode error"}, - {ERR_REASON(PKCS12_R_ENCRYPT_ERROR), "encrypt error"}, - {ERR_REASON(PKCS12_R_ERROR_SETTING_ENCRYPTED_DATA_TYPE), - "error setting encrypted data type"}, - {ERR_REASON(PKCS12_R_INVALID_NULL_ARGUMENT), "invalid null argument"}, - {ERR_REASON(PKCS12_R_INVALID_NULL_PKCS12_POINTER), - "invalid null pkcs12 pointer"}, - {ERR_REASON(PKCS12_R_IV_GEN_ERROR), "iv gen error"}, - {ERR_REASON(PKCS12_R_KEY_GEN_ERROR), "key gen error"}, - {ERR_REASON(PKCS12_R_MAC_ABSENT), "mac absent"}, - {ERR_REASON(PKCS12_R_MAC_GENERATION_ERROR), "mac generation error"}, - {ERR_REASON(PKCS12_R_MAC_SETUP_ERROR), "mac setup error"}, - {ERR_REASON(PKCS12_R_MAC_STRING_SET_ERROR), "mac string set error"}, - {ERR_REASON(PKCS12_R_MAC_VERIFY_FAILURE), "mac verify failure"}, - {ERR_REASON(PKCS12_R_PARSE_ERROR), "parse error"}, - {ERR_REASON(PKCS12_R_PKCS12_ALGOR_CIPHERINIT_ERROR), - "pkcs12 algor cipherinit error"}, - {ERR_REASON(PKCS12_R_PKCS12_CIPHERFINAL_ERROR), - "pkcs12 cipherfinal error"}, - {ERR_REASON(PKCS12_R_PKCS12_PBE_CRYPT_ERROR), "pkcs12 pbe crypt error"}, - {ERR_REASON(PKCS12_R_UNKNOWN_DIGEST_ALGORITHM), - "unknown digest algorithm"}, - {ERR_REASON(PKCS12_R_UNSUPPORTED_PKCS12_MODE), "unsupported pkcs12 mode"}, +static const ERR_STRING_DATA PKCS12_str_reasons[] = { + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_CANT_PACK_STRUCTURE), + "cant pack structure"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_CONTENT_TYPE_NOT_DATA), + "content type not data"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_DECODE_ERROR), "decode error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_ENCODE_ERROR), "encode error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_ENCRYPT_ERROR), "encrypt error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_ERROR_SETTING_ENCRYPTED_DATA_TYPE), + "error setting encrypted data type"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_INVALID_NULL_ARGUMENT), + "invalid null argument"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_INVALID_NULL_PKCS12_POINTER), + "invalid null pkcs12 pointer"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_IV_GEN_ERROR), "iv gen error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_KEY_GEN_ERROR), "key gen error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_ABSENT), "mac absent"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_GENERATION_ERROR), + "mac generation error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_SETUP_ERROR), "mac setup error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_STRING_SET_ERROR), + "mac string set error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_VERIFY_FAILURE), + "mac verify failure"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_PARSE_ERROR), "parse error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_PKCS12_ALGOR_CIPHERINIT_ERROR), + "pkcs12 algor cipherinit error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_PKCS12_CIPHERFINAL_ERROR), + "pkcs12 cipherfinal error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_PKCS12_PBE_CRYPT_ERROR), + "pkcs12 pbe crypt error"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_UNKNOWN_DIGEST_ALGORITHM), + "unknown digest algorithm"}, + {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_UNSUPPORTED_PKCS12_MODE), + "unsupported pkcs12 mode"}, {0, NULL} }; @@ -85,10 +102,9 @@ static ERR_STRING_DATA PKCS12_str_reasons[] = { int ERR_load_PKCS12_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(PKCS12_str_functs[0].error) == NULL) { - ERR_load_strings(0, PKCS12_str_functs); - ERR_load_strings(0, PKCS12_str_reasons); + ERR_load_strings_const(PKCS12_str_functs); + ERR_load_strings_const(PKCS12_str_reasons); } #endif return 1; diff --git a/crypto/pkcs7/pk7_dgst.c b/crypto/pkcs7/pk7_dgst.c deleted file mode 100644 index 965fb37e..00000000 --- a/crypto/pkcs7/pk7_dgst.c +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright 1995-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 - */ - -#include -#include "internal/cryptlib.h" -#include -#include -#include -#include diff --git a/crypto/pkcs7/pk7_doit.c b/crypto/pkcs7/pk7_doit.c index e6e80f08..c5baf046 100644 --- a/crypto/pkcs7/pk7_doit.c +++ b/crypto/pkcs7/pk7_doit.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -316,18 +316,16 @@ BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio) } 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); - } else { + if (bio == NULL) { 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); @@ -809,13 +807,13 @@ int PKCS7_dataFinal(PKCS7 *p7, BIO *bio) ret = 1; err: EVP_MD_CTX_free(ctx_tmp); - return (ret); + return ret; } int PKCS7_SIGNER_INFO_sign(PKCS7_SIGNER_INFO *si) { EVP_MD_CTX *mctx; - EVP_PKEY_CTX *pctx; + EVP_PKEY_CTX *pctx = NULL; unsigned char *abuf = NULL; int alen; size_t siglen; @@ -1041,7 +1039,7 @@ int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si, ret = 1; err: EVP_MD_CTX_free(mdc_tmp); - return (ret); + return ret; } PKCS7_ISSUER_AND_SERIAL *PKCS7_get_issuer_and_serial(PKCS7 *p7, int idx) @@ -1059,19 +1057,19 @@ PKCS7_ISSUER_AND_SERIAL *PKCS7_get_issuer_and_serial(PKCS7 *p7, int idx) if (rsk == NULL) return NULL; if (sk_PKCS7_RECIP_INFO_num(rsk) <= idx) - return (NULL); + return NULL; ri = sk_PKCS7_RECIP_INFO_value(rsk, idx); - return (ri->issuer_and_serial); + return ri->issuer_and_serial; } ASN1_TYPE *PKCS7_get_signed_attribute(PKCS7_SIGNER_INFO *si, int nid) { - return (get_attribute(si->auth_attr, 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)); + return get_attribute(si->unauth_attr, nid); } static ASN1_TYPE *get_attribute(STACK_OF(X509_ATTRIBUTE) *sk, int nid) @@ -1105,9 +1103,9 @@ int PKCS7_set_signed_attributes(PKCS7_SIGNER_INFO *p7si, X509_ATTRIBUTE_dup(sk_X509_ATTRIBUTE_value (sk, i)))) == NULL) - return (0); + return 0; } - return (1); + return 1; } int PKCS7_set_attributes(PKCS7_SIGNER_INFO *p7si, @@ -1124,21 +1122,21 @@ int PKCS7_set_attributes(PKCS7_SIGNER_INFO *p7si, X509_ATTRIBUTE_dup(sk_X509_ATTRIBUTE_value (sk, i)))) == NULL) - return (0); + return 0; } - return (1); + 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)); + 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)); + return add_attribute(&(p7si->unauth_attr), nid, atrtype, value); } static int add_attribute(STACK_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype, @@ -1176,5 +1174,5 @@ static int add_attribute(STACK_OF(X509_ATTRIBUTE) **sk, int nid, int atrtype, goto new_attrib; } end: - return (1); + return 1; } diff --git a/crypto/pkcs7/pk7_enc.c b/crypto/pkcs7/pk7_enc.c deleted file mode 100644 index 3c59f9c8..00000000 --- a/crypto/pkcs7/pk7_enc.c +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 1995-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 - */ - -#include -#include "internal/cryptlib.h" -#include -#include -#include -#include - -PKCS7_in_bio(PKCS7 *p7, BIO *in); -PKCS7_out_bio(PKCS7 *p7, BIO *out); - -PKCS7_add_signer(PKCS7 *p7, X509 *cert, EVP_PKEY *key); -PKCS7_cipher(PKCS7 *p7, EVP_CIPHER *cipher); - -PKCS7_Init(PKCS7 *p7); -PKCS7_Update(PKCS7 *p7); -PKCS7_Finish(PKCS7 *p7); diff --git a/crypto/pkcs7/pk7_lib.c b/crypto/pkcs7/pk7_lib.c index 69c68cf5..88dd613c 100644 --- a/crypto/pkcs7/pk7_lib.c +++ b/crypto/pkcs7/pk7_lib.c @@ -57,7 +57,7 @@ long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg) PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_UNKNOWN_OPERATION); ret = 0; } - return (ret); + return ret; } int PKCS7_content_new(PKCS7 *p7, int type) @@ -71,10 +71,10 @@ int PKCS7_content_new(PKCS7 *p7, int type) if (!PKCS7_set_content(p7, ret)) goto err; - return (1); + return 1; err: PKCS7_free(ret); - return (0); + return 0; } int PKCS7_set_content(PKCS7 *p7, PKCS7 *p7_data) @@ -99,9 +99,9 @@ int PKCS7_set_content(PKCS7 *p7, PKCS7 *p7_data) PKCS7err(PKCS7_F_PKCS7_SET_CONTENT, PKCS7_R_UNSUPPORTED_CONTENT_TYPE); goto err; } - return (1); + return 1; err: - return (0); + return 0; } int PKCS7_set_type(PKCS7 *p7, int type) @@ -171,9 +171,9 @@ int PKCS7_set_type(PKCS7 *p7, int type) PKCS7err(PKCS7_F_PKCS7_SET_TYPE, PKCS7_R_UNSUPPORTED_CONTENT_TYPE); goto err; } - return (1); + return 1; err: - return (0); + return 0; } int PKCS7_set0_type_other(PKCS7 *p7, int type, ASN1_TYPE *other) @@ -202,7 +202,7 @@ int PKCS7_add_signer(PKCS7 *p7, PKCS7_SIGNER_INFO *psi) break; default: PKCS7err(PKCS7_F_PKCS7_ADD_SIGNER, PKCS7_R_WRONG_CONTENT_TYPE); - return (0); + return 0; } nid = OBJ_obj2nid(psi->digest_alg->algorithm); @@ -221,7 +221,7 @@ int PKCS7_add_signer(PKCS7 *p7, PKCS7_SIGNER_INFO *psi) || (alg->parameter = ASN1_TYPE_new()) == NULL) { X509_ALGOR_free(alg); PKCS7err(PKCS7_F_PKCS7_ADD_SIGNER, ERR_R_MALLOC_FAILURE); - return (0); + return 0; } alg->algorithm = OBJ_nid2obj(nid); alg->parameter->type = V_ASN1_NULL; @@ -233,7 +233,7 @@ int PKCS7_add_signer(PKCS7 *p7, PKCS7_SIGNER_INFO *psi) if (!sk_PKCS7_SIGNER_INFO_push(signer_sk, psi)) return 0; - return (1); + return 1; } int PKCS7_add_certificate(PKCS7 *p7, X509 *x509) @@ -251,7 +251,7 @@ int PKCS7_add_certificate(PKCS7 *p7, X509 *x509) break; default: PKCS7err(PKCS7_F_PKCS7_ADD_CERTIFICATE, PKCS7_R_WRONG_CONTENT_TYPE); - return (0); + return 0; } if (*sk == NULL) @@ -265,7 +265,7 @@ int PKCS7_add_certificate(PKCS7 *p7, X509 *x509) X509_free(x509); return 0; } - return (1); + return 1; } int PKCS7_add_crl(PKCS7 *p7, X509_CRL *crl) @@ -283,7 +283,7 @@ int PKCS7_add_crl(PKCS7 *p7, X509_CRL *crl) break; default: PKCS7err(PKCS7_F_PKCS7_ADD_CRL, PKCS7_R_WRONG_CONTENT_TYPE); - return (0); + return 0; } if (*sk == NULL) @@ -298,7 +298,7 @@ int PKCS7_add_crl(PKCS7 *p7, X509_CRL *crl) X509_CRL_free(crl); return 0; } - return (1); + return 1; } int PKCS7_SIGNER_INFO_set(PKCS7_SIGNER_INFO *p7i, X509 *x509, EVP_PKEY *pkey, @@ -369,10 +369,10 @@ PKCS7_SIGNER_INFO *PKCS7_add_signature(PKCS7 *p7, X509 *x509, EVP_PKEY *pkey, goto err; if (!PKCS7_add_signer(p7, si)) goto err; - return (si); + return si; err: PKCS7_SIGNER_INFO_free(si); - return (NULL); + return NULL; } int PKCS7_set_digest(PKCS7 *p7, const EVP_MD *md) @@ -396,11 +396,11 @@ STACK_OF(PKCS7_SIGNER_INFO) *PKCS7_get_signer_info(PKCS7 *p7) if (p7 == NULL || p7->d.ptr == NULL) return NULL; if (PKCS7_type_is_signed(p7)) { - return (p7->d.sign->signer_info); + return p7->d.sign->signer_info; } else if (PKCS7_type_is_signedAndEnveloped(p7)) { - return (p7->d.signed_and_enveloped->signer_info); + return p7->d.signed_and_enveloped->signer_info; } else - return (NULL); + return NULL; } void PKCS7_SIGNER_INFO_get0_algs(PKCS7_SIGNER_INFO *si, EVP_PKEY **pk, @@ -452,12 +452,12 @@ int PKCS7_add_recipient_info(PKCS7 *p7, PKCS7_RECIP_INFO *ri) default: PKCS7err(PKCS7_F_PKCS7_ADD_RECIPIENT_INFO, PKCS7_R_WRONG_CONTENT_TYPE); - return (0); + return 0; } if (!sk_PKCS7_RECIP_INFO_push(sk, ri)) return 0; - return (1); + return 1; } int PKCS7_RECIP_INFO_set(PKCS7_RECIP_INFO *p7i, X509 *x509) @@ -512,7 +512,7 @@ X509 *PKCS7_cert_from_signer_info(PKCS7 *p7, PKCS7_SIGNER_INFO *si) si-> issuer_and_serial->serial)); else - return (NULL); + return NULL; } int PKCS7_set_cipher(PKCS7 *p7, const EVP_CIPHER *cipher) @@ -530,7 +530,7 @@ int PKCS7_set_cipher(PKCS7 *p7, const EVP_CIPHER *cipher) break; default: PKCS7err(PKCS7_F_PKCS7_SET_CIPHER, PKCS7_R_WRONG_CONTENT_TYPE); - return (0); + return 0; } /* Check cipher OID exists and has data in it */ @@ -538,7 +538,7 @@ int PKCS7_set_cipher(PKCS7 *p7, const EVP_CIPHER *cipher) if (i == NID_undef) { PKCS7err(PKCS7_F_PKCS7_SET_CIPHER, PKCS7_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER); - return (0); + return 0; } ec->cipher = cipher; diff --git a/crypto/pkcs7/pk7_mime.c b/crypto/pkcs7/pk7_mime.c index 97474cf5..19e68681 100644 --- a/crypto/pkcs7/pk7_mime.c +++ b/crypto/pkcs7/pk7_mime.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-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 @@ -8,7 +8,6 @@ */ #include -#include #include "internal/cryptlib.h" #include #include diff --git a/crypto/pkcs7/pkcs7err.c b/crypto/pkcs7/pkcs7err.c index d5baa9b8..07490c1a 100644 --- a/crypto/pkcs7/pkcs7err.c +++ b/crypto/pkcs7/pkcs7err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,111 +8,137 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_PKCS7,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_PKCS7,0,reason) - -static ERR_STRING_DATA PKCS7_str_functs[] = { - {ERR_FUNC(PKCS7_F_DO_PKCS7_SIGNED_ATTRIB), "do_pkcs7_signed_attrib"}, - {ERR_FUNC(PKCS7_F_PKCS7_ADD0_ATTRIB_SIGNING_TIME), +static const ERR_STRING_DATA PKCS7_str_functs[] = { + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_DO_PKCS7_SIGNED_ATTRIB, 0), + "do_pkcs7_signed_attrib"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_ADD0_ATTRIB_SIGNING_TIME, 0), "PKCS7_add0_attrib_signing_time"}, - {ERR_FUNC(PKCS7_F_PKCS7_ADD_ATTRIB_SMIMECAP), + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_ADD_ATTRIB_SMIMECAP, 0), "PKCS7_add_attrib_smimecap"}, - {ERR_FUNC(PKCS7_F_PKCS7_ADD_CERTIFICATE), "PKCS7_add_certificate"}, - {ERR_FUNC(PKCS7_F_PKCS7_ADD_CRL), "PKCS7_add_crl"}, - {ERR_FUNC(PKCS7_F_PKCS7_ADD_RECIPIENT_INFO), "PKCS7_add_recipient_info"}, - {ERR_FUNC(PKCS7_F_PKCS7_ADD_SIGNATURE), "PKCS7_add_signature"}, - {ERR_FUNC(PKCS7_F_PKCS7_ADD_SIGNER), "PKCS7_add_signer"}, - {ERR_FUNC(PKCS7_F_PKCS7_BIO_ADD_DIGEST), "PKCS7_bio_add_digest"}, - {ERR_FUNC(PKCS7_F_PKCS7_COPY_EXISTING_DIGEST), + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_ADD_CERTIFICATE, 0), + "PKCS7_add_certificate"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_ADD_CRL, 0), "PKCS7_add_crl"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_ADD_RECIPIENT_INFO, 0), + "PKCS7_add_recipient_info"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_ADD_SIGNATURE, 0), + "PKCS7_add_signature"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_ADD_SIGNER, 0), "PKCS7_add_signer"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_BIO_ADD_DIGEST, 0), + "PKCS7_bio_add_digest"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_COPY_EXISTING_DIGEST, 0), "pkcs7_copy_existing_digest"}, - {ERR_FUNC(PKCS7_F_PKCS7_CTRL), "PKCS7_ctrl"}, - {ERR_FUNC(PKCS7_F_PKCS7_DATADECODE), "PKCS7_dataDecode"}, - {ERR_FUNC(PKCS7_F_PKCS7_DATAFINAL), "PKCS7_dataFinal"}, - {ERR_FUNC(PKCS7_F_PKCS7_DATAINIT), "PKCS7_dataInit"}, - {ERR_FUNC(PKCS7_F_PKCS7_DATAVERIFY), "PKCS7_dataVerify"}, - {ERR_FUNC(PKCS7_F_PKCS7_DECRYPT), "PKCS7_decrypt"}, - {ERR_FUNC(PKCS7_F_PKCS7_DECRYPT_RINFO), "pkcs7_decrypt_rinfo"}, - {ERR_FUNC(PKCS7_F_PKCS7_ENCODE_RINFO), "pkcs7_encode_rinfo"}, - {ERR_FUNC(PKCS7_F_PKCS7_ENCRYPT), "PKCS7_encrypt"}, - {ERR_FUNC(PKCS7_F_PKCS7_FINAL), "PKCS7_final"}, - {ERR_FUNC(PKCS7_F_PKCS7_FIND_DIGEST), "PKCS7_find_digest"}, - {ERR_FUNC(PKCS7_F_PKCS7_GET0_SIGNERS), "PKCS7_get0_signers"}, - {ERR_FUNC(PKCS7_F_PKCS7_RECIP_INFO_SET), "PKCS7_RECIP_INFO_set"}, - {ERR_FUNC(PKCS7_F_PKCS7_SET_CIPHER), "PKCS7_set_cipher"}, - {ERR_FUNC(PKCS7_F_PKCS7_SET_CONTENT), "PKCS7_set_content"}, - {ERR_FUNC(PKCS7_F_PKCS7_SET_DIGEST), "PKCS7_set_digest"}, - {ERR_FUNC(PKCS7_F_PKCS7_SET_TYPE), "PKCS7_set_type"}, - {ERR_FUNC(PKCS7_F_PKCS7_SIGN), "PKCS7_sign"}, - {ERR_FUNC(PKCS7_F_PKCS7_SIGNATUREVERIFY), "PKCS7_signatureVerify"}, - {ERR_FUNC(PKCS7_F_PKCS7_SIGNER_INFO_SET), "PKCS7_SIGNER_INFO_set"}, - {ERR_FUNC(PKCS7_F_PKCS7_SIGNER_INFO_SIGN), "PKCS7_SIGNER_INFO_sign"}, - {ERR_FUNC(PKCS7_F_PKCS7_SIGN_ADD_SIGNER), "PKCS7_sign_add_signer"}, - {ERR_FUNC(PKCS7_F_PKCS7_SIMPLE_SMIMECAP), "PKCS7_simple_smimecap"}, - {ERR_FUNC(PKCS7_F_PKCS7_VERIFY), "PKCS7_verify"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_CTRL, 0), "PKCS7_ctrl"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_DATADECODE, 0), "PKCS7_dataDecode"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_DATAFINAL, 0), "PKCS7_dataFinal"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_DATAINIT, 0), "PKCS7_dataInit"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_DATAVERIFY, 0), "PKCS7_dataVerify"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_DECRYPT, 0), "PKCS7_decrypt"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_DECRYPT_RINFO, 0), + "pkcs7_decrypt_rinfo"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_ENCODE_RINFO, 0), + "pkcs7_encode_rinfo"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_ENCRYPT, 0), "PKCS7_encrypt"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_FINAL, 0), "PKCS7_final"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_FIND_DIGEST, 0), + "PKCS7_find_digest"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_GET0_SIGNERS, 0), + "PKCS7_get0_signers"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_RECIP_INFO_SET, 0), + "PKCS7_RECIP_INFO_set"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_SET_CIPHER, 0), "PKCS7_set_cipher"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_SET_CONTENT, 0), + "PKCS7_set_content"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_SET_DIGEST, 0), "PKCS7_set_digest"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_SET_TYPE, 0), "PKCS7_set_type"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_SIGN, 0), "PKCS7_sign"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_SIGNATUREVERIFY, 0), + "PKCS7_signatureVerify"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_SIGNER_INFO_SET, 0), + "PKCS7_SIGNER_INFO_set"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_SIGNER_INFO_SIGN, 0), + "PKCS7_SIGNER_INFO_sign"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_SIGN_ADD_SIGNER, 0), + "PKCS7_sign_add_signer"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_SIMPLE_SMIMECAP, 0), + "PKCS7_simple_smimecap"}, + {ERR_PACK(ERR_LIB_PKCS7, PKCS7_F_PKCS7_VERIFY, 0), "PKCS7_verify"}, {0, NULL} }; -static ERR_STRING_DATA PKCS7_str_reasons[] = { - {ERR_REASON(PKCS7_R_CERTIFICATE_VERIFY_ERROR), - "certificate verify error"}, - {ERR_REASON(PKCS7_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER), - "cipher has no object identifier"}, - {ERR_REASON(PKCS7_R_CIPHER_NOT_INITIALIZED), "cipher not initialized"}, - {ERR_REASON(PKCS7_R_CONTENT_AND_DATA_PRESENT), - "content and data present"}, - {ERR_REASON(PKCS7_R_CTRL_ERROR), "ctrl error"}, - {ERR_REASON(PKCS7_R_DECRYPT_ERROR), "decrypt error"}, - {ERR_REASON(PKCS7_R_DIGEST_FAILURE), "digest failure"}, - {ERR_REASON(PKCS7_R_ENCRYPTION_CTRL_FAILURE), "encryption ctrl failure"}, - {ERR_REASON(PKCS7_R_ENCRYPTION_NOT_SUPPORTED_FOR_THIS_KEY_TYPE), - "encryption not supported for this key type"}, - {ERR_REASON(PKCS7_R_ERROR_ADDING_RECIPIENT), "error adding recipient"}, - {ERR_REASON(PKCS7_R_ERROR_SETTING_CIPHER), "error setting cipher"}, - {ERR_REASON(PKCS7_R_INVALID_NULL_POINTER), "invalid null pointer"}, - {ERR_REASON(PKCS7_R_INVALID_SIGNED_DATA_TYPE), - "invalid signed data type"}, - {ERR_REASON(PKCS7_R_NO_CONTENT), "no content"}, - {ERR_REASON(PKCS7_R_NO_DEFAULT_DIGEST), "no default digest"}, - {ERR_REASON(PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND), - "no matching digest type found"}, - {ERR_REASON(PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE), - "no recipient matches certificate"}, - {ERR_REASON(PKCS7_R_NO_SIGNATURES_ON_DATA), "no signatures on data"}, - {ERR_REASON(PKCS7_R_NO_SIGNERS), "no signers"}, - {ERR_REASON(PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE), - "operation not supported on this type"}, - {ERR_REASON(PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR), - "pkcs7 add signature error"}, - {ERR_REASON(PKCS7_R_PKCS7_ADD_SIGNER_ERROR), "pkcs7 add signer error"}, - {ERR_REASON(PKCS7_R_PKCS7_DATASIGN), "pkcs7 datasign"}, - {ERR_REASON(PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), - "private key does not match certificate"}, - {ERR_REASON(PKCS7_R_SIGNATURE_FAILURE), "signature failure"}, - {ERR_REASON(PKCS7_R_SIGNER_CERTIFICATE_NOT_FOUND), - "signer certificate not found"}, - {ERR_REASON(PKCS7_R_SIGNING_CTRL_FAILURE), "signing ctrl failure"}, - {ERR_REASON(PKCS7_R_SIGNING_NOT_SUPPORTED_FOR_THIS_KEY_TYPE), - "signing not supported for this key type"}, - {ERR_REASON(PKCS7_R_SMIME_TEXT_ERROR), "smime text error"}, - {ERR_REASON(PKCS7_R_UNABLE_TO_FIND_CERTIFICATE), - "unable to find certificate"}, - {ERR_REASON(PKCS7_R_UNABLE_TO_FIND_MEM_BIO), "unable to find mem bio"}, - {ERR_REASON(PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST), - "unable to find message digest"}, - {ERR_REASON(PKCS7_R_UNKNOWN_DIGEST_TYPE), "unknown digest type"}, - {ERR_REASON(PKCS7_R_UNKNOWN_OPERATION), "unknown operation"}, - {ERR_REASON(PKCS7_R_UNSUPPORTED_CIPHER_TYPE), "unsupported cipher type"}, - {ERR_REASON(PKCS7_R_UNSUPPORTED_CONTENT_TYPE), - "unsupported content type"}, - {ERR_REASON(PKCS7_R_WRONG_CONTENT_TYPE), "wrong content type"}, - {ERR_REASON(PKCS7_R_WRONG_PKCS7_TYPE), "wrong pkcs7 type"}, +static const ERR_STRING_DATA PKCS7_str_reasons[] = { + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_CERTIFICATE_VERIFY_ERROR), + "certificate verify error"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER), + "cipher has no object identifier"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_CIPHER_NOT_INITIALIZED), + "cipher not initialized"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_CONTENT_AND_DATA_PRESENT), + "content and data present"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_CTRL_ERROR), "ctrl error"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_DECRYPT_ERROR), "decrypt error"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_DIGEST_FAILURE), "digest failure"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_ENCRYPTION_CTRL_FAILURE), + "encryption ctrl failure"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_ENCRYPTION_NOT_SUPPORTED_FOR_THIS_KEY_TYPE), + "encryption not supported for this key type"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_ERROR_ADDING_RECIPIENT), + "error adding recipient"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_ERROR_SETTING_CIPHER), + "error setting cipher"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_INVALID_NULL_POINTER), + "invalid null pointer"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_INVALID_SIGNED_DATA_TYPE), + "invalid signed data type"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_CONTENT), "no content"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_DEFAULT_DIGEST), + "no default digest"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND), + "no matching digest type found"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE), + "no recipient matches certificate"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_SIGNATURES_ON_DATA), + "no signatures on data"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_SIGNERS), "no signers"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE), + "operation not supported on this type"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR), + "pkcs7 add signature error"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_PKCS7_ADD_SIGNER_ERROR), + "pkcs7 add signer error"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_PKCS7_DATASIGN), "pkcs7 datasign"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), + "private key does not match certificate"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_SIGNATURE_FAILURE), + "signature failure"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_SIGNER_CERTIFICATE_NOT_FOUND), + "signer certificate not found"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_SIGNING_CTRL_FAILURE), + "signing ctrl failure"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_SIGNING_NOT_SUPPORTED_FOR_THIS_KEY_TYPE), + "signing not supported for this key type"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_SMIME_TEXT_ERROR), "smime text error"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNABLE_TO_FIND_CERTIFICATE), + "unable to find certificate"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNABLE_TO_FIND_MEM_BIO), + "unable to find mem bio"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST), + "unable to find message digest"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNKNOWN_DIGEST_TYPE), + "unknown digest type"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNKNOWN_OPERATION), + "unknown operation"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNSUPPORTED_CIPHER_TYPE), + "unsupported cipher type"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNSUPPORTED_CONTENT_TYPE), + "unsupported content type"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_WRONG_CONTENT_TYPE), + "wrong content type"}, + {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_WRONG_PKCS7_TYPE), "wrong pkcs7 type"}, {0, NULL} }; @@ -121,10 +147,9 @@ static ERR_STRING_DATA PKCS7_str_reasons[] = { int ERR_load_PKCS7_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(PKCS7_str_functs[0].error) == NULL) { - ERR_load_strings(0, PKCS7_str_functs); - ERR_load_strings(0, PKCS7_str_reasons); + ERR_load_strings_const(PKCS7_str_functs); + ERR_load_strings_const(PKCS7_str_reasons); } #endif return 1; diff --git a/crypto/poly1305/asm/poly1305-armv8.pl b/crypto/poly1305/asm/poly1305-armv8.pl index 0fc8667a..ac06457b 100755 --- a/crypto/poly1305/asm/poly1305-armv8.pl +++ b/crypto/poly1305/asm/poly1305-armv8.pl @@ -28,6 +28,7 @@ # Denver 1.64/+50% 1.18(*) # X-Gene 2.13/+68% 2.27 # Mongoose 1.77/+75% 1.12 +# Kryo 2.70/+55% 1.13 # # (*) estimate based on resources availability is less than 1.0, # i.e. measured result is worse than expected, presumably binary diff --git a/crypto/poly1305/asm/poly1305-mips.pl b/crypto/poly1305/asm/poly1305-mips.pl index d2b3e90d..28b6772e 100755 --- a/crypto/poly1305/asm/poly1305-mips.pl +++ b/crypto/poly1305/asm/poly1305-mips.pl @@ -67,6 +67,8 @@ $SAVED_REGS_MASK = ($flavour =~ /nubi/i) ? "0x0003f000" : "0x00030000"; ($in0,$in1,$tmp0,$tmp1,$tmp2,$tmp3,$tmp4) = ($a4,$a5,$a6,$a7,$at,$t0,$t1); $code.=<<___; +#include "mips_arch.h" + #ifdef MIPSEB # define MSB 0 # define LSB 7 @@ -92,10 +94,15 @@ poly1305_init: beqz $inp,.Lno_key +#if defined(_MIPS_ARCH_MIPS64R6) + ld $in0,0($inp) + ld $in1,8($inp) +#else ldl $in0,0+MSB($inp) ldl $in1,8+MSB($inp) ldr $in0,0+LSB($inp) ldr $in1,8+LSB($inp) +#endif #ifdef MIPSEB # if defined(_MIPS_ARCH_MIPS64R2) dsbh $in0,$in0 # byte swap @@ -182,7 +189,7 @@ poly1305_blocks_internal: .frame $sp,6*8,$ra .mask $SAVED_REGS_MASK,-8 .set noreorder - dsub $sp,6*8 + dsubu $sp,6*8 sd $s5,40($sp) sd $s4,32($sp) ___ @@ -204,11 +211,16 @@ $code.=<<___; ld $s1,40($ctx) .Loop: +#if defined(_MIPS_ARCH_MIPS64R6) + ld $in0,0($inp) # load input + ld $in1,8($inp) +#else ldl $in0,0+MSB($inp) # load input ldl $in1,8+MSB($inp) ldr $in0,0+LSB($inp) - daddiu $len,-1 ldr $in1,8+LSB($inp) +#endif + daddiu $len,-1 daddiu $inp,16 #ifdef MIPSEB # if defined(_MIPS_ARCH_MIPS64R2) @@ -258,42 +270,42 @@ $code.=<<___; sltu $tmp1,$h1,$in1 daddu $h1,$tmp0 - dmultu $r0,$h0 # h0*r0 + dmultu ($r0,$h0) # h0*r0 daddu $h2,$padbit sltu $tmp0,$h1,$tmp0 - mflo $d0 - mfhi $d1 + mflo ($d0,$r0,$h0) + mfhi ($d1,$r0,$h0) - dmultu $s1,$h1 # h1*5*r1 + dmultu ($s1,$h1) # h1*5*r1 daddu $tmp0,$tmp1 daddu $h2,$tmp0 - mflo $tmp0 - mfhi $tmp1 + mflo ($tmp0,$s1,$h1) + mfhi ($tmp1,$s1,$h1) - dmultu $r1,$h0 # h0*r1 + dmultu ($r1,$h0) # h0*r1 daddu $d0,$tmp0 daddu $d1,$tmp1 - mflo $tmp2 - mfhi $d2 + mflo ($tmp2,$r1,$h0) + mfhi ($d2,$r1,$h0) sltu $tmp0,$d0,$tmp0 daddu $d1,$tmp0 - dmultu $r0,$h1 # h1*r0 + dmultu ($r0,$h1) # h1*r0 daddu $d1,$tmp2 sltu $tmp2,$d1,$tmp2 - mflo $tmp0 - mfhi $tmp1 + mflo ($tmp0,$r0,$h1) + mfhi ($tmp1,$r0,$h1) daddu $d2,$tmp2 - dmultu $s1,$h2 # h2*5*r1 + dmultu ($s1,$h2) # h2*5*r1 daddu $d1,$tmp0 daddu $d2,$tmp1 - mflo $tmp2 + mflo ($tmp2,$s1,$h2) - dmultu $r0,$h2 # h2*r0 + dmultu ($r0,$h2) # h2*r0 sltu $tmp0,$d1,$tmp0 daddu $d2,$tmp0 - mflo $tmp3 + mflo ($tmp3,$r0,$h2) daddu $d1,$tmp2 daddu $d2,$tmp3 @@ -329,7 +341,7 @@ $code.=<<___ if ($flavour =~ /nubi/i); # optimize non-nubi epilogue ___ $code.=<<___; jr $ra - dadd $sp,6*8 + daddu $sp,6*8 .end poly1305_blocks_internal ___ } diff --git a/crypto/poly1305/asm/poly1305-x86.pl b/crypto/poly1305/asm/poly1305-x86.pl index ab24dfcf..ec1efd93 100755 --- a/crypto/poly1305/asm/poly1305-x86.pl +++ b/crypto/poly1305/asm/poly1305-x86.pl @@ -29,6 +29,7 @@ # Westmere 4.58/+100% 1.43 # Sandy Bridge 3.90/+100% 1.36 # Haswell 3.88/+70% 1.18 0.72 +# Skylake 3.10/+60% 1.14 0.62 # Silvermont 11.0/+40% 4.80 # Goldmont 4.10/+200% 2.10 # VIA Nano 6.71/+90% 2.47 @@ -49,7 +50,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"poly1305-x86.pl",$ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$ARGV[$#ARGV] eq "386"); $sse2=$avx=0; for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } @@ -729,7 +730,7 @@ my $extra = shift; &movdqa ($T0,$T1); # -> base 2^26 ... &pand ($T1,$MASK); - &paddd ($D0,$T1); # ... and accumuate + &paddd ($D0,$T1); # ... and accumulate &movdqa ($T1,$T0); &psrlq ($T0,26); diff --git a/crypto/poly1305/asm/poly1305-x86_64.pl b/crypto/poly1305/asm/poly1305-x86_64.pl index 4c22ded5..0d1c0de6 100755 --- a/crypto/poly1305/asm/poly1305-x86_64.pl +++ b/crypto/poly1305/asm/poly1305-x86_64.pl @@ -18,21 +18,39 @@ # # March 2015 # +# Initial release. +# +# December 2016 +# +# Add AVX512F+VL+BW code path. +# +# November 2017 +# +# Convert AVX512F+VL+BW code path to pure AVX512F, so that it can be +# executed even on Knights Landing. Trigger for modification was +# observation that AVX512 code paths can negatively affect overall +# Skylake-X system performance. Since we are likely to suppress +# AVX512F capability flag [at least on Skylake-X], conversion serves +# as kind of "investment protection". Note that next *lake processor, +# Cannolake, has AVX512IFMA code path to execute... +# # Numbers are cycles per processed byte with poly1305_blocks alone, # measured with rdtsc at fixed clock frequency. # -# IALU/gcc-4.8(*) AVX(**) AVX2 +# IALU/gcc-4.8(*) AVX(**) AVX2 AVX-512 # P4 4.46/+120% - # Core 2 2.41/+90% - # Westmere 1.88/+120% - # Sandy Bridge 1.39/+140% 1.10 # Haswell 1.14/+175% 1.11 0.65 -# Skylake 1.13/+120% 0.96 0.51 +# Skylake[-X] 1.13/+120% 0.96 0.51 [0.35] # Silvermont 2.83/+95% - +# Knights L 3.60/? 1.65 1.10 0.41(***) # Goldmont 1.70/+180% - # VIA Nano 1.82/+150% - # Sledgehammer 1.38/+160% - # Bulldozer 2.30/+130% 0.97 +# Ryzen 1.15/+200% 1.08 1.18 # # (*) improvement coefficients relative to clang are more modest and # are ~50% on most processors, in both cases we are comparing to @@ -42,6 +60,8 @@ # Core processors, 50-30%, less newer processor is, but slower on # contemporary ones, for example almost 2x slower on Atom, and as # former are naturally disappearing, SSE2 is deemed unnecessary; +# (***) strangely enough performance seems to vary from core to core, +# listed result is best case; $flavour = shift; $output = shift; @@ -56,12 +76,13 @@ die "can't locate x86_64-xlate.pl"; if (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1` =~ /GNU assembler version ([2-9]\.[0-9]+)/) { - $avx = ($1>=2.19) + ($1>=2.22); + $avx = ($1>=2.19) + ($1>=2.22) + ($1>=2.25) + ($1>=2.26); } if (!$avx && $win64 && ($flavour =~ /nasm/ || $ENV{ASM} =~ /nasm/) && - `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)/) { - $avx = ($1>=2.09) + ($1>=2.10); + `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)(?:\.([0-9]+))?/) { + $avx = ($1>=2.09) + ($1>=2.10) + 2 * ($1>=2.12); + $avx += 2 if ($1==2.11 && $2>=8); } if (!$avx && $win64 && ($flavour =~ /masm/ || $ENV{ASM} =~ /ml64/) && @@ -171,6 +192,13 @@ $code.=<<___ if ($avx>1); bt \$`5+32`,%r9 # AVX2? cmovc %rax,%r10 ___ +$code.=<<___ if ($avx>3); + mov \$`(1<<31|1<<21|1<<16)`,%rax + shr \$32,%r9 + and %rax,%r9 + cmp %rax,%r9 + je .Linit_base2_44 +___ $code.=<<___; mov \$0x0ffffffc0fffffff,%rax mov \$0x0ffffffc0ffffffc,%rcx @@ -196,16 +224,23 @@ $code.=<<___; .type poly1305_blocks,\@function,4 .align 32 poly1305_blocks: +.cfi_startproc .Lblocks: shr \$4,$len jz .Lno_data # too short push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lblocks_body: mov $len,%r15 # reassign $len @@ -241,15 +276,23 @@ $code.=<<___; mov $h2,16($ctx) mov 0(%rsp),%r15 +.cfi_restore %r15 mov 8(%rsp),%r14 +.cfi_restore %r14 mov 16(%rsp),%r13 +.cfi_restore %r13 mov 24(%rsp),%r12 +.cfi_restore %r12 mov 32(%rsp),%rbp +.cfi_restore %rbp mov 40(%rsp),%rbx +.cfi_restore %rbx lea 48(%rsp),%rsp +.cfi_adjust_cfa_offset -48 .Lno_data: .Lblocks_epilogue: ret +.cfi_endproc .size poly1305_blocks,.-poly1305_blocks .type poly1305_emit,\@function,3 @@ -265,7 +308,7 @@ poly1305_emit: mov %r9,%rcx adc \$0,%r9 adc \$0,%r10 - shr \$2,%r10 # did 130-bit value overfow? + shr \$2,%r10 # did 130-bit value overflow? cmovnz %r8,%rax cmovnz %r9,%rcx @@ -470,6 +513,7 @@ __poly1305_init_avx: .type poly1305_blocks_avx,\@function,4 .align 32 poly1305_blocks_avx: +.cfi_startproc mov 20($ctx),%r8d # is_base2_26 cmp \$128,$len jae .Lblocks_avx @@ -489,11 +533,17 @@ poly1305_blocks_avx: jz .Leven_avx push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lblocks_avx_body: mov $len,%r15 # reassign $len @@ -596,24 +646,39 @@ poly1305_blocks_avx: .align 16 .Ldone_avx: mov 0(%rsp),%r15 +.cfi_restore %r15 mov 8(%rsp),%r14 +.cfi_restore %r14 mov 16(%rsp),%r13 +.cfi_restore %r13 mov 24(%rsp),%r12 +.cfi_restore %r12 mov 32(%rsp),%rbp +.cfi_restore %rbp mov 40(%rsp),%rbx +.cfi_restore %rbx lea 48(%rsp),%rsp +.cfi_adjust_cfa_offset -48 .Lno_data_avx: .Lblocks_avx_epilogue: ret +.cfi_endproc .align 32 .Lbase2_64_avx: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lbase2_64_avx_body: mov $len,%r15 # reassign $len @@ -673,18 +738,27 @@ poly1305_blocks_avx: mov %r15,$len mov 0(%rsp),%r15 +.cfi_restore %r15 mov 8(%rsp),%r14 +.cfi_restore %r14 mov 16(%rsp),%r13 +.cfi_restore %r13 mov 24(%rsp),%r12 +.cfi_restore %r12 mov 32(%rsp),%rbp +.cfi_restore %rbp mov 40(%rsp),%rbx +.cfi_restore %rbx lea 48(%rsp),%rax lea 48(%rsp),%rsp +.cfi_adjust_cfa_offset -48 .Lbase2_64_avx_epilogue: jmp .Ldo_avx +.cfi_endproc .align 32 .Leven_avx: +.cfi_startproc vmovd 4*0($ctx),$H0 # load hash value vmovd 4*1($ctx),$H1 vmovd 4*2($ctx),$H2 @@ -695,6 +769,7 @@ poly1305_blocks_avx: ___ $code.=<<___ if (!$win64); lea -0x58(%rsp),%r11 +.cfi_def_cfa %r11,0x60 sub \$0x178,%rsp ___ $code.=<<___ if ($win64); @@ -1287,10 +1362,12 @@ $code.=<<___ if ($win64); ___ $code.=<<___ if (!$win64); lea 0x58(%r11),%rsp +.cfi_def_cfa %rsp,8 ___ $code.=<<___; vzeroupper ret +.cfi_endproc .size poly1305_blocks_avx,.-poly1305_blocks_avx .type poly1305_emit_avx,\@function,3 @@ -1336,7 +1413,7 @@ poly1305_emit_avx: mov %r9,%rcx adc \$0,%r9 adc \$0,%r10 - shr \$2,%r10 # did 130-bit value overfow? + shr \$2,%r10 # did 130-bit value overflow? cmovnz %r8,%rax cmovnz %r9,%rcx @@ -1358,6 +1435,7 @@ $code.=<<___; .type poly1305_blocks_avx2,\@function,4 .align 32 poly1305_blocks_avx2: +.cfi_startproc mov 20($ctx),%r8d # is_base2_26 cmp \$128,$len jae .Lblocks_avx2 @@ -1377,11 +1455,17 @@ poly1305_blocks_avx2: jz .Leven_avx2 push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lblocks_avx2_body: mov $len,%r15 # reassign $len @@ -1490,24 +1574,39 @@ poly1305_blocks_avx2: .align 16 .Ldone_avx2: mov 0(%rsp),%r15 +.cfi_restore %r15 mov 8(%rsp),%r14 +.cfi_restore %r14 mov 16(%rsp),%r13 +.cfi_restore %r13 mov 24(%rsp),%r12 +.cfi_restore %r12 mov 32(%rsp),%rbp +.cfi_restore %rbp mov 40(%rsp),%rbx +.cfi_restore %rbx lea 48(%rsp),%rsp +.cfi_adjust_cfa_offset -48 .Lno_data_avx2: .Lblocks_avx2_epilogue: ret +.cfi_endproc .align 32 .Lbase2_64_avx2: +.cfi_startproc push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 .Lbase2_64_avx2_body: mov $len,%r15 # reassign $len @@ -1569,21 +1668,33 @@ poly1305_blocks_avx2: call __poly1305_init_avx .Lproceed_avx2: - mov %r15,$len + mov %r15,$len # restore $len + mov OPENSSL_ia32cap_P+8(%rip),%r10d + mov \$`(1<<31|1<<30|1<<16)`,%r11d mov 0(%rsp),%r15 +.cfi_restore %r15 mov 8(%rsp),%r14 +.cfi_restore %r14 mov 16(%rsp),%r13 +.cfi_restore %r13 mov 24(%rsp),%r12 +.cfi_restore %r12 mov 32(%rsp),%rbp +.cfi_restore %rbp mov 40(%rsp),%rbx +.cfi_restore %rbx lea 48(%rsp),%rax lea 48(%rsp),%rsp +.cfi_adjust_cfa_offset -48 .Lbase2_64_avx2_epilogue: jmp .Ldo_avx2 +.cfi_endproc .align 32 .Leven_avx2: +.cfi_startproc + mov OPENSSL_ia32cap_P+8(%rip),%r10d vmovd 4*0($ctx),%x#$H0 # load hash value base 2^26 vmovd 4*1($ctx),%x#$H1 vmovd 4*2($ctx),%x#$H2 @@ -1592,8 +1703,17 @@ poly1305_blocks_avx2: .Ldo_avx2: ___ +$code.=<<___ if ($avx>2); + cmp \$512,$len + jb .Lskip_avx512 + and %r11d,%r10d + test \$`1<<16`,%r10d # check for AVX512F + jnz .Lblocks_avx512 +.Lskip_avx512: +___ $code.=<<___ if (!$win64); lea -8(%rsp),%r11 +.cfi_def_cfa %r11,16 sub \$0x128,%rsp ___ $code.=<<___ if ($win64); @@ -1612,8 +1732,9 @@ $code.=<<___ if ($win64); .Ldo_avx2_body: ___ $code.=<<___; - lea 48+64($ctx),$ctx # size optimization lea .Lconst(%rip),%rcx + lea 48+64($ctx),$ctx # size optimization + vmovdqa 96(%rcx),$T0 # .Lpermd_avx2 # expand and copy pre-calculated table to stack vmovdqu `16*0-64`($ctx),%x#$T2 @@ -1623,36 +1744,28 @@ $code.=<<___; vmovdqu `16*3-64`($ctx),%x#$D0 vmovdqu `16*4-64`($ctx),%x#$D1 vmovdqu `16*5-64`($ctx),%x#$D2 + lea 0x90(%rsp),%rax # size optimization vmovdqu `16*6-64`($ctx),%x#$D3 - vpermq \$0x15,$T2,$T2 # 00003412 -> 12343434 + vpermd $T2,$T0,$T2 # 00003412 -> 14243444 vmovdqu `16*7-64`($ctx),%x#$D4 - vpermq \$0x15,$T3,$T3 - vpshufd \$0xc8,$T2,$T2 # 12343434 -> 14243444 + vpermd $T3,$T0,$T3 vmovdqu `16*8-64`($ctx),%x#$MASK - vpermq \$0x15,$T4,$T4 - vpshufd \$0xc8,$T3,$T3 + vpermd $T4,$T0,$T4 vmovdqa $T2,0x00(%rsp) - vpermq \$0x15,$D0,$D0 - vpshufd \$0xc8,$T4,$T4 - vmovdqa $T3,0x20(%rsp) - vpermq \$0x15,$D1,$D1 - vpshufd \$0xc8,$D0,$D0 - vmovdqa $T4,0x40(%rsp) - vpermq \$0x15,$D2,$D2 - vpshufd \$0xc8,$D1,$D1 - vmovdqa $D0,0x60(%rsp) - vpermq \$0x15,$D3,$D3 - vpshufd \$0xc8,$D2,$D2 - vmovdqa $D1,0x80(%rsp) - vpermq \$0x15,$D4,$D4 - vpshufd \$0xc8,$D3,$D3 - vmovdqa $D2,0xa0(%rsp) - vpermq \$0x15,$MASK,$MASK - vpshufd \$0xc8,$D4,$D4 - vmovdqa $D3,0xc0(%rsp) - vpshufd \$0xc8,$MASK,$MASK - vmovdqa $D4,0xe0(%rsp) - vmovdqa $MASK,0x100(%rsp) + vpermd $D0,$T0,$D0 + vmovdqa $T3,0x20-0x90(%rax) + vpermd $D1,$T0,$D1 + vmovdqa $T4,0x40-0x90(%rax) + vpermd $D2,$T0,$D2 + vmovdqa $D0,0x60-0x90(%rax) + vpermd $D3,$T0,$D3 + vmovdqa $D1,0x80-0x90(%rax) + vpermd $D4,$T0,$D4 + vmovdqa $D2,0xa0-0x90(%rax) + vpermd $MASK,$T0,$MASK + vmovdqa $D3,0xc0-0x90(%rax) + vmovdqa $D4,0xe0-0x90(%rax) + vmovdqa $MASK,0x100-0x90(%rax) vmovdqa 64(%rcx),$MASK # .Lmask26 ################################################################ @@ -1679,7 +1792,6 @@ $code.=<<___; vpand $MASK,$T3,$T3 # 3 vpor 32(%rcx),$T4,$T4 # padbit, yes, always - lea 0x90(%rsp),%rax # size optimization vpaddq $H2,$T2,$H2 # accumulate input sub \$64,$len jz .Ltail_avx2 @@ -1688,11 +1800,11 @@ $code.=<<___; .align 32 .Loop_avx2: ################################################################ - # ((inp[0]*r^4+r[4])*r^4+r[8])*r^4 - # ((inp[1]*r^4+r[5])*r^4+r[9])*r^3 - # ((inp[2]*r^4+r[6])*r^4+r[10])*r^2 - # ((inp[3]*r^4+r[7])*r^4+r[11])*r^1 - # \________/\________/ + # ((inp[0]*r^4+inp[4])*r^4+inp[ 8])*r^4 + # ((inp[1]*r^4+inp[5])*r^4+inp[ 9])*r^3 + # ((inp[2]*r^4+inp[6])*r^4+inp[10])*r^2 + # ((inp[3]*r^4+inp[7])*r^4+inp[11])*r^1 + # \________/\__________/ ################################################################ #vpaddq $H2,$T2,$H2 # accumulate input vpaddq $H0,$T0,$H0 @@ -1990,13 +2102,1657 @@ $code.=<<___ if ($win64); ___ $code.=<<___ if (!$win64); lea 8(%r11),%rsp +.cfi_def_cfa %rsp,8 ___ $code.=<<___; vzeroupper ret +.cfi_endproc .size poly1305_blocks_avx2,.-poly1305_blocks_avx2 ___ +####################################################################### +if ($avx>2) { +# On entry we have input length divisible by 64. But since inner loop +# processes 128 bytes per iteration, cases when length is not divisible +# by 128 are handled by passing tail 64 bytes to .Ltail_avx2. For this +# reason stack layout is kept identical to poly1305_blocks_avx2. If not +# for this tail, we wouldn't have to even allocate stack frame... + +my ($R0,$R1,$R2,$R3,$R4, $S1,$S2,$S3,$S4) = map("%zmm$_",(16..24)); +my ($M0,$M1,$M2,$M3,$M4) = map("%zmm$_",(25..29)); +my $PADBIT="%zmm30"; + +map(s/%y/%z/,($T4,$T0,$T1,$T2,$T3)); # switch to %zmm domain +map(s/%y/%z/,($D0,$D1,$D2,$D3,$D4)); +map(s/%y/%z/,($H0,$H1,$H2,$H3,$H4)); +map(s/%y/%z/,($MASK)); + +$code.=<<___; +.type poly1305_blocks_avx512,\@function,4 +.align 32 +poly1305_blocks_avx512: +.cfi_startproc +.Lblocks_avx512: + mov \$15,%eax + kmovw %eax,%k2 +___ +$code.=<<___ if (!$win64); + lea -8(%rsp),%r11 +.cfi_def_cfa %r11,16 + sub \$0x128,%rsp +___ +$code.=<<___ if ($win64); + lea -0xf8(%rsp),%r11 + sub \$0x1c8,%rsp + vmovdqa %xmm6,0x50(%r11) + vmovdqa %xmm7,0x60(%r11) + vmovdqa %xmm8,0x70(%r11) + vmovdqa %xmm9,0x80(%r11) + vmovdqa %xmm10,0x90(%r11) + vmovdqa %xmm11,0xa0(%r11) + vmovdqa %xmm12,0xb0(%r11) + vmovdqa %xmm13,0xc0(%r11) + vmovdqa %xmm14,0xd0(%r11) + vmovdqa %xmm15,0xe0(%r11) +.Ldo_avx512_body: +___ +$code.=<<___; + lea .Lconst(%rip),%rcx + lea 48+64($ctx),$ctx # size optimization + vmovdqa 96(%rcx),%y#$T2 # .Lpermd_avx2 + + # expand pre-calculated table + vmovdqu `16*0-64`($ctx),%x#$D0 # will become expanded ${R0} + and \$-512,%rsp + vmovdqu `16*1-64`($ctx),%x#$D1 # will become ... ${R1} + mov \$0x20,%rax + vmovdqu `16*2-64`($ctx),%x#$T0 # ... ${S1} + vmovdqu `16*3-64`($ctx),%x#$D2 # ... ${R2} + vmovdqu `16*4-64`($ctx),%x#$T1 # ... ${S2} + vmovdqu `16*5-64`($ctx),%x#$D3 # ... ${R3} + vmovdqu `16*6-64`($ctx),%x#$T3 # ... ${S3} + vmovdqu `16*7-64`($ctx),%x#$D4 # ... ${R4} + vmovdqu `16*8-64`($ctx),%x#$T4 # ... ${S4} + vpermd $D0,$T2,$R0 # 00003412 -> 14243444 + vpbroadcastq 64(%rcx),$MASK # .Lmask26 + vpermd $D1,$T2,$R1 + vpermd $T0,$T2,$S1 + vpermd $D2,$T2,$R2 + vmovdqa64 $R0,0x00(%rsp){%k2} # save in case $len%128 != 0 + vpsrlq \$32,$R0,$T0 # 14243444 -> 01020304 + vpermd $T1,$T2,$S2 + vmovdqu64 $R1,0x00(%rsp,%rax){%k2} + vpsrlq \$32,$R1,$T1 + vpermd $D3,$T2,$R3 + vmovdqa64 $S1,0x40(%rsp){%k2} + vpermd $T3,$T2,$S3 + vpermd $D4,$T2,$R4 + vmovdqu64 $R2,0x40(%rsp,%rax){%k2} + vpermd $T4,$T2,$S4 + vmovdqa64 $S2,0x80(%rsp){%k2} + vmovdqu64 $R3,0x80(%rsp,%rax){%k2} + vmovdqa64 $S3,0xc0(%rsp){%k2} + vmovdqu64 $R4,0xc0(%rsp,%rax){%k2} + vmovdqa64 $S4,0x100(%rsp){%k2} + + ################################################################ + # calculate 5th through 8th powers of the key + # + # d0 = r0'*r0 + r1'*5*r4 + r2'*5*r3 + r3'*5*r2 + r4'*5*r1 + # d1 = r0'*r1 + r1'*r0 + r2'*5*r4 + r3'*5*r3 + r4'*5*r2 + # d2 = r0'*r2 + r1'*r1 + r2'*r0 + r3'*5*r4 + r4'*5*r3 + # d3 = r0'*r3 + r1'*r2 + r2'*r1 + r3'*r0 + r4'*5*r4 + # d4 = r0'*r4 + r1'*r3 + r2'*r2 + r3'*r1 + r4'*r0 + + vpmuludq $T0,$R0,$D0 # d0 = r0'*r0 + vpmuludq $T0,$R1,$D1 # d1 = r0'*r1 + vpmuludq $T0,$R2,$D2 # d2 = r0'*r2 + vpmuludq $T0,$R3,$D3 # d3 = r0'*r3 + vpmuludq $T0,$R4,$D4 # d4 = r0'*r4 + vpsrlq \$32,$R2,$T2 + + vpmuludq $T1,$S4,$M0 + vpmuludq $T1,$R0,$M1 + vpmuludq $T1,$R1,$M2 + vpmuludq $T1,$R2,$M3 + vpmuludq $T1,$R3,$M4 + vpsrlq \$32,$R3,$T3 + vpaddq $M0,$D0,$D0 # d0 += r1'*5*r4 + vpaddq $M1,$D1,$D1 # d1 += r1'*r0 + vpaddq $M2,$D2,$D2 # d2 += r1'*r1 + vpaddq $M3,$D3,$D3 # d3 += r1'*r2 + vpaddq $M4,$D4,$D4 # d4 += r1'*r3 + + vpmuludq $T2,$S3,$M0 + vpmuludq $T2,$S4,$M1 + vpmuludq $T2,$R1,$M3 + vpmuludq $T2,$R2,$M4 + vpmuludq $T2,$R0,$M2 + vpsrlq \$32,$R4,$T4 + vpaddq $M0,$D0,$D0 # d0 += r2'*5*r3 + vpaddq $M1,$D1,$D1 # d1 += r2'*5*r4 + vpaddq $M3,$D3,$D3 # d3 += r2'*r1 + vpaddq $M4,$D4,$D4 # d4 += r2'*r2 + vpaddq $M2,$D2,$D2 # d2 += r2'*r0 + + vpmuludq $T3,$S2,$M0 + vpmuludq $T3,$R0,$M3 + vpmuludq $T3,$R1,$M4 + vpmuludq $T3,$S3,$M1 + vpmuludq $T3,$S4,$M2 + vpaddq $M0,$D0,$D0 # d0 += r3'*5*r2 + vpaddq $M3,$D3,$D3 # d3 += r3'*r0 + vpaddq $M4,$D4,$D4 # d4 += r3'*r1 + vpaddq $M1,$D1,$D1 # d1 += r3'*5*r3 + vpaddq $M2,$D2,$D2 # d2 += r3'*5*r4 + + vpmuludq $T4,$S4,$M3 + vpmuludq $T4,$R0,$M4 + vpmuludq $T4,$S1,$M0 + vpmuludq $T4,$S2,$M1 + vpmuludq $T4,$S3,$M2 + vpaddq $M3,$D3,$D3 # d3 += r2'*5*r4 + vpaddq $M4,$D4,$D4 # d4 += r2'*r0 + vpaddq $M0,$D0,$D0 # d0 += r2'*5*r1 + vpaddq $M1,$D1,$D1 # d1 += r2'*5*r2 + vpaddq $M2,$D2,$D2 # d2 += r2'*5*r3 + + ################################################################ + # load input + vmovdqu64 16*0($inp),%z#$T3 + vmovdqu64 16*4($inp),%z#$T4 + lea 16*8($inp),$inp + + ################################################################ + # lazy reduction + + vpsrlq \$26,$D3,$M3 + vpandq $MASK,$D3,$D3 + vpaddq $M3,$D4,$D4 # d3 -> d4 + + vpsrlq \$26,$D0,$M0 + vpandq $MASK,$D0,$D0 + vpaddq $M0,$D1,$D1 # d0 -> d1 + + vpsrlq \$26,$D4,$M4 + vpandq $MASK,$D4,$D4 + + vpsrlq \$26,$D1,$M1 + vpandq $MASK,$D1,$D1 + vpaddq $M1,$D2,$D2 # d1 -> d2 + + vpaddq $M4,$D0,$D0 + vpsllq \$2,$M4,$M4 + vpaddq $M4,$D0,$D0 # d4 -> d0 + + vpsrlq \$26,$D2,$M2 + vpandq $MASK,$D2,$D2 + vpaddq $M2,$D3,$D3 # d2 -> d3 + + vpsrlq \$26,$D0,$M0 + vpandq $MASK,$D0,$D0 + vpaddq $M0,$D1,$D1 # d0 -> d1 + + vpsrlq \$26,$D3,$M3 + vpandq $MASK,$D3,$D3 + vpaddq $M3,$D4,$D4 # d3 -> d4 + + ################################################################ + # at this point we have 14243444 in $R0-$S4 and 05060708 in + # $D0-$D4, ... + + vpunpcklqdq $T4,$T3,$T0 # transpose input + vpunpckhqdq $T4,$T3,$T4 + + # ... since input 64-bit lanes are ordered as 73625140, we could + # "vperm" it to 76543210 (here and in each loop iteration), *or* + # we could just flow along, hence the goal for $R0-$S4 is + # 1858286838784888 ... + + vmovdqa32 128(%rcx),$M0 # .Lpermd_avx512: + mov \$0x7777,%eax + kmovw %eax,%k1 + + vpermd $R0,$M0,$R0 # 14243444 -> 1---2---3---4--- + vpermd $R1,$M0,$R1 + vpermd $R2,$M0,$R2 + vpermd $R3,$M0,$R3 + vpermd $R4,$M0,$R4 + + vpermd $D0,$M0,${R0}{%k1} # 05060708 -> 1858286838784888 + vpermd $D1,$M0,${R1}{%k1} + vpermd $D2,$M0,${R2}{%k1} + vpermd $D3,$M0,${R3}{%k1} + vpermd $D4,$M0,${R4}{%k1} + + vpslld \$2,$R1,$S1 # *5 + vpslld \$2,$R2,$S2 + vpslld \$2,$R3,$S3 + vpslld \$2,$R4,$S4 + vpaddd $R1,$S1,$S1 + vpaddd $R2,$S2,$S2 + vpaddd $R3,$S3,$S3 + vpaddd $R4,$S4,$S4 + + vpbroadcastq 32(%rcx),$PADBIT # .L129 + + vpsrlq \$52,$T0,$T2 # splat input + vpsllq \$12,$T4,$T3 + vporq $T3,$T2,$T2 + vpsrlq \$26,$T0,$T1 + vpsrlq \$14,$T4,$T3 + vpsrlq \$40,$T4,$T4 # 4 + vpandq $MASK,$T2,$T2 # 2 + vpandq $MASK,$T0,$T0 # 0 + #vpandq $MASK,$T1,$T1 # 1 + #vpandq $MASK,$T3,$T3 # 3 + #vporq $PADBIT,$T4,$T4 # padbit, yes, always + + vpaddq $H2,$T2,$H2 # accumulate input + sub \$192,$len + jbe .Ltail_avx512 + jmp .Loop_avx512 + +.align 32 +.Loop_avx512: + ################################################################ + # ((inp[0]*r^8+inp[ 8])*r^8+inp[16])*r^8 + # ((inp[1]*r^8+inp[ 9])*r^8+inp[17])*r^7 + # ((inp[2]*r^8+inp[10])*r^8+inp[18])*r^6 + # ((inp[3]*r^8+inp[11])*r^8+inp[19])*r^5 + # ((inp[4]*r^8+inp[12])*r^8+inp[20])*r^4 + # ((inp[5]*r^8+inp[13])*r^8+inp[21])*r^3 + # ((inp[6]*r^8+inp[14])*r^8+inp[22])*r^2 + # ((inp[7]*r^8+inp[15])*r^8+inp[23])*r^1 + # \________/\___________/ + ################################################################ + #vpaddq $H2,$T2,$H2 # accumulate input + + # d4 = h4*r0 + h3*r1 + h2*r2 + h1*r3 + h0*r4 + # d3 = h3*r0 + h2*r1 + h1*r2 + h0*r3 + h4*5*r4 + # d2 = h2*r0 + h1*r1 + h0*r2 + h4*5*r3 + h3*5*r4 + # d1 = h1*r0 + h0*r1 + h4*5*r2 + h3*5*r3 + h2*5*r4 + # d0 = h0*r0 + h4*5*r1 + h3*5*r2 + h2*5*r3 + h1*5*r4 + # + # however, as h2 is "chronologically" first one available pull + # corresponding operations up, so it's + # + # d3 = h2*r1 + h0*r3 + h1*r2 + h3*r0 + h4*5*r4 + # d4 = h2*r2 + h0*r4 + h1*r3 + h3*r1 + h4*r0 + # d0 = h2*5*r3 + h0*r0 + h1*5*r4 + h3*5*r2 + h4*5*r1 + # d1 = h2*5*r4 + h0*r1 + h1*r0 + h3*5*r3 + h4*5*r2 + # d2 = h2*r0 + h0*r2 + h1*r1 + h3*5*r4 + h4*5*r3 + + vpmuludq $H2,$R1,$D3 # d3 = h2*r1 + vpaddq $H0,$T0,$H0 + vpmuludq $H2,$R2,$D4 # d4 = h2*r2 + vpandq $MASK,$T1,$T1 # 1 + vpmuludq $H2,$S3,$D0 # d0 = h2*s3 + vpandq $MASK,$T3,$T3 # 3 + vpmuludq $H2,$S4,$D1 # d1 = h2*s4 + vporq $PADBIT,$T4,$T4 # padbit, yes, always + vpmuludq $H2,$R0,$D2 # d2 = h2*r0 + vpaddq $H1,$T1,$H1 # accumulate input + vpaddq $H3,$T3,$H3 + vpaddq $H4,$T4,$H4 + + vmovdqu64 16*0($inp),$T3 # load input + vmovdqu64 16*4($inp),$T4 + lea 16*8($inp),$inp + vpmuludq $H0,$R3,$M3 + vpmuludq $H0,$R4,$M4 + vpmuludq $H0,$R0,$M0 + vpmuludq $H0,$R1,$M1 + vpaddq $M3,$D3,$D3 # d3 += h0*r3 + vpaddq $M4,$D4,$D4 # d4 += h0*r4 + vpaddq $M0,$D0,$D0 # d0 += h0*r0 + vpaddq $M1,$D1,$D1 # d1 += h0*r1 + + vpmuludq $H1,$R2,$M3 + vpmuludq $H1,$R3,$M4 + vpmuludq $H1,$S4,$M0 + vpmuludq $H0,$R2,$M2 + vpaddq $M3,$D3,$D3 # d3 += h1*r2 + vpaddq $M4,$D4,$D4 # d4 += h1*r3 + vpaddq $M0,$D0,$D0 # d0 += h1*s4 + vpaddq $M2,$D2,$D2 # d2 += h0*r2 + + vpunpcklqdq $T4,$T3,$T0 # transpose input + vpunpckhqdq $T4,$T3,$T4 + + vpmuludq $H3,$R0,$M3 + vpmuludq $H3,$R1,$M4 + vpmuludq $H1,$R0,$M1 + vpmuludq $H1,$R1,$M2 + vpaddq $M3,$D3,$D3 # d3 += h3*r0 + vpaddq $M4,$D4,$D4 # d4 += h3*r1 + vpaddq $M1,$D1,$D1 # d1 += h1*r0 + vpaddq $M2,$D2,$D2 # d2 += h1*r1 + + vpmuludq $H4,$S4,$M3 + vpmuludq $H4,$R0,$M4 + vpmuludq $H3,$S2,$M0 + vpmuludq $H3,$S3,$M1 + vpaddq $M3,$D3,$D3 # d3 += h4*s4 + vpmuludq $H3,$S4,$M2 + vpaddq $M4,$D4,$D4 # d4 += h4*r0 + vpaddq $M0,$D0,$D0 # d0 += h3*s2 + vpaddq $M1,$D1,$D1 # d1 += h3*s3 + vpaddq $M2,$D2,$D2 # d2 += h3*s4 + + vpmuludq $H4,$S1,$M0 + vpmuludq $H4,$S2,$M1 + vpmuludq $H4,$S3,$M2 + vpaddq $M0,$D0,$H0 # h0 = d0 + h4*s1 + vpaddq $M1,$D1,$H1 # h1 = d2 + h4*s2 + vpaddq $M2,$D2,$H2 # h2 = d3 + h4*s3 + + ################################################################ + # lazy reduction (interleaved with input splat) + + vpsrlq \$52,$T0,$T2 # splat input + vpsllq \$12,$T4,$T3 + + vpsrlq \$26,$D3,$H3 + vpandq $MASK,$D3,$D3 + vpaddq $H3,$D4,$H4 # h3 -> h4 + + vporq $T3,$T2,$T2 + + vpsrlq \$26,$H0,$D0 + vpandq $MASK,$H0,$H0 + vpaddq $D0,$H1,$H1 # h0 -> h1 + + vpandq $MASK,$T2,$T2 # 2 + + vpsrlq \$26,$H4,$D4 + vpandq $MASK,$H4,$H4 + + vpsrlq \$26,$H1,$D1 + vpandq $MASK,$H1,$H1 + vpaddq $D1,$H2,$H2 # h1 -> h2 + + vpaddq $D4,$H0,$H0 + vpsllq \$2,$D4,$D4 + vpaddq $D4,$H0,$H0 # h4 -> h0 + + vpaddq $T2,$H2,$H2 # modulo-scheduled + vpsrlq \$26,$T0,$T1 + + vpsrlq \$26,$H2,$D2 + vpandq $MASK,$H2,$H2 + vpaddq $D2,$D3,$H3 # h2 -> h3 + + vpsrlq \$14,$T4,$T3 + + vpsrlq \$26,$H0,$D0 + vpandq $MASK,$H0,$H0 + vpaddq $D0,$H1,$H1 # h0 -> h1 + + vpsrlq \$40,$T4,$T4 # 4 + + vpsrlq \$26,$H3,$D3 + vpandq $MASK,$H3,$H3 + vpaddq $D3,$H4,$H4 # h3 -> h4 + + vpandq $MASK,$T0,$T0 # 0 + #vpandq $MASK,$T1,$T1 # 1 + #vpandq $MASK,$T3,$T3 # 3 + #vporq $PADBIT,$T4,$T4 # padbit, yes, always + + sub \$128,$len + ja .Loop_avx512 + +.Ltail_avx512: + ################################################################ + # while above multiplications were by r^8 in all lanes, in last + # iteration we multiply least significant lane by r^8 and most + # significant one by r, that's why table gets shifted... + + vpsrlq \$32,$R0,$R0 # 0105020603070408 + vpsrlq \$32,$R1,$R1 + vpsrlq \$32,$R2,$R2 + vpsrlq \$32,$S3,$S3 + vpsrlq \$32,$S4,$S4 + vpsrlq \$32,$R3,$R3 + vpsrlq \$32,$R4,$R4 + vpsrlq \$32,$S1,$S1 + vpsrlq \$32,$S2,$S2 + + ################################################################ + # load either next or last 64 byte of input + lea ($inp,$len),$inp + + #vpaddq $H2,$T2,$H2 # accumulate input + vpaddq $H0,$T0,$H0 + + vpmuludq $H2,$R1,$D3 # d3 = h2*r1 + vpmuludq $H2,$R2,$D4 # d4 = h2*r2 + vpmuludq $H2,$S3,$D0 # d0 = h2*s3 + vpandq $MASK,$T1,$T1 # 1 + vpmuludq $H2,$S4,$D1 # d1 = h2*s4 + vpandq $MASK,$T3,$T3 # 3 + vpmuludq $H2,$R0,$D2 # d2 = h2*r0 + vporq $PADBIT,$T4,$T4 # padbit, yes, always + vpaddq $H1,$T1,$H1 # accumulate input + vpaddq $H3,$T3,$H3 + vpaddq $H4,$T4,$H4 + + vmovdqu 16*0($inp),%x#$T0 + vpmuludq $H0,$R3,$M3 + vpmuludq $H0,$R4,$M4 + vpmuludq $H0,$R0,$M0 + vpmuludq $H0,$R1,$M1 + vpaddq $M3,$D3,$D3 # d3 += h0*r3 + vpaddq $M4,$D4,$D4 # d4 += h0*r4 + vpaddq $M0,$D0,$D0 # d0 += h0*r0 + vpaddq $M1,$D1,$D1 # d1 += h0*r1 + + vmovdqu 16*1($inp),%x#$T1 + vpmuludq $H1,$R2,$M3 + vpmuludq $H1,$R3,$M4 + vpmuludq $H1,$S4,$M0 + vpmuludq $H0,$R2,$M2 + vpaddq $M3,$D3,$D3 # d3 += h1*r2 + vpaddq $M4,$D4,$D4 # d4 += h1*r3 + vpaddq $M0,$D0,$D0 # d0 += h1*s4 + vpaddq $M2,$D2,$D2 # d2 += h0*r2 + + vinserti128 \$1,16*2($inp),%y#$T0,%y#$T0 + vpmuludq $H3,$R0,$M3 + vpmuludq $H3,$R1,$M4 + vpmuludq $H1,$R0,$M1 + vpmuludq $H1,$R1,$M2 + vpaddq $M3,$D3,$D3 # d3 += h3*r0 + vpaddq $M4,$D4,$D4 # d4 += h3*r1 + vpaddq $M1,$D1,$D1 # d1 += h1*r0 + vpaddq $M2,$D2,$D2 # d2 += h1*r1 + + vinserti128 \$1,16*3($inp),%y#$T1,%y#$T1 + vpmuludq $H4,$S4,$M3 + vpmuludq $H4,$R0,$M4 + vpmuludq $H3,$S2,$M0 + vpmuludq $H3,$S3,$M1 + vpmuludq $H3,$S4,$M2 + vpaddq $M3,$D3,$H3 # h3 = d3 + h4*s4 + vpaddq $M4,$D4,$D4 # d4 += h4*r0 + vpaddq $M0,$D0,$D0 # d0 += h3*s2 + vpaddq $M1,$D1,$D1 # d1 += h3*s3 + vpaddq $M2,$D2,$D2 # d2 += h3*s4 + + vpmuludq $H4,$S1,$M0 + vpmuludq $H4,$S2,$M1 + vpmuludq $H4,$S3,$M2 + vpaddq $M0,$D0,$H0 # h0 = d0 + h4*s1 + vpaddq $M1,$D1,$H1 # h1 = d2 + h4*s2 + vpaddq $M2,$D2,$H2 # h2 = d3 + h4*s3 + + ################################################################ + # horizontal addition + + mov \$1,%eax + vpermq \$0xb1,$H3,$D3 + vpermq \$0xb1,$D4,$H4 + vpermq \$0xb1,$H0,$D0 + vpermq \$0xb1,$H1,$D1 + vpermq \$0xb1,$H2,$D2 + vpaddq $D3,$H3,$H3 + vpaddq $D4,$H4,$H4 + vpaddq $D0,$H0,$H0 + vpaddq $D1,$H1,$H1 + vpaddq $D2,$H2,$H2 + + kmovw %eax,%k3 + vpermq \$0x2,$H3,$D3 + vpermq \$0x2,$H4,$D4 + vpermq \$0x2,$H0,$D0 + vpermq \$0x2,$H1,$D1 + vpermq \$0x2,$H2,$D2 + vpaddq $D3,$H3,$H3 + vpaddq $D4,$H4,$H4 + vpaddq $D0,$H0,$H0 + vpaddq $D1,$H1,$H1 + vpaddq $D2,$H2,$H2 + + vextracti64x4 \$0x1,$H3,%y#$D3 + vextracti64x4 \$0x1,$H4,%y#$D4 + vextracti64x4 \$0x1,$H0,%y#$D0 + vextracti64x4 \$0x1,$H1,%y#$D1 + vextracti64x4 \$0x1,$H2,%y#$D2 + vpaddq $D3,$H3,${H3}{%k3}{z} # keep single qword in case + vpaddq $D4,$H4,${H4}{%k3}{z} # it's passed to .Ltail_avx2 + vpaddq $D0,$H0,${H0}{%k3}{z} + vpaddq $D1,$H1,${H1}{%k3}{z} + vpaddq $D2,$H2,${H2}{%k3}{z} +___ +map(s/%z/%y/,($T0,$T1,$T2,$T3,$T4, $PADBIT)); +map(s/%z/%y/,($H0,$H1,$H2,$H3,$H4, $D0,$D1,$D2,$D3,$D4, $MASK)); +$code.=<<___; + ################################################################ + # lazy reduction (interleaved with input splat) + + vpsrlq \$26,$H3,$D3 + vpand $MASK,$H3,$H3 + vpsrldq \$6,$T0,$T2 # splat input + vpsrldq \$6,$T1,$T3 + vpunpckhqdq $T1,$T0,$T4 # 4 + vpaddq $D3,$H4,$H4 # h3 -> h4 + + vpsrlq \$26,$H0,$D0 + vpand $MASK,$H0,$H0 + vpunpcklqdq $T3,$T2,$T2 # 2:3 + vpunpcklqdq $T1,$T0,$T0 # 0:1 + vpaddq $D0,$H1,$H1 # h0 -> h1 + + vpsrlq \$26,$H4,$D4 + vpand $MASK,$H4,$H4 + + vpsrlq \$26,$H1,$D1 + vpand $MASK,$H1,$H1 + vpsrlq \$30,$T2,$T3 + vpsrlq \$4,$T2,$T2 + vpaddq $D1,$H2,$H2 # h1 -> h2 + + vpaddq $D4,$H0,$H0 + vpsllq \$2,$D4,$D4 + vpsrlq \$26,$T0,$T1 + vpsrlq \$40,$T4,$T4 # 4 + vpaddq $D4,$H0,$H0 # h4 -> h0 + + vpsrlq \$26,$H2,$D2 + vpand $MASK,$H2,$H2 + vpand $MASK,$T2,$T2 # 2 + vpand $MASK,$T0,$T0 # 0 + vpaddq $D2,$H3,$H3 # h2 -> h3 + + vpsrlq \$26,$H0,$D0 + vpand $MASK,$H0,$H0 + vpaddq $H2,$T2,$H2 # accumulate input for .Ltail_avx2 + vpand $MASK,$T1,$T1 # 1 + vpaddq $D0,$H1,$H1 # h0 -> h1 + + vpsrlq \$26,$H3,$D3 + vpand $MASK,$H3,$H3 + vpand $MASK,$T3,$T3 # 3 + vpor 32(%rcx),$T4,$T4 # padbit, yes, always + vpaddq $D3,$H4,$H4 # h3 -> h4 + + lea 0x90(%rsp),%rax # size optimization for .Ltail_avx2 + add \$64,$len + jnz .Ltail_avx2 + + vpsubq $T2,$H2,$H2 # undo input accumulation + vmovd %x#$H0,`4*0-48-64`($ctx)# save partially reduced + vmovd %x#$H1,`4*1-48-64`($ctx) + vmovd %x#$H2,`4*2-48-64`($ctx) + vmovd %x#$H3,`4*3-48-64`($ctx) + vmovd %x#$H4,`4*4-48-64`($ctx) + vzeroall +___ +$code.=<<___ if ($win64); + movdqa 0x50(%r11),%xmm6 + movdqa 0x60(%r11),%xmm7 + movdqa 0x70(%r11),%xmm8 + movdqa 0x80(%r11),%xmm9 + movdqa 0x90(%r11),%xmm10 + movdqa 0xa0(%r11),%xmm11 + movdqa 0xb0(%r11),%xmm12 + movdqa 0xc0(%r11),%xmm13 + movdqa 0xd0(%r11),%xmm14 + movdqa 0xe0(%r11),%xmm15 + lea 0xf8(%r11),%rsp +.Ldo_avx512_epilogue: +___ +$code.=<<___ if (!$win64); + lea 8(%r11),%rsp +.cfi_def_cfa %rsp,8 +___ +$code.=<<___; + ret +.cfi_endproc +.size poly1305_blocks_avx512,.-poly1305_blocks_avx512 +___ +if ($avx>3) { +######################################################################## +# VPMADD52 version using 2^44 radix. +# +# One can argue that base 2^52 would be more natural. Well, even though +# some operations would be more natural, one has to recognize couple of +# things. Base 2^52 doesn't provide advantage over base 2^44 if you look +# at amount of multiply-n-accumulate operations. Secondly, it makes it +# impossible to pre-compute multiples of 5 [referred to as s[]/sN in +# reference implementations], which means that more such operations +# would have to be performed in inner loop, which in turn makes critical +# path longer. In other words, even though base 2^44 reduction might +# look less elegant, overall critical path is actually shorter... + +######################################################################## +# Layout of opaque area is following. +# +# unsigned __int64 h[3]; # current hash value base 2^44 +# unsigned __int64 s[2]; # key value*20 base 2^44 +# unsigned __int64 r[3]; # key value base 2^44 +# struct { unsigned __int64 r^1, r^3, r^2, r^4; } R[4]; +# # r^n positions reflect +# # placement in register, not +# # memory, R[3] is R[1]*20 + +$code.=<<___; +.type poly1305_init_base2_44,\@function,3 +.align 32 +poly1305_init_base2_44: + xor %rax,%rax + mov %rax,0($ctx) # initialize hash value + mov %rax,8($ctx) + mov %rax,16($ctx) + +.Linit_base2_44: + lea poly1305_blocks_vpmadd52(%rip),%r10 + lea poly1305_emit_base2_44(%rip),%r11 + + mov \$0x0ffffffc0fffffff,%rax + mov \$0x0ffffffc0ffffffc,%rcx + and 0($inp),%rax + mov \$0x00000fffffffffff,%r8 + and 8($inp),%rcx + mov \$0x00000fffffffffff,%r9 + and %rax,%r8 + shrd \$44,%rcx,%rax + mov %r8,40($ctx) # r0 + and %r9,%rax + shr \$24,%rcx + mov %rax,48($ctx) # r1 + lea (%rax,%rax,4),%rax # *5 + mov %rcx,56($ctx) # r2 + shl \$2,%rax # magic <<2 + lea (%rcx,%rcx,4),%rcx # *5 + shl \$2,%rcx # magic <<2 + mov %rax,24($ctx) # s1 + mov %rcx,32($ctx) # s2 + movq \$-1,64($ctx) # write impossible value +___ +$code.=<<___ if ($flavour !~ /elf32/); + mov %r10,0(%rdx) + mov %r11,8(%rdx) +___ +$code.=<<___ if ($flavour =~ /elf32/); + mov %r10d,0(%rdx) + mov %r11d,4(%rdx) +___ +$code.=<<___; + mov \$1,%eax + ret +.size poly1305_init_base2_44,.-poly1305_init_base2_44 +___ +{ +my ($H0,$H1,$H2,$r2r1r0,$r1r0s2,$r0s2s1,$Dlo,$Dhi) = map("%ymm$_",(0..5,16,17)); +my ($T0,$inp_permd,$inp_shift,$PAD) = map("%ymm$_",(18..21)); +my ($reduc_mask,$reduc_rght,$reduc_left) = map("%ymm$_",(22..25)); + +$code.=<<___; +.type poly1305_blocks_vpmadd52,\@function,4 +.align 32 +poly1305_blocks_vpmadd52: + shr \$4,$len + jz .Lno_data_vpmadd52 # too short + + shl \$40,$padbit + mov 64($ctx),%r8 # peek on power of the key + + # if powers of the key are not calculated yet, process up to 3 + # blocks with this single-block subroutine, otherwise ensure that + # length is divisible by 2 blocks and pass the rest down to next + # subroutine... + + mov \$3,%rax + mov \$1,%r10 + cmp \$4,$len # is input long + cmovae %r10,%rax + test %r8,%r8 # is power value impossible? + cmovns %r10,%rax + + and $len,%rax # is input of favourable length? + jz .Lblocks_vpmadd52_4x + + sub %rax,$len + mov \$7,%r10d + mov \$1,%r11d + kmovw %r10d,%k7 + lea .L2_44_inp_permd(%rip),%r10 + kmovw %r11d,%k1 + + vmovq $padbit,%x#$PAD + vmovdqa64 0(%r10),$inp_permd # .L2_44_inp_permd + vmovdqa64 32(%r10),$inp_shift # .L2_44_inp_shift + vpermq \$0xcf,$PAD,$PAD + vmovdqa64 64(%r10),$reduc_mask # .L2_44_mask + + vmovdqu64 0($ctx),${Dlo}{%k7}{z} # load hash value + vmovdqu64 40($ctx),${r2r1r0}{%k7}{z} # load keys + vmovdqu64 32($ctx),${r1r0s2}{%k7}{z} + vmovdqu64 24($ctx),${r0s2s1}{%k7}{z} + + vmovdqa64 96(%r10),$reduc_rght # .L2_44_shift_rgt + vmovdqa64 128(%r10),$reduc_left # .L2_44_shift_lft + + jmp .Loop_vpmadd52 + +.align 32 +.Loop_vpmadd52: + vmovdqu32 0($inp),%x#$T0 # load input as ----3210 + lea 16($inp),$inp + + vpermd $T0,$inp_permd,$T0 # ----3210 -> --322110 + vpsrlvq $inp_shift,$T0,$T0 + vpandq $reduc_mask,$T0,$T0 + vporq $PAD,$T0,$T0 + + vpaddq $T0,$Dlo,$Dlo # accumulate input + + vpermq \$0,$Dlo,${H0}{%k7}{z} # smash hash value + vpermq \$0b01010101,$Dlo,${H1}{%k7}{z} + vpermq \$0b10101010,$Dlo,${H2}{%k7}{z} + + vpxord $Dlo,$Dlo,$Dlo + vpxord $Dhi,$Dhi,$Dhi + + vpmadd52luq $r2r1r0,$H0,$Dlo + vpmadd52huq $r2r1r0,$H0,$Dhi + + vpmadd52luq $r1r0s2,$H1,$Dlo + vpmadd52huq $r1r0s2,$H1,$Dhi + + vpmadd52luq $r0s2s1,$H2,$Dlo + vpmadd52huq $r0s2s1,$H2,$Dhi + + vpsrlvq $reduc_rght,$Dlo,$T0 # 0 in topmost qword + vpsllvq $reduc_left,$Dhi,$Dhi # 0 in topmost qword + vpandq $reduc_mask,$Dlo,$Dlo + + vpaddq $T0,$Dhi,$Dhi + + vpermq \$0b10010011,$Dhi,$Dhi # 0 in lowest qword + + vpaddq $Dhi,$Dlo,$Dlo # note topmost qword :-) + + vpsrlvq $reduc_rght,$Dlo,$T0 # 0 in topmost word + vpandq $reduc_mask,$Dlo,$Dlo + + vpermq \$0b10010011,$T0,$T0 + + vpaddq $T0,$Dlo,$Dlo + + vpermq \$0b10010011,$Dlo,${T0}{%k1}{z} + + vpaddq $T0,$Dlo,$Dlo + vpsllq \$2,$T0,$T0 + + vpaddq $T0,$Dlo,$Dlo + + dec %rax # len-=16 + jnz .Loop_vpmadd52 + + vmovdqu64 $Dlo,0($ctx){%k7} # store hash value + + test $len,$len + jnz .Lblocks_vpmadd52_4x + +.Lno_data_vpmadd52: + ret +.size poly1305_blocks_vpmadd52,.-poly1305_blocks_vpmadd52 +___ } +{ +######################################################################## +# As implied by its name 4x subroutine processes 4 blocks in parallel +# (but handles even 4*n+2 blocks lengths). It takes up to 4th key power +# and is handled in 256-bit %ymm registers. + +my ($H0,$H1,$H2,$R0,$R1,$R2,$S1,$S2) = map("%ymm$_",(0..5,16,17)); +my ($D0lo,$D0hi,$D1lo,$D1hi,$D2lo,$D2hi) = map("%ymm$_",(18..23)); +my ($T0,$T1,$T2,$T3,$mask44,$mask42,$tmp,$PAD) = map("%ymm$_",(24..31)); + +$code.=<<___; +.type poly1305_blocks_vpmadd52_4x,\@function,4 +.align 32 +poly1305_blocks_vpmadd52_4x: + shr \$4,$len + jz .Lno_data_vpmadd52_4x # too short + + shl \$40,$padbit + mov 64($ctx),%r8 # peek on power of the key + +.Lblocks_vpmadd52_4x: + vpbroadcastq $padbit,$PAD + + vmovdqa64 .Lx_mask44(%rip),$mask44 + mov \$5,%eax + vmovdqa64 .Lx_mask42(%rip),$mask42 + kmovw %eax,%k1 # used in 2x path + + test %r8,%r8 # is power value impossible? + js .Linit_vpmadd52 # if it is, then init R[4] + + vmovq 0($ctx),%x#$H0 # load current hash value + vmovq 8($ctx),%x#$H1 + vmovq 16($ctx),%x#$H2 + + test \$3,$len # is length 4*n+2? + jnz .Lblocks_vpmadd52_2x_do + +.Lblocks_vpmadd52_4x_do: + vpbroadcastq 64($ctx),$R0 # load 4th power of the key + vpbroadcastq 96($ctx),$R1 + vpbroadcastq 128($ctx),$R2 + vpbroadcastq 160($ctx),$S1 + +.Lblocks_vpmadd52_4x_key_loaded: + vpsllq \$2,$R2,$S2 # S2 = R2*5*4 + vpaddq $R2,$S2,$S2 + vpsllq \$2,$S2,$S2 + + test \$7,$len # is len 8*n? + jz .Lblocks_vpmadd52_8x + + vmovdqu64 16*0($inp),$T2 # load data + vmovdqu64 16*2($inp),$T3 + lea 16*4($inp),$inp + + vpunpcklqdq $T3,$T2,$T1 # transpose data + vpunpckhqdq $T3,$T2,$T3 + + # at this point 64-bit lanes are ordered as 3-1-2-0 + + vpsrlq \$24,$T3,$T2 # splat the data + vporq $PAD,$T2,$T2 + vpaddq $T2,$H2,$H2 # accumulate input + vpandq $mask44,$T1,$T0 + vpsrlq \$44,$T1,$T1 + vpsllq \$20,$T3,$T3 + vporq $T3,$T1,$T1 + vpandq $mask44,$T1,$T1 + + sub \$4,$len + jz .Ltail_vpmadd52_4x + jmp .Loop_vpmadd52_4x + ud2 + +.align 32 +.Linit_vpmadd52: + vmovq 24($ctx),%x#$S1 # load key + vmovq 56($ctx),%x#$H2 + vmovq 32($ctx),%x#$S2 + vmovq 40($ctx),%x#$R0 + vmovq 48($ctx),%x#$R1 + + vmovdqa $R0,$H0 + vmovdqa $R1,$H1 + vmovdqa $H2,$R2 + + mov \$2,%eax + +.Lmul_init_vpmadd52: + vpxorq $D0lo,$D0lo,$D0lo + vpmadd52luq $H2,$S1,$D0lo + vpxorq $D0hi,$D0hi,$D0hi + vpmadd52huq $H2,$S1,$D0hi + vpxorq $D1lo,$D1lo,$D1lo + vpmadd52luq $H2,$S2,$D1lo + vpxorq $D1hi,$D1hi,$D1hi + vpmadd52huq $H2,$S2,$D1hi + vpxorq $D2lo,$D2lo,$D2lo + vpmadd52luq $H2,$R0,$D2lo + vpxorq $D2hi,$D2hi,$D2hi + vpmadd52huq $H2,$R0,$D2hi + + vpmadd52luq $H0,$R0,$D0lo + vpmadd52huq $H0,$R0,$D0hi + vpmadd52luq $H0,$R1,$D1lo + vpmadd52huq $H0,$R1,$D1hi + vpmadd52luq $H0,$R2,$D2lo + vpmadd52huq $H0,$R2,$D2hi + + vpmadd52luq $H1,$S2,$D0lo + vpmadd52huq $H1,$S2,$D0hi + vpmadd52luq $H1,$R0,$D1lo + vpmadd52huq $H1,$R0,$D1hi + vpmadd52luq $H1,$R1,$D2lo + vpmadd52huq $H1,$R1,$D2hi + + ################################################################ + # partial reduction + vpsrlq \$44,$D0lo,$tmp + vpsllq \$8,$D0hi,$D0hi + vpandq $mask44,$D0lo,$H0 + vpaddq $tmp,$D0hi,$D0hi + + vpaddq $D0hi,$D1lo,$D1lo + + vpsrlq \$44,$D1lo,$tmp + vpsllq \$8,$D1hi,$D1hi + vpandq $mask44,$D1lo,$H1 + vpaddq $tmp,$D1hi,$D1hi + + vpaddq $D1hi,$D2lo,$D2lo + + vpsrlq \$42,$D2lo,$tmp + vpsllq \$10,$D2hi,$D2hi + vpandq $mask42,$D2lo,$H2 + vpaddq $tmp,$D2hi,$D2hi + + vpaddq $D2hi,$H0,$H0 + vpsllq \$2,$D2hi,$D2hi + + vpaddq $D2hi,$H0,$H0 + + vpsrlq \$44,$H0,$tmp # additional step + vpandq $mask44,$H0,$H0 + + vpaddq $tmp,$H1,$H1 + + dec %eax + jz .Ldone_init_vpmadd52 + + vpunpcklqdq $R1,$H1,$R1 # 1,2 + vpbroadcastq %x#$H1,%x#$H1 # 2,2 + vpunpcklqdq $R2,$H2,$R2 + vpbroadcastq %x#$H2,%x#$H2 + vpunpcklqdq $R0,$H0,$R0 + vpbroadcastq %x#$H0,%x#$H0 + + vpsllq \$2,$R1,$S1 # S1 = R1*5*4 + vpsllq \$2,$R2,$S2 # S2 = R2*5*4 + vpaddq $R1,$S1,$S1 + vpaddq $R2,$S2,$S2 + vpsllq \$2,$S1,$S1 + vpsllq \$2,$S2,$S2 + + jmp .Lmul_init_vpmadd52 + ud2 + +.align 32 +.Ldone_init_vpmadd52: + vinserti128 \$1,%x#$R1,$H1,$R1 # 1,2,3,4 + vinserti128 \$1,%x#$R2,$H2,$R2 + vinserti128 \$1,%x#$R0,$H0,$R0 + + vpermq \$0b11011000,$R1,$R1 # 1,3,2,4 + vpermq \$0b11011000,$R2,$R2 + vpermq \$0b11011000,$R0,$R0 + + vpsllq \$2,$R1,$S1 # S1 = R1*5*4 + vpaddq $R1,$S1,$S1 + vpsllq \$2,$S1,$S1 + + vmovq 0($ctx),%x#$H0 # load current hash value + vmovq 8($ctx),%x#$H1 + vmovq 16($ctx),%x#$H2 + + test \$3,$len # is length 4*n+2? + jnz .Ldone_init_vpmadd52_2x + + vmovdqu64 $R0,64($ctx) # save key powers + vpbroadcastq %x#$R0,$R0 # broadcast 4th power + vmovdqu64 $R1,96($ctx) + vpbroadcastq %x#$R1,$R1 + vmovdqu64 $R2,128($ctx) + vpbroadcastq %x#$R2,$R2 + vmovdqu64 $S1,160($ctx) + vpbroadcastq %x#$S1,$S1 + + jmp .Lblocks_vpmadd52_4x_key_loaded + ud2 + +.align 32 +.Ldone_init_vpmadd52_2x: + vmovdqu64 $R0,64($ctx) # save key powers + vpsrldq \$8,$R0,$R0 # 0-1-0-2 + vmovdqu64 $R1,96($ctx) + vpsrldq \$8,$R1,$R1 + vmovdqu64 $R2,128($ctx) + vpsrldq \$8,$R2,$R2 + vmovdqu64 $S1,160($ctx) + vpsrldq \$8,$S1,$S1 + jmp .Lblocks_vpmadd52_2x_key_loaded + ud2 + +.align 32 +.Lblocks_vpmadd52_2x_do: + vmovdqu64 128+8($ctx),${R2}{%k1}{z}# load 2nd and 1st key powers + vmovdqu64 160+8($ctx),${S1}{%k1}{z} + vmovdqu64 64+8($ctx),${R0}{%k1}{z} + vmovdqu64 96+8($ctx),${R1}{%k1}{z} + +.Lblocks_vpmadd52_2x_key_loaded: + vmovdqu64 16*0($inp),$T2 # load data + vpxorq $T3,$T3,$T3 + lea 16*2($inp),$inp + + vpunpcklqdq $T3,$T2,$T1 # transpose data + vpunpckhqdq $T3,$T2,$T3 + + # at this point 64-bit lanes are ordered as x-1-x-0 + + vpsrlq \$24,$T3,$T2 # splat the data + vporq $PAD,$T2,$T2 + vpaddq $T2,$H2,$H2 # accumulate input + vpandq $mask44,$T1,$T0 + vpsrlq \$44,$T1,$T1 + vpsllq \$20,$T3,$T3 + vporq $T3,$T1,$T1 + vpandq $mask44,$T1,$T1 + + jmp .Ltail_vpmadd52_2x + ud2 + +.align 32 +.Loop_vpmadd52_4x: + #vpaddq $T2,$H2,$H2 # accumulate input + vpaddq $T0,$H0,$H0 + vpaddq $T1,$H1,$H1 + + vpxorq $D0lo,$D0lo,$D0lo + vpmadd52luq $H2,$S1,$D0lo + vpxorq $D0hi,$D0hi,$D0hi + vpmadd52huq $H2,$S1,$D0hi + vpxorq $D1lo,$D1lo,$D1lo + vpmadd52luq $H2,$S2,$D1lo + vpxorq $D1hi,$D1hi,$D1hi + vpmadd52huq $H2,$S2,$D1hi + vpxorq $D2lo,$D2lo,$D2lo + vpmadd52luq $H2,$R0,$D2lo + vpxorq $D2hi,$D2hi,$D2hi + vpmadd52huq $H2,$R0,$D2hi + + vmovdqu64 16*0($inp),$T2 # load data + vmovdqu64 16*2($inp),$T3 + lea 16*4($inp),$inp + vpmadd52luq $H0,$R0,$D0lo + vpmadd52huq $H0,$R0,$D0hi + vpmadd52luq $H0,$R1,$D1lo + vpmadd52huq $H0,$R1,$D1hi + vpmadd52luq $H0,$R2,$D2lo + vpmadd52huq $H0,$R2,$D2hi + + vpunpcklqdq $T3,$T2,$T1 # transpose data + vpunpckhqdq $T3,$T2,$T3 + vpmadd52luq $H1,$S2,$D0lo + vpmadd52huq $H1,$S2,$D0hi + vpmadd52luq $H1,$R0,$D1lo + vpmadd52huq $H1,$R0,$D1hi + vpmadd52luq $H1,$R1,$D2lo + vpmadd52huq $H1,$R1,$D2hi + + ################################################################ + # partial reduction (interleaved with data splat) + vpsrlq \$44,$D0lo,$tmp + vpsllq \$8,$D0hi,$D0hi + vpandq $mask44,$D0lo,$H0 + vpaddq $tmp,$D0hi,$D0hi + + vpsrlq \$24,$T3,$T2 + vporq $PAD,$T2,$T2 + vpaddq $D0hi,$D1lo,$D1lo + + vpsrlq \$44,$D1lo,$tmp + vpsllq \$8,$D1hi,$D1hi + vpandq $mask44,$D1lo,$H1 + vpaddq $tmp,$D1hi,$D1hi + + vpandq $mask44,$T1,$T0 + vpsrlq \$44,$T1,$T1 + vpsllq \$20,$T3,$T3 + vpaddq $D1hi,$D2lo,$D2lo + + vpsrlq \$42,$D2lo,$tmp + vpsllq \$10,$D2hi,$D2hi + vpandq $mask42,$D2lo,$H2 + vpaddq $tmp,$D2hi,$D2hi + + vpaddq $T2,$H2,$H2 # accumulate input + vpaddq $D2hi,$H0,$H0 + vpsllq \$2,$D2hi,$D2hi + + vpaddq $D2hi,$H0,$H0 + vporq $T3,$T1,$T1 + vpandq $mask44,$T1,$T1 + + vpsrlq \$44,$H0,$tmp # additional step + vpandq $mask44,$H0,$H0 + + vpaddq $tmp,$H1,$H1 + + sub \$4,$len # len-=64 + jnz .Loop_vpmadd52_4x + +.Ltail_vpmadd52_4x: + vmovdqu64 128($ctx),$R2 # load all key powers + vmovdqu64 160($ctx),$S1 + vmovdqu64 64($ctx),$R0 + vmovdqu64 96($ctx),$R1 + +.Ltail_vpmadd52_2x: + vpsllq \$2,$R2,$S2 # S2 = R2*5*4 + vpaddq $R2,$S2,$S2 + vpsllq \$2,$S2,$S2 + + #vpaddq $T2,$H2,$H2 # accumulate input + vpaddq $T0,$H0,$H0 + vpaddq $T1,$H1,$H1 + + vpxorq $D0lo,$D0lo,$D0lo + vpmadd52luq $H2,$S1,$D0lo + vpxorq $D0hi,$D0hi,$D0hi + vpmadd52huq $H2,$S1,$D0hi + vpxorq $D1lo,$D1lo,$D1lo + vpmadd52luq $H2,$S2,$D1lo + vpxorq $D1hi,$D1hi,$D1hi + vpmadd52huq $H2,$S2,$D1hi + vpxorq $D2lo,$D2lo,$D2lo + vpmadd52luq $H2,$R0,$D2lo + vpxorq $D2hi,$D2hi,$D2hi + vpmadd52huq $H2,$R0,$D2hi + + vpmadd52luq $H0,$R0,$D0lo + vpmadd52huq $H0,$R0,$D0hi + vpmadd52luq $H0,$R1,$D1lo + vpmadd52huq $H0,$R1,$D1hi + vpmadd52luq $H0,$R2,$D2lo + vpmadd52huq $H0,$R2,$D2hi + + vpmadd52luq $H1,$S2,$D0lo + vpmadd52huq $H1,$S2,$D0hi + vpmadd52luq $H1,$R0,$D1lo + vpmadd52huq $H1,$R0,$D1hi + vpmadd52luq $H1,$R1,$D2lo + vpmadd52huq $H1,$R1,$D2hi + + ################################################################ + # horizontal addition + + mov \$1,%eax + kmovw %eax,%k1 + vpsrldq \$8,$D0lo,$T0 + vpsrldq \$8,$D0hi,$H0 + vpsrldq \$8,$D1lo,$T1 + vpsrldq \$8,$D1hi,$H1 + vpaddq $T0,$D0lo,$D0lo + vpaddq $H0,$D0hi,$D0hi + vpsrldq \$8,$D2lo,$T2 + vpsrldq \$8,$D2hi,$H2 + vpaddq $T1,$D1lo,$D1lo + vpaddq $H1,$D1hi,$D1hi + vpermq \$0x2,$D0lo,$T0 + vpermq \$0x2,$D0hi,$H0 + vpaddq $T2,$D2lo,$D2lo + vpaddq $H2,$D2hi,$D2hi + + vpermq \$0x2,$D1lo,$T1 + vpermq \$0x2,$D1hi,$H1 + vpaddq $T0,$D0lo,${D0lo}{%k1}{z} + vpaddq $H0,$D0hi,${D0hi}{%k1}{z} + vpermq \$0x2,$D2lo,$T2 + vpermq \$0x2,$D2hi,$H2 + vpaddq $T1,$D1lo,${D1lo}{%k1}{z} + vpaddq $H1,$D1hi,${D1hi}{%k1}{z} + vpaddq $T2,$D2lo,${D2lo}{%k1}{z} + vpaddq $H2,$D2hi,${D2hi}{%k1}{z} + + ################################################################ + # partial reduction + vpsrlq \$44,$D0lo,$tmp + vpsllq \$8,$D0hi,$D0hi + vpandq $mask44,$D0lo,$H0 + vpaddq $tmp,$D0hi,$D0hi + + vpaddq $D0hi,$D1lo,$D1lo + + vpsrlq \$44,$D1lo,$tmp + vpsllq \$8,$D1hi,$D1hi + vpandq $mask44,$D1lo,$H1 + vpaddq $tmp,$D1hi,$D1hi + + vpaddq $D1hi,$D2lo,$D2lo + + vpsrlq \$42,$D2lo,$tmp + vpsllq \$10,$D2hi,$D2hi + vpandq $mask42,$D2lo,$H2 + vpaddq $tmp,$D2hi,$D2hi + + vpaddq $D2hi,$H0,$H0 + vpsllq \$2,$D2hi,$D2hi + + vpaddq $D2hi,$H0,$H0 + + vpsrlq \$44,$H0,$tmp # additional step + vpandq $mask44,$H0,$H0 + + vpaddq $tmp,$H1,$H1 + # at this point $len is + # either 4*n+2 or 0... + sub \$2,$len # len-=32 + ja .Lblocks_vpmadd52_4x_do + + vmovq %x#$H0,0($ctx) + vmovq %x#$H1,8($ctx) + vmovq %x#$H2,16($ctx) + vzeroall + +.Lno_data_vpmadd52_4x: + ret +.size poly1305_blocks_vpmadd52_4x,.-poly1305_blocks_vpmadd52_4x +___ +} +{ +######################################################################## +# As implied by its name 8x subroutine processes 8 blocks in parallel... +# This is intermediate version, as it's used only in cases when input +# length is either 8*n, 8*n+1 or 8*n+2... + +my ($H0,$H1,$H2,$R0,$R1,$R2,$S1,$S2) = map("%ymm$_",(0..5,16,17)); +my ($D0lo,$D0hi,$D1lo,$D1hi,$D2lo,$D2hi) = map("%ymm$_",(18..23)); +my ($T0,$T1,$T2,$T3,$mask44,$mask42,$tmp,$PAD) = map("%ymm$_",(24..31)); +my ($RR0,$RR1,$RR2,$SS1,$SS2) = map("%ymm$_",(6..10)); + +$code.=<<___; +.type poly1305_blocks_vpmadd52_8x,\@function,4 +.align 32 +poly1305_blocks_vpmadd52_8x: + shr \$4,$len + jz .Lno_data_vpmadd52_8x # too short + + shl \$40,$padbit + mov 64($ctx),%r8 # peek on power of the key + + vmovdqa64 .Lx_mask44(%rip),$mask44 + vmovdqa64 .Lx_mask42(%rip),$mask42 + + test %r8,%r8 # is power value impossible? + js .Linit_vpmadd52 # if it is, then init R[4] + + vmovq 0($ctx),%x#$H0 # load current hash value + vmovq 8($ctx),%x#$H1 + vmovq 16($ctx),%x#$H2 + +.Lblocks_vpmadd52_8x: + ################################################################ + # fist we calculate more key powers + + vmovdqu64 128($ctx),$R2 # load 1-3-2-4 powers + vmovdqu64 160($ctx),$S1 + vmovdqu64 64($ctx),$R0 + vmovdqu64 96($ctx),$R1 + + vpsllq \$2,$R2,$S2 # S2 = R2*5*4 + vpaddq $R2,$S2,$S2 + vpsllq \$2,$S2,$S2 + + vpbroadcastq %x#$R2,$RR2 # broadcast 4th power + vpbroadcastq %x#$R0,$RR0 + vpbroadcastq %x#$R1,$RR1 + + vpxorq $D0lo,$D0lo,$D0lo + vpmadd52luq $RR2,$S1,$D0lo + vpxorq $D0hi,$D0hi,$D0hi + vpmadd52huq $RR2,$S1,$D0hi + vpxorq $D1lo,$D1lo,$D1lo + vpmadd52luq $RR2,$S2,$D1lo + vpxorq $D1hi,$D1hi,$D1hi + vpmadd52huq $RR2,$S2,$D1hi + vpxorq $D2lo,$D2lo,$D2lo + vpmadd52luq $RR2,$R0,$D2lo + vpxorq $D2hi,$D2hi,$D2hi + vpmadd52huq $RR2,$R0,$D2hi + + vpmadd52luq $RR0,$R0,$D0lo + vpmadd52huq $RR0,$R0,$D0hi + vpmadd52luq $RR0,$R1,$D1lo + vpmadd52huq $RR0,$R1,$D1hi + vpmadd52luq $RR0,$R2,$D2lo + vpmadd52huq $RR0,$R2,$D2hi + + vpmadd52luq $RR1,$S2,$D0lo + vpmadd52huq $RR1,$S2,$D0hi + vpmadd52luq $RR1,$R0,$D1lo + vpmadd52huq $RR1,$R0,$D1hi + vpmadd52luq $RR1,$R1,$D2lo + vpmadd52huq $RR1,$R1,$D2hi + + ################################################################ + # partial reduction + vpsrlq \$44,$D0lo,$tmp + vpsllq \$8,$D0hi,$D0hi + vpandq $mask44,$D0lo,$RR0 + vpaddq $tmp,$D0hi,$D0hi + + vpaddq $D0hi,$D1lo,$D1lo + + vpsrlq \$44,$D1lo,$tmp + vpsllq \$8,$D1hi,$D1hi + vpandq $mask44,$D1lo,$RR1 + vpaddq $tmp,$D1hi,$D1hi + + vpaddq $D1hi,$D2lo,$D2lo + + vpsrlq \$42,$D2lo,$tmp + vpsllq \$10,$D2hi,$D2hi + vpandq $mask42,$D2lo,$RR2 + vpaddq $tmp,$D2hi,$D2hi + + vpaddq $D2hi,$RR0,$RR0 + vpsllq \$2,$D2hi,$D2hi + + vpaddq $D2hi,$RR0,$RR0 + + vpsrlq \$44,$RR0,$tmp # additional step + vpandq $mask44,$RR0,$RR0 + + vpaddq $tmp,$RR1,$RR1 + + ################################################################ + # At this point Rx holds 1324 powers, RRx - 5768, and the goal + # is 15263748, which reflects how data is loaded... + + vpunpcklqdq $R2,$RR2,$T2 # 3748 + vpunpckhqdq $R2,$RR2,$R2 # 1526 + vpunpcklqdq $R0,$RR0,$T0 + vpunpckhqdq $R0,$RR0,$R0 + vpunpcklqdq $R1,$RR1,$T1 + vpunpckhqdq $R1,$RR1,$R1 +___ +######## switch to %zmm +map(s/%y/%z/, $H0,$H1,$H2,$R0,$R1,$R2,$S1,$S2); +map(s/%y/%z/, $D0lo,$D0hi,$D1lo,$D1hi,$D2lo,$D2hi); +map(s/%y/%z/, $T0,$T1,$T2,$T3,$mask44,$mask42,$tmp,$PAD); +map(s/%y/%z/, $RR0,$RR1,$RR2,$SS1,$SS2); + +$code.=<<___; + vshufi64x2 \$0x44,$R2,$T2,$RR2 # 15263748 + vshufi64x2 \$0x44,$R0,$T0,$RR0 + vshufi64x2 \$0x44,$R1,$T1,$RR1 + + vmovdqu64 16*0($inp),$T2 # load data + vmovdqu64 16*4($inp),$T3 + lea 16*8($inp),$inp + + vpsllq \$2,$RR2,$SS2 # S2 = R2*5*4 + vpsllq \$2,$RR1,$SS1 # S1 = R1*5*4 + vpaddq $RR2,$SS2,$SS2 + vpaddq $RR1,$SS1,$SS1 + vpsllq \$2,$SS2,$SS2 + vpsllq \$2,$SS1,$SS1 + + vpbroadcastq $padbit,$PAD + vpbroadcastq %x#$mask44,$mask44 + vpbroadcastq %x#$mask42,$mask42 + + vpbroadcastq %x#$SS1,$S1 # broadcast 8th power + vpbroadcastq %x#$SS2,$S2 + vpbroadcastq %x#$RR0,$R0 + vpbroadcastq %x#$RR1,$R1 + vpbroadcastq %x#$RR2,$R2 + + vpunpcklqdq $T3,$T2,$T1 # transpose data + vpunpckhqdq $T3,$T2,$T3 + + # at this point 64-bit lanes are ordered as 73625140 + + vpsrlq \$24,$T3,$T2 # splat the data + vporq $PAD,$T2,$T2 + vpaddq $T2,$H2,$H2 # accumulate input + vpandq $mask44,$T1,$T0 + vpsrlq \$44,$T1,$T1 + vpsllq \$20,$T3,$T3 + vporq $T3,$T1,$T1 + vpandq $mask44,$T1,$T1 + + sub \$8,$len + jz .Ltail_vpmadd52_8x + jmp .Loop_vpmadd52_8x + +.align 32 +.Loop_vpmadd52_8x: + #vpaddq $T2,$H2,$H2 # accumulate input + vpaddq $T0,$H0,$H0 + vpaddq $T1,$H1,$H1 + + vpxorq $D0lo,$D0lo,$D0lo + vpmadd52luq $H2,$S1,$D0lo + vpxorq $D0hi,$D0hi,$D0hi + vpmadd52huq $H2,$S1,$D0hi + vpxorq $D1lo,$D1lo,$D1lo + vpmadd52luq $H2,$S2,$D1lo + vpxorq $D1hi,$D1hi,$D1hi + vpmadd52huq $H2,$S2,$D1hi + vpxorq $D2lo,$D2lo,$D2lo + vpmadd52luq $H2,$R0,$D2lo + vpxorq $D2hi,$D2hi,$D2hi + vpmadd52huq $H2,$R0,$D2hi + + vmovdqu64 16*0($inp),$T2 # load data + vmovdqu64 16*4($inp),$T3 + lea 16*8($inp),$inp + vpmadd52luq $H0,$R0,$D0lo + vpmadd52huq $H0,$R0,$D0hi + vpmadd52luq $H0,$R1,$D1lo + vpmadd52huq $H0,$R1,$D1hi + vpmadd52luq $H0,$R2,$D2lo + vpmadd52huq $H0,$R2,$D2hi + + vpunpcklqdq $T3,$T2,$T1 # transpose data + vpunpckhqdq $T3,$T2,$T3 + vpmadd52luq $H1,$S2,$D0lo + vpmadd52huq $H1,$S2,$D0hi + vpmadd52luq $H1,$R0,$D1lo + vpmadd52huq $H1,$R0,$D1hi + vpmadd52luq $H1,$R1,$D2lo + vpmadd52huq $H1,$R1,$D2hi + + ################################################################ + # partial reduction (interleaved with data splat) + vpsrlq \$44,$D0lo,$tmp + vpsllq \$8,$D0hi,$D0hi + vpandq $mask44,$D0lo,$H0 + vpaddq $tmp,$D0hi,$D0hi + + vpsrlq \$24,$T3,$T2 + vporq $PAD,$T2,$T2 + vpaddq $D0hi,$D1lo,$D1lo + + vpsrlq \$44,$D1lo,$tmp + vpsllq \$8,$D1hi,$D1hi + vpandq $mask44,$D1lo,$H1 + vpaddq $tmp,$D1hi,$D1hi + + vpandq $mask44,$T1,$T0 + vpsrlq \$44,$T1,$T1 + vpsllq \$20,$T3,$T3 + vpaddq $D1hi,$D2lo,$D2lo + + vpsrlq \$42,$D2lo,$tmp + vpsllq \$10,$D2hi,$D2hi + vpandq $mask42,$D2lo,$H2 + vpaddq $tmp,$D2hi,$D2hi + + vpaddq $T2,$H2,$H2 # accumulate input + vpaddq $D2hi,$H0,$H0 + vpsllq \$2,$D2hi,$D2hi + + vpaddq $D2hi,$H0,$H0 + vporq $T3,$T1,$T1 + vpandq $mask44,$T1,$T1 + + vpsrlq \$44,$H0,$tmp # additional step + vpandq $mask44,$H0,$H0 + + vpaddq $tmp,$H1,$H1 + + sub \$8,$len # len-=128 + jnz .Loop_vpmadd52_8x + +.Ltail_vpmadd52_8x: + #vpaddq $T2,$H2,$H2 # accumulate input + vpaddq $T0,$H0,$H0 + vpaddq $T1,$H1,$H1 + + vpxorq $D0lo,$D0lo,$D0lo + vpmadd52luq $H2,$SS1,$D0lo + vpxorq $D0hi,$D0hi,$D0hi + vpmadd52huq $H2,$SS1,$D0hi + vpxorq $D1lo,$D1lo,$D1lo + vpmadd52luq $H2,$SS2,$D1lo + vpxorq $D1hi,$D1hi,$D1hi + vpmadd52huq $H2,$SS2,$D1hi + vpxorq $D2lo,$D2lo,$D2lo + vpmadd52luq $H2,$RR0,$D2lo + vpxorq $D2hi,$D2hi,$D2hi + vpmadd52huq $H2,$RR0,$D2hi + + vpmadd52luq $H0,$RR0,$D0lo + vpmadd52huq $H0,$RR0,$D0hi + vpmadd52luq $H0,$RR1,$D1lo + vpmadd52huq $H0,$RR1,$D1hi + vpmadd52luq $H0,$RR2,$D2lo + vpmadd52huq $H0,$RR2,$D2hi + + vpmadd52luq $H1,$SS2,$D0lo + vpmadd52huq $H1,$SS2,$D0hi + vpmadd52luq $H1,$RR0,$D1lo + vpmadd52huq $H1,$RR0,$D1hi + vpmadd52luq $H1,$RR1,$D2lo + vpmadd52huq $H1,$RR1,$D2hi + + ################################################################ + # horizontal addition + + mov \$1,%eax + kmovw %eax,%k1 + vpsrldq \$8,$D0lo,$T0 + vpsrldq \$8,$D0hi,$H0 + vpsrldq \$8,$D1lo,$T1 + vpsrldq \$8,$D1hi,$H1 + vpaddq $T0,$D0lo,$D0lo + vpaddq $H0,$D0hi,$D0hi + vpsrldq \$8,$D2lo,$T2 + vpsrldq \$8,$D2hi,$H2 + vpaddq $T1,$D1lo,$D1lo + vpaddq $H1,$D1hi,$D1hi + vpermq \$0x2,$D0lo,$T0 + vpermq \$0x2,$D0hi,$H0 + vpaddq $T2,$D2lo,$D2lo + vpaddq $H2,$D2hi,$D2hi + + vpermq \$0x2,$D1lo,$T1 + vpermq \$0x2,$D1hi,$H1 + vpaddq $T0,$D0lo,$D0lo + vpaddq $H0,$D0hi,$D0hi + vpermq \$0x2,$D2lo,$T2 + vpermq \$0x2,$D2hi,$H2 + vpaddq $T1,$D1lo,$D1lo + vpaddq $H1,$D1hi,$D1hi + vextracti64x4 \$1,$D0lo,%y#$T0 + vextracti64x4 \$1,$D0hi,%y#$H0 + vpaddq $T2,$D2lo,$D2lo + vpaddq $H2,$D2hi,$D2hi + + vextracti64x4 \$1,$D1lo,%y#$T1 + vextracti64x4 \$1,$D1hi,%y#$H1 + vextracti64x4 \$1,$D2lo,%y#$T2 + vextracti64x4 \$1,$D2hi,%y#$H2 +___ +######## switch back to %ymm +map(s/%z/%y/, $H0,$H1,$H2,$R0,$R1,$R2,$S1,$S2); +map(s/%z/%y/, $D0lo,$D0hi,$D1lo,$D1hi,$D2lo,$D2hi); +map(s/%z/%y/, $T0,$T1,$T2,$T3,$mask44,$mask42,$tmp,$PAD); + +$code.=<<___; + vpaddq $T0,$D0lo,${D0lo}{%k1}{z} + vpaddq $H0,$D0hi,${D0hi}{%k1}{z} + vpaddq $T1,$D1lo,${D1lo}{%k1}{z} + vpaddq $H1,$D1hi,${D1hi}{%k1}{z} + vpaddq $T2,$D2lo,${D2lo}{%k1}{z} + vpaddq $H2,$D2hi,${D2hi}{%k1}{z} + + ################################################################ + # partial reduction + vpsrlq \$44,$D0lo,$tmp + vpsllq \$8,$D0hi,$D0hi + vpandq $mask44,$D0lo,$H0 + vpaddq $tmp,$D0hi,$D0hi + + vpaddq $D0hi,$D1lo,$D1lo + + vpsrlq \$44,$D1lo,$tmp + vpsllq \$8,$D1hi,$D1hi + vpandq $mask44,$D1lo,$H1 + vpaddq $tmp,$D1hi,$D1hi + + vpaddq $D1hi,$D2lo,$D2lo + + vpsrlq \$42,$D2lo,$tmp + vpsllq \$10,$D2hi,$D2hi + vpandq $mask42,$D2lo,$H2 + vpaddq $tmp,$D2hi,$D2hi + + vpaddq $D2hi,$H0,$H0 + vpsllq \$2,$D2hi,$D2hi + + vpaddq $D2hi,$H0,$H0 + + vpsrlq \$44,$H0,$tmp # additional step + vpandq $mask44,$H0,$H0 + + vpaddq $tmp,$H1,$H1 + + ################################################################ + + vmovq %x#$H0,0($ctx) + vmovq %x#$H1,8($ctx) + vmovq %x#$H2,16($ctx) + vzeroall + +.Lno_data_vpmadd52_8x: + ret +.size poly1305_blocks_vpmadd52_8x,.-poly1305_blocks_vpmadd52_8x +___ +} +$code.=<<___; +.type poly1305_emit_base2_44,\@function,3 +.align 32 +poly1305_emit_base2_44: + mov 0($ctx),%r8 # load hash value + mov 8($ctx),%r9 + mov 16($ctx),%r10 + + mov %r9,%rax + shr \$20,%r9 + shl \$44,%rax + mov %r10,%rcx + shr \$40,%r10 + shl \$24,%rcx + + add %rax,%r8 + adc %rcx,%r9 + adc \$0,%r10 + + mov %r8,%rax + add \$5,%r8 # compare to modulus + mov %r9,%rcx + adc \$0,%r9 + adc \$0,%r10 + shr \$2,%r10 # did 130-bit value overflow? + cmovnz %r8,%rax + cmovnz %r9,%rcx + + add 0($nonce),%rax # accumulate nonce + adc 8($nonce),%rcx + mov %rax,0($mac) # write result + mov %rcx,8($mac) + + ret +.size poly1305_emit_base2_44,.-poly1305_emit_base2_44 +___ +} } } $code.=<<___; .align 64 .Lconst: @@ -2006,8 +3762,29 @@ $code.=<<___; .long `1<<24`,0,`1<<24`,0,`1<<24`,0,`1<<24`,0 .Lmask26: .long 0x3ffffff,0,0x3ffffff,0,0x3ffffff,0,0x3ffffff,0 -.Lfive: -.long 5,0,5,0,5,0,5,0 +.Lpermd_avx2: +.long 2,2,2,3,2,0,2,1 +.Lpermd_avx512: +.long 0,0,0,1, 0,2,0,3, 0,4,0,5, 0,6,0,7 + +.L2_44_inp_permd: +.long 0,1,1,2,2,3,7,7 +.L2_44_inp_shift: +.quad 0,12,24,64 +.L2_44_mask: +.quad 0xfffffffffff,0xfffffffffff,0x3ffffffffff,0xffffffffffffffff +.L2_44_shift_rgt: +.quad 44,44,42,64 +.L2_44_shift_lft: +.quad 8,8,10,64 + +.align 64 +.Lx_mask44: +.quad 0xfffffffffff,0xfffffffffff,0xfffffffffff,0xfffffffffff +.quad 0xfffffffffff,0xfffffffffff,0xfffffffffff,0xfffffffffff +.Lx_mask42: +.quad 0x3ffffffffff,0x3ffffffffff,0x3ffffffffff,0x3ffffffffff +.quad 0x3ffffffffff,0x3ffffffffff,0x3ffffffffff,0x3ffffffffff ___ } @@ -2200,6 +3977,11 @@ $code.=<<___ if ($avx>1); .rva .LSEH_end_poly1305_blocks_avx2 .rva .LSEH_info_poly1305_blocks_avx2_3 ___ +$code.=<<___ if ($avx>2); + .rva .LSEH_begin_poly1305_blocks_avx512 + .rva .LSEH_end_poly1305_blocks_avx512 + .rva .LSEH_info_poly1305_blocks_avx512 +___ $code.=<<___; .section .xdata .align 8 @@ -2255,13 +4037,19 @@ $code.=<<___ if ($avx>1); .rva avx_handler .rva .Ldo_avx2_body,.Ldo_avx2_epilogue # HandlerData[] ___ +$code.=<<___ if ($avx>2); +.LSEH_info_poly1305_blocks_avx512: + .byte 9,0,0,0 + .rva avx_handler + .rva .Ldo_avx512_body,.Ldo_avx512_epilogue # HandlerData[] +___ } foreach (split('\n',$code)) { s/\`([^\`]*)\`/eval($1)/ge; s/%r([a-z]+)#d/%e$1/g; s/%r([0-9]+)#d/%r$1d/g; - s/%x#%y/%x/g; + s/%x#%[yz]/%x/g or s/%y#%z/%y/g or s/%z#%[yz]/%z/g; print $_,"\n"; } diff --git a/crypto/poly1305/build.info b/crypto/poly1305/build.info index d575f5a6..631b32b8 100644 --- a/crypto/poly1305/build.info +++ b/crypto/poly1305/build.info @@ -1,10 +1,13 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ + poly1305_pmeth.c \ + poly1305_ameth.c \ poly1305.c {- $target{poly1305_asm_src} -} GENERATE[poly1305-sparcv9.S]=asm/poly1305-sparcv9.pl $(PERLASM_SCHEME) INCLUDE[poly1305-sparcv9.o]=.. -GENERATE[poly1305-x86.s]=asm/poly1305-x86.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[poly1305-x86.s]=asm/poly1305-x86.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) GENERATE[poly1305-x86_64.s]=asm/poly1305-x86_64.pl $(PERLASM_SCHEME) GENERATE[poly1305-ppc.s]=asm/poly1305-ppc.pl $(PERLASM_SCHEME) GENERATE[poly1305-ppcfp.s]=asm/poly1305-ppcfp.pl $(PERLASM_SCHEME) @@ -13,6 +16,7 @@ INCLUDE[poly1305-armv4.o]=.. GENERATE[poly1305-armv8.S]=asm/poly1305-armv8.pl $(PERLASM_SCHEME) INCLUDE[poly1305-armv8.o]=.. GENERATE[poly1305-mips.S]=asm/poly1305-mips.pl $(PERLASM_SCHEME) +INCLUDE[poly1305-mips.o]=.. BEGINRAW[Makefile(unix)] {- $builddir -}/poly1305-%.S: {- $sourcedir -}/asm/poly1305-%.pl diff --git a/crypto/poly1305/poly1305.c b/crypto/poly1305/poly1305.c index eec4d67f..e3eb5da5 100644 --- a/crypto/poly1305/poly1305.c +++ b/crypto/poly1305/poly1305.c @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-2018 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 @@ -12,25 +12,7 @@ #include #include "internal/poly1305.h" - -typedef void (*poly1305_blocks_f) (void *ctx, const unsigned char *inp, - size_t len, unsigned int padbit); -typedef void (*poly1305_emit_f) (void *ctx, unsigned char mac[16], - const unsigned int nonce[4]); - -struct poly1305_context { - double opaque[24]; /* large enough to hold internal state, declared - * 'double' to ensure at least 64-bit invariant - * alignment across all platforms and - * configurations */ - unsigned int nonce[4]; - unsigned char data[POLY1305_BLOCK_SIZE]; - size_t num; - struct { - poly1305_blocks_f blocks; - poly1305_emit_f emit; - } func; -}; +#include "poly1305_local.h" size_t Poly1305_ctx_size () { @@ -113,12 +95,11 @@ poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, u32 padbit); (a ^ ((a ^ b) | ((a - b) ^ b))) >> (sizeof(a) * 8 - 1) \ ) -# if !defined(PEDANTIC) && \ - (defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16) && \ +# if (defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16) && \ (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__==8) typedef unsigned long u64; -typedef unsigned __int128 u128; +typedef __uint128_t u128; typedef struct { u64 h[3]; @@ -548,490 +529,3 @@ void Poly1305_Final(POLY1305 *ctx, unsigned char mac[16]) /* zero out the state */ OPENSSL_cleanse(ctx, sizeof(*ctx)); } - -#ifdef SELFTEST -#include - -struct poly1305_test { - const char *inputhex; - const char *keyhex; - const char *outhex; -}; - -static const struct poly1305_test poly1305_tests[] = { - /* - * RFC7539 - */ - { - "43727970746f6772617068696320466f72756d2052657365617263682047726f" - "7570", - "85d6be7857556d337f4452fe42d506a8""0103808afb0db2fd4abff6af4149f51b", - "a8061dc1305136c6c22b8baf0c0127a9" - }, - /* - * test vectors from "The Poly1305-AES message-authentication code" - */ - { - "f3f6", - "851fc40c3467ac0be05cc20404f3f700""580b3b0f9447bb1e69d095b5928b6dbc", - "f4c633c3044fc145f84f335cb81953de" - }, - { - "", - "a0f3080000f46400d0c7e9076c834403""dd3fab2251f11ac759f0887129cc2ee7", - "dd3fab2251f11ac759f0887129cc2ee7" - }, - { - "663cea190ffb83d89593f3f476b6bc24d7e679107ea26adb8caf6652d0656136", - "48443d0bb0d21109c89a100b5ce2c208""83149c69b561dd88298a1798b10716ef", - "0ee1c16bb73f0f4fd19881753c01cdbe" - }, - { - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9", - "12976a08c4426d0ce8a82407c4f48207""80f8c20aa71202d1e29179cbcb555a57", - "5154ad0d2cb26e01274fc51148491f1b" - }, - /* - * self-generated vectors exercise "significant" lengths, such that - * are handled by different code paths - */ - { - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9af", - "12976a08c4426d0ce8a82407c4f48207""80f8c20aa71202d1e29179cbcb555a57", - "812059a5da198637cac7c4a631bee466" - }, - { - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67", - "12976a08c4426d0ce8a82407c4f48207""80f8c20aa71202d1e29179cbcb555a57", - "5b88d7f6228b11e2e28579a5c0c1f761" - }, - { - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9af" - "663cea190ffb83d89593f3f476b6bc24d7e679107ea26adb8caf6652d0656136", - "12976a08c4426d0ce8a82407c4f48207""80f8c20aa71202d1e29179cbcb555a57", - "bbb613b2b6d753ba07395b916aaece15" - }, - { - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9af" - "48443d0bb0d21109c89a100b5ce2c20883149c69b561dd88298a1798b10716ef" - "663cea190ffb83d89593f3f476b6bc24", - "12976a08c4426d0ce8a82407c4f48207""80f8c20aa71202d1e29179cbcb555a57", - "c794d7057d1778c4bbee0a39b3d97342" - }, - { - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9af" - "48443d0bb0d21109c89a100b5ce2c20883149c69b561dd88298a1798b10716ef" - "663cea190ffb83d89593f3f476b6bc24d7e679107ea26adb8caf6652d0656136", - "12976a08c4426d0ce8a82407c4f48207""80f8c20aa71202d1e29179cbcb555a57", - "ffbcb9b371423152d7fca5ad042fbaa9" - }, - { - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9af" - "48443d0bb0d21109c89a100b5ce2c20883149c69b561dd88298a1798b10716ef" - "663cea190ffb83d89593f3f476b6bc24d7e679107ea26adb8caf6652d0656136" - "812059a5da198637cac7c4a631bee466", - "12976a08c4426d0ce8a82407c4f48207""80f8c20aa71202d1e29179cbcb555a57", - "069ed6b8ef0f207b3e243bb1019fe632" - }, - { - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9af" - "48443d0bb0d21109c89a100b5ce2c20883149c69b561dd88298a1798b10716ef" - "663cea190ffb83d89593f3f476b6bc24d7e679107ea26adb8caf6652d0656136" - "812059a5da198637cac7c4a631bee4665b88d7f6228b11e2e28579a5c0c1f761", - "12976a08c4426d0ce8a82407c4f48207""80f8c20aa71202d1e29179cbcb555a57", - "cca339d9a45fa2368c2c68b3a4179133" - }, - { - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9af" - "48443d0bb0d21109c89a100b5ce2c20883149c69b561dd88298a1798b10716ef" - "663cea190ffb83d89593f3f476b6bc24d7e679107ea26adb8caf6652d0656136" - "812059a5da198637cac7c4a631bee4665b88d7f6228b11e2e28579a5c0c1f761" - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9af" - "48443d0bb0d21109c89a100b5ce2c20883149c69b561dd88298a1798b10716ef" - "663cea190ffb83d89593f3f476b6bc24d7e679107ea26adb8caf6652d0656136", - "12976a08c4426d0ce8a82407c4f48207""80f8c20aa71202d1e29179cbcb555a57", - "53f6e828a2f0fe0ee815bf0bd5841a34" - }, - { - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9af" - "48443d0bb0d21109c89a100b5ce2c20883149c69b561dd88298a1798b10716ef" - "663cea190ffb83d89593f3f476b6bc24d7e679107ea26adb8caf6652d0656136" - "812059a5da198637cac7c4a631bee4665b88d7f6228b11e2e28579a5c0c1f761" - "ab0812724a7f1e342742cbed374d94d136c6b8795d45b3819830f2c04491faf0" - "990c62e48b8018b2c3e4a0fa3134cb67fa83e158c994d961c4cb21095c1bf9af" - "48443d0bb0d21109c89a100b5ce2c20883149c69b561dd88298a1798b10716ef" - "663cea190ffb83d89593f3f476b6bc24d7e679107ea26adb8caf6652d0656136" - "812059a5da198637cac7c4a631bee4665b88d7f6228b11e2e28579a5c0c1f761", - "12976a08c4426d0ce8a82407c4f48207""80f8c20aa71202d1e29179cbcb555a57", - "b846d44e9bbd53cedffbfbb6b7fa4933" - }, - /* - * 4th power of the key spills to 131th bit in SIMD key setup - */ - { - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - "ad628107e8351d0f2c231a05dc4a4106""00000000000000000000000000000000", - "07145a4c02fe5fa32036de68fabe9066" - }, - { - /* - * poly1305_ieee754.c failed this in final stage - */ - "842364e156336c0998b933a6237726180d9e3fdcbde4cd5d17080fc3beb49614" - "d7122c037463ff104d73f19c12704628d417c4c54a3fe30d3c3d7714382d43b0" - "382a50a5dee54be844b076e8df88201a1cd43b90eb21643fa96f39b518aa8340" - "c942ff3c31baf7c9bdbf0f31ae3fa096bf8c63030609829fe72e179824890bc8" - "e08c315c1cce2a83144dbbff09f74e3efc770b54d0984a8f19b14719e6363564" - "1d6b1eedf63efbf080e1783d32445412114c20de0b837a0dfa33d6b82825fff4" - "4c9a70ea54ce47f07df698e6b03323b53079364a5fc3e9dd034392bdde86dccd" - "da94321c5e44060489336cb65bf3989c36f7282c2f5d2b882c171e74", - "95d5c005503e510d8cd0aa072c4a4d06""6eabc52d11653df47fbf63ab198bcc26", - "f248312e578d9d58f8b7bb4d19105431" - }, - /* - * AVX2 in poly1305-x86.pl failed this with 176+32 split - */ - { - "248ac31085b6c2adaaa38259a0d7192c5c35d1bb4ef39ad94c38d1c82479e2dd" - "2159a077024b0589bc8a20101b506f0a1ad0bbab76e83a83f1b94be6beae74e8" - "74cab692c5963a75436b776121ec9f62399a3e66b2d22707dae81933b6277f3c" - "8516bcbe26dbbd86f373103d7cf4cad1888c952118fbfbd0d7b4bedc4ae4936a" - "ff91157e7aa47c54442ea78d6ac251d324a0fbe49d89cc3521b66d16e9c66a37" - "09894e4eb0a4eedc4ae19468e66b81f2" - "71351b1d921ea551047abcc6b87a901fde7db79fa1818c11336dbc07244a40eb", - "000102030405060708090a0b0c0d0e0f""00000000000000000000000000000000", - "bc939bc5281480fa99c6d68c258ec42f" - }, - /* - * test vectors from Google - */ - { - "", - "c8afaac331ee372cd6082de134943b17""4710130e9f6fea8d72293850a667d86c", - "4710130e9f6fea8d72293850a667d86c", - }, - { - "48656c6c6f20776f726c6421", - "746869732069732033322d6279746520""6b657920666f7220506f6c7931333035", - "a6f745008f81c916a20dcc74eef2b2f0" - }, - { - "0000000000000000000000000000000000000000000000000000000000000000", - "746869732069732033322d6279746520""6b657920666f7220506f6c7931333035", - "49ec78090e481ec6c26b33b91ccc0307" - }, - { - "89dab80b7717c1db5db437860a3f70218e93e1b8f461fb677f16f35f6f87e2a9" - "1c99bc3a47ace47640cc95c345be5ecca5a3523c35cc01893af0b64a62033427" - "0372ec12482d1b1e363561698a578b359803495bb4e2ef1930b17a5190b580f1" - "41300df30adbeca28f6427a8bc1a999fd51c554a017d095d8c3e3127daf9f595", - "2d773be37adb1e4d683bf0075e79c4ee""037918535a7f99ccb7040fb5f5f43aea", - "c85d15ed44c378d6b00e23064c7bcd51" - }, - { - "000000000000000b1703030200000000" - "06db1f1f368d696a810a349c0c714c9a5e7850c2407d721acded95e018d7a852" - "66a6e1289cdb4aeb18da5ac8a2b0026d24a59ad485227f3eaedbb2e7e35e1c66" - "cd60f9abf716dcc9ac42682dd7dab287a7024c4eefc321cc0574e16793e37cec" - "03c5bda42b54c114a80b57af26416c7be742005e20855c73e21dc8e2edc9d435" - "cb6f6059280011c270b71570051c1c9b3052126620bc1e2730fa066c7a509d53" - "c60e5ae1b40aa6e39e49669228c90eecb4a50db32a50bc49e90b4f4b359a1dfd" - "11749cd3867fcf2fb7bb6cd4738f6a4ad6f7ca5058f7618845af9f020f6c3b96" - "7b8f4cd4a91e2813b507ae66f2d35c18284f7292186062e10fd5510d18775351" - "ef334e7634ab4743f5b68f49adcab384d3fd75f7390f4006ef2a295c8c7a076a" - "d54546cd25d2107fbe1436c840924aaebe5b370893cd63d1325b8616fc481088" - "6bc152c53221b6df373119393255ee72bcaa880174f1717f9184fa91646f17a2" - "4ac55d16bfddca9581a92eda479201f0edbf633600d6066d1ab36d5d2415d713" - "51bbcd608a25108d25641992c1f26c531cf9f90203bc4cc19f5927d834b0a471" - "16d3884bbb164b8ec883d1ac832e56b3918a98601a08d171881541d594db399c" - "6ae6151221745aec814c45b0b05b565436fd6f137aa10a0c0b643761dbd6f9a9" - "dcb99b1a6e690854ce0769cde39761d82fcdec15f0d92d7d8e94ade8eb83fbe0", - "99e5822dd4173c995e3dae0ddefb9774""3fde3b080134b39f76e9bf8d0e88d546", - "2637408fe13086ea73f971e3425e2820" - }, - /* - * test vectors from Hanno Böck - */ - { - "cccccccccccccccccccccccccccccccccccccccccccccccccc80cccccccccccc" - "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccecccccc" - "ccccccccccccccccccccccccccccccc5cccccccccccccccccccccccccccccccc" - "cccccccccce3cccccccccccccccccccccccccccccccccccccccccccccccccccc" - "ccccccccaccccccccccccccccccccce6cccccccccc000000afcccccccccccccc" - "ccccfffffff50000000000000000000000000000000000000000000000000000" - "00ffffffe7000000000000000000000000000000000000000000000000000000" - "0000000000000000000000000000000000000000000000000000719205a8521d" - "fc", - "7f1b0264000000000000000000000000""0000000000000000cccccccccccccccc", - "8559b876eceed66eb37798c0457baff9" - }, - { - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0000000000" - "00000000800264", - "e0001600000000000000000000000000""0000aaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "00bd1258978e205444c9aaaa82006fed" - }, - { - "02fc", - "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c""0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c", - "06120c0c0c0c0c0c0c0c0c0c0c0c0c0c" - }, - { - "7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b" - "7b7b7b7b7b7b7a7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b" - "7b7b5c7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b" - "7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b6e7b007b7b7b7b7b7b7b7b7b" - "7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7a7b7b7b7b7b7b7b7b7b7b7b7b" - "7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b5c7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b" - "7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b" - "7b6e7b001300000000b300000000000000000000000000000000000000000000" - "f20000000000000000000000000000000000002000efff000900000000000000" - "0000000000100000000009000000640000000000000000000000001300000000" - "b300000000000000000000000000000000000000000000f20000000000000000" - "000000000000000000002000efff00090000000000000000007a000010000000" - "000900000064000000000000000000000000000000000000000000000000fc", - "00ff0000000000000000000000000000""00000000001e00000000000000007b7b", - "33205bbf9e9f8f7212ab9e2ab9b7e4a5" - }, - { - "7777777777777777777777777777777777777777777777777777777777777777" - "7777777777777777777777777777777777777777777777777777777777777777" - "777777777777777777777777ffffffe9e9acacacacacacacacacacac0000acac" - "ec0100acacac2caca2acacacacacacacacacacac64f2", - "0000007f0000007f0100002000000000""0000cf77777777777777777777777777", - "02ee7c8c546ddeb1a467e4c3981158b9" - }, - /* - * test vectors from Andrew Moon - */ - { /* nacl */ - "8e993b9f48681273c29650ba32fc76ce48332ea7164d96a4476fb8c531a1186a" - "c0dfc17c98dce87b4da7f011ec48c97271d2c20f9b928fe2270d6fb863d51738" - "b48eeee314a7cc8ab932164548e526ae90224368517acfeabd6bb3732bc0e9da" - "99832b61ca01b6de56244a9e88d5f9b37973f622a43d14a6599b1f654cb45a74" - "e355a5", - "eea6a7251c1e72916d11c2cb214d3c25""2539121d8e234e652d651fa4c8cff880", - "f3ffc7703f9400e52a7dfb4b3d3305d9" - }, - { /* wrap 2^130-5 */ - "ffffffffffffffffffffffffffffffff", - "02000000000000000000000000000000""00000000000000000000000000000000", - "03000000000000000000000000000000" - }, - { /* wrap 2^128 */ - "02000000000000000000000000000000", - "02000000000000000000000000000000""ffffffffffffffffffffffffffffffff", - "03000000000000000000000000000000" - }, - { /* limb carry */ - "fffffffffffffffffffffffffffffffff0ffffffffffffffffffffffffffffff" - "11000000000000000000000000000000", - "01000000000000000000000000000000""00000000000000000000000000000000", - "05000000000000000000000000000000" - }, - { /* 2^130-5 */ - "fffffffffffffffffffffffffffffffffbfefefefefefefefefefefefefefefe" - "01010101010101010101010101010101", - "01000000000000000000000000000000""00000000000000000000000000000000", - "00000000000000000000000000000000" - }, - { /* 2^130-6 */ - "fdffffffffffffffffffffffffffffff", - "02000000000000000000000000000000""00000000000000000000000000000000", - "faffffffffffffffffffffffffffffff" - }, - { /* 5*H+L reduction intermediate */ - "e33594d7505e43b900000000000000003394d7505e4379cd0100000000000000" - "0000000000000000000000000000000001000000000000000000000000000000", - "01000000000000000400000000000000""00000000000000000000000000000000", - "14000000000000005500000000000000" - }, - { /* 5*H+L reduction final */ - "e33594d7505e43b900000000000000003394d7505e4379cd0100000000000000" - "00000000000000000000000000000000", - "01000000000000000400000000000000""00000000000000000000000000000000", - "13000000000000000000000000000000" - } -}; - -static unsigned char hex_digit(char h) -{ - int i = OPENSSL_hexchar2int(h); - - if (i < 0) - abort(); - return i; -} - -static void hex_decode(unsigned char *out, const char *hex) -{ - size_t j = 0; - - while (*hex != 0) { - unsigned char v = hex_digit(*hex++); - v <<= 4; - v |= hex_digit(*hex++); - out[j++] = v; - } -} - -static void hexdump(unsigned char *a, size_t len) -{ - size_t i; - - for (i = 0; i < len; i++) - printf("%02x", a[i]); -} - -int main() -{ - static const unsigned num_tests = - sizeof(poly1305_tests) / sizeof(struct poly1305_test); - unsigned i; - unsigned char key[32], out[16], expected[16]; - POLY1305 poly1305; - - for (i = 0; i < num_tests; i++) { - const struct poly1305_test *test = &poly1305_tests[i]; - unsigned char *in; - size_t inlen = strlen(test->inputhex); - - if (strlen(test->keyhex) != sizeof(key) * 2 || - strlen(test->outhex) != sizeof(out) * 2 || (inlen & 1) == 1) - return 1; - - inlen /= 2; - - hex_decode(key, test->keyhex); - hex_decode(expected, test->outhex); - - in = malloc(inlen); - - hex_decode(in, test->inputhex); - - Poly1305_Init(&poly1305, key); - Poly1305_Update(&poly1305, in, inlen); - Poly1305_Final(&poly1305, out); - - if (memcmp(out, expected, sizeof(expected)) != 0) { - printf("Poly1305 test #%d failed.\n", i); - printf("got: "); - hexdump(out, sizeof(out)); - printf("\nexpected: "); - hexdump(expected, sizeof(expected)); - printf("\n"); - return 1; - } - - if (inlen > 16) { - Poly1305_Init(&poly1305, key); - Poly1305_Update(&poly1305, in, 1); - Poly1305_Update(&poly1305, in+1, inlen-1); - Poly1305_Final(&poly1305, out); - - if (memcmp(out, expected, sizeof(expected)) != 0) { - printf("Poly1305 test #%d/1+(N-1) failed.\n", i); - printf("got: "); - hexdump(out, sizeof(out)); - printf("\nexpected: "); - hexdump(expected, sizeof(expected)); - printf("\n"); - return 1; - } - } - - if (inlen > 32) { - size_t half = inlen / 2; - - Poly1305_Init(&poly1305, key); - Poly1305_Update(&poly1305, in, half); - Poly1305_Update(&poly1305, in+half, inlen-half); - Poly1305_Final(&poly1305, out); - - if (memcmp(out, expected, sizeof(expected)) != 0) { - printf("Poly1305 test #%d/2 failed.\n", i); - printf("got: "); - hexdump(out, sizeof(out)); - printf("\nexpected: "); - hexdump(expected, sizeof(expected)); - printf("\n"); - return 1; - } - - for (half = 16; half < inlen; half += 16) { - Poly1305_Init(&poly1305, key); - Poly1305_Update(&poly1305, in, half); - Poly1305_Update(&poly1305, in+half, inlen-half); - Poly1305_Final(&poly1305, out); - - if (memcmp(out, expected, sizeof(expected)) != 0) { - printf("Poly1305 test #%d/%d+%d failed.\n", - i, half, inlen-half); - printf("got: "); - hexdump(out, sizeof(out)); - printf("\nexpected: "); - hexdump(expected, sizeof(expected)); - printf("\n"); - return 1; - } - } - } - - free(in); - } - - printf("PASS\n"); - -# ifdef OPENSSL_CPUID_OBJ - { - unsigned char buf[8192]; - unsigned long long stopwatch; - unsigned long long OPENSSL_rdtsc(); - - memset (buf,0x55,sizeof(buf)); - memset (key,0xAA,sizeof(key)); - - Poly1305_Init(&poly1305, key); - - for (i=0;i<100000;i++) - Poly1305_Update(&poly1305,buf,sizeof(buf)); - - stopwatch = OPENSSL_rdtsc(); - for (i=0;i<10000;i++) - Poly1305_Update(&poly1305,buf,sizeof(buf)); - stopwatch = OPENSSL_rdtsc() - stopwatch; - - printf("%g\n",stopwatch/(double)(i*sizeof(buf))); - - stopwatch = OPENSSL_rdtsc(); - for (i=0;i<10000;i++) { - Poly1305_Init(&poly1305, key); - Poly1305_Update(&poly1305,buf,16); - Poly1305_Final(&poly1305,buf); - } - stopwatch = OPENSSL_rdtsc() - stopwatch; - - printf("%g\n",stopwatch/(double)(i)); - } -# endif - return 0; -} -#endif diff --git a/crypto/poly1305/poly1305_ameth.c b/crypto/poly1305/poly1305_ameth.c new file mode 100644 index 00000000..93c6bc0c --- /dev/null +++ b/crypto/poly1305/poly1305_ameth.c @@ -0,0 +1,67 @@ +/* + * Copyright 2007-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 +#include "internal/cryptlib.h" +#include +#include "internal/asn1_int.h" +#include "internal/poly1305.h" +#include "poly1305_local.h" + +/* + * POLY1305 "ASN1" method. This is just here to indicate the maximum + * POLY1305 output length and to free up a POLY1305 key. + */ + +static int poly1305_size(const EVP_PKEY *pkey) +{ + return POLY1305_DIGEST_SIZE; +} + +static void poly1305_key_free(EVP_PKEY *pkey) +{ + ASN1_OCTET_STRING *os = EVP_PKEY_get0(pkey); + if (os != NULL) { + if (os->data != NULL) + OPENSSL_cleanse(os->data, os->length); + ASN1_OCTET_STRING_free(os); + } +} + +static int poly1305_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) +{ + /* nothing, (including ASN1_PKEY_CTRL_DEFAULT_MD_NID), is supported */ + return -2; +} + +static int poly1305_pkey_public_cmp(const EVP_PKEY *a, const EVP_PKEY *b) +{ + return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b)); +} + +const EVP_PKEY_ASN1_METHOD poly1305_asn1_meth = { + EVP_PKEY_POLY1305, + EVP_PKEY_POLY1305, + 0, + + "POLY1305", + "OpenSSL POLY1305 method", + + 0, 0, poly1305_pkey_public_cmp, 0, + + 0, 0, 0, + + poly1305_size, + 0, 0, + 0, 0, 0, 0, 0, 0, 0, + + poly1305_key_free, + poly1305_pkey_ctrl, + 0, 0 +}; diff --git a/crypto/poly1305/poly1305_base2_44.c b/crypto/poly1305/poly1305_base2_44.c new file mode 100644 index 00000000..b6313d01 --- /dev/null +++ b/crypto/poly1305/poly1305_base2_44.c @@ -0,0 +1,171 @@ +/* + * 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 + */ + +/* + * This module is meant to be used as template for base 2^44 assembly + * implementation[s]. On side note compiler-generated code is not + * slower than compiler-generated base 2^64 code on [high-end] x86_64, + * even though amount of multiplications is 50% higher. Go figure... + */ +#include + +typedef unsigned char u8; +typedef unsigned int u32; +typedef unsigned long u64; +typedef unsigned __int128 u128; + +typedef struct { + u64 h[3]; + u64 s[2]; + u64 r[3]; +} poly1305_internal; + +#define POLY1305_BLOCK_SIZE 16 + +/* pick 64-bit unsigned integer in little endian order */ +static u64 U8TOU64(const unsigned char *p) +{ + return (((u64)(p[0] & 0xff)) | + ((u64)(p[1] & 0xff) << 8) | + ((u64)(p[2] & 0xff) << 16) | + ((u64)(p[3] & 0xff) << 24) | + ((u64)(p[4] & 0xff) << 32) | + ((u64)(p[5] & 0xff) << 40) | + ((u64)(p[6] & 0xff) << 48) | + ((u64)(p[7] & 0xff) << 56)); +} + +/* store a 64-bit unsigned integer in little endian */ +static void U64TO8(unsigned char *p, u64 v) +{ + p[0] = (unsigned char)((v) & 0xff); + p[1] = (unsigned char)((v >> 8) & 0xff); + p[2] = (unsigned char)((v >> 16) & 0xff); + p[3] = (unsigned char)((v >> 24) & 0xff); + p[4] = (unsigned char)((v >> 32) & 0xff); + p[5] = (unsigned char)((v >> 40) & 0xff); + p[6] = (unsigned char)((v >> 48) & 0xff); + p[7] = (unsigned char)((v >> 56) & 0xff); +} + +int poly1305_init(void *ctx, const unsigned char key[16]) +{ + poly1305_internal *st = (poly1305_internal *)ctx; + u64 r0, r1; + + /* h = 0 */ + st->h[0] = 0; + st->h[1] = 0; + st->h[2] = 0; + + r0 = U8TOU64(&key[0]) & 0x0ffffffc0fffffff; + r1 = U8TOU64(&key[8]) & 0x0ffffffc0ffffffc; + + /* break r1:r0 to three 44-bit digits, masks are 1<<44-1 */ + st->r[0] = r0 & 0x0fffffffffff; + st->r[1] = ((r0 >> 44) | (r1 << 20)) & 0x0fffffffffff; + st->r[2] = (r1 >> 24); + + st->s[0] = (st->r[1] + (st->r[1] << 2)) << 2; + st->s[1] = (st->r[2] + (st->r[2] << 2)) << 2; + + return 0; +} + +void poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, + u32 padbit) +{ + poly1305_internal *st = (poly1305_internal *)ctx; + u64 r0, r1, r2; + u64 s1, s2; + u64 h0, h1, h2, c; + u128 d0, d1, d2; + u64 pad = (u64)padbit << 40; + + r0 = st->r[0]; + r1 = st->r[1]; + r2 = st->r[2]; + + s1 = st->s[0]; + s2 = st->s[1]; + + h0 = st->h[0]; + h1 = st->h[1]; + h2 = st->h[2]; + + while (len >= POLY1305_BLOCK_SIZE) { + u64 m0, m1; + + m0 = U8TOU64(inp + 0); + m1 = U8TOU64(inp + 8); + + /* h += m[i], m[i] is broken to 44-bit digits */ + h0 += m0 & 0x0fffffffffff; + h1 += ((m0 >> 44) | (m1 << 20)) & 0x0fffffffffff; + h2 += (m1 >> 24) + pad; + + /* h *= r "%" p, where "%" stands for "partial remainder" */ + d0 = ((u128)h0 * r0) + ((u128)h1 * s2) + ((u128)h2 * s1); + d1 = ((u128)h0 * r1) + ((u128)h1 * r0) + ((u128)h2 * s2); + d2 = ((u128)h0 * r2) + ((u128)h1 * r1) + ((u128)h2 * r0); + + /* "lazy" reduction step */ + h0 = (u64)d0 & 0x0fffffffffff; + h1 = (u64)(d1 += (u64)(d0 >> 44)) & 0x0fffffffffff; + h2 = (u64)(d2 += (u64)(d1 >> 44)) & 0x03ffffffffff; /* last 42 bits */ + + c = (d2 >> 42); + h0 += c + (c << 2); + + inp += POLY1305_BLOCK_SIZE; + len -= POLY1305_BLOCK_SIZE; + } + + st->h[0] = h0; + st->h[1] = h1; + st->h[2] = h2; +} + +void poly1305_emit(void *ctx, unsigned char mac[16], const u32 nonce[4]) +{ + poly1305_internal *st = (poly1305_internal *) ctx; + u64 h0, h1, h2; + u64 g0, g1, g2; + u128 t; + u64 mask; + + h0 = st->h[0]; + h1 = st->h[1]; + h2 = st->h[2]; + + /* after "lazy" reduction, convert 44+bit digits to 64-bit ones */ + h0 = (u64)(t = (u128)h0 + (h1 << 44)); h1 >>= 20; + h1 = (u64)(t = (u128)h1 + (h2 << 24) + (t >> 64)); h2 >>= 40; + h2 += (u64)(t >> 64); + + /* compare to modulus by computing h + -p */ + g0 = (u64)(t = (u128)h0 + 5); + g1 = (u64)(t = (u128)h1 + (t >> 64)); + g2 = h2 + (u64)(t >> 64); + + /* if there was carry into 131st bit, h1:h0 = g1:g0 */ + mask = 0 - (g2 >> 2); + g0 &= mask; + g1 &= mask; + mask = ~mask; + h0 = (h0 & mask) | g0; + h1 = (h1 & mask) | g1; + + /* mac = (h + nonce) % (2^128) */ + h0 = (u64)(t = (u128)h0 + nonce[0] + ((u64)nonce[1]<<32)); + h1 = (u64)(t = (u128)h1 + nonce[2] + ((u64)nonce[3]<<32) + (t >> 64)); + + U64TO8(mac + 0, h0); + U64TO8(mac + 8, h1); +} diff --git a/crypto/poly1305/poly1305_ieee754.c b/crypto/poly1305/poly1305_ieee754.c index 08a5b58c..e9aaae3b 100644 --- a/crypto/poly1305/poly1305_ieee754.c +++ b/crypto/poly1305/poly1305_ieee754.c @@ -1,5 +1,5 @@ /* - * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2016-20018 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 @@ -101,6 +101,8 @@ static const u64 one = 1; static const u32 fpc = 1; #elif defined(__sparc__) static const u64 fsr = 1ULL<<30; +#elif defined(__mips__) +static const u32 fcsr = 1; #else #error "unrecognized platform" #endif @@ -147,6 +149,11 @@ int poly1305_init(void *ctx, const unsigned char key[16]) asm volatile ("stx %%fsr,%0":"=m"(fsr_orig)); asm volatile ("ldx %0,%%fsr"::"m"(fsr)); +#elif defined(__mips__) + u32 fcsr_orig; + + asm volatile ("cfc1 %0,$31":"=r"(fcsr_orig)); + asm volatile ("ctc1 %0,$31"::"r"(fcsr)); #endif /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */ @@ -206,6 +213,8 @@ int poly1305_init(void *ctx, const unsigned char key[16]) asm volatile ("lfpc %0"::"m"(fpc_orig)); #elif defined(__sparc__) asm volatile ("ldx %0,%%fsr"::"m"(fsr_orig)); +#elif defined(__mips__) + asm volatile ("ctc1 %0,$31"::"r"(fcsr_orig)); #endif } @@ -262,6 +271,11 @@ void poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, asm volatile ("stx %%fsr,%0":"=m"(fsr_orig)); asm volatile ("ldx %0,%%fsr"::"m"(fsr)); +#elif defined(__mips__) + u32 fcsr_orig; + + asm volatile ("cfc1 %0,$31":"=r"(fcsr_orig)); + asm volatile ("ctc1 %0,$31"::"r"(fcsr)); #endif /* @@ -408,6 +422,8 @@ void poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, asm volatile ("lfpc %0"::"m"(fpc_orig)); #elif defined(__sparc__) asm volatile ("ldx %0,%%fsr"::"m"(fsr_orig)); +#elif defined(__mips__) + asm volatile ("ctc1 %0,$31"::"r"(fcsr_orig)); #endif } diff --git a/crypto/poly1305/poly1305_local.h b/crypto/poly1305/poly1305_local.h new file mode 100644 index 00000000..6d4d9dc5 --- /dev/null +++ b/crypto/poly1305/poly1305_local.h @@ -0,0 +1,27 @@ +/* + * Copyright 2015-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 + */ + +typedef void (*poly1305_blocks_f) (void *ctx, const unsigned char *inp, + size_t len, unsigned int padbit); +typedef void (*poly1305_emit_f) (void *ctx, unsigned char mac[16], + const unsigned int nonce[4]); + +struct poly1305_context { + double opaque[24]; /* large enough to hold internal state, declared + * 'double' to ensure at least 64-bit invariant + * alignment across all platforms and + * configurations */ + unsigned int nonce[4]; + unsigned char data[POLY1305_BLOCK_SIZE]; + size_t num; + struct { + poly1305_blocks_f blocks; + poly1305_emit_f emit; + } func; +}; diff --git a/crypto/poly1305/poly1305_pmeth.c b/crypto/poly1305/poly1305_pmeth.c new file mode 100644 index 00000000..7bc6add6 --- /dev/null +++ b/crypto/poly1305/poly1305_pmeth.c @@ -0,0 +1,192 @@ +/* + * Copyright 2007-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 +#include "internal/cryptlib.h" +#include +#include +#include +#include "internal/poly1305.h" +#include "poly1305_local.h" +#include "internal/evp_int.h" + +/* POLY1305 pkey context structure */ + +typedef struct { + ASN1_OCTET_STRING ktmp; /* Temp storage for key */ + POLY1305 ctx; +} POLY1305_PKEY_CTX; + +static int pkey_poly1305_init(EVP_PKEY_CTX *ctx) +{ + POLY1305_PKEY_CTX *pctx; + + pctx = OPENSSL_zalloc(sizeof(*pctx)); + if (pctx == NULL) + return 0; + pctx->ktmp.type = V_ASN1_OCTET_STRING; + + EVP_PKEY_CTX_set_data(ctx, pctx); + EVP_PKEY_CTX_set0_keygen_info(ctx, NULL, 0); + return 1; +} + +static void pkey_poly1305_cleanup(EVP_PKEY_CTX *ctx) +{ + POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx); + + if (pctx != NULL) { + OPENSSL_clear_free(pctx->ktmp.data, pctx->ktmp.length); + OPENSSL_clear_free(pctx, sizeof(*pctx)); + EVP_PKEY_CTX_set_data(ctx, NULL); + } +} + +static int pkey_poly1305_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) +{ + POLY1305_PKEY_CTX *sctx, *dctx; + + /* allocate memory for dst->data and a new POLY1305_CTX in dst->data->ctx */ + if (!pkey_poly1305_init(dst)) + return 0; + sctx = EVP_PKEY_CTX_get_data(src); + dctx = EVP_PKEY_CTX_get_data(dst); + if (ASN1_STRING_get0_data(&sctx->ktmp) != NULL && + !ASN1_STRING_copy(&dctx->ktmp, &sctx->ktmp)) { + /* cleanup and free the POLY1305_PKEY_CTX in dst->data */ + pkey_poly1305_cleanup(dst); + return 0; + } + memcpy(&dctx->ctx, &sctx->ctx, sizeof(POLY1305)); + return 1; +} + +static int pkey_poly1305_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) +{ + ASN1_OCTET_STRING *key; + POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx); + + if (ASN1_STRING_get0_data(&pctx->ktmp) == NULL) + return 0; + key = ASN1_OCTET_STRING_dup(&pctx->ktmp); + if (key == NULL) + return 0; + return EVP_PKEY_assign_POLY1305(pkey, key); +} + +static int int_update(EVP_MD_CTX *ctx, const void *data, size_t count) +{ + POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(EVP_MD_CTX_pkey_ctx(ctx)); + + Poly1305_Update(&pctx->ctx, data, count); + return 1; +} + +static int poly1305_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx) +{ + POLY1305_PKEY_CTX *pctx = ctx->data; + ASN1_OCTET_STRING *key = (ASN1_OCTET_STRING *)ctx->pkey->pkey.ptr; + + if (key->length != POLY1305_KEY_SIZE) + return 0; + EVP_MD_CTX_set_flags(mctx, EVP_MD_CTX_FLAG_NO_INIT); + EVP_MD_CTX_set_update_fn(mctx, int_update); + Poly1305_Init(&pctx->ctx, key->data); + return 1; +} +static int poly1305_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, + EVP_MD_CTX *mctx) +{ + POLY1305_PKEY_CTX *pctx = ctx->data; + + *siglen = POLY1305_DIGEST_SIZE; + if (sig != NULL) + Poly1305_Final(&pctx->ctx, sig); + return 1; +} + +static int pkey_poly1305_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) +{ + POLY1305_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx); + const unsigned char *key; + size_t len; + + switch (type) { + + case EVP_PKEY_CTRL_MD: + /* ignore */ + break; + + case EVP_PKEY_CTRL_SET_MAC_KEY: + case EVP_PKEY_CTRL_DIGESTINIT: + if (type == EVP_PKEY_CTRL_SET_MAC_KEY) { + /* user explicitly setting the key */ + key = p2; + len = p1; + } else { + /* user indirectly setting the key via EVP_DigestSignInit */ + key = EVP_PKEY_get0_poly1305(EVP_PKEY_CTX_get0_pkey(ctx), &len); + } + if (key == NULL || len != POLY1305_KEY_SIZE || + !ASN1_OCTET_STRING_set(&pctx->ktmp, key, len)) + return 0; + Poly1305_Init(&pctx->ctx, ASN1_STRING_get0_data(&pctx->ktmp)); + break; + + default: + return -2; + + } + return 1; +} + +static int pkey_poly1305_ctrl_str(EVP_PKEY_CTX *ctx, + const char *type, const char *value) +{ + if (value == NULL) + return 0; + if (strcmp(type, "key") == 0) + return EVP_PKEY_CTX_str2ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, value); + if (strcmp(type, "hexkey") == 0) + return EVP_PKEY_CTX_hex2ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, value); + return -2; +} + +const EVP_PKEY_METHOD poly1305_pkey_meth = { + EVP_PKEY_POLY1305, + EVP_PKEY_FLAG_SIGCTX_CUSTOM, /* we don't deal with a separate MD */ + pkey_poly1305_init, + pkey_poly1305_copy, + pkey_poly1305_cleanup, + + 0, 0, + + 0, + pkey_poly1305_keygen, + + 0, 0, + + 0, 0, + + 0, 0, + + poly1305_signctx_init, + poly1305_signctx, + + 0, 0, + + 0, 0, + + 0, 0, + + 0, 0, + + pkey_poly1305_ctrl, + pkey_poly1305_ctrl_str +}; diff --git a/crypto/ppccap.c b/crypto/ppccap.c index 3baf9f7b..2f7cd8e6 100644 --- a/crypto/ppccap.c +++ b/crypto/ppccap.c @@ -39,38 +39,24 @@ static sigset_t all_masked; int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num) { - int bn_mul_mont_fpu64(BN_ULONG *rp, const BN_ULONG *ap, - const BN_ULONG *bp, const BN_ULONG *np, - const BN_ULONG *n0, int num); int bn_mul_mont_int(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); + int bn_mul4x_mont_int(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, + const BN_ULONG *np, const BN_ULONG *n0, int num); - if (sizeof(size_t) == 4) { -# if 1 || (defined(__APPLE__) && defined(__MACH__)) - if (num >= 8 && (num & 3) == 0 && (OPENSSL_ppccap_P & PPC_FPU64)) - return bn_mul_mont_fpu64(rp, ap, bp, np, n0, num); -# else - /* - * boundary of 32 was experimentally determined on Linux 2.6.22, - * might have to be adjusted on AIX... - */ - if (num >= 32 && (num & 3) == 0 && (OPENSSL_ppccap_P & PPC_FPU64)) { - sigset_t oset; - int ret; + if (num < 4) + return 0; - sigprocmask(SIG_SETMASK, &all_masked, &oset); - ret = bn_mul_mont_fpu64(rp, ap, bp, np, n0, num); - sigprocmask(SIG_SETMASK, &oset, NULL); + if ((num & 3) == 0) + return bn_mul4x_mont_int(rp, ap, bp, np, n0, num); - return ret; - } -# endif - } else if ((OPENSSL_ppccap_P & PPC_FPU64)) - /* - * this is a "must" on POWER6, but run-time detection is not - * implemented yet... - */ - return bn_mul_mont_fpu64(rp, ap, bp, np, n0, num); + /* + * There used to be [optional] call to bn_mul_mont_fpu64 here, + * but above subroutine is faster on contemporary processors. + * Formulation means that there might be old processors where + * FPU code path would be faster, POWER6 perhaps, but there was + * no opportunity to figure it out... + */ return bn_mul_mont_int(rp, ap, bp, np, n0, num); } @@ -135,6 +121,30 @@ int poly1305_init(void *ctx, const unsigned char key[16], void *func[2]) } #endif +#ifdef ECP_NISTZ256_ASM +void ecp_nistz256_mul_mont(unsigned long res[4], const unsigned long a[4], + const unsigned long b[4]); + +void ecp_nistz256_to_mont(unsigned long res[4], const unsigned long in[4]); +void ecp_nistz256_to_mont(unsigned long res[4], const unsigned long in[4]) +{ + static const unsigned long RR[] = { 0x0000000000000003U, + 0xfffffffbffffffffU, + 0xfffffffffffffffeU, + 0x00000004fffffffdU }; + + ecp_nistz256_mul_mont(res, in, RR); +} + +void ecp_nistz256_from_mont(unsigned long res[4], const unsigned long in[4]); +void ecp_nistz256_from_mont(unsigned long res[4], const unsigned long in[4]) +{ + static const unsigned long one[] = { 1, 0, 0, 0 }; + + ecp_nistz256_mul_mont(res, in, one); +} +#endif + static sigjmp_buf ill_jmp; static void ill_handler(int sig) { diff --git a/crypto/rand/build.info b/crypto/rand/build.info index 3ad50e25..df9bac67 100644 --- a/crypto/rand/build.info +++ b/crypto/rand/build.info @@ -1,4 +1,4 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ - md_rand.c randfile.c rand_lib.c rand_err.c rand_egd.c \ - rand_win.c rand_unix.c rand_vms.c + randfile.c rand_lib.c rand_err.c rand_egd.c \ + rand_win.c rand_unix.c rand_vms.c drbg_lib.c drbg_ctr.c diff --git a/crypto/rand/drbg_ctr.c b/crypto/rand/drbg_ctr.c new file mode 100644 index 00000000..99cd9976 --- /dev/null +++ b/crypto/rand/drbg_ctr.c @@ -0,0 +1,371 @@ +/* + * Copyright 2011-2018 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 +#include +#include +#include +#include +#include "rand_lcl.h" +#include "internal/thread_once.h" + +/* + * Implementation of NIST SP 800-90A CTR DRBG. + */ + +static void inc_128(RAND_DRBG_CTR *ctr) +{ + int i; + unsigned char c; + unsigned char *p = &ctr->V[15]; + + for (i = 0; i < 16; i++, p--) { + c = *p; + c++; + *p = c; + if (c != 0) { + /* If we didn't wrap around, we're done. */ + break; + } + } +} + +static void ctr_XOR(RAND_DRBG_CTR *ctr, const unsigned char *in, size_t inlen) +{ + size_t i, n; + + if (in == NULL || inlen == 0) + return; + + /* + * Any zero padding will have no effect on the result as we + * are XORing. So just process however much input we have. + */ + n = inlen < ctr->keylen ? inlen : ctr->keylen; + for (i = 0; i < n; i++) + ctr->K[i] ^= in[i]; + if (inlen <= ctr->keylen) + return; + + n = inlen - ctr->keylen; + if (n > 16) { + /* Should never happen */ + n = 16; + } + for (i = 0; i < n; i++) + ctr->V[i] ^= in[i + ctr->keylen]; +} + +/* + * Process a complete block using BCC algorithm of SP 800-90A 10.3.3 + */ +static void ctr_BCC_block(RAND_DRBG_CTR *ctr, unsigned char *out, + const unsigned char *in) +{ + int i; + + for (i = 0; i < 16; i++) + out[i] ^= in[i]; + AES_encrypt(out, out, &ctr->df_ks); +} + + +/* + * Handle several BCC operations for as much data as we need for K and X + */ +static void ctr_BCC_blocks(RAND_DRBG_CTR *ctr, const unsigned char *in) +{ + ctr_BCC_block(ctr, ctr->KX, in); + ctr_BCC_block(ctr, ctr->KX + 16, in); + if (ctr->keylen != 16) + ctr_BCC_block(ctr, ctr->KX + 32, in); +} + +/* + * Initialise BCC blocks: these have the value 0,1,2 in leftmost positions: + * see 10.3.1 stage 7. + */ +static void ctr_BCC_init(RAND_DRBG_CTR *ctr) +{ + memset(ctr->KX, 0, 48); + memset(ctr->bltmp, 0, 16); + ctr_BCC_block(ctr, ctr->KX, ctr->bltmp); + ctr->bltmp[3] = 1; + ctr_BCC_block(ctr, ctr->KX + 16, ctr->bltmp); + if (ctr->keylen != 16) { + ctr->bltmp[3] = 2; + ctr_BCC_block(ctr, ctr->KX + 32, ctr->bltmp); + } +} + +/* + * Process several blocks into BCC algorithm, some possibly partial + */ +static void ctr_BCC_update(RAND_DRBG_CTR *ctr, + const unsigned char *in, size_t inlen) +{ + if (in == NULL || inlen == 0) + return; + + /* If we have partial block handle it first */ + if (ctr->bltmp_pos) { + size_t left = 16 - ctr->bltmp_pos; + + /* If we now have a complete block process it */ + if (inlen >= left) { + memcpy(ctr->bltmp + ctr->bltmp_pos, in, left); + ctr_BCC_blocks(ctr, ctr->bltmp); + ctr->bltmp_pos = 0; + inlen -= left; + in += left; + } + } + + /* Process zero or more complete blocks */ + for (; inlen >= 16; in += 16, inlen -= 16) { + ctr_BCC_blocks(ctr, in); + } + + /* Copy any remaining partial block to the temporary buffer */ + if (inlen > 0) { + memcpy(ctr->bltmp + ctr->bltmp_pos, in, inlen); + ctr->bltmp_pos += inlen; + } +} + +static void ctr_BCC_final(RAND_DRBG_CTR *ctr) +{ + if (ctr->bltmp_pos) { + memset(ctr->bltmp + ctr->bltmp_pos, 0, 16 - ctr->bltmp_pos); + ctr_BCC_blocks(ctr, ctr->bltmp); + } +} + +static void ctr_df(RAND_DRBG_CTR *ctr, + const unsigned char *in1, size_t in1len, + const unsigned char *in2, size_t in2len, + const unsigned char *in3, size_t in3len) +{ + static unsigned char c80 = 0x80; + size_t inlen; + unsigned char *p = ctr->bltmp; + + ctr_BCC_init(ctr); + if (in1 == NULL) + in1len = 0; + if (in2 == NULL) + in2len = 0; + if (in3 == NULL) + in3len = 0; + inlen = in1len + in2len + in3len; + /* Initialise L||N in temporary block */ + *p++ = (inlen >> 24) & 0xff; + *p++ = (inlen >> 16) & 0xff; + *p++ = (inlen >> 8) & 0xff; + *p++ = inlen & 0xff; + + /* NB keylen is at most 32 bytes */ + *p++ = 0; + *p++ = 0; + *p++ = 0; + *p = (unsigned char)((ctr->keylen + 16) & 0xff); + ctr->bltmp_pos = 8; + ctr_BCC_update(ctr, in1, in1len); + ctr_BCC_update(ctr, in2, in2len); + ctr_BCC_update(ctr, in3, in3len); + ctr_BCC_update(ctr, &c80, 1); + ctr_BCC_final(ctr); + /* Set up key K */ + AES_set_encrypt_key(ctr->KX, ctr->keylen * 8, &ctr->df_kxks); + /* X follows key K */ + AES_encrypt(ctr->KX + ctr->keylen, ctr->KX, &ctr->df_kxks); + AES_encrypt(ctr->KX, ctr->KX + 16, &ctr->df_kxks); + if (ctr->keylen != 16) + AES_encrypt(ctr->KX + 16, ctr->KX + 32, &ctr->df_kxks); +} + +/* + * NB the no-df Update in SP800-90A specifies a constant input length + * of seedlen, however other uses of this algorithm pad the input with + * zeroes if necessary and have up to two parameters XORed together, + * so we handle both cases in this function instead. + */ +static void ctr_update(RAND_DRBG *drbg, + const unsigned char *in1, size_t in1len, + const unsigned char *in2, size_t in2len, + const unsigned char *nonce, size_t noncelen) +{ + RAND_DRBG_CTR *ctr = &drbg->data.ctr; + + /* ks is already setup for correct key */ + inc_128(ctr); + AES_encrypt(ctr->V, ctr->K, &ctr->ks); + + /* If keylen longer than 128 bits need extra encrypt */ + if (ctr->keylen != 16) { + inc_128(ctr); + AES_encrypt(ctr->V, ctr->K + 16, &ctr->ks); + } + inc_128(ctr); + AES_encrypt(ctr->V, ctr->V, &ctr->ks); + + /* If 192 bit key part of V is on end of K */ + if (ctr->keylen == 24) { + memcpy(ctr->V + 8, ctr->V, 8); + memcpy(ctr->V, ctr->K + 24, 8); + } + + if ((drbg->flags & RAND_DRBG_FLAG_CTR_NO_DF) == 0) { + /* If no input reuse existing derived value */ + if (in1 != NULL || nonce != NULL || in2 != NULL) + ctr_df(ctr, in1, in1len, nonce, noncelen, in2, in2len); + /* If this a reuse input in1len != 0 */ + if (in1len) + ctr_XOR(ctr, ctr->KX, drbg->seedlen); + } else { + ctr_XOR(ctr, in1, in1len); + ctr_XOR(ctr, in2, in2len); + } + + AES_set_encrypt_key(ctr->K, drbg->strength, &ctr->ks); +} + +static int drbg_ctr_instantiate(RAND_DRBG *drbg, + const unsigned char *entropy, size_t entropylen, + const unsigned char *nonce, size_t noncelen, + const unsigned char *pers, size_t perslen) +{ + RAND_DRBG_CTR *ctr = &drbg->data.ctr; + + if (entropy == NULL) + return 0; + + memset(ctr->K, 0, sizeof(ctr->K)); + memset(ctr->V, 0, sizeof(ctr->V)); + AES_set_encrypt_key(ctr->K, drbg->strength, &ctr->ks); + ctr_update(drbg, entropy, entropylen, pers, perslen, nonce, noncelen); + return 1; +} + +static int drbg_ctr_reseed(RAND_DRBG *drbg, + const unsigned char *entropy, size_t entropylen, + const unsigned char *adin, size_t adinlen) +{ + if (entropy == NULL) + return 0; + ctr_update(drbg, entropy, entropylen, adin, adinlen, NULL, 0); + return 1; +} + +static int drbg_ctr_generate(RAND_DRBG *drbg, + unsigned char *out, size_t outlen, + const unsigned char *adin, size_t adinlen) +{ + RAND_DRBG_CTR *ctr = &drbg->data.ctr; + + if (adin != NULL && adinlen != 0) { + ctr_update(drbg, adin, adinlen, NULL, 0, NULL, 0); + /* This means we reuse derived value */ + if ((drbg->flags & RAND_DRBG_FLAG_CTR_NO_DF) == 0) { + adin = NULL; + adinlen = 1; + } + } else { + adinlen = 0; + } + + for ( ; ; ) { + inc_128(ctr); + if (outlen < 16) { + /* Use K as temp space as it will be updated */ + AES_encrypt(ctr->V, ctr->K, &ctr->ks); + memcpy(out, ctr->K, outlen); + break; + } + AES_encrypt(ctr->V, out, &ctr->ks); + out += 16; + outlen -= 16; + if (outlen == 0) + break; + } + + ctr_update(drbg, adin, adinlen, NULL, 0, NULL, 0); + return 1; +} + +static int drbg_ctr_uninstantiate(RAND_DRBG *drbg) +{ + OPENSSL_cleanse(&drbg->data.ctr, sizeof(drbg->data.ctr)); + return 1; +} + +static RAND_DRBG_METHOD drbg_ctr_meth = { + drbg_ctr_instantiate, + drbg_ctr_reseed, + drbg_ctr_generate, + drbg_ctr_uninstantiate +}; + +int drbg_ctr_init(RAND_DRBG *drbg) +{ + RAND_DRBG_CTR *ctr = &drbg->data.ctr; + size_t keylen; + + switch (drbg->nid) { + default: + /* This can't happen, but silence the compiler warning. */ + return 0; + case NID_aes_128_ctr: + keylen = 16; + break; + case NID_aes_192_ctr: + keylen = 24; + break; + case NID_aes_256_ctr: + keylen = 32; + break; + } + + drbg->meth = &drbg_ctr_meth; + + ctr->keylen = keylen; + drbg->strength = keylen * 8; + drbg->seedlen = keylen + 16; + + if ((drbg->flags & RAND_DRBG_FLAG_CTR_NO_DF) == 0) { + /* df initialisation */ + static unsigned char df_key[32] = { + 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, + 0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f, + 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17, + 0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f + }; + /* Set key schedule for df_key */ + AES_set_encrypt_key(df_key, drbg->strength, &ctr->df_ks); + + drbg->min_entropylen = ctr->keylen; + drbg->max_entropylen = DRBG_MINMAX_FACTOR * drbg->min_entropylen; + drbg->min_noncelen = drbg->min_entropylen / 2; + drbg->max_noncelen = DRBG_MINMAX_FACTOR * drbg->min_noncelen; + drbg->max_perslen = DRBG_MAX_LENGTH; + drbg->max_adinlen = DRBG_MAX_LENGTH; + } else { + drbg->min_entropylen = drbg->seedlen; + drbg->max_entropylen = drbg->seedlen; + /* Nonce not used */ + drbg->min_noncelen = 0; + drbg->max_noncelen = 0; + drbg->max_perslen = drbg->seedlen; + drbg->max_adinlen = drbg->seedlen; + } + + drbg->max_request = 1 << 16; + drbg->reseed_interval = MAX_RESEED_INTERVAL; + return 1; +} diff --git a/crypto/rand/drbg_lib.c b/crypto/rand/drbg_lib.c new file mode 100644 index 00000000..c43f571d --- /dev/null +++ b/crypto/rand/drbg_lib.c @@ -0,0 +1,980 @@ +/* + * Copyright 2011-2018 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 +#include +#include +#include +#include "rand_lcl.h" +#include "internal/thread_once.h" +#include "internal/rand_int.h" + +/* + * Support framework for NIST SP 800-90A DRBG, AES-CTR mode. + * The RAND_DRBG is OpenSSL's pointer to an instance of the DRBG. + * + * The OpenSSL model is to have new and free functions, and that new + * does all initialization. That is not the NIST model, which has + * instantiation and un-instantiate, and re-use within a new/free + * lifecycle. (No doubt this comes from the desire to support hardware + * DRBG, where allocation of resources on something like an HSM is + * a much bigger deal than just re-setting an allocated resource.) + */ + +/* + * THE THREE SHARED DRBGs + * + * There are three shared DRBGs (master, public and private), which are + * accessed concurrently by all threads. + * + * THE MASTER DRBG + * + * Not used directly by the application, only for reseeding the two other + * DRBGs. It reseeds itself by pulling either randomness from os entropy + * sources or by consuming randomnes which was added by RAND_add() + */ +static RAND_DRBG *drbg_master; +/* + * THE PUBLIC DRBG + * + * Used by default for generating random bytes using RAND_bytes(). + */ +static RAND_DRBG *drbg_public; +/* + * THE PRIVATE DRBG + * + * Used by default for generating private keys using RAND_priv_bytes() + */ +static RAND_DRBG *drbg_private; +/*+ + * DRBG HIERARCHY + * + * In addition there are DRBGs, which are not shared, but used only by a + * single thread at every time, for example the DRBGs which are owned by + * an SSL context. All DRBGs are organized in a hierarchical fashion + * with the DRBG as root. + * + * This gives the following overall picture: + * + * + * | + * RAND_add() ==> \ + * / \ | shared DRBGs (with locking) + * / + * | + * owned by an SSL context + * + * AUTOMATIC RESEEDING + * + * Before satisfying a generate request, a DRBG reseeds itself automatically, + * if one of the following two conditions holds: + * + * - the number of generate requests since the last reseeding exceeds a + * certain threshold, the so called |reseed_interval|. This behaviour + * can be disabled by setting the |reseed_interval| to 0. + * + * - the time elapsed since the last reseeding exceeds a certain time + * interval, the so called |reseed_time_interval|. This behaviour + * can be disabled by setting the |reseed_time_interval| to 0. + * + * MANUAL RESEEDING + * + * For the three shared DRBGs (and only for these) there is another way to + * reseed them manually by calling RAND_seed() (or RAND_add() with a positive + * |randomness| argument). This will immediately reseed the DRBG. + * The and DRBG will detect this on their next generate + * call and reseed, pulling randomness from . + * + * LOCKING + * + * The three shared DRBGs are intended to be used concurrently, so they + * support locking. The RAND methods take the locks automatically, so using + * the RAND api (in particular RAND_bytes() and RAND_priv_bytes()) is + * thread-safe. Note however that accessing the shared DRBGs directly via + * the RAND_DRBG interface is *not* thread-safe. + * + * All other DRBG instances don't support locking, because they are + * intendended to be used by a single thread. Instead of accessing a single + * DRBG instance concurrently from different threads, it is recommended to + * instantiate a separate DRBG instance per thread. Using the same shared + * DRBG (preferrably the public DRBG) as parent of DRBG instances on + * different threads is safe. + */ + + +/* NIST SP 800-90A DRBG recommends the use of a personalization string. */ +static const char ossl_pers_string[] = "OpenSSL NIST SP 800-90A DRBG"; + +static CRYPTO_ONCE rand_drbg_init = CRYPTO_ONCE_STATIC_INIT; + +static RAND_DRBG *drbg_setup(RAND_DRBG *parent); + +static RAND_DRBG *rand_drbg_new(int secure, + int type, + unsigned int flags, + RAND_DRBG *parent); + +/* + * Set/initialize |drbg| to be of type |nid|, with optional |flags|. + * + * Returns 1 on success, 0 on failure. + */ +int RAND_DRBG_set(RAND_DRBG *drbg, int nid, unsigned int flags) +{ + int ret = 1; + + drbg->state = DRBG_UNINITIALISED; + drbg->flags = flags; + drbg->nid = nid; + + switch (nid) { + default: + RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE); + return 0; + case 0: + /* Uninitialized; that's okay. */ + return 1; + case NID_aes_128_ctr: + case NID_aes_192_ctr: + case NID_aes_256_ctr: + ret = drbg_ctr_init(drbg); + break; + } + + if (ret == 0) + RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG); + return ret; +} + +/* + * Allocate memory and initialize a new DRBG. The DRBG is allocated on + * the secure heap if |secure| is nonzero and the secure heap is enabled. + * The |parent|, if not NULL, will be used as random source for reseeding. + * + * Returns a pointer to the new DRBG instance on success, NULL on failure. + */ +static RAND_DRBG *rand_drbg_new(int secure, + int type, + unsigned int flags, + RAND_DRBG *parent) +{ + RAND_DRBG *drbg = secure ? + OPENSSL_secure_zalloc(sizeof(*drbg)) : OPENSSL_zalloc(sizeof(*drbg)); + + if (drbg == NULL) { + RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE); + goto err; + } + + drbg->secure = secure && CRYPTO_secure_allocated(drbg); + drbg->fork_count = rand_fork_count; + drbg->parent = parent; + if (RAND_DRBG_set(drbg, type, flags) == 0) + goto err; + + if (!RAND_DRBG_set_callbacks(drbg, rand_drbg_get_entropy, + rand_drbg_cleanup_entropy, + NULL, NULL)) + goto err; + + return drbg; + +err: + if (drbg->secure) + OPENSSL_secure_free(drbg); + else + OPENSSL_free(drbg); + + return NULL; +} + +RAND_DRBG *RAND_DRBG_new(int type, unsigned int flags, RAND_DRBG *parent) +{ + return rand_drbg_new(0, type, flags, parent); +} + +RAND_DRBG *RAND_DRBG_secure_new(int type, unsigned int flags, RAND_DRBG *parent) +{ + return rand_drbg_new(1, type, flags, parent); +} + +/* + * Uninstantiate |drbg| and free all memory. + */ +void RAND_DRBG_free(RAND_DRBG *drbg) +{ + if (drbg == NULL) + return; + + if (drbg->meth != NULL) + drbg->meth->uninstantiate(drbg); + CRYPTO_THREAD_lock_free(drbg->lock); + CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DRBG, drbg, &drbg->ex_data); + + if (drbg->secure) + OPENSSL_secure_clear_free(drbg, sizeof(*drbg)); + else + OPENSSL_clear_free(drbg, sizeof(*drbg)); +} + +/* + * Instantiate |drbg|, after it has been initialized. Use |pers| and + * |perslen| as prediction-resistance input. + * + * Requires that drbg->lock is already locked for write, if non-null. + * + * Returns 1 on success, 0 on failure. + */ +int RAND_DRBG_instantiate(RAND_DRBG *drbg, + const unsigned char *pers, size_t perslen) +{ + unsigned char *nonce = NULL, *entropy = NULL; + size_t noncelen = 0, entropylen = 0; + + if (perslen > drbg->max_perslen) { + RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, + RAND_R_PERSONALISATION_STRING_TOO_LONG); + goto end; + } + + if (drbg->meth == NULL) + { + RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, + RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED); + goto end; + } + + if (drbg->state != DRBG_UNINITIALISED) { + RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, + drbg->state == DRBG_ERROR ? RAND_R_IN_ERROR_STATE + : RAND_R_ALREADY_INSTANTIATED); + goto end; + } + + drbg->state = DRBG_ERROR; + if (drbg->get_entropy != NULL) + entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength, + drbg->min_entropylen, drbg->max_entropylen); + if (entropylen < drbg->min_entropylen + || entropylen > drbg->max_entropylen) { + RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_RETRIEVING_ENTROPY); + goto end; + } + + if (drbg->max_noncelen > 0 && drbg->get_nonce != NULL) { + noncelen = drbg->get_nonce(drbg, &nonce, drbg->strength / 2, + drbg->min_noncelen, drbg->max_noncelen); + if (noncelen < drbg->min_noncelen || noncelen > drbg->max_noncelen) { + RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, + RAND_R_ERROR_RETRIEVING_NONCE); + goto end; + } + } + + if (!drbg->meth->instantiate(drbg, entropy, entropylen, + nonce, noncelen, pers, perslen)) { + RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, RAND_R_ERROR_INSTANTIATING_DRBG); + goto end; + } + + drbg->state = DRBG_READY; + drbg->generate_counter = 0; + drbg->reseed_time = time(NULL); + if (drbg->reseed_counter > 0) { + if (drbg->parent == NULL) + drbg->reseed_counter++; + else + drbg->reseed_counter = drbg->parent->reseed_counter; + } + +end: + if (entropy != NULL && drbg->cleanup_entropy != NULL) + drbg->cleanup_entropy(drbg, entropy, entropylen); + if (nonce != NULL && drbg->cleanup_nonce!= NULL ) + drbg->cleanup_nonce(drbg, nonce, noncelen); + if (drbg->pool != NULL) { + if (drbg->state == DRBG_READY) { + RANDerr(RAND_F_RAND_DRBG_INSTANTIATE, + RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED); + drbg->state = DRBG_ERROR; + } + RAND_POOL_free(drbg->pool); + drbg->pool = NULL; + } + if (drbg->state == DRBG_READY) + return 1; + return 0; +} + +/* + * Uninstantiate |drbg|. Must be instantiated before it can be used. + * + * Requires that drbg->lock is already locked for write, if non-null. + * + * Returns 1 on success, 0 on failure. + */ +int RAND_DRBG_uninstantiate(RAND_DRBG *drbg) +{ + if (drbg->meth == NULL) + { + RANDerr(RAND_F_RAND_DRBG_UNINSTANTIATE, + RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED); + return 0; + } + + /* Clear the entire drbg->ctr struct, then reset some important + * members of the drbg->ctr struct (e.g. keysize, df_ks) to their + * initial values. + */ + drbg->meth->uninstantiate(drbg); + return RAND_DRBG_set(drbg, drbg->nid, drbg->flags); +} + +/* + * Reseed |drbg|, mixing in the specified data + * + * Requires that drbg->lock is already locked for write, if non-null. + * + * Returns 1 on success, 0 on failure. + */ +int RAND_DRBG_reseed(RAND_DRBG *drbg, + const unsigned char *adin, size_t adinlen) +{ + unsigned char *entropy = NULL; + size_t entropylen = 0; + + if (drbg->state == DRBG_ERROR) { + RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_IN_ERROR_STATE); + return 0; + } + if (drbg->state == DRBG_UNINITIALISED) { + RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_NOT_INSTANTIATED); + return 0; + } + + if (adin == NULL) + adinlen = 0; + else if (adinlen > drbg->max_adinlen) { + RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ADDITIONAL_INPUT_TOO_LONG); + return 0; + } + + drbg->state = DRBG_ERROR; + if (drbg->get_entropy != NULL) + entropylen = drbg->get_entropy(drbg, &entropy, drbg->strength, + drbg->min_entropylen, drbg->max_entropylen); + if (entropylen < drbg->min_entropylen + || entropylen > drbg->max_entropylen) { + RANDerr(RAND_F_RAND_DRBG_RESEED, RAND_R_ERROR_RETRIEVING_ENTROPY); + goto end; + } + + if (!drbg->meth->reseed(drbg, entropy, entropylen, adin, adinlen)) + goto end; + + drbg->state = DRBG_READY; + drbg->generate_counter = 0; + drbg->reseed_time = time(NULL); + if (drbg->reseed_counter > 0) { + if (drbg->parent == NULL) + drbg->reseed_counter++; + else + drbg->reseed_counter = drbg->parent->reseed_counter; + } + +end: + if (entropy != NULL && drbg->cleanup_entropy != NULL) + drbg->cleanup_entropy(drbg, entropy, entropylen); + if (drbg->state == DRBG_READY) + return 1; + return 0; +} + +/* + * Restart |drbg|, using the specified entropy or additional input + * + * Tries its best to get the drbg instantiated by all means, + * regardless of its current state. + * + * Optionally, a |buffer| of |len| random bytes can be passed, + * which is assumed to contain at least |entropy| bits of entropy. + * + * If |entropy| > 0, the buffer content is used as entropy input. + * + * If |entropy| == 0, the buffer content is used as additional input + * + * Returns 1 on success, 0 on failure. + * + * This function is used internally only. + */ +int rand_drbg_restart(RAND_DRBG *drbg, + const unsigned char *buffer, size_t len, size_t entropy) +{ + int reseeded = 0; + const unsigned char *adin = NULL; + size_t adinlen = 0; + + if (drbg->pool != NULL) { + RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR); + RAND_POOL_free(drbg->pool); + drbg->pool = NULL; + } + + if (buffer != NULL) { + if (entropy > 0) { + if (drbg->max_entropylen < len) { + RANDerr(RAND_F_RAND_DRBG_RESTART, + RAND_R_ENTROPY_INPUT_TOO_LONG); + return 0; + } + + if (entropy > 8 * len) { + RANDerr(RAND_F_RAND_DRBG_RESTART, RAND_R_ENTROPY_OUT_OF_RANGE); + return 0; + } + + /* will be picked up by the rand_drbg_get_entropy() callback */ + drbg->pool = RAND_POOL_new(entropy, len, len); + if (drbg->pool == NULL) + return 0; + + RAND_POOL_add(drbg->pool, buffer, len, entropy); + } else { + if (drbg->max_adinlen < len) { + RANDerr(RAND_F_RAND_DRBG_RESTART, + RAND_R_ADDITIONAL_INPUT_TOO_LONG); + return 0; + } + adin = buffer; + adinlen = len; + } + } + + /* repair error state */ + if (drbg->state == DRBG_ERROR) + RAND_DRBG_uninstantiate(drbg); + + /* repair uninitialized state */ + if (drbg->state == DRBG_UNINITIALISED) { + /* reinstantiate drbg */ + RAND_DRBG_instantiate(drbg, + (const unsigned char *) ossl_pers_string, + sizeof(ossl_pers_string) - 1); + /* already reseeded. prevent second reseeding below */ + reseeded = (drbg->state == DRBG_READY); + } + + /* refresh current state if entropy or additional input has been provided */ + if (drbg->state == DRBG_READY) { + if (adin != NULL) { + /* + * mix in additional input without reseeding + * + * Similar to RAND_DRBG_reseed(), but the provided additional + * data |adin| is mixed into the current state without pulling + * entropy from the trusted entropy source using get_entropy(). + * This is not a reseeding in the strict sense of NIST SP 800-90A. + */ + drbg->meth->reseed(drbg, adin, adinlen, NULL, 0); + } else if (reseeded == 0) { + /* do a full reseeding if it has not been done yet above */ + RAND_DRBG_reseed(drbg, NULL, 0); + } + } + + /* check whether a given entropy pool was cleared properly during reseed */ + if (drbg->pool != NULL) { + drbg->state = DRBG_ERROR; + RANDerr(RAND_F_RAND_DRBG_RESTART, ERR_R_INTERNAL_ERROR); + RAND_POOL_free(drbg->pool); + drbg->pool = NULL; + return 0; + } + + return drbg->state == DRBG_READY; +} + +/* + * Generate |outlen| bytes into the buffer at |out|. Reseed if we need + * to or if |prediction_resistance| is set. Additional input can be + * sent in |adin| and |adinlen|. + * + * Requires that drbg->lock is already locked for write, if non-null. + * + * Returns 1 on success, 0 on failure. + * + */ +int RAND_DRBG_generate(RAND_DRBG *drbg, unsigned char *out, size_t outlen, + int prediction_resistance, + const unsigned char *adin, size_t adinlen) +{ + int reseed_required = 0; + + if (drbg->state != DRBG_READY) { + /* try to recover from previous errors */ + rand_drbg_restart(drbg, NULL, 0, 0); + + if (drbg->state == DRBG_ERROR) { + RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_IN_ERROR_STATE); + return 0; + } + if (drbg->state == DRBG_UNINITIALISED) { + RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_NOT_INSTANTIATED); + return 0; + } + } + + if (outlen > drbg->max_request) { + RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG); + return 0; + } + if (adinlen > drbg->max_adinlen) { + RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_ADDITIONAL_INPUT_TOO_LONG); + return 0; + } + + if (drbg->fork_count != rand_fork_count) { + drbg->fork_count = rand_fork_count; + reseed_required = 1; + } + + if (drbg->reseed_interval > 0) { + if (drbg->generate_counter >= drbg->reseed_interval) + reseed_required = 1; + } + if (drbg->reseed_time_interval > 0) { + time_t now = time(NULL); + if (now < drbg->reseed_time + || now - drbg->reseed_time >= drbg->reseed_time_interval) + reseed_required = 1; + } + if (drbg->reseed_counter > 0 && drbg->parent != NULL) { + if (drbg->reseed_counter != drbg->parent->reseed_counter) + reseed_required = 1; + } + + if (reseed_required || prediction_resistance) { + if (!RAND_DRBG_reseed(drbg, adin, adinlen)) { + RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_RESEED_ERROR); + return 0; + } + adin = NULL; + adinlen = 0; + } + + if (!drbg->meth->generate(drbg, out, outlen, adin, adinlen)) { + drbg->state = DRBG_ERROR; + RANDerr(RAND_F_RAND_DRBG_GENERATE, RAND_R_GENERATE_ERROR); + return 0; + } + + drbg->generate_counter++; + + return 1; +} + +/* + * Generates |outlen| random bytes and stores them in |out|. It will + * using the given |drbg| to generate the bytes. + * + * Requires that drbg->lock is already locked for write, if non-null. + * + * Returns 1 on success 0 on failure. + */ +int RAND_DRBG_bytes(RAND_DRBG *drbg, unsigned char *out, size_t outlen) +{ + unsigned char *additional = NULL; + size_t additional_len; + size_t chunk; + size_t ret; + + additional_len = rand_drbg_get_additional_data(&additional, drbg->max_adinlen); + + for ( ; outlen > 0; outlen -= chunk, out += chunk) { + chunk = outlen; + if (chunk > drbg->max_request) + chunk = drbg->max_request; + ret = RAND_DRBG_generate(drbg, out, chunk, 0, additional, additional_len); + if (!ret) + goto err; + } + ret = 1; + +err: + if (additional_len != 0) + OPENSSL_secure_clear_free(additional, additional_len); + + return ret; +} + +/* + * Set the RAND_DRBG callbacks for obtaining entropy and nonce. + * + * In the following, the signature and the semantics of the + * get_entropy() and cleanup_entropy() callbacks are explained. + * + * GET_ENTROPY + * + * size_t get_entropy(RAND_DRBG *ctx, + * unsigned char **pout, + * int entropy, + * size_t min_len, size_t max_len); + * + * This is a request to allocate and fill a buffer of size + * |min_len| <= size <= |max_len| (in bytes) which contains + * at least |entropy| bits of randomness. The buffer's address is + * to be returned in |*pout| and the number of collected + * randomness bytes (which may be less than the allocated size + * of the buffer) as return value. + * + * If the callback fails to acquire at least |entropy| bits of + * randomness, it shall return a buffer length of 0. + * + * CLEANUP_ENTROPY + * + * void cleanup_entropy(RAND_DRBG *ctx, + * unsigned char *out, size_t outlen); + * + * A request to clear and free the buffer allocated by get_entropy(). + * The values |out| and |outlen| are expected to be the random buffer's + * address and length, as returned by the get_entropy() callback. + * + * GET_NONCE, CLEANUP_NONCE + * + * Signature and semantics of the get_nonce() and cleanup_nonce() + * callbacks are analogous to get_entropy() and cleanup_entropy(). + * Currently, the nonce is used only for the known answer tests. + */ +int RAND_DRBG_set_callbacks(RAND_DRBG *drbg, + RAND_DRBG_get_entropy_fn get_entropy, + RAND_DRBG_cleanup_entropy_fn cleanup_entropy, + RAND_DRBG_get_nonce_fn get_nonce, + RAND_DRBG_cleanup_nonce_fn cleanup_nonce) +{ + if (drbg->state != DRBG_UNINITIALISED) + return 0; + drbg->get_entropy = get_entropy; + drbg->cleanup_entropy = cleanup_entropy; + drbg->get_nonce = get_nonce; + drbg->cleanup_nonce = cleanup_nonce; + return 1; +} + +/* + * Set the reseed interval. + * + * The drbg will reseed automatically whenever the number of generate + * requests exceeds the given reseed interval. If the reseed interval + * is 0, then this feature is disabled. + * + * Returns 1 on success, 0 on failure. + */ +int RAND_DRBG_set_reseed_interval(RAND_DRBG *drbg, unsigned int interval) +{ + if (interval > MAX_RESEED_INTERVAL) + return 0; + drbg->reseed_interval = interval; + return 1; +} + +/* + * Set the reseed time interval. + * + * The drbg will reseed automatically whenever the time elapsed since + * the last reseeding exceeds the given reseed time interval. For safety, + * a reseeding will also occur if the clock has been reset to a smaller + * value. + * + * Returns 1 on success, 0 on failure. + */ +int RAND_DRBG_set_reseed_time_interval(RAND_DRBG *drbg, time_t interval) +{ + if (interval > MAX_RESEED_TIME_INTERVAL) + return 0; + drbg->reseed_time_interval = interval; + return 1; +} + + +/* + * Locks the given drbg. Locking a drbg which does not have locking + * enabled is considered a successful no-op. + * + * Returns 1 on success, 0 on failure. + */ +int rand_drbg_lock(RAND_DRBG *drbg) +{ + if (drbg->lock != NULL) + return CRYPTO_THREAD_write_lock(drbg->lock); + + return 1; +} + +/* + * Unlocks the given drbg. Unlocking a drbg which does not have locking + * enabled is considered a successful no-op. + * + * Returns 1 on success, 0 on failure. + */ +int rand_drbg_unlock(RAND_DRBG *drbg) +{ + if (drbg->lock != NULL) + return CRYPTO_THREAD_unlock(drbg->lock); + + return 1; +} + +/* + * Enables locking for the given drbg + * + * Locking can only be enabled if the random generator + * is in the uninitialized state. + * + * Returns 1 on success, 0 on failure. + */ +int rand_drbg_enable_locking(RAND_DRBG *drbg) +{ + if (drbg->state != DRBG_UNINITIALISED) { + RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING, + RAND_R_DRBG_ALREADY_INITIALIZED); + return 0; + } + + if (drbg->lock == NULL) { + if (drbg->parent != NULL && drbg->parent->lock == NULL) { + RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING, + RAND_R_PARENT_LOCKING_NOT_ENABLED); + return 0; + } + + drbg->lock = CRYPTO_THREAD_lock_new(); + if (drbg->lock == NULL) { + RANDerr(RAND_F_RAND_DRBG_ENABLE_LOCKING, + RAND_R_FAILED_TO_CREATE_LOCK); + return 0; + } + } + + return 1; +} + +/* + * Get and set the EXDATA + */ +int RAND_DRBG_set_ex_data(RAND_DRBG *drbg, int idx, void *arg) +{ + return CRYPTO_set_ex_data(&drbg->ex_data, idx, arg); +} + +void *RAND_DRBG_get_ex_data(const RAND_DRBG *drbg, int idx) +{ + return CRYPTO_get_ex_data(&drbg->ex_data, idx); +} + + +/* + * The following functions provide a RAND_METHOD that works on the + * global DRBG. They lock. + */ + +/* + * Allocates a new global DRBG on the secure heap (if enabled) and + * initializes it with default settings. + * + * Returns a pointer to the new DRBG instance on success, NULL on failure. + */ +static RAND_DRBG *drbg_setup(RAND_DRBG *parent) +{ + RAND_DRBG *drbg; + + drbg = RAND_DRBG_secure_new(RAND_DRBG_NID, 0, parent); + if (drbg == NULL) + return NULL; + + if (rand_drbg_enable_locking(drbg) == 0) + goto err; + + if (parent == NULL) { + drbg->reseed_interval = MASTER_RESEED_INTERVAL; + drbg->reseed_time_interval = MASTER_RESEED_TIME_INTERVAL; + } else { + drbg->reseed_interval = SLAVE_RESEED_INTERVAL; + drbg->reseed_time_interval = SLAVE_RESEED_TIME_INTERVAL; + } + + /* enable seed propagation */ + drbg->reseed_counter = 1; + + /* + * Ignore instantiation error so support just-in-time instantiation. + * + * The state of the drbg will be checked in RAND_DRBG_generate() and + * an automatic recovery is attempted. + */ + RAND_DRBG_instantiate(drbg, + (const unsigned char *) ossl_pers_string, + sizeof(ossl_pers_string) - 1); + return drbg; + +err: + RAND_DRBG_free(drbg); + return NULL; +} + +/* + * Initialize the global DRBGs on first use. + * Returns 1 on success, 0 on failure. + */ +DEFINE_RUN_ONCE_STATIC(do_rand_drbg_init) +{ + /* + * ensure that libcrypto is initialized, otherwise the + * DRBG locks are not cleaned up properly + */ + if (!OPENSSL_init_crypto(0, NULL)) + return 0; + + drbg_master = drbg_setup(NULL); + drbg_public = drbg_setup(drbg_master); + drbg_private = drbg_setup(drbg_master); + + if (drbg_master == NULL || drbg_public == NULL || drbg_private == NULL) + return 0; + + return 1; +} + +/* Clean up the global DRBGs before exit */ +void rand_drbg_cleanup_int(void) +{ + RAND_DRBG_free(drbg_private); + RAND_DRBG_free(drbg_public); + RAND_DRBG_free(drbg_master); + + drbg_private = drbg_public = drbg_master = NULL; +} + +/* Implements the default OpenSSL RAND_bytes() method */ +static int drbg_bytes(unsigned char *out, int count) +{ + int ret; + RAND_DRBG *drbg = RAND_DRBG_get0_public(); + + if (drbg == NULL) + return 0; + + rand_drbg_lock(drbg); + ret = RAND_DRBG_bytes(drbg, out, count); + rand_drbg_unlock(drbg); + + return ret; +} + +/* Implements the default OpenSSL RAND_add() method */ +static int drbg_add(const void *buf, int num, double randomness) +{ + int ret = 0; + RAND_DRBG *drbg = RAND_DRBG_get0_master(); + + if (drbg == NULL) + return 0; + + if (num < 0 || randomness < 0.0) + return 0; + + if (randomness > (double)drbg->max_entropylen) { + /* + * The purpose of this check is to bound |randomness| by a + * relatively small value in order to prevent an integer + * overflow when multiplying by 8 in the rand_drbg_restart() + * call below. + */ + return 0; + } + + rand_drbg_lock(drbg); + ret = rand_drbg_restart(drbg, buf, + (size_t)(unsigned int)num, + (size_t)(8*randomness)); + rand_drbg_unlock(drbg); + + return ret; +} + +/* Implements the default OpenSSL RAND_seed() method */ +static int drbg_seed(const void *buf, int num) +{ + return drbg_add(buf, num, num); +} + +/* Implements the default OpenSSL RAND_status() method */ +static int drbg_status(void) +{ + int ret; + RAND_DRBG *drbg = RAND_DRBG_get0_master(); + + if (drbg == NULL) + return 0; + + rand_drbg_lock(drbg); + ret = drbg->state == DRBG_READY ? 1 : 0; + rand_drbg_unlock(drbg); + return ret; +} + +/* + * Get the master DRBG. + * Returns pointer to the DRBG on success, NULL on failure. + * + */ +RAND_DRBG *RAND_DRBG_get0_master(void) +{ + if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init)) + return NULL; + + return drbg_master; +} + +/* + * Get the public DRBG. + * Returns pointer to the DRBG on success, NULL on failure. + */ +RAND_DRBG *RAND_DRBG_get0_public(void) +{ + if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init)) + return NULL; + + return drbg_public; +} + +/* + * Get the private DRBG. + * Returns pointer to the DRBG on success, NULL on failure. + */ +RAND_DRBG *RAND_DRBG_get0_private(void) +{ + if (!RUN_ONCE(&rand_drbg_init, do_rand_drbg_init)) + return NULL; + + return drbg_private; +} + +RAND_METHOD rand_meth = { + drbg_seed, + drbg_bytes, + NULL, + drbg_add, + drbg_bytes, + drbg_status +}; + +RAND_METHOD *RAND_OpenSSL(void) +{ + return &rand_meth; +} diff --git a/crypto/rand/md_rand.c b/crypto/rand/md_rand.c deleted file mode 100644 index 7d5fcb7f..00000000 --- a/crypto/rand/md_rand.c +++ /dev/null @@ -1,667 +0,0 @@ -/* - * Copyright 1995-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 - */ - -#include -#include - -#include "e_os.h" - -#if !(defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_DSPBIOS)) -# include -#endif -#if defined(OPENSSL_SYS_VXWORKS) -# include -#endif - -#include -#include -#include -#include -#include "rand_lcl.h" - -#include - -#include - -#ifdef OPENSSL_FIPS -# include -#endif - -#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 CRYPTO_RWLOCK *rand_lock = NULL; -static CRYPTO_RWLOCK *rand_tmp_lock = NULL; -static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT; - -/* May be set only when a thread holds rand_lock (to prevent double locking) */ -static unsigned int crypto_lock_rand = 0; -/* access to locking_threadid is synchronized by rand_tmp_lock */ -/* valid iff crypto_lock_rand is set */ -static CRYPTO_THREAD_ID locking_threadid; - -#ifdef PREDICT -int rand_predictable = 0; -#endif - -static int rand_hw_seed(EVP_MD_CTX *ctx); - -static void rand_cleanup(void); -static int rand_seed(const void *buf, int num); -static int rand_add(const void *buf, int num, double add_entropy); -static int rand_bytes(unsigned char *buf, int num, int pseudo); -static int rand_nopseudo_bytes(unsigned char *buf, int num); -#if OPENSSL_API_COMPAT < 0x10100000L -static int rand_pseudo_bytes(unsigned char *buf, int num); -#endif -static int rand_status(void); - -static RAND_METHOD rand_meth = { - rand_seed, - rand_nopseudo_bytes, - rand_cleanup, - rand_add, -#if OPENSSL_API_COMPAT < 0x10100000L - rand_pseudo_bytes, -#else - NULL, -#endif - rand_status -}; - -DEFINE_RUN_ONCE_STATIC(do_rand_lock_init) -{ - OPENSSL_init_crypto(0, NULL); - rand_lock = CRYPTO_THREAD_lock_new(); - rand_tmp_lock = CRYPTO_THREAD_lock_new(); - return rand_lock != NULL && rand_tmp_lock != NULL; -} - -RAND_METHOD *RAND_OpenSSL(void) -{ - return (&rand_meth); -} - -static void 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; - CRYPTO_THREAD_lock_free(rand_lock); - CRYPTO_THREAD_lock_free(rand_tmp_lock); -} - -static int 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; - int rv = 0; - - if (!num) - return 1; - - /* - * (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. - */ - - m = EVP_MD_CTX_new(); - if (m == NULL) - goto err; - - if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init)) - goto err; - - /* check if we already have the lock */ - if (crypto_lock_rand) { - CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id(); - CRYPTO_THREAD_read_lock(rand_tmp_lock); - do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur); - CRYPTO_THREAD_unlock(rand_tmp_lock); - } else - do_not_lock = 0; - - if (!do_not_lock) - CRYPTO_THREAD_write_lock(rand_lock); - 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)); - - /* 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_THREAD_unlock(rand_lock); - - 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)) - goto err; - if (!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)) - goto err; - if (!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))) - goto err; - if (!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 (intermediate 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_THREAD_write_lock(rand_lock); - /* - * 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_THREAD_unlock(rand_lock); - - rv = 1; - err: - EVP_MD_CTX_free(m); - return rv; -} - -static int rand_seed(const void *buf, int num) -{ - return rand_add(buf, num, (double)num); -} - -static int rand_bytes(unsigned char *buf, int num, int pseudo) -{ - 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 - time_t curr_time = time(NULL); - int do_stir_pool = 0; -/* time value for various platforms */ -#ifdef OPENSSL_SYS_WIN32 - FILETIME tv; -# ifdef _WIN32_WCE - SYSTEMTIME t; - GetSystemTime(&t); - SystemTimeToFileTime(&t, &tv); -# else - GetSystemTimeAsFileTime(&tv); -# endif -#elif defined(OPENSSL_SYS_VXWORKS) - struct timespec tv; - clock_gettime(CLOCK_REALTIME, &ts); -#elif defined(OPENSSL_SYS_DSPBIOS) - unsigned long long tv, OPENSSL_rdtsc(); - tv = OPENSSL_rdtsc(); -#else - struct timeval tv; - gettimeofday(&tv, NULL); -#endif - -#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; - - m = EVP_MD_CTX_new(); - if (m == NULL) - goto err_mem; - - /* 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 (!RUN_ONCE(&rand_lock_init, do_rand_lock_init)) - goto err_mem; - - CRYPTO_THREAD_write_lock(rand_lock); - /* - * We could end up in an async engine while holding this lock so ensure - * we don't pause and cause a deadlock - */ - ASYNC_block_pause(); - - /* prevent rand_bytes() from trying to obtain the lock again */ - CRYPTO_THREAD_write_lock(rand_tmp_lock); - locking_threadid = CRYPTO_THREAD_get_current_id(); - CRYPTO_THREAD_unlock(rand_tmp_lock); - 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 (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 - * rand_add expects to have something to hash. - */ - 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)); - - 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; - ASYNC_unblock_pause(); - CRYPTO_THREAD_unlock(rand_lock); - - 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))) - goto err; - curr_pid = 0; - } -#endif - if (curr_time) { /* just in the first iteration to save time */ - if (!MD_Update(m, (unsigned char *)&curr_time, sizeof(curr_time))) - goto err; - if (!MD_Update(m, (unsigned char *)&tv, sizeof(tv))) - goto err; - curr_time = 0; - if (!rand_hw_seed(m)) - goto err; - } - if (!MD_Update(m, local_md, MD_DIGEST_LENGTH)) - goto err; - if (!MD_Update(m, (unsigned char *)&(md_c[0]), sizeof(md_c))) - goto err; - - k = (st_idx + MD_DIGEST_LENGTH / 2) - st_num; - if (k > 0) { - if (!MD_Update(m, &(state[st_idx]), MD_DIGEST_LENGTH / 2 - k)) - goto err; - if (!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; - CRYPTO_THREAD_write_lock(rand_lock); - /* - * Prevent deadlocks if we end up in an async engine - */ - ASYNC_block_pause(); - if (!MD_Update(m, md, MD_DIGEST_LENGTH) || !MD_Final(m, md)) { - ASYNC_unblock_pause(); - CRYPTO_THREAD_unlock(rand_lock); - goto err; - } - ASYNC_unblock_pause(); - CRYPTO_THREAD_unlock(rand_lock); - - EVP_MD_CTX_free(m); - if (ok) - return (1); - else if (pseudo) - return 0; - else { - RANDerr(RAND_F_RAND_BYTES, RAND_R_PRNG_NOT_SEEDED); - ERR_add_error_data(1, "You need to read the OpenSSL FAQ, " - "https://www.openssl.org/docs/faq.html"); - return (0); - } - err: - RANDerr(RAND_F_RAND_BYTES, ERR_R_EVP_LIB); - EVP_MD_CTX_free(m); - return 0; - err_mem: - RANDerr(RAND_F_RAND_BYTES, ERR_R_MALLOC_FAILURE); - EVP_MD_CTX_free(m); - return 0; - -} - -static int rand_nopseudo_bytes(unsigned char *buf, int num) -{ - return rand_bytes(buf, num, 0); -} - -#if OPENSSL_API_COMPAT < 0x10100000L -/* - * pseudo-random bytes that are guaranteed to be unique but not unpredictable - */ -static int rand_pseudo_bytes(unsigned char *buf, int num) -{ - return rand_bytes(buf, num, 1); -} -#endif - -static int rand_status(void) -{ - CRYPTO_THREAD_ID cur; - int ret; - int do_not_lock; - - if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init)) - return 0; - - cur = CRYPTO_THREAD_get_current_id(); - /* - * check if we already have the lock (could happen if a RAND_poll() - * implementation calls RAND_status()) - */ - if (crypto_lock_rand) { - CRYPTO_THREAD_read_lock(rand_tmp_lock); - do_not_lock = CRYPTO_THREAD_compare_id(locking_threadid, cur); - CRYPTO_THREAD_unlock(rand_tmp_lock); - } else - do_not_lock = 0; - - if (!do_not_lock) { - CRYPTO_THREAD_write_lock(rand_lock); - /* - * Prevent deadlocks in case we end up in an async engine - */ - ASYNC_block_pause(); - - /* - * prevent rand_bytes() from trying to obtain the lock again - */ - CRYPTO_THREAD_write_lock(rand_tmp_lock); - locking_threadid = cur; - CRYPTO_THREAD_unlock(rand_tmp_lock); - 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; - - ASYNC_unblock_pause(); - CRYPTO_THREAD_unlock(rand_lock); - } - - return ret; -} - -/* - * rand_hw_seed: get seed data from any available hardware RNG. only - * currently supports rdrand. - */ - -/* Adapted from eng_rdrand.c */ - -#if (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ - defined(__x86_64) || defined(__x86_64__) || \ - defined(_M_AMD64) || defined (_M_X64)) && defined(OPENSSL_CPUID_OBJ) \ - && !defined(OPENSSL_NO_RDRAND) - -# define RDRAND_CALLS 4 - -size_t OPENSSL_ia32_rdrand(void); -extern unsigned int OPENSSL_ia32cap_P[]; - -static int rand_hw_seed(EVP_MD_CTX *ctx) -{ - int i; - if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32)))) - return 1; - for (i = 0; i < RDRAND_CALLS; i++) { - size_t rnd; - rnd = OPENSSL_ia32_rdrand(); - if (rnd == 0) - return 1; - if (!MD_Update(ctx, (unsigned char *)&rnd, sizeof(size_t))) - return 0; - } - return 1; -} - -/* XOR an existing buffer with random data */ - -void rand_hw_xor(unsigned char *buf, size_t num) -{ - size_t rnd; - if (!(OPENSSL_ia32cap_P[1] & (1 << (62 - 32)))) - return; - while (num >= sizeof(size_t)) { - rnd = OPENSSL_ia32_rdrand(); - if (rnd == 0) - return; - *((size_t *)buf) ^= rnd; - buf += sizeof(size_t); - num -= sizeof(size_t); - } - if (num) { - rnd = OPENSSL_ia32_rdrand(); - if (rnd == 0) - return; - while (num) { - *buf ^= rnd & 0xff; - rnd >>= 8; - buf++; - num--; - } - } -} - -#else - -static int rand_hw_seed(EVP_MD_CTX *ctx) -{ - return 1; -} - -void rand_hw_xor(unsigned char *buf, size_t num) -{ - return; -} - -#endif diff --git a/crypto/rand/rand_egd.c b/crypto/rand/rand_egd.c index 50963b8e..5eb3225b 100644 --- a/crypto/rand/rand_egd.c +++ b/crypto/rand/rand_egd.c @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-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 @@ -16,59 +16,28 @@ NON_EMPTY_TRANSLATION_UNIT # include # include -/*- - * Query the EGD . - * - * 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 occurred 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 occurred 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 retrieved to seed - * the PRNG. - * RAND_egd() is a wrapper for RAND_egd_bytes() with numbytes=255. +/* + * Query an EGD */ # if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_VOS) || defined(OPENSSL_SYS_UEFI) int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes) { - return (-1); + return -1; } int RAND_egd(const char *path) { - return (-1); + return -1; } int RAND_egd_bytes(const char *path, int bytes) { - return (-1); + return -1; } + # else + # include # include OPENSSL_UNISTD # include @@ -91,157 +60,98 @@ struct sockaddr_un { int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes) { - int ret = 0; + FILE *fp = NULL; struct sockaddr_un addr; - int len, num, numbytes; - int fd = -1; - int success; - unsigned char egdbuf[2], tempbuf[255], *retrievebuf; + int mybuffer, ret = -1, i, numbytes, fd; + unsigned char tempbuf[255]; + if (bytes > (int)sizeof(tempbuf)) + return -1; + + /* Make socket. */ memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; if (strlen(path) >= sizeof(addr.sun_path)) - return (-1); - OPENSSL_strlcpy(addr.sun_path, path, sizeof(addr.sun_path)); - len = offsetof(struct sockaddr_un, sun_path) + strlen(path); + return -1; + strcpy(addr.sun_path, path); + i = 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) { + if (fd == -1 || (fp = fdopen(fd, "r+")) == NULL) + return -1; + setbuf(fp, NULL); + + /* Try to connect */ + for ( ; ; ) { + if (connect(fd, (struct sockaddr *)&addr, i) == 0) + break; +# ifdef EISCONN + if (errno == EISCONN) + break; +# endif + switch (errno) { # ifdef EINTR - case EINTR: + case EINTR: # endif # ifdef EAGAIN - case EAGAIN: + case EAGAIN: # endif # ifdef EINPROGRESS - case EINPROGRESS: + case EINPROGRESS: # endif # ifdef EALREADY - case EALREADY: + case EALREADY: # endif - /* No error, try again */ - break; -# ifdef EISCONN - case EISCONN: - success = 1; - break; -# endif - default: - ret = -1; - goto err; /* failure */ - } + /* No error, try again */ + break; + default: + ret = -1; + goto err; } } - 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]); - } + /* Make request, see how many bytes we can get back. */ + tempbuf[0] = 1; + tempbuf[1] = bytes; + if (fwrite(tempbuf, sizeof(char), 2, fp) != 2 || fflush(fp) == EOF) + goto err; + if (fread(tempbuf, sizeof(char), 1, fp) != 1 || tempbuf[0] == 0) + goto err; + numbytes = tempbuf[0]; + + /* Which buffer are we using? */ + mybuffer = buf == NULL; + if (mybuffer) + buf = tempbuf; + + /* Read bytes. */ + i = fread(buf, sizeof(char), numbytes, fp); + if (i < numbytes) + goto err; + ret = numbytes; + if (mybuffer) + RAND_add(tempbuf, i, i); + err: - if (fd != -1) - close(fd); - return (ret); + if (fp != NULL) + fclose(fp); + return ret; } int RAND_egd_bytes(const char *path, int bytes) { - int num, ret = -1; + int num; num = RAND_query_egd_bytes(path, NULL, bytes); if (num < 0) - goto err; - if (RAND_status() == 1) - ret = num; - err: - return (ret); + return -1; + if (RAND_status() != 1) + return -1; + return num; } int RAND_egd(const char *path) { - return (RAND_egd_bytes(path, 255)); + return RAND_egd_bytes(path, 255); } # endif diff --git a/crypto/rand/rand_err.c b/crypto/rand/rand_err.c index 55431264..e92c33f4 100644 --- a/crypto/rand/rand_err.c +++ b/crypto/rand/rand_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -8,23 +8,95 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_RAND,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_RAND,0,reason) - -static ERR_STRING_DATA RAND_str_functs[] = { - {ERR_FUNC(RAND_F_RAND_BYTES), "RAND_bytes"}, +static const ERR_STRING_DATA RAND_str_functs[] = { + {ERR_PACK(ERR_LIB_RAND, RAND_F_DRBG_BYTES, 0), "drbg_bytes"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_DRBG_GET_ENTROPY, 0), "drbg_get_entropy"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_DRBG_SETUP, 0), "drbg_setup"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_GET_ENTROPY, 0), "get_entropy"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_BYTES, 0), "RAND_bytes"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_ENABLE_LOCKING, 0), + "rand_drbg_enable_locking"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_GENERATE, 0), + "RAND_DRBG_generate"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_INSTANTIATE, 0), + "RAND_DRBG_instantiate"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_NEW, 0), "RAND_DRBG_new"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_RESEED, 0), "RAND_DRBG_reseed"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_RESTART, 0), "rand_drbg_restart"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_SET, 0), "RAND_DRBG_set"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_DRBG_UNINSTANTIATE, 0), + "RAND_DRBG_uninstantiate"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_LOAD_FILE, 0), "RAND_load_file"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_POOL_ADD, 0), "RAND_POOL_add"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_POOL_ADD_BEGIN, 0), + "RAND_POOL_add_begin"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_POOL_ADD_END, 0), "RAND_POOL_add_end"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_POOL_BYTES_NEEDED, 0), + "RAND_POOL_bytes_needed"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_POOL_NEW, 0), "RAND_POOL_new"}, + {ERR_PACK(ERR_LIB_RAND, RAND_F_RAND_WRITE_FILE, 0), "RAND_write_file"}, {0, NULL} }; -static ERR_STRING_DATA RAND_str_reasons[] = { - {ERR_REASON(RAND_R_PRNG_NOT_SEEDED), "PRNG not seeded"}, +static const ERR_STRING_DATA RAND_str_reasons[] = { + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ADDITIONAL_INPUT_TOO_LONG), + "additional input too long"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ALREADY_INSTANTIATED), + "already instantiated"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ARGUMENT_OUT_OF_RANGE), + "argument out of range"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_CANNOT_OPEN_FILE), "Cannot open file"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_DRBG_ALREADY_INITIALIZED), + "drbg already initialized"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_DRBG_NOT_INITIALISED), + "drbg not initialised"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ENTROPY_INPUT_TOO_LONG), + "entropy input too long"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ENTROPY_OUT_OF_RANGE), + "entropy out of range"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED), + "error entropy pool was ignored"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_INITIALISING_DRBG), + "error initialising drbg"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_INSTANTIATING_DRBG), + "error instantiating drbg"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_ADDITIONAL_INPUT), + "error retrieving additional input"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_ENTROPY), + "error retrieving entropy"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_ERROR_RETRIEVING_NONCE), + "error retrieving nonce"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FAILED_TO_CREATE_LOCK), + "failed to create lock"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FUNC_NOT_IMPLEMENTED), + "Function not implemented"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_FWRITE_ERROR), "Error writing file"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_GENERATE_ERROR), "generate error"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_INTERNAL_ERROR), "internal error"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_IN_ERROR_STATE), "in error state"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NOT_A_REGULAR_FILE), + "Not a regular file"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NOT_INSTANTIATED), "not instantiated"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED), + "no drbg implementation selected"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PARENT_LOCKING_NOT_ENABLED), + "parent locking not enabled"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PERSONALISATION_STRING_TOO_LONG), + "personalisation string too long"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_PRNG_NOT_SEEDED), "PRNG not seeded"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_RANDOM_POOL_OVERFLOW), + "random pool overflow"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_REQUEST_TOO_LARGE_FOR_DRBG), + "request too large for drbg"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_RESEED_ERROR), "reseed error"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_SELFTEST_FAILURE), "selftest failure"}, + {ERR_PACK(ERR_LIB_RAND, 0, RAND_R_UNSUPPORTED_DRBG_TYPE), + "unsupported drbg type"}, {0, NULL} }; @@ -33,10 +105,9 @@ static ERR_STRING_DATA RAND_str_reasons[] = { int ERR_load_RAND_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(RAND_str_functs[0].error) == NULL) { - ERR_load_strings(0, RAND_str_functs); - ERR_load_strings(0, RAND_str_reasons); + ERR_load_strings_const(RAND_str_functs); + ERR_load_strings_const(RAND_str_reasons); } #endif return 1; diff --git a/crypto/rand/rand_lcl.h b/crypto/rand/rand_lcl.h index d98c90e2..ceba8bba 100644 --- a/crypto/rand/rand_lcl.h +++ b/crypto/rand/rand_lcl.h @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -10,37 +10,225 @@ #ifndef HEADER_RAND_LCL_H # define HEADER_RAND_LCL_H -# define ENTROPY_NEEDED 32 /* require 256 bits = 32 bytes of randomness */ - -# if !defined(USE_MD5_RAND) && !defined(USE_SHA1_RAND) && !defined(USE_MDC2_RAND) && !defined(USE_MD2_RAND) -# define USE_SHA1_RAND -# endif - +# include # include -# define MD_Update(a,b,c) EVP_DigestUpdate(a,b,c) -# define MD_Final(a,b) EVP_DigestFinal_ex(a,b,NULL) -# if defined(USE_MD5_RAND) -# include -# define MD_DIGEST_LENGTH MD5_DIGEST_LENGTH -# define MD_Init(a) EVP_DigestInit_ex(a,EVP_md5(), NULL) -# define MD(a,b,c) EVP_Digest(a,b,c,NULL,EVP_md5(), NULL) -# elif defined(USE_SHA1_RAND) -# include -# define MD_DIGEST_LENGTH SHA_DIGEST_LENGTH -# define MD_Init(a) EVP_DigestInit_ex(a,EVP_sha1(), NULL) -# define MD(a,b,c) EVP_Digest(a,b,c,NULL,EVP_sha1(), NULL) -# elif defined(USE_MDC2_RAND) -# include -# define MD_DIGEST_LENGTH MDC2_DIGEST_LENGTH -# define MD_Init(a) EVP_DigestInit_ex(a,EVP_mdc2(), NULL) -# define MD(a,b,c) EVP_Digest(a,b,c,NULL,EVP_mdc2(), NULL) -# elif defined(USE_MD2_RAND) -# include -# define MD_DIGEST_LENGTH MD2_DIGEST_LENGTH -# define MD_Init(a) EVP_DigestInit_ex(a,EVP_md2(), NULL) -# define MD(a,b,c) EVP_Digest(a,b,c,NULL,EVP_md2(), NULL) -# endif +# include +# include +# include +# include "internal/rand.h" -void rand_hw_xor(unsigned char *buf, size_t num); +/* How many times to read the TSC as a randomness source. */ +# define TSC_READ_COUNT 4 + +/* Maximum reseed intervals */ +# define MAX_RESEED_INTERVAL (1 << 24) +# define MAX_RESEED_TIME_INTERVAL (1 << 20) /* approx. 12 days */ + +/* Default reseed intervals */ +# define MASTER_RESEED_INTERVAL (1 << 8) +# define SLAVE_RESEED_INTERVAL (1 << 16) +# define MASTER_RESEED_TIME_INTERVAL (60*60) /* 1 hour */ +# define SLAVE_RESEED_TIME_INTERVAL (7*60) /* 7 minutes */ + + + +/* Max size of additional input and personalization string. */ +# define DRBG_MAX_LENGTH 4096 + +/* + * The quotient between max_{entropy,nonce}len and min_{entropy,nonce}len + * + * The current factor is large enough that the RAND_POOL can store a + * random input which has a lousy entropy rate of 0.0625 bits per byte. + * This input will be sent through the derivation function which 'compresses' + * the low quality input into a high quality output. + */ +# define DRBG_MINMAX_FACTOR 128 + + +/* DRBG status values */ +typedef enum drbg_status_e { + DRBG_UNINITIALISED, + DRBG_READY, + DRBG_ERROR +} DRBG_STATUS; + + +/* intantiate */ +typedef int (*RAND_DRBG_instantiate_fn)(RAND_DRBG *ctx, + const unsigned char *ent, + size_t entlen, + const unsigned char *nonce, + size_t noncelen, + const unsigned char *pers, + size_t perslen); +/* reseed */ +typedef int (*RAND_DRBG_reseed_fn)(RAND_DRBG *ctx, + const unsigned char *ent, + size_t entlen, + const unsigned char *adin, + size_t adinlen); +/* generat output */ +typedef int (*RAND_DRBG_generate_fn)(RAND_DRBG *ctx, + unsigned char *out, + size_t outlen, + const unsigned char *adin, + size_t adinlen); +/* uninstantiate */ +typedef int (*RAND_DRBG_uninstantiate_fn)(RAND_DRBG *ctx); + + +/* + * The DRBG methods + */ + +typedef struct rand_drbg_method_st { + RAND_DRBG_instantiate_fn instantiate; + RAND_DRBG_reseed_fn reseed; + RAND_DRBG_generate_fn generate; + RAND_DRBG_uninstantiate_fn uninstantiate; +} RAND_DRBG_METHOD; + + +/* + * The state of a DRBG AES-CTR. + */ +typedef struct rand_drbg_ctr_st { + AES_KEY ks; + size_t keylen; + unsigned char K[32]; + unsigned char V[16]; + /* Temp variables used by derivation function */ + AES_KEY df_ks; + AES_KEY df_kxks; + /* Temporary block storage used by ctr_df */ + unsigned char bltmp[16]; + size_t bltmp_pos; + unsigned char KX[48]; +} RAND_DRBG_CTR; + + +/* + * The state of all types of DRBGs, even though we only have CTR mode + * right now. + */ +struct rand_drbg_st { + CRYPTO_RWLOCK *lock; + RAND_DRBG *parent; + int secure; /* 1: allocated on the secure heap, 0: otherwise */ + int nid; /* the underlying algorithm */ + int fork_count; + unsigned short flags; /* various external flags */ + + /* + * The random pool is used by RAND_add()/drbg_add() to attach random + * data to the global drbg, such that the rand_drbg_get_entropy() callback + * can pull it during instantiation and reseeding. This is necessary to + * reconcile the different philosophies of the RAND and the RAND_DRBG + * with respect to how randomness is added to the RNG during reseeding + * (see PR #4328). + */ + RAND_POOL *pool; + + /* + * The following parameters are setup by the per-type "init" function. + * + * Currently the only type is CTR_DRBG, its init function is drbg_ctr_init(). + * + * The parameters are closely related to the ones described in + * section '10.2.1 CTR_DRBG' of [NIST SP 800-90Ar1], with one + * crucial difference: In the NIST standard, all counts are given + * in bits, whereas in OpenSSL entropy counts are given in bits + * and buffer lengths are given in bytes. + * + * Since this difference has lead to some confusion in the past, + * (see [GitHub Issue #2443], formerly [rt.openssl.org #4055]) + * the 'len' suffix has been added to all buffer sizes for + * clarification. + */ + + int strength; + size_t max_request; + size_t min_entropylen, max_entropylen; + size_t min_noncelen, max_noncelen; + size_t max_perslen, max_adinlen; + + /* Counts the number of generate requests since the last reseed. */ + unsigned int generate_counter; + /* + * Maximum number of generate requests until a reseed is required. + * This value is ignored if it is zero. + */ + unsigned int reseed_interval; + /* Stores the time when the last reseeding occurred */ + time_t reseed_time; + /* + * Specifies the maximum time interval (in seconds) between reseeds. + * This value is ignored if it is zero. + */ + time_t reseed_time_interval; + /* + * Counts the number of reseeds since instantiation. + * This value is ignored if it is zero. + * + * This counter is used only for seed propagation from the DRBG + * to its two children, the and DRBG. This feature is + * very special and its sole purpose is to ensure that any randomness which + * is added by RAND_add() or RAND_seed() will have an immediate effect on + * the output of RAND_bytes() resp. RAND_priv_bytes(). + */ + unsigned int reseed_counter; + + size_t seedlen; + DRBG_STATUS state; + + /* Application data, mainly used in the KATs. */ + CRYPTO_EX_DATA ex_data; + + /* Implementation specific data (currently only one implementation) */ + union { + RAND_DRBG_CTR ctr; + } data; + + /* Implementation specific methods */ + RAND_DRBG_METHOD *meth; + + /* Callback functions. See comments in rand_lib.c */ + RAND_DRBG_get_entropy_fn get_entropy; + RAND_DRBG_cleanup_entropy_fn cleanup_entropy; + RAND_DRBG_get_nonce_fn get_nonce; + RAND_DRBG_cleanup_nonce_fn cleanup_nonce; +}; + +/* The global RAND method, and the global buffer and DRBG instance. */ +extern RAND_METHOD rand_meth; + +/* How often we've forked (only incremented in child). */ +extern int rand_fork_count; + +/* Hardware-based seeding functions. */ +size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool); +size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool); + +/* DRBG entropy callbacks. */ +size_t rand_drbg_get_entropy(RAND_DRBG *drbg, + unsigned char **pout, + int entropy, size_t min_len, size_t max_len); +void rand_drbg_cleanup_entropy(RAND_DRBG *drbg, + unsigned char *out, size_t outlen); +size_t rand_drbg_get_additional_data(unsigned char **pout, size_t max_len); + +/* DRBG helpers */ +int rand_drbg_restart(RAND_DRBG *drbg, + const unsigned char *buffer, size_t len, size_t entropy); + +/* locking api */ +int rand_drbg_lock(RAND_DRBG *drbg); +int rand_drbg_unlock(RAND_DRBG *drbg); +int rand_drbg_enable_locking(RAND_DRBG *drbg); + + +/* initializes the AES-CTR DRBG implementation */ +int drbg_ctr_init(RAND_DRBG *drbg); #endif diff --git a/crypto/rand/rand_lib.c b/crypto/rand/rand_lib.c index 62770d49..b8b7b6e8 100644 --- a/crypto/rand/rand_lib.c +++ b/crypto/rand/rand_lib.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -11,39 +11,697 @@ #include #include "internal/cryptlib.h" #include -#include "internal/rand.h" +#include "internal/rand_int.h" #include #include "internal/thread_once.h" +#include "rand_lcl.h" +#ifdef OPENSSL_SYS_UNIX +# include +# include +# include +#endif +#include "e_os.h" -#ifdef OPENSSL_FIPS -# include -# include +/* Macro to convert two thirty two bit values into a sixty four bit one */ +#define TWO32TO64(a, b) ((((uint64_t)(a)) << 32) + (b)) + +/* + * Check for the existence and support of POSIX timers. The standard + * says that the _POSIX_TIMERS macro will have a positive value if they + * are available. + * + * However, we want an additional constraint: that the timer support does + * not require an extra library dependency. Early versions of glibc + * require -lrt to be specified on the link line to access the timers, + * so this needs to be checked for. + * + * It is worse because some libraries define __GLIBC__ but don't + * support the version testing macro (e.g. uClibc). This means + * an extra check is needed. + * + * The final condition is: + * "have posix timers and either not glibc or glibc without -lrt" + * + * The nested #if sequences are required to avoid using a parameterised + * macro that might be undefined. + */ +#undef OSSL_POSIX_TIMER_OKAY +#if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 +# if defined(__GLIBC__) +# if defined(__GLIBC_PREREQ) +# if __GLIBC_PREREQ(2, 17) +# define OSSL_POSIX_TIMER_OKAY +# endif +# endif +# else +# define OSSL_POSIX_TIMER_OKAY +# endif #endif #ifndef OPENSSL_NO_ENGINE /* non-NULL if default_RAND_meth is ENGINE-provided */ -static ENGINE *funct_ref = NULL; -static CRYPTO_RWLOCK *rand_engine_lock = NULL; +static ENGINE *funct_ref; +static CRYPTO_RWLOCK *rand_engine_lock; #endif -static const RAND_METHOD *default_RAND_meth = NULL; -static CRYPTO_RWLOCK *rand_meth_lock = NULL; -static CRYPTO_ONCE rand_lock_init = CRYPTO_ONCE_STATIC_INIT; +static CRYPTO_RWLOCK *rand_meth_lock; +static const RAND_METHOD *default_RAND_meth; +static CRYPTO_ONCE rand_init = CRYPTO_ONCE_STATIC_INIT; -DEFINE_RUN_ONCE_STATIC(do_rand_lock_init) +int rand_fork_count; + +#ifdef OPENSSL_RAND_SEED_RDTSC +/* + * IMPORTANT NOTE: It is not currently possible to use this code + * because we are not sure about the amount of randomness it provides. + * Some SP900 tests have been run, but there is internal skepticism. + * So for now this code is not used. + */ +# error "RDTSC enabled? Should not be possible!" + +/* + * Acquire entropy from high-speed clock + * + * Since we get some randomness from the low-order bits of the + * high-speed clock, it can help. + * + * Returns the total entropy count, if it exceeds the requested + * entropy count. Otherwise, returns an entropy count of 0. + */ +size_t rand_acquire_entropy_from_tsc(RAND_POOL *pool) +{ + unsigned char c; + int i; + + if ((OPENSSL_ia32cap_P[0] & (1 << 4)) != 0) { + for (i = 0; i < TSC_READ_COUNT; i++) { + c = (unsigned char)(OPENSSL_rdtsc() & 0xFF); + RAND_POOL_add(pool, &c, 1, 4); + } + } + return RAND_POOL_entropy_available(pool); +} +#endif + +#ifdef OPENSSL_RAND_SEED_RDCPU +size_t OPENSSL_ia32_rdseed_bytes(unsigned char *buf, size_t len); +size_t OPENSSL_ia32_rdrand_bytes(unsigned char *buf, size_t len); + +extern unsigned int OPENSSL_ia32cap_P[]; + +/* + * Acquire entropy using Intel-specific cpu instructions + * + * Uses the RDSEED instruction if available, otherwise uses + * RDRAND if available. + * + * For the differences between RDSEED and RDRAND, and why RDSEED + * is the preferred choice, see https://goo.gl/oK3KcN + * + * Returns the total entropy count, if it exceeds the requested + * entropy count. Otherwise, returns an entropy count of 0. + */ +size_t rand_acquire_entropy_from_cpu(RAND_POOL *pool) +{ + size_t bytes_needed; + unsigned char *buffer; + + bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/); + if (bytes_needed > 0) { + buffer = RAND_POOL_add_begin(pool, bytes_needed); + + if (buffer != NULL) { + + /* If RDSEED is available, use that. */ + if ((OPENSSL_ia32cap_P[2] & (1 << 18)) != 0) { + if (OPENSSL_ia32_rdseed_bytes(buffer, bytes_needed) + == bytes_needed) + return RAND_POOL_add_end(pool, + bytes_needed, + 8 * bytes_needed); + } + + /* Second choice is RDRAND. */ + if ((OPENSSL_ia32cap_P[1] & (1 << (62 - 32))) != 0) { + if (OPENSSL_ia32_rdrand_bytes(buffer, bytes_needed) + == bytes_needed) + return RAND_POOL_add_end(pool, + bytes_needed, + 8 * bytes_needed); + } + + return RAND_POOL_add_end(pool, 0, 0); + } + } + + return RAND_POOL_entropy_available(pool); +} +#endif + + +/* + * Implements the get_entropy() callback (see RAND_DRBG_set_callbacks()) + * + * If the DRBG has a parent, then the required amount of entropy input + * is fetched using the parent's RAND_DRBG_generate(). + * + * Otherwise, the entropy is polled from the system entropy sources + * using RAND_POOL_acquire_entropy(). + * + * If a random pool has been added to the DRBG using RAND_add(), then + * its entropy will be used up first. + */ +size_t rand_drbg_get_entropy(RAND_DRBG *drbg, + unsigned char **pout, + int entropy, size_t min_len, size_t max_len) +{ + size_t ret = 0; + size_t entropy_available = 0; + RAND_POOL *pool = RAND_POOL_new(entropy, min_len, max_len); + + if (pool == NULL) + return 0; + + if (drbg->pool) { + RAND_POOL_add(pool, + RAND_POOL_buffer(drbg->pool), + RAND_POOL_length(drbg->pool), + RAND_POOL_entropy(drbg->pool)); + RAND_POOL_free(drbg->pool); + drbg->pool = NULL; + } + + if (drbg->parent) { + size_t bytes_needed = RAND_POOL_bytes_needed(pool, 8); + unsigned char *buffer = RAND_POOL_add_begin(pool, bytes_needed); + + if (buffer != NULL) { + size_t bytes = 0; + + /* + * Get random from parent, include our state as additional input. + * Our lock is already held, but we need to lock our parent before + * generating bits from it. (Note: taking the lock will be a no-op + * if locking if drbg->parent->lock == NULL.) + */ + rand_drbg_lock(drbg->parent); + if (RAND_DRBG_generate(drbg->parent, + buffer, bytes_needed, + 0, + (unsigned char *)drbg, sizeof(*drbg)) != 0) + bytes = bytes_needed; + rand_drbg_unlock(drbg->parent); + + entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes); + } + + } else { + /* Get entropy by polling system entropy sources. */ + entropy_available = RAND_POOL_acquire_entropy(pool); + } + + if (entropy_available > 0) { + ret = RAND_POOL_length(pool); + *pout = RAND_POOL_detach(pool); + } + + RAND_POOL_free(pool); + return ret; +} + +/* + * Find a suitable source of time. Start with the highest resolution source + * and work down to the slower ones. This is added as additional data and + * isn't counted as randomness, so any result is acceptable. + * + * Returns 0 when we weren't able to find any time source + */ +static uint64_t get_timer_bits(void) +{ + uint64_t res = OPENSSL_rdtsc(); + + if (res != 0) + return res; +#if defined(_WIN32) + { + LARGE_INTEGER t; + FILETIME ft; + + if (QueryPerformanceCounter(&t) != 0) + return t.QuadPart; + GetSystemTimeAsFileTime(&ft); + return TWO32TO64(ft.dwHighDateTime, ft.dwLowDateTime); + } +#elif defined(__sun) || defined(__hpux) + return gethrtime(); +#elif defined(_AIX) + { + timebasestruct_t t; + + read_wall_time(&t, TIMEBASE_SZ); + return TWO32TO64(t.tb_high, t.tb_low); + } +#else + +# if defined(OSSL_POSIX_TIMER_OKAY) + { + struct timespec ts; + clockid_t cid; + +# ifdef CLOCK_BOOTTIME + cid = CLOCK_BOOTTIME; +# elif defined(_POSIX_MONOTONIC_CLOCK) + cid = CLOCK_MONOTONIC; +# else + cid = CLOCK_REALTIME; +# endif + + if (clock_gettime(cid, &ts) == 0) + return TWO32TO64(ts.tv_sec, ts.tv_nsec); + } +# endif +# if defined(__unix__) \ + || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) + { + struct timeval tv; + + if (gettimeofday(&tv, NULL) == 0) + return TWO32TO64(tv.tv_sec, tv.tv_usec); + } +# endif + { + time_t t = time(NULL); + if (t == (time_t)-1) + return 0; + return t; + } +#endif +} + +/* + * Generate additional data that can be used for the drbg. The data does + * not need to contain entropy, but it's useful if it contains at least + * some bits that are unpredictable. + * + * Returns 0 on failure. + * + * On success it allocates a buffer at |*pout| and returns the length of + * the data. The buffer should get freed using OPENSSL_secure_clear_free(). + */ +size_t rand_drbg_get_additional_data(unsigned char **pout, size_t max_len) +{ + RAND_POOL *pool; + CRYPTO_THREAD_ID thread_id; + size_t len; +#ifdef OPENSSL_SYS_UNIX + pid_t pid; +#elif defined(OPENSSL_SYS_WIN32) + DWORD pid; +#endif + uint64_t tbits; + + pool = RAND_POOL_new(0, 0, max_len); + if (pool == NULL) + return 0; + +#ifdef OPENSSL_SYS_UNIX + pid = getpid(); + RAND_POOL_add(pool, (unsigned char *)&pid, sizeof(pid), 0); +#elif defined(OPENSSL_SYS_WIN32) + pid = GetCurrentProcessId(); + RAND_POOL_add(pool, (unsigned char *)&pid, sizeof(pid), 0); +#endif + + thread_id = CRYPTO_THREAD_get_current_id(); + if (thread_id != 0) + RAND_POOL_add(pool, (unsigned char *)&thread_id, sizeof(thread_id), 0); + + tbits = get_timer_bits(); + if (tbits != 0) + RAND_POOL_add(pool, (unsigned char *)&tbits, sizeof(tbits), 0); + + /* TODO: Use RDSEED? */ + + len = RAND_POOL_length(pool); + if (len != 0) + *pout = RAND_POOL_detach(pool); + RAND_POOL_free(pool); + + return len; +} + +/* + * Implements the cleanup_entropy() callback (see RAND_DRBG_set_callbacks()) + * + */ +void rand_drbg_cleanup_entropy(RAND_DRBG *drbg, + unsigned char *out, size_t outlen) +{ + OPENSSL_secure_clear_free(out, outlen); +} + +void rand_fork() +{ + rand_fork_count++; +} + +DEFINE_RUN_ONCE_STATIC(do_rand_init) { int ret = 1; + #ifndef OPENSSL_NO_ENGINE rand_engine_lock = CRYPTO_THREAD_lock_new(); ret &= rand_engine_lock != NULL; #endif rand_meth_lock = CRYPTO_THREAD_lock_new(); ret &= rand_meth_lock != NULL; + return ret; } +void rand_cleanup_int(void) +{ + const RAND_METHOD *meth = default_RAND_meth; + + if (meth != NULL && meth->cleanup != NULL) + meth->cleanup(); + RAND_set_rand_method(NULL); +#ifndef OPENSSL_NO_ENGINE + CRYPTO_THREAD_lock_free(rand_engine_lock); +#endif + CRYPTO_THREAD_lock_free(rand_meth_lock); +} + +/* + * RAND_poll() reseeds the default RNG using random input + * + * The random input is obtained from polling various entropy + * sources which depend on the operating system and are + * configurable via the --with-rand-seed configure option. + */ +int RAND_poll(void) +{ + int ret = 0; + + RAND_POOL *pool = NULL; + + const RAND_METHOD *meth = RAND_get_rand_method(); + + if (meth == RAND_OpenSSL()) { + /* fill random pool and seed the master DRBG */ + RAND_DRBG *drbg = RAND_DRBG_get0_master(); + + if (drbg == NULL) + return 0; + + rand_drbg_lock(drbg); + ret = rand_drbg_restart(drbg, NULL, 0, 0); + rand_drbg_unlock(drbg); + + return ret; + + } else { + /* fill random pool and seed the current legacy RNG */ + pool = RAND_POOL_new(RAND_DRBG_STRENGTH, + RAND_DRBG_STRENGTH / 8, + DRBG_MINMAX_FACTOR * (RAND_DRBG_STRENGTH / 8)); + if (pool == NULL) + return 0; + + if (RAND_POOL_acquire_entropy(pool) == 0) + goto err; + + if (meth->add == NULL + || meth->add(RAND_POOL_buffer(pool), + RAND_POOL_length(pool), + (RAND_POOL_entropy(pool) / 8.0)) == 0) + goto err; + + ret = 1; + } + +err: + RAND_POOL_free(pool); + return ret; +} + +/* + * The 'random pool' acts as a dumb container for collecting random + * input from various entropy sources. The pool has no knowledge about + * whether its randomness is fed into a legacy RAND_METHOD via RAND_add() + * or into a new style RAND_DRBG. It is the callers duty to 1) initialize the + * random pool, 2) pass it to the polling callbacks, 3) seed the RNG, and + * 4) cleanup the random pool again. + * + * The random pool contains no locking mechanism because its scope and + * lifetime is intended to be restricted to a single stack frame. + */ +struct rand_pool_st { + unsigned char *buffer; /* points to the beginning of the random pool */ + size_t len; /* current number of random bytes contained in the pool */ + + size_t min_len; /* minimum number of random bytes requested */ + size_t max_len; /* maximum number of random bytes (allocated buffer size) */ + size_t entropy; /* current entropy count in bits */ + size_t requested_entropy; /* requested entropy count in bits */ +}; + +/* + * Allocate memory and initialize a new random pool + */ + +RAND_POOL *RAND_POOL_new(int entropy, size_t min_len, size_t max_len) +{ + RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool)); + + if (pool == NULL) { + RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE); + goto err; + } + + pool->min_len = min_len; + pool->max_len = max_len; + + pool->buffer = OPENSSL_secure_zalloc(pool->max_len); + if (pool->buffer == NULL) { + RANDerr(RAND_F_RAND_POOL_NEW, ERR_R_MALLOC_FAILURE); + goto err; + } + + pool->requested_entropy = entropy; + + return pool; + +err: + OPENSSL_free(pool); + return NULL; +} + +/* + * Free |pool|, securely erasing its buffer. + */ +void RAND_POOL_free(RAND_POOL *pool) +{ + if (pool == NULL) + return; + + OPENSSL_secure_clear_free(pool->buffer, pool->max_len); + OPENSSL_free(pool); +} + +/* + * Return the |pool|'s buffer to the caller (readonly). + */ +const unsigned char *RAND_POOL_buffer(RAND_POOL *pool) +{ + return pool->buffer; +} + +/* + * Return the |pool|'s entropy to the caller. + */ +size_t RAND_POOL_entropy(RAND_POOL *pool) +{ + return pool->entropy; +} + +/* + * Return the |pool|'s buffer length to the caller. + */ +size_t RAND_POOL_length(RAND_POOL *pool) +{ + return pool->len; +} + +/* + * Detach the |pool| buffer and return it to the caller. + * It's the responsibility of the caller to free the buffer + * using OPENSSL_secure_clear_free(). + */ +unsigned char *RAND_POOL_detach(RAND_POOL *pool) +{ + unsigned char *ret = pool->buffer; + pool->buffer = NULL; + return ret; +} + + +/* + * If every byte of the input contains |entropy_per_bytes| bits of entropy, + * how many bytes does one need to obtain at least |bits| bits of entropy? + */ +#define ENTROPY_TO_BYTES(bits, entropy_per_bytes) \ + (((bits) + ((entropy_per_bytes) - 1))/(entropy_per_bytes)) + + +/* + * Checks whether the |pool|'s entropy is available to the caller. + * This is the case when entropy count and buffer length are high enough. + * Returns + * + * |entropy| if the entropy count and buffer size is large enough + * 0 otherwise + */ +size_t RAND_POOL_entropy_available(RAND_POOL *pool) +{ + if (pool->entropy < pool->requested_entropy) + return 0; + + if (pool->len < pool->min_len) + return 0; + + return pool->entropy; +} + +/* + * Returns the (remaining) amount of entropy needed to fill + * the random pool. + */ + +size_t RAND_POOL_entropy_needed(RAND_POOL *pool) +{ + if (pool->entropy < pool->requested_entropy) + return pool->requested_entropy - pool->entropy; + + return 0; +} + +/* + * Returns the number of bytes needed to fill the pool, assuming + * the input has 'entropy_per_byte' entropy bits per byte. + * In case of an error, 0 is returned. + */ + +size_t RAND_POOL_bytes_needed(RAND_POOL *pool, unsigned int entropy_per_byte) +{ + size_t bytes_needed; + size_t entropy_needed = RAND_POOL_entropy_needed(pool); + + if (entropy_per_byte < 1 || entropy_per_byte > 8) { + RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_ARGUMENT_OUT_OF_RANGE); + return 0; + } + + bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_per_byte); + + if (bytes_needed > pool->max_len - pool->len) { + /* not enough space left */ + RANDerr(RAND_F_RAND_POOL_BYTES_NEEDED, RAND_R_RANDOM_POOL_OVERFLOW); + return 0; + } + + if (pool->len < pool->min_len && + bytes_needed < pool->min_len - pool->len) + /* to meet the min_len requirement */ + bytes_needed = pool->min_len - pool->len; + + return bytes_needed; +} + +/* Returns the remaining number of bytes available */ +size_t RAND_POOL_bytes_remaining(RAND_POOL *pool) +{ + return pool->max_len - pool->len; +} + +/* + * Add random bytes to the random pool. + * + * It is expected that the |buffer| contains |len| bytes of + * random input which contains at least |entropy| bits of + * randomness. + * + * Return available amount of entropy after this operation. + * (see RAND_POOL_entropy_available(pool)) + */ +size_t RAND_POOL_add(RAND_POOL *pool, + const unsigned char *buffer, size_t len, size_t entropy) +{ + if (len > pool->max_len - pool->len) { + RANDerr(RAND_F_RAND_POOL_ADD, RAND_R_ENTROPY_INPUT_TOO_LONG); + return 0; + } + + if (len > 0) { + memcpy(pool->buffer + pool->len, buffer, len); + pool->len += len; + pool->entropy += entropy; + } + + return RAND_POOL_entropy_available(pool); +} + +/* + * Start to add random bytes to the random pool in-place. + * + * Reserves the next |len| bytes for adding random bytes in-place + * and returns a pointer to the buffer. + * The caller is allowed to copy up to |len| bytes into the buffer. + * If |len| == 0 this is considered a no-op and a NULL pointer + * is returned without producing an error message. + * + * After updating the buffer, RAND_POOL_add_end() needs to be called + * to finish the udpate operation (see next comment). + */ +unsigned char *RAND_POOL_add_begin(RAND_POOL *pool, size_t len) +{ + if (len == 0) + return NULL; + + if (len > pool->max_len - pool->len) { + RANDerr(RAND_F_RAND_POOL_ADD_BEGIN, RAND_R_RANDOM_POOL_OVERFLOW); + return NULL; + } + + return pool->buffer + pool->len; +} + +/* + * Finish to add random bytes to the random pool in-place. + * + * Finishes an in-place update of the random pool started by + * RAND_POOL_add_begin() (see previous comment). + * It is expected that |len| bytes of random input have been added + * to the buffer which contain at least |entropy| bits of randomness. + * It is allowed to add less bytes than originally reserved. + */ +size_t RAND_POOL_add_end(RAND_POOL *pool, size_t len, size_t entropy) +{ + if (len > pool->max_len - pool->len) { + RANDerr(RAND_F_RAND_POOL_ADD_END, RAND_R_RANDOM_POOL_OVERFLOW); + return 0; + } + + if (len > 0) { + pool->len += len; + pool->entropy += entropy; + } + + return RAND_POOL_entropy_available(pool); +} + int RAND_set_rand_method(const RAND_METHOD *meth) { - if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init)) + if (!RUN_ONCE(&rand_init, do_rand_init)) return 0; CRYPTO_THREAD_write_lock(rand_meth_lock); @@ -60,25 +718,26 @@ const RAND_METHOD *RAND_get_rand_method(void) { const RAND_METHOD *tmp_meth = NULL; - if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init)) + if (!RUN_ONCE(&rand_init, do_rand_init)) return NULL; CRYPTO_THREAD_write_lock(rand_meth_lock); - if (!default_RAND_meth) { + if (default_RAND_meth == NULL) { #ifndef OPENSSL_NO_ENGINE - ENGINE *e = ENGINE_get_default_RAND(); - if (e) { - default_RAND_meth = ENGINE_get_RAND(e); - if (default_RAND_meth == NULL) { - ENGINE_finish(e); - e = NULL; - } - } - if (e) + ENGINE *e; + + /* If we have an engine that can do RAND, use it. */ + if ((e = ENGINE_get_default_RAND()) != NULL + && (tmp_meth = ENGINE_get_RAND(e)) != NULL) { funct_ref = e; - else + default_RAND_meth = tmp_meth; + } else { + ENGINE_finish(e); + default_RAND_meth = &rand_meth; + } +#else + default_RAND_meth = &rand_meth; #endif - default_RAND_meth = RAND_OpenSSL(); } tmp_meth = default_RAND_meth; CRYPTO_THREAD_unlock(rand_meth_lock); @@ -90,10 +749,10 @@ int RAND_set_rand_engine(ENGINE *engine) { const RAND_METHOD *tmp_meth = NULL; - if (!RUN_ONCE(&rand_lock_init, do_rand_lock_init)) + if (!RUN_ONCE(&rand_init, do_rand_init)) return 0; - if (engine) { + if (engine != NULL) { if (!ENGINE_init(engine)) return 0; tmp_meth = ENGINE_get_RAND(engine); @@ -111,54 +770,73 @@ int RAND_set_rand_engine(ENGINE *engine) } #endif -void rand_cleanup_int(void) -{ - const RAND_METHOD *meth = default_RAND_meth; - if (meth && meth->cleanup) - meth->cleanup(); - RAND_set_rand_method(NULL); - CRYPTO_THREAD_lock_free(rand_meth_lock); -#ifndef OPENSSL_NO_ENGINE - CRYPTO_THREAD_lock_free(rand_engine_lock); -#endif -} - void RAND_seed(const void *buf, int num) { const RAND_METHOD *meth = RAND_get_rand_method(); - if (meth && meth->seed) + + if (meth->seed != NULL) meth->seed(buf, num); } -void RAND_add(const void *buf, int num, double entropy) +void RAND_add(const void *buf, int num, double randomness) { const RAND_METHOD *meth = RAND_get_rand_method(); - if (meth && meth->add) - meth->add(buf, num, entropy); + + if (meth->add != NULL) + meth->add(buf, num, randomness); +} + +/* + * This function is not part of RAND_METHOD, so if we're not using + * the default method, then just call RAND_bytes(). Otherwise make + * sure we're instantiated and use the private DRBG. + */ +int RAND_priv_bytes(unsigned char *buf, int num) +{ + const RAND_METHOD *meth = RAND_get_rand_method(); + RAND_DRBG *drbg; + int ret; + + if (meth != RAND_OpenSSL()) + return RAND_bytes(buf, num); + + drbg = RAND_DRBG_get0_private(); + if (drbg == NULL) + return 0; + + /* We have to lock the DRBG before generating bits from it. */ + rand_drbg_lock(drbg); + ret = RAND_DRBG_bytes(drbg, buf, num); + rand_drbg_unlock(drbg); + return ret; } int RAND_bytes(unsigned char *buf, int num) { const RAND_METHOD *meth = RAND_get_rand_method(); - if (meth && meth->bytes) + + if (meth->bytes != NULL) return meth->bytes(buf, num); - return (-1); + RANDerr(RAND_F_RAND_BYTES, RAND_R_FUNC_NOT_IMPLEMENTED); + return -1; } #if OPENSSL_API_COMPAT < 0x10100000L int RAND_pseudo_bytes(unsigned char *buf, int num) { const RAND_METHOD *meth = RAND_get_rand_method(); - if (meth && meth->pseudorand) + + if (meth->pseudorand != NULL) return meth->pseudorand(buf, num); - return (-1); + return -1; } #endif int RAND_status(void) { const RAND_METHOD *meth = RAND_get_rand_method(); - if (meth && meth->status) + + if (meth->status != NULL) return meth->status(); return 0; } diff --git a/crypto/rand/rand_unix.c b/crypto/rand/rand_unix.c index 7a5a9484..74c82823 100644 --- a/crypto/rand/rand_unix.c +++ b/crypto/rand/rand_unix.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -7,91 +7,81 @@ * https://www.openssl.org/source/license.html */ -#include - -#define USE_SOCKETS #include "e_os.h" +#include #include "internal/cryptlib.h" #include #include "rand_lcl.h" +#include -#if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) +#if (defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)) && \ + !defined(OPENSSL_RAND_SEED_NONE) +# error "UEFI and VXWorks only support seeding NONE" +#endif -# include -# include -# include -# include -# include -# include -# include -# if defined(OPENSSL_SYS_LINUX) /* should actually be available virtually - * everywhere */ -# include -# endif -# include -# ifndef FD_SETSIZE -# define FD_SETSIZE (8*sizeof(fd_set)) -# endif +#if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) \ + || defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_VXWORKS) \ + || defined(OPENSSL_SYS_UEFI)) # if defined(OPENSSL_SYS_VOS) +# ifndef OPENSSL_RAND_SEED_OS +# error "Unsupported seeding method configured; must be os" +# endif + +# if defined(OPENSSL_SYS_VOS_HPPA) && defined(OPENSSL_SYS_VOS_IA32) +# error "Unsupported HP-PA and IA32 at the same time." +# endif +# if !defined(OPENSSL_SYS_VOS_HPPA) && !defined(OPENSSL_SYS_VOS_IA32) +# error "Must have one of HP-PA or IA32" +# endif + /* * 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. + * it can be read. If it 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. This should only be used for legacy + * platforms. * - * 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. + * As a precaution, we assume only 2 bits of entropy per byte. */ - -int RAND_poll(void) +size_t RAND_POOL_acquire_entropy(RAND_POOL *pool) { short int code; gid_t curr_gid; pid_t curr_pid; uid_t curr_uid; int i, k; + size_t bytes_needed; 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 */ +# endif /* * 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); - curr_gid = 0; - + RAND_POOL_add(pool, &curr_gid, sizeof(curr_gid), 0); curr_pid = getpid(); - RAND_add(&curr_pid, sizeof(curr_pid), 1); - curr_pid = 0; - + RAND_POOL_add(pool, &curr_pid, sizeof(curr_pid), 0); curr_uid = getuid(); - RAND_add(&curr_uid, sizeof(curr_uid), 1); - curr_uid = 0; + RAND_POOL_add(pool, &curr_uid, sizeof(curr_uid), 0); - for (i = 0; i < (ENTROPY_NEEDED * 4); i++) { + bytes_needed = RAND_POOL_bytes_needed(pool, 2 /*entropy_per_byte*/); + + for (i = 0; i < bytes_needed; i++) { /* * burn some cpu; hope for interrupts, cache collisions, bus * interference, etc. @@ -104,221 +94,163 @@ int RAND_poll(void) 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 */ +# endif - /* get wall clock time. */ + /* Get wall clock time, take 8 bits. */ clock_gettime(CLOCK_REALTIME, &ts); - - /* take 8 bits */ - v = (unsigned char)(ts.tv_nsec % 256); - RAND_add(&v, sizeof(v), 1); - v = 0; + v = (unsigned char)(ts.tv_nsec & 0xFF); + RAND_POOL_add(pool, arg, &v, sizeof(v) , 2); } - return 1; + return RAND_POOL_entropy_available(pool); } -# 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; +# else + +# if defined(OPENSSL_RAND_SEED_EGD) && \ + (defined(OPENSSL_NO_EGD) || !defined(DEVRANDOM_EGD)) +# error "Seeding uses EGD but EGD is turned off or no device given" +# endif + +# if defined(OPENSSL_RAND_SEED_DEVRANDOM) && !defined(DEVRANDOM) +# error "Seeding uses urandom but DEVRANDOM is not configured" +# endif + +# if defined(OPENSSL_RAND_SEED_OS) +# if !defined(DEVRANDOM) +# error "OS seeding requires DEVRANDOM to be configured" +# endif +# define OPENSSL_RAND_SEED_DEVRANDOM +# if defined(__GLIBC__) && defined(__GLIBC_PREREQ) +# if __GLIBC_PREREQ(2, 25) +# define OPENSSL_RAND_SEED_GETRANDOM +# endif +# endif +# endif + +# ifdef OPENSSL_RAND_SEED_GETRANDOM +# include +# endif + +# if defined(OPENSSL_RAND_SEED_LIBRANDOM) +# error "librandom not (yet) supported" +# endif + +/* + * Try the various seeding methods in turn, exit when successful. + * + * TODO(DRBG): If more than one entropy source is available, is it + * preferable to stop as soon as enough entropy has been collected + * (as favored by @rsalz) or should one rather be defensive and add + * more entropy than requested and/or from different sources? + * + * Currently, the user can select multiple entropy sources in the + * configure step, yet in practice only the first available source + * will be used. A more flexible solution has been requested, but + * currently it is not clear how this can be achieved without + * overengineering the problem. There are many parameters which + * could be taken into account when selecting the order and amount + * of input from the different entropy sources (trust, quality, + * possibility of blocking). + */ +size_t RAND_POOL_acquire_entropy(RAND_POOL *pool) +{ +# ifdef OPENSSL_RAND_SEED_NONE + return RAND_POOL_entropy_available(pool); +# else + size_t bytes_needed; + size_t entropy_available = 0; + unsigned char *buffer; + +# ifdef OPENSSL_RAND_SEED_GETRANDOM + bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/); + buffer = RAND_POOL_add_begin(pool, bytes_needed); + if (buffer != NULL) { + size_t bytes = 0; + + if (getrandom(buffer, bytes_needed, 0) == (int)bytes_needed) + bytes = bytes_needed; + + entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes); } - 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(OPENSS_NO_EGD) && defined(DEVRANDOM_EGD)) - unsigned char tmpbuf[ENTROPY_NEEDED]; - int n = 0; -# endif -# ifdef DEVRANDOM - static const char *randomfiles[] = { DEVRANDOM }; - struct stat randomstats[OSSL_NELEM(randomfiles)]; - int fd; - unsigned int i; -# endif -# if !defined(OPENSSL_NO_EGD) && defined(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 < OSSL_NELEM(randomfiles)) && (n < ENTROPY_NEEDED); i++) { - if ((fd = open(randomfiles[i], O_RDONLY -# ifdef O_NONBLOCK - | O_NONBLOCK + if (entropy_available > 0) + return entropy_available; # 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); +# if defined(OPENSSL_RAND_SEED_LIBRANDOM) + { + /* Not yet implemented. */ + } +# endif + +# ifdef OPENSSL_RAND_SEED_DEVRANDOM + bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/); + if (bytes_needed > 0) { + static const char *paths[] = { DEVRANDOM, NULL }; + FILE *fp; + int i; + + for (i = 0; paths[i] != NULL; i++) { + if ((fp = fopen(paths[i], "rb")) == NULL) continue; + setbuf(fp, NULL); + buffer = RAND_POOL_add_begin(pool, bytes_needed); + if (buffer != NULL) { + size_t bytes = 0; + if (fread(buffer, 1, bytes_needed, fp) == bytes_needed) + bytes = bytes_needed; + + entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes); } + fclose(fp); + if (entropy_available > 0) + return entropy_available; - do { - int try_read = 0; - -# if 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; - } 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); + bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/); } } -# endif /* defined(DEVRANDOM) */ +# endif -# if !defined(OPENSSL_NO_EGD) && defined(DEVRANDOM_EGD) - /* - * Use an EGD socket to read entropy from an EGD or PRNGD entropy - * collecting daemon. - */ +# ifdef OPENSSL_RAND_SEED_RDTSC + entropy_available = rand_acquire_entropy_from_tsc(pool); + if (entropy_available > 0) + return entropy_available; +# endif - for (egdsocket = egdsockets; *egdsocket && n < ENTROPY_NEEDED; - egdsocket++) { - int r; +# ifdef OPENSSL_RAND_SEED_RDCPU + entropy_available = rand_acquire_entropy_from_cpu(pool); + if (entropy_available > 0) + return entropy_available; +# endif - r = RAND_query_egd_bytes(*egdsocket, (unsigned char *)tmpbuf + n, - ENTROPY_NEEDED - n); - if (r > 0) - n += r; +# ifdef OPENSSL_RAND_SEED_EGD + bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/); + if (bytes_needed > 0) { + static const char *paths[] = { DEVRANDOM_EGD, NULL }; + int i; + + for (i = 0; paths[i] != NULL; i++) { + buffer = RAND_POOL_add_begin(pool, bytes_needed); + if (buffer != NULL) { + size_t bytes = 0; + int num = RAND_query_egd_bytes(paths[i], + buffer, (int)bytes_needed); + if (num == (int)bytes_needed) + bytes = bytes_needed; + + entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes); + } + if (entropy_available > 0) + return entropy_available; + } } -# endif /* defined(DEVRANDOM_EGD) */ +# endif -# if defined(DEVRANDOM) || (!defined(OPENSSL_NO_EGD) && defined(DEVRANDOM_EGD)) - if (n > 0) { - 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(DEVRANDOM) || (!defined(OPENSSL_NO_EGD) && defined(DEVRANDOM_EGD)) - return 1; -# else - return 0; + return RAND_POOL_entropy_available(pool); # endif } +# endif -# endif /* defined(__OpenBSD__) */ -#endif /* !(defined(OPENSSL_SYS_WINDOWS) || - * defined(OPENSSL_SYS_WIN32) || - * defined(OPENSSL_SYS_VMS) || - * defined(OPENSSL_SYS_VXWORKS) */ - -#if defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI) -int RAND_poll(void) -{ - return 0; -} #endif diff --git a/crypto/rand/rand_vms.c b/crypto/rand/rand_vms.c index 9c462dd3..4ec4b35b 100644 --- a/crypto/rand/rand_vms.c +++ b/crypto/rand/rand_vms.c @@ -1,5 +1,5 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-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 @@ -7,16 +7,11 @@ * https://www.openssl.org/source/license.html */ -/* - * Modified by VMS Software, Inc (2016) - * Eliminate looping through all processes (performance) - * Add additional randomizations using rand() function - */ - -#include -#include "rand_lcl.h" +#include "e_os.h" #if defined(OPENSSL_SYS_VMS) +# include +# include "rand_lcl.h" # include # include # include @@ -26,6 +21,10 @@ # pragma message disable DOLLARID # endif +# ifndef OPENSSL_RAND_SEED_OS +# error "Unsupported seeding method configured; must be os" +# endif + /* * Use 32-bit pointers almost everywhere. Define the type to which to cast a * pointer passed to an external function. @@ -34,9 +33,9 @@ # define PTR_T __void_ptr64 # pragma pointer_size save # pragma pointer_size 32 -# else /* __INITIAL_POINTER_SIZE == 64 */ +# else # define PTR_T void * -# endif /* __INITIAL_POINTER_SIZE == 64 [else] */ +# endif static struct items_data_st { short length, code; /* length is number of bytes */ @@ -52,27 +51,22 @@ static struct items_data_st { {4, JPI$_PPGCNT}, {4, JPI$_WSPEAK}, {4, JPI$_FINALEXC}, - {0, 0} /* zero terminated */ + {0, 0} }; -int RAND_poll(void) +size_t RAND_POOL_acquire_entropy(RAND_POOL *pool) { - /* determine the number of items in the JPI array */ - struct items_data_st item_entry; - int item_entry_count = sizeof(items_data)/sizeof(item_entry); - + int item_entry_count = OSSL_NELEM(items_data); /* Create the JPI itemlist array to hold item_data content */ - struct { short length, code; int *buffer; int *retlen; - } item[item_entry_count], *pitem; /* number of entries in items_data */ - + } item[item_entry_count], *pitem; struct items_data_st *pitems_data; - int data_buffer[(item_entry_count*2)+4]; /* 8 bytes per entry max */ + int data_buffer[(item_entry_count * 2) + 4]; /* 8 bytes per entry max */ int iosb[2]; int sys_time[2]; int *ptr; @@ -80,54 +74,52 @@ int RAND_poll(void) int tmp_length = 0; int total_length = 0; - pitems_data = items_data; - pitem = item; - - /* Setup itemlist for GETJPI */ - while (pitems_data->length) { + pitems_data = items_data; + for (pitem = item; pitems_data->length != 0; pitem++) { pitem->length = pitems_data->length; pitem->code = pitems_data->code; pitem->buffer = &data_buffer[total_length]; pitem->retlen = 0; /* total_length is in longwords */ - total_length += pitems_data->length/4; + total_length += pitems_data->length / 4; pitems_data++; - pitem ++; } pitem->length = pitem->code = 0; /* Fill data_buffer with various info bits from this process */ - /* and twist that data to seed the SSL random number init */ - - if (sys$getjpiw(EFN$C_ENF, NULL, NULL, item, &iosb, 0, 0) == SS$_NORMAL) { - for (i = 0; i < total_length; i++) { - sys$gettim((struct _generic_64 *)&sys_time[0]); - srand(sys_time[0] * data_buffer[0] * data_buffer[1] + i); - - if (i == (total_length - 1)) { /* for JPI$_FINALEXC */ - ptr = &data_buffer[i]; - for (j = 0; j < 4; j++) { - data_buffer[i + j] = ptr[j]; - /* OK to use rand() just to scramble the seed */ - data_buffer[i + j] ^= (sys_time[0] ^ rand()); - tmp_length++; - } - } else { - /* OK to use rand() just to scramble the seed */ - data_buffer[i] ^= (sys_time[0] ^ rand()); - } - } - - total_length += (tmp_length - 1); - - /* size of seed is total_length*4 bytes (64bytes) */ - RAND_add((PTR_T) data_buffer, total_length*4, total_length * 2); - } else { + if (sys$getjpiw(EFN$C_ENF, NULL, NULL, item, &iosb, 0, 0) != SS$_NORMAL) return 0; + + /* Now twist that data to seed the SSL random number init */ + for (i = 0; i < total_length; i++) { + sys$gettim((struct _generic_64 *)&sys_time[0]); + srand(sys_time[0] * data_buffer[0] * data_buffer[1] + i); + + if (i == (total_length - 1)) { /* for JPI$_FINALEXC */ + ptr = &data_buffer[i]; + for (j = 0; j < 4; j++) { + data_buffer[i + j] = ptr[j]; + /* OK to use rand() just to scramble the seed */ + data_buffer[i + j] ^= (sys_time[0] ^ rand()); + tmp_length++; + } + } else { + /* OK to use rand() just to scramble the seed */ + data_buffer[i] ^= (sys_time[0] ^ rand()); + } } - return 1; + total_length += (tmp_length - 1); + + /* + * Size of seed is total_length*4 bytes (64bytes). The original assumption + * was that it contains 4 bits of entropy per byte. This makes a total + * amount of total_length*16 bits (256bits). + */ + return RAND_POOL_add(pool, + (PTR_T)data_buffer, total_length * 4, + total_length * 16); } #endif diff --git a/crypto/rand/rand_win.c b/crypto/rand/rand_win.c index 1be0ed3c..9eff319b 100644 --- a/crypto/rand/rand_win.c +++ b/crypto/rand/rand_win.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -10,15 +10,19 @@ #include "internal/cryptlib.h" #include #include "rand_lcl.h" - #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) -# include -/* On Windows 7 or higher use BCrypt instead of the legacy CryptoAPI */ -# if defined(_MSC_VER) && defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0601 -# define RAND_WINDOWS_USE_BCRYPT + +# ifndef OPENSSL_RAND_SEED_OS +# error "Unsupported seeding method configured; must be os" # endif -# ifdef RAND_WINDOWS_USE_BCRYPT +# include +/* On Windows 7 or higher use BCrypt instead of the legacy CryptoAPI */ +# if defined(_MSC_VER) && defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0601 +# define USE_BCRYPTGENRANDOM +# endif + +# ifdef USE_BCRYPTGENRANDOM # include # pragma comment(lib, "bcrypt.lib") # ifndef STATUS_SUCCESS @@ -34,55 +38,83 @@ # define INTEL_DEF_PROV L"Intel Hardware Cryptographic Service Provider" # endif -static void readtimer(void); - -int RAND_poll(void) +size_t RAND_POOL_acquire_entropy(RAND_POOL *pool) { - MEMORYSTATUS mst; -# ifndef RAND_WINDOWS_USE_BCRYPT +# ifndef USE_BCRYPTGENRANDOM HCRYPTPROV hProvider; # endif - DWORD w; - BYTE buf[64]; + unsigned char *buffer; + size_t bytes_needed; + size_t entropy_available = 0; -# ifdef RAND_WINDOWS_USE_BCRYPT - if (BCryptGenRandom(NULL, buf, (ULONG)sizeof(buf), BCRYPT_USE_SYSTEM_PREFERRED_RNG) == STATUS_SUCCESS) { - RAND_add(buf, sizeof(buf), sizeof(buf)); - } -# else - /* poll the CryptoAPI PRNG */ - /* The CryptoAPI returns sizeof(buf) bytes of randomness */ - if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { - if (CryptGenRandom(hProvider, (DWORD)sizeof(buf), buf) != 0) { - RAND_add(buf, sizeof(buf), sizeof(buf)); - } - CryptReleaseContext(hProvider, 0); - } - /* poll the Pentium PRG with CryptoAPI */ - if (CryptAcquireContextW(&hProvider, NULL, INTEL_DEF_PROV, PROV_INTEL_SEC, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { - if (CryptGenRandom(hProvider, (DWORD)sizeof(buf), buf) != 0) { - RAND_add(buf, sizeof(buf), sizeof(buf)); - } - CryptReleaseContext(hProvider, 0); - } +# ifdef OPENSSL_RAND_SEED_RDTSC + entropy_available = rand_acquire_entropy_from_tsc(pool); + if (entropy_available > 0) + return entropy_available; # endif - /* timer data */ - readtimer(); +# ifdef OPENSSL_RAND_SEED_RDCPU + entropy_available = rand_acquire_entropy_from_cpu(pool); + if (entropy_available > 0) + return entropy_available; +# endif - /* memory usage statistics */ - GlobalMemoryStatus(&mst); - RAND_add(&mst, sizeof(mst), 1); +# ifdef USE_BCRYPTGENRANDOM + bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/); + buffer = RAND_POOL_add_begin(pool, bytes_needed); + if (buffer != NULL) { + size_t bytes = 0; + if (BCryptGenRandom(NULL, buffer, bytes_needed, + BCRYPT_USE_SYSTEM_PREFERRED_RNG) == STATUS_SUCCESS) + bytes = bytes_needed; - /* process ID */ - w = GetCurrentProcessId(); - RAND_add(&w, sizeof(w), 1); + entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes); + } + if (entropy_available > 0) + return entropy_available; +# else + bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/); + buffer = RAND_POOL_add_begin(pool, bytes_needed); + if (buffer != NULL) { + size_t bytes = 0; + /* poll the CryptoAPI PRNG */ + if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT) != 0) { + if (CryptGenRandom(hProvider, bytes_needed, buffer) != 0) + bytes = bytes_needed; - return (1); + CryptReleaseContext(hProvider, 0); + } + + entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes); + } + if (entropy_available > 0) + return entropy_available; + + bytes_needed = RAND_POOL_bytes_needed(pool, 8 /*entropy_per_byte*/); + buffer = RAND_POOL_add_begin(pool, bytes_needed); + if (buffer != NULL) { + size_t bytes = 0; + /* poll the Pentium PRG with CryptoAPI */ + if (CryptAcquireContextW(&hProvider, NULL, + INTEL_DEF_PROV, PROV_INTEL_SEC, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT) != 0) { + if (CryptGenRandom(hProvider, bytes_needed, buffer) != 0) + bytes = bytes_needed; + + CryptReleaseContext(hProvider, 0); + } + entropy_available = RAND_POOL_add_end(pool, bytes, 8 * bytes); + } + if (entropy_available > 0) + return entropy_available; +# endif + + return RAND_POOL_entropy_available(pool); } -#if OPENSSL_API_COMPAT < 0x10100000L +# if OPENSSL_API_COMPAT < 0x10100000L int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam) { RAND_poll(); @@ -93,43 +125,6 @@ void RAND_screen(void) { RAND_poll(); } -#endif - -/* feed timing information to the PRNG */ -static void readtimer(void) -{ - DWORD w; - LARGE_INTEGER l; - static int have_perfc = 1; -# if defined(_MSC_VER) && defined(_M_X86) - static int have_tsc = 1; - DWORD cyclecount; - - if (have_tsc) { - __try { - __asm { - _emit 0x0f _emit 0x31 mov cyclecount, eax} - RAND_add(&cyclecount, sizeof(cyclecount), 1); - } - __except(EXCEPTION_EXECUTE_HANDLER) { - have_tsc = 0; - } - } -# else -# define have_tsc 0 # endif - if (have_perfc) { - if (QueryPerformanceCounter(&l) == 0) - have_perfc = 0; - else - RAND_add(&l, sizeof(l), 0); - } - - if (!have_tsc && !have_perfc) { - w = GetTickCount(); - RAND_add(&w, sizeof(w), 0); - } -} - #endif diff --git a/crypto/rand/randfile.c b/crypto/rand/randfile.c index dbd03ff2..d4edc50b 100644 --- a/crypto/rand/randfile.c +++ b/crypto/rand/randfile.c @@ -25,6 +25,11 @@ #ifndef OPENSSL_NO_POSIX_IO # include # include +# ifdef _WIN32 +# include +# endif +#endif + /* * Following should not be needed, and we could have been stricter * and demand S_IS*. But some systems just don't comply... Formally @@ -32,184 +37,106 @@ * would look like ((m) & MASK == TYPE), but since MASK availability * is as questionable, we settle for this poor-man fallback... */ -# if !defined(S_ISBLK) -# if defined(_S_IFBLK) -# define S_ISBLK(m) ((m) & _S_IFBLK) -# elif defined(S_IFBLK) -# define S_ISBLK(m) ((m) & S_IFBLK) -# elif defined(_WIN32) -# define S_ISBLK(m) 0 /* no concept of block devices on Windows */ -# endif +# if !defined(S_ISREG) +# define S_ISREG(m) ((m) & S_IFREG) # endif -# if !defined(S_ISCHR) -# if defined(_S_IFCHR) -# define S_ISCHR(m) ((m) & _S_IFCHR) -# elif defined(S_IFCHR) -# define S_ISCHR(m) ((m) & S_IFCHR) -# endif -# endif -#endif #ifdef _WIN32 # define stat _stat # define chmod _chmod # define open _open # define fdopen _fdopen -# define fstat _fstat -# define fileno _fileno #endif -#undef BUFSIZE -#define BUFSIZE 1024 -#define RAND_DATA 1024 +#define RAND_FILE_SIZE 1024 +#define RFILE ".rnd" #ifdef OPENSSL_SYS_VMS /* - * Misc hacks needed for specific cases. - * * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically) * to make sure the FILE* is a 32-bit pointer no matter what. We know that - * stdio function return this type (a study of stdio.h proves it). - * Additionally, we create a similar char pointer type for the sake of - * vms_setbuf below. - */ -# if __INITIAL_POINTER_SIZE == 64 -# pragma pointer_size save -# pragma pointer_size 32 -typedef char *char_ptr32; -# pragma pointer_size restore -/* - * On VMS, setbuf() will only take 32-bit pointers, and a compilation - * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here. - * Since we know that the FILE* really is a 32-bit pointer expanded to - * 64 bits, we also know it's safe to convert it back to a 32-bit pointer. - * As for the buffer parameter, we only use NULL here, so that passes as - * well... - */ -# define setbuf(fp,buf) (setbuf)((__FILE_ptr32)(fp), (char_ptr32)(buf)) -# endif - -/* + * stdio functions return this type (a study of stdio.h proves it). + * * This declaration is a nasty hack to get around vms' extension to fopen for * passing in sharing options being disabled by /STANDARD=ANSI89 */ static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) = - (__FILE_ptr32 (*)(const char *, const char *, ...))fopen; -# define VMS_OPEN_ATTRS "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0" - -# define openssl_fopen(fname,mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS) + (__FILE_ptr32 (*)(const char *, const char *, ...))fopen; +# define VMS_OPEN_ATTRS \ + "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0" +# define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS) #endif -#define RFILE ".rnd" - /* * Note that these functions are intended for seed files only. Entropy - * devices and EGD sockets are handled in rand_unix.c + * devices and EGD sockets are handled in rand_unix.c If |bytes| is + * -1 read the complete file; otherwise read the specified amount. */ - int RAND_load_file(const char *file, long bytes) { - /*- - * If bytes >= 0, read up to 'bytes' bytes. - * if bytes == -1, read complete file. - */ - - unsigned char buf[BUFSIZE]; + unsigned char buf[RAND_FILE_SIZE]; #ifndef OPENSSL_NO_POSIX_IO struct stat sb; #endif - int i, ret = 0, n; - FILE *in = NULL; - - if (file == NULL) - return 0; + int i, n, ret = 0; + FILE *in; if (bytes == 0) - return ret; - - in = openssl_fopen(file, "rb"); - if (in == NULL) - goto err; + return 0; #ifndef OPENSSL_NO_POSIX_IO - /* - * struct stat can have padding and unused fields that may not be - * initialized in the call to stat(). We need to clear the entire - * structure before calling RAND_add() to avoid complaints from - * applications such as Valgrind. - */ - memset(&sb, 0, sizeof(sb)); - if (fstat(fileno(in), &sb) < 0) - goto err; - RAND_add(&sb, sizeof(sb), 0.0); - -# if defined(S_ISBLK) && defined(S_ISCHR) - if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) { - /* - * this file is a device. we don't want read an infinite number of - * bytes from a random device, nor do we want to use buffered I/O - * because we will waste system entropy. - */ - bytes = (bytes == -1) ? 2048 : bytes; /* ok, is 2048 enough? */ - setbuf(in, NULL); /* don't do buffered reads */ + if (stat(file, &sb) < 0 || !S_ISREG(sb.st_mode)) { + RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_NOT_A_REGULAR_FILE); + ERR_add_error_data(2, "Filename=", file); + return -1; } -# endif #endif - for (;;) { + if ((in = openssl_fopen(file, "rb")) == NULL) { + RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_CANNOT_OPEN_FILE); + ERR_add_error_data(2, "Filename=", file); + return -1; + } + + for ( ; ; ) { if (bytes > 0) - n = (bytes < BUFSIZE) ? (int)bytes : BUFSIZE; + n = (bytes < RAND_FILE_SIZE) ? (int)bytes : RAND_FILE_SIZE; else - n = BUFSIZE; + n = RAND_FILE_SIZE; i = fread(buf, 1, n, in); if (i <= 0) break; - RAND_add(buf, i, (double)i); ret += i; - if (bytes > 0) { - bytes -= n; - if (bytes <= 0) - break; - } + + /* If given a bytecount, and we did it, break. */ + if (bytes > 0 && (bytes -= i) <= 0) + break; } - OPENSSL_cleanse(buf, BUFSIZE); - err: - if (in != NULL) - fclose(in); + + OPENSSL_cleanse(buf, sizeof(buf)); + fclose(in); return ret; } int RAND_write_file(const char *file) { - unsigned char buf[BUFSIZE]; - int i, ret = 0, rand_err = 0; + unsigned char buf[RAND_FILE_SIZE]; + int ret = -1; FILE *out = NULL; - int n; #ifndef OPENSSL_NO_POSIX_IO struct stat sb; -# if defined(S_ISBLK) && defined(S_ISCHR) -# ifdef _WIN32 - /* - * Check for |file| being a driver as "ASCII-safe" on Windows, - * because driver paths are always ASCII. - */ -# endif - i = stat(file, &sb); - if (i != -1) { - if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) { - /* - * this file is a device. we don't write back to it. we - * "succeed" on the assumption this is some sort of random - * device. Otherwise attempting to write to and chmod the device - * causes problems. - */ - return 1; - } + if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) { + RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_NOT_A_REGULAR_FILE); + ERR_add_error_data(2, "Filename=", file); + return -1; } -# endif #endif + /* Collect enough random data. */ + if (RAND_bytes(buf, (int)sizeof(buf)) != 1) + return -1; + #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \ !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS) { @@ -244,69 +171,57 @@ int RAND_write_file(const char *file) * application level. Also consider whether or not you NEED a persistent * rand file in a concurrent use situation. */ - out = openssl_fopen(file, "rb+"); #endif + if (out == NULL) out = openssl_fopen(file, "wb"); - if (out == NULL) - goto err; - -#if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO) - chmod(file, 0600); -#endif - n = RAND_DATA; - for (;;) { - i = (n > BUFSIZE) ? BUFSIZE : n; - n -= BUFSIZE; - if (RAND_bytes(buf, i) <= 0) - rand_err = 1; - i = fwrite(buf, 1, i, out); - if (i <= 0) { - ret = 0; - break; - } - ret += i; - if (n <= 0) - break; + if (out == NULL) { + RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_CANNOT_OPEN_FILE); + ERR_add_error_data(2, "Filename=", file); + return -1; } +#if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO) + /* + * Yes it's late to do this (see above comment), but better than nothing. + */ + chmod(file, 0600); +#endif + + ret = fwrite(buf, 1, RAND_FILE_SIZE, out); fclose(out); - OPENSSL_cleanse(buf, BUFSIZE); - err: - return (rand_err ? -1 : ret); + OPENSSL_cleanse(buf, RAND_FILE_SIZE); + return ret; } const char *RAND_file_name(char *buf, size_t size) { char *s = NULL; + size_t len; int use_randfile = 1; -#ifdef __OpenBSD__ - struct stat sb; -#endif #if defined(_WIN32) && defined(CP_UTF8) - DWORD len; - WCHAR *var, *val; + DWORD envlen; + WCHAR *var; - if ((var = L"RANDFILE", - len = GetEnvironmentVariableW(var, NULL, 0)) == 0 - && (var = L"HOME", use_randfile = 0, - len = GetEnvironmentVariableW(var, NULL, 0)) == 0 - && (var = L"USERPROFILE", - len = GetEnvironmentVariableW(var, NULL, 0)) == 0) { - var = L"SYSTEMROOT", - len = GetEnvironmentVariableW(var, NULL, 0); + /* Look up various environment variables. */ + if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) { + use_randfile = 0; + if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0 + && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE", + NULL, 0)) == 0) + envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0); } - if (len != 0) { + /* If we got a value, allocate space to hold it and then get it. */ + if (envlen != 0) { int sz; + WCHAR *val = _alloca(envlen * sizeof(WCHAR)); - val = _alloca(len * sizeof(WCHAR)); - - if (GetEnvironmentVariableW(var, val, len) < len - && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0, - NULL, NULL)) != 0) { + if (GetEnvironmentVariableW(var, val, envlen) < envlen + && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0, + NULL, NULL)) != 0) { s = _alloca(sz); if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz, NULL, NULL) == 0) @@ -316,49 +231,33 @@ const char *RAND_file_name(char *buf, size_t size) #else if (OPENSSL_issetugid() != 0) { use_randfile = 0; - } else { - s = getenv("RANDFILE"); - if (s == NULL || *s == '\0') { - use_randfile = 0; - s = getenv("HOME"); - } + } else if ((s = getenv("RANDFILE")) == NULL || *s == '\0') { + use_randfile = 0; + s = getenv("HOME"); } #endif + #ifdef DEFAULT_HOME - if (!use_randfile && s == NULL) { + if (!use_randfile && s == NULL) s = DEFAULT_HOME; - } #endif - if (s != NULL && *s) { - size_t len = strlen(s); + if (s == NULL || *s == '\0') + return NULL; - if (use_randfile && len + 1 < size) { - if (OPENSSL_strlcpy(buf, s, size) >= size) - return NULL; - } else if (len + strlen(RFILE) + 2 < size) { - OPENSSL_strlcpy(buf, s, size); -#ifndef OPENSSL_SYS_VMS - OPENSSL_strlcat(buf, "/", size); -#endif - OPENSSL_strlcat(buf, RFILE, size); - } - } else { - buf[0] = '\0'; /* no file name */ - } - -#ifdef __OpenBSD__ - /* - * given that all random loads just fail if the file can't be seen on a - * stat, we stat the file we're returning, if it fails, use /dev/arandom - * instead. this allows the user to use their own source for good random - * data, but defaults to something hopefully decent if that isn't - * available. - */ - - if (!buf[0] || stat(buf, &sb) == -1) - if (OPENSSL_strlcpy(buf, "/dev/arandom", size) >= size) { + len = strlen(s); + if (use_randfile) { + if (len + 1 >= size) return NULL; - } + strcpy(buf, s); + } else { + if (len + 1 + strlen(RFILE) + 1 >= size) + return NULL; + strcpy(buf, s); +#ifndef OPENSSL_SYS_VMS + strcat(buf, "/"); #endif - return buf[0] ? buf : NULL; + strcat(buf, RFILE); + } + + return buf; } diff --git a/crypto/rc2/rc2_ecb.c b/crypto/rc2/rc2_ecb.c index b87931f2..fb2f7827 100644 --- a/crypto/rc2/rc2_ecb.c +++ b/crypto/rc2/rc2_ecb.c @@ -14,7 +14,6 @@ /*- * RC2 as implemented frm a posting from * Newsgroups: sci.crypt - * Sender: pgut01@cs.auckland.ac.nz (Peter Gutmann) * Subject: Specification for Ron Rivests Cipher No.2 * Message-ID: <4fk39f$f70@net.auckland.ac.nz> * Date: 11 Feb 1996 06:45:03 GMT diff --git a/crypto/rc2/tab.c b/crypto/rc2/tab.c deleted file mode 100644 index bc95dc40..00000000 --- a/crypto/rc2/tab.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 1998-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 - */ - -#include - -unsigned char ebits_to_num[256] = { - 0xbd, 0x56, 0xea, 0xf2, 0xa2, 0xf1, 0xac, 0x2a, - 0xb0, 0x93, 0xd1, 0x9c, 0x1b, 0x33, 0xfd, 0xd0, - 0x30, 0x04, 0xb6, 0xdc, 0x7d, 0xdf, 0x32, 0x4b, - 0xf7, 0xcb, 0x45, 0x9b, 0x31, 0xbb, 0x21, 0x5a, - 0x41, 0x9f, 0xe1, 0xd9, 0x4a, 0x4d, 0x9e, 0xda, - 0xa0, 0x68, 0x2c, 0xc3, 0x27, 0x5f, 0x80, 0x36, - 0x3e, 0xee, 0xfb, 0x95, 0x1a, 0xfe, 0xce, 0xa8, - 0x34, 0xa9, 0x13, 0xf0, 0xa6, 0x3f, 0xd8, 0x0c, - 0x78, 0x24, 0xaf, 0x23, 0x52, 0xc1, 0x67, 0x17, - 0xf5, 0x66, 0x90, 0xe7, 0xe8, 0x07, 0xb8, 0x60, - 0x48, 0xe6, 0x1e, 0x53, 0xf3, 0x92, 0xa4, 0x72, - 0x8c, 0x08, 0x15, 0x6e, 0x86, 0x00, 0x84, 0xfa, - 0xf4, 0x7f, 0x8a, 0x42, 0x19, 0xf6, 0xdb, 0xcd, - 0x14, 0x8d, 0x50, 0x12, 0xba, 0x3c, 0x06, 0x4e, - 0xec, 0xb3, 0x35, 0x11, 0xa1, 0x88, 0x8e, 0x2b, - 0x94, 0x99, 0xb7, 0x71, 0x74, 0xd3, 0xe4, 0xbf, - 0x3a, 0xde, 0x96, 0x0e, 0xbc, 0x0a, 0xed, 0x77, - 0xfc, 0x37, 0x6b, 0x03, 0x79, 0x89, 0x62, 0xc6, - 0xd7, 0xc0, 0xd2, 0x7c, 0x6a, 0x8b, 0x22, 0xa3, - 0x5b, 0x05, 0x5d, 0x02, 0x75, 0xd5, 0x61, 0xe3, - 0x18, 0x8f, 0x55, 0x51, 0xad, 0x1f, 0x0b, 0x5e, - 0x85, 0xe5, 0xc2, 0x57, 0x63, 0xca, 0x3d, 0x6c, - 0xb4, 0xc5, 0xcc, 0x70, 0xb2, 0x91, 0x59, 0x0d, - 0x47, 0x20, 0xc8, 0x4f, 0x58, 0xe0, 0x01, 0xe2, - 0x16, 0x38, 0xc4, 0x6f, 0x3b, 0x0f, 0x65, 0x46, - 0xbe, 0x7e, 0x2d, 0x7b, 0x82, 0xf9, 0x40, 0xb5, - 0x1d, 0x73, 0xf8, 0xeb, 0x26, 0xc7, 0x87, 0x97, - 0x25, 0x54, 0xb1, 0x28, 0xaa, 0x98, 0x9d, 0xa5, - 0x64, 0x6d, 0x7a, 0xd4, 0x10, 0x81, 0x44, 0xef, - 0x49, 0xd6, 0xae, 0x2e, 0xdd, 0x76, 0x5c, 0x2f, - 0xa7, 0x1c, 0xc9, 0x09, 0x69, 0x9a, 0x83, 0xcf, - 0x29, 0x39, 0xb9, 0xe9, 0x4c, 0xff, 0x43, 0xab, -}; - -unsigned char num_to_ebits[256] = { - 0x5d, 0xbe, 0x9b, 0x8b, 0x11, 0x99, 0x6e, 0x4d, - 0x59, 0xf3, 0x85, 0xa6, 0x3f, 0xb7, 0x83, 0xc5, - 0xe4, 0x73, 0x6b, 0x3a, 0x68, 0x5a, 0xc0, 0x47, - 0xa0, 0x64, 0x34, 0x0c, 0xf1, 0xd0, 0x52, 0xa5, - 0xb9, 0x1e, 0x96, 0x43, 0x41, 0xd8, 0xd4, 0x2c, - 0xdb, 0xf8, 0x07, 0x77, 0x2a, 0xca, 0xeb, 0xef, - 0x10, 0x1c, 0x16, 0x0d, 0x38, 0x72, 0x2f, 0x89, - 0xc1, 0xf9, 0x80, 0xc4, 0x6d, 0xae, 0x30, 0x3d, - 0xce, 0x20, 0x63, 0xfe, 0xe6, 0x1a, 0xc7, 0xb8, - 0x50, 0xe8, 0x24, 0x17, 0xfc, 0x25, 0x6f, 0xbb, - 0x6a, 0xa3, 0x44, 0x53, 0xd9, 0xa2, 0x01, 0xab, - 0xbc, 0xb6, 0x1f, 0x98, 0xee, 0x9a, 0xa7, 0x2d, - 0x4f, 0x9e, 0x8e, 0xac, 0xe0, 0xc6, 0x49, 0x46, - 0x29, 0xf4, 0x94, 0x8a, 0xaf, 0xe1, 0x5b, 0xc3, - 0xb3, 0x7b, 0x57, 0xd1, 0x7c, 0x9c, 0xed, 0x87, - 0x40, 0x8c, 0xe2, 0xcb, 0x93, 0x14, 0xc9, 0x61, - 0x2e, 0xe5, 0xcc, 0xf6, 0x5e, 0xa8, 0x5c, 0xd6, - 0x75, 0x8d, 0x62, 0x95, 0x58, 0x69, 0x76, 0xa1, - 0x4a, 0xb5, 0x55, 0x09, 0x78, 0x33, 0x82, 0xd7, - 0xdd, 0x79, 0xf5, 0x1b, 0x0b, 0xde, 0x26, 0x21, - 0x28, 0x74, 0x04, 0x97, 0x56, 0xdf, 0x3c, 0xf0, - 0x37, 0x39, 0xdc, 0xff, 0x06, 0xa4, 0xea, 0x42, - 0x08, 0xda, 0xb4, 0x71, 0xb0, 0xcf, 0x12, 0x7a, - 0x4e, 0xfa, 0x6c, 0x1d, 0x84, 0x00, 0xc8, 0x7f, - 0x91, 0x45, 0xaa, 0x2b, 0xc2, 0xb1, 0x8f, 0xd5, - 0xba, 0xf2, 0xad, 0x19, 0xb2, 0x67, 0x36, 0xf7, - 0x0f, 0x0a, 0x92, 0x7d, 0xe3, 0x9d, 0xe9, 0x90, - 0x3e, 0x23, 0x27, 0x66, 0x13, 0xec, 0x81, 0x15, - 0xbd, 0x22, 0xbf, 0x9f, 0x7e, 0xa9, 0x51, 0x4b, - 0x4c, 0xfb, 0x02, 0xd3, 0x70, 0x86, 0x31, 0xe7, - 0x3b, 0x05, 0x03, 0x54, 0x60, 0x48, 0x65, 0x18, - 0xd2, 0xcd, 0x5f, 0x32, 0x88, 0x0e, 0x35, 0xfd, -}; - -main() -{ - int i, j; - - for (i = 0; i < 256; i++) { - for (j = 0; j < 256; j++) - if (ebits_to_num[j] == i) { - printf("0x%02x,", j); - break; - } - } -} diff --git a/crypto/rc4/asm/rc4-586.pl b/crypto/rc4/asm/rc4-586.pl index 7d6f97c5..8c5cf87d 100644 --- a/crypto/rc4/asm/rc4-586.pl +++ b/crypto/rc4/asm/rc4-586.pl @@ -8,7 +8,7 @@ # ==================================================================== -# [Re]written by Andy Polyakov for the OpenSSL +# [Re]written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -32,8 +32,6 @@ # performance on the same Opteron machine. # (**) This number requires compressed key schedule set up by # RC4_set_key [see commentary below for further details]. -# -# # May 2011 # @@ -73,7 +71,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"rc4-586.pl",$x86only = $ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$x86only = $ARGV[$#ARGV] eq "386"); $xx="eax"; $yy="ebx"; @@ -136,7 +134,7 @@ if ($alt=0) { push (@XX,shift(@XX)) if ($i>=0); } } else { - # Using pinsrw here improves performane on Intel CPUs by 2-3%, but + # Using pinsrw here improves performance on Intel CPUs by 2-3%, but # brings down AMD by 7%... $RC4_loop_mmx = sub { my $i=shift; diff --git a/crypto/rc4/asm/rc4-c64xplus.pl b/crypto/rc4/asm/rc4-c64xplus.pl index 184922c1..9f282fe4 100644 --- a/crypto/rc4/asm/rc4-c64xplus.pl +++ b/crypto/rc4/asm/rc4-c64xplus.pl @@ -1,5 +1,5 @@ #! /usr/bin/env perl -# Copyright 2014-2018 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2014-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 @@ -89,7 +89,7 @@ _RC4: || NOP 5 STB $XX,*${KEYA}[-2] ; key->x || SUB4 $YY,$TX,$YY -|| BNOP B3 +|| BNOP B3 STB $YY,*${KEYB}[-1] ; key->y || NOP 5 .endasmfunc @@ -186,7 +186,5 @@ rc4_options: .align 4 ___ -$output=pop; -open STDOUT,">$output"; print $code; close STDOUT; diff --git a/crypto/rc4/asm/rc4-ia64.pl b/crypto/rc4/asm/rc4-ia64.pl deleted file mode 100644 index 5e8f5f55..00000000 --- a/crypto/rc4/asm/rc4-ia64.pl +++ /dev/null @@ -1,767 +0,0 @@ -#! /usr/bin/env perl -# Copyright 2005-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 - -# -# ==================================================================== -# Written by David Mosberger based on the -# Itanium optimized Crypto code which was released by HP Labs at -# http://www.hpl.hp.com/research/linux/crypto/. -# -# Copyright (c) 2005 Hewlett-Packard Development Company, L.P. -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. - -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - - - -# This is a little helper program which generates a software-pipelined -# for RC4 encryption. The basic algorithm looks like this: -# -# for (counter = 0; counter < len; ++counter) -# { -# in = inp[counter]; -# SI = S[I]; -# J = (SI + J) & 0xff; -# SJ = S[J]; -# T = (SI + SJ) & 0xff; -# S[I] = SJ, S[J] = SI; -# ST = S[T]; -# outp[counter] = in ^ ST; -# I = (I + 1) & 0xff; -# } -# -# Pipelining this loop isn't easy, because the stores to the S[] array -# need to be observed in the right order. The loop generated by the -# code below has the following pipeline diagram: -# -# cycle -# | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 |11 |12 |13 |14 |15 |16 |17 | -# iter -# 1: xxx LDI xxx xxx xxx LDJ xxx SWP xxx LDT xxx xxx -# 2: xxx LDI xxx xxx xxx LDJ xxx SWP xxx LDT xxx xxx -# 3: xxx LDI xxx xxx xxx LDJ xxx SWP xxx LDT xxx xxx -# -# where: -# LDI = load of S[I] -# LDJ = load of S[J] -# SWP = swap of S[I] and S[J] -# LDT = load of S[T] -# -# Note that in the above diagram, the major trouble-spot is that LDI -# of the 2nd iteration is performed BEFORE the SWP of the first -# iteration. Fortunately, this is easy to detect (I of the 1st -# iteration will be equal to J of the 2nd iteration) and when this -# happens, we simply forward the proper value from the 1st iteration -# to the 2nd one. The proper value in this case is simply the value -# of S[I] from the first iteration (thanks to the fact that SWP -# simply swaps the contents of S[I] and S[J]). -# -# Another potential trouble-spot is in cycle 7, where SWP of the 1st -# iteration issues at the same time as the LDI of the 3rd iteration. -# However, thanks to IA-64 execution semantics, this can be taken -# care of simply by placing LDI later in the instruction-group than -# SWP. IA-64 CPUs will automatically forward the value if they -# detect that the SWP and LDI are accessing the same memory-location. - -# The core-loop that can be pipelined then looks like this (annotated -# with McKinley/Madison issue port & latency numbers, assuming L1 -# cache hits for the most part): - -# operation: instruction: issue-ports: latency -# ------------------ ----------------------------- ------------- ------- - -# Data = *inp++ ld1 data = [inp], 1 M0-M1 1 cyc c0 -# shladd Iptr = I, KeyTable, 3 M0-M3, I0, I1 1 cyc -# I = (I + 1) & 0xff padd1 nextI = I, one M0-M3, I0, I1 3 cyc -# ;; -# SI = S[I] ld8 SI = [Iptr] M0-M1 1 cyc c1 * after SWAP! -# ;; -# cmp.eq.unc pBypass = I, J * after J is valid! -# J = SI + J add J = J, SI M0-M3, I0, I1 1 cyc c2 -# (pBypass) br.cond.spnt Bypass -# ;; -# --------------------------------------------------------------------------------------- -# J = J & 0xff zxt1 J = J I0, I1, 1 cyc c3 -# ;; -# shladd Jptr = J, KeyTable, 3 M0-M3, I0, I1 1 cyc c4 -# ;; -# SJ = S[J] ld8 SJ = [Jptr] M0-M1 1 cyc c5 -# ;; -# --------------------------------------------------------------------------------------- -# T = (SI + SJ) add T = SI, SJ M0-M3, I0, I1 1 cyc c6 -# ;; -# T = T & 0xff zxt1 T = T I0, I1 1 cyc -# S[I] = SJ st8 [Iptr] = SJ M2-M3 c7 -# S[J] = SI st8 [Jptr] = SI M2-M3 -# ;; -# shladd Tptr = T, KeyTable, 3 M0-M3, I0, I1 1 cyc c8 -# ;; -# --------------------------------------------------------------------------------------- -# T = S[T] ld8 T = [Tptr] M0-M1 1 cyc c9 -# ;; -# data ^= T xor data = data, T M0-M3, I0, I1 1 cyc c10 -# ;; -# *out++ = Data ^ T dep word = word, data, 8, POS I0, I1 1 cyc c11 -# ;; -# --------------------------------------------------------------------------------------- - -# There are several points worth making here: - -# - Note that due to the bypass/forwarding-path, the first two -# phases of the loop are strangly mingled together. In -# particular, note that the first stage of the pipeline is -# using the value of "J", as calculated by the second stage. -# - Each bundle-pair will have exactly 6 instructions. -# - Pipelined, the loop can execute in 3 cycles/iteration and -# 4 stages. However, McKinley/Madison can issue "st1" to -# the same bank at a rate of at most one per 4 cycles. Thus, -# instead of storing each byte, we accumulate them in a word -# and then write them back at once with a single "st8" (this -# implies that the setup code needs to ensure that the output -# buffer is properly aligned, if need be, by encoding the -# first few bytes separately). -# - There is no space for a "br.ctop" instruction. For this -# reason we can't use module-loop support in IA-64 and have -# to do a traditional, purely software-pipelined loop. -# - We can't replace any of the remaining "add/zxt1" pairs with -# "padd1" because the latency for that instruction is too high -# and would push the loop to the point where more bypasses -# would be needed, which we don't have space for. -# - The above loop runs at around 3.26 cycles/byte, or roughly -# 440 MByte/sec on a 1.5GHz Madison. This is well below the -# system bus bandwidth and hence with judicious use of -# "lfetch" this loop can run at (almost) peak speed even when -# the input and output data reside in memory. The -# max. latency that can be tolerated is (PREFETCH_DISTANCE * -# L2_LINE_SIZE * 3 cyc), or about 384 cycles assuming (at -# least) 1-ahead prefetching of 128 byte cache-lines. Note -# that we do NOT prefetch into L1, since that would only -# interfere with the S[] table values stored there. This is -# acceptable because there is a 10 cycle latency between -# load and first use of the input data. -# - We use a branch to out-of-line bypass-code of cycle-pressure: -# we calculate the next J, check for the need to activate the -# bypass path, and activate the bypass path ALL IN THE SAME -# CYCLE. If we didn't have these constraints, we could do -# the bypass with a simple conditional move instruction. -# Fortunately, the bypass paths get activated relatively -# infrequently, so the extra branches don't cost all that much -# (about 0.04 cycles/byte, measured on a 16396 byte file with -# random input data). -# - -$output = pop; -open STDOUT,">$output"; - -$phases = 4; # number of stages/phases in the pipelined-loop -$unroll_count = 6; # number of times we unrolled it -$pComI = (1 << 0); -$pComJ = (1 << 1); -$pComT = (1 << 2); -$pOut = (1 << 3); - -$NData = 4; -$NIP = 3; -$NJP = 2; -$NI = 2; -$NSI = 3; -$NSJ = 2; -$NT = 2; -$NOutWord = 2; - -# -# $threshold is the minimum length before we attempt to use the -# big software-pipelined loop. It MUST be greater-or-equal -# to: -# PHASES * (UNROLL_COUNT + 1) + 7 -# -# The "+ 7" comes from the fact we may have to encode up to -# 7 bytes separately before the output pointer is aligned. -# -$threshold = (3 * ($phases * ($unroll_count + 1)) + 7); - -sub I { - local *code = shift; - local $format = shift; - $code .= sprintf ("\t\t".$format."\n", @_); -} - -sub P { - local *code = shift; - local $format = shift; - $code .= sprintf ($format."\n", @_); -} - -sub STOP { - local *code = shift; - $code .=<<___; - ;; -___ -} - -sub emit_body { - local *c = shift; - local *bypass = shift; - local ($iteration, $p) = @_; - - local $i0 = $iteration; - local $i1 = $iteration - 1; - local $i2 = $iteration - 2; - local $i3 = $iteration - 3; - local $iw0 = ($iteration - 3) / 8; - local $iw1 = ($iteration > 3) ? ($iteration - 4) / 8 : 1; - local $byte_num = ($iteration - 3) % 8; - local $label = $iteration + 1; - local $pAny = ($p & 0xf) == 0xf; - local $pByp = (($p & $pComI) && ($iteration > 0)); - - $c.=<<___; -////////////////////////////////////////////////// -___ - - if (($p & 0xf) == 0) { - $c.="#ifdef HOST_IS_BIG_ENDIAN\n"; - &I(\$c,"shr.u OutWord[%u] = OutWord[%u], 32;;", - $iw1 % $NOutWord, $iw1 % $NOutWord); - $c.="#endif\n"; - &I(\$c, "st4 [OutPtr] = OutWord[%u], 4", $iw1 % $NOutWord); - return; - } - - # Cycle 0 - &I(\$c, "{ .mmi") if ($pAny); - &I(\$c, "ld1 Data[%u] = [InPtr], 1", $i0 % $NData) if ($p & $pComI); - &I(\$c, "padd1 I[%u] = One, I[%u]", $i0 % $NI, $i1 % $NI)if ($p & $pComI); - &I(\$c, "zxt1 J = J") if ($p & $pComJ); - &I(\$c, "}") if ($pAny); - &I(\$c, "{ .mmi") if ($pAny); - &I(\$c, "LKEY T[%u] = [T[%u]]", $i1 % $NT, $i1 % $NT) if ($p & $pOut); - &I(\$c, "add T[%u] = SI[%u], SJ[%u]", - $i0 % $NT, $i2 % $NSI, $i1 % $NSJ) if ($p & $pComT); - &I(\$c, "KEYADDR(IPr[%u], I[%u])", $i0 % $NIP, $i1 % $NI) if ($p & $pComI); - &I(\$c, "}") if ($pAny); - &STOP(\$c); - - # Cycle 1 - &I(\$c, "{ .mmi") if ($pAny); - &I(\$c, "SKEY [IPr[%u]] = SJ[%u]", $i2 % $NIP, $i1%$NSJ)if ($p & $pComT); - &I(\$c, "SKEY [JP[%u]] = SI[%u]", $i1 % $NJP, $i2%$NSI) if ($p & $pComT); - &I(\$c, "zxt1 T[%u] = T[%u]", $i0 % $NT, $i0 % $NT) if ($p & $pComT); - &I(\$c, "}") if ($pAny); - &I(\$c, "{ .mmi") if ($pAny); - &I(\$c, "LKEY SI[%u] = [IPr[%u]]", $i0 % $NSI, $i0%$NIP)if ($p & $pComI); - &I(\$c, "KEYADDR(JP[%u], J)", $i0 % $NJP) if ($p & $pComJ); - &I(\$c, "xor Data[%u] = Data[%u], T[%u]", - $i3 % $NData, $i3 % $NData, $i1 % $NT) if ($p & $pOut); - &I(\$c, "}") if ($pAny); - &STOP(\$c); - - # Cycle 2 - &I(\$c, "{ .mmi") if ($pAny); - &I(\$c, "LKEY SJ[%u] = [JP[%u]]", $i0 % $NSJ, $i0%$NJP) if ($p & $pComJ); - &I(\$c, "cmp.eq pBypass, p0 = I[%u], J", $i1 % $NI) if ($pByp); - &I(\$c, "dep OutWord[%u] = Data[%u], OutWord[%u], BYTE_POS(%u), 8", - $iw0%$NOutWord, $i3%$NData, $iw1%$NOutWord, $byte_num) if ($p & $pOut); - &I(\$c, "}") if ($pAny); - &I(\$c, "{ .mmb") if ($pAny); - &I(\$c, "add J = J, SI[%u]", $i0 % $NSI) if ($p & $pComI); - &I(\$c, "KEYADDR(T[%u], T[%u])", $i0 % $NT, $i0 % $NT) if ($p & $pComT); - &P(\$c, "(pBypass)\tbr.cond.spnt.many .rc4Bypass%u",$label)if ($pByp); - &I(\$c, "}") if ($pAny); - &STOP(\$c); - - &P(\$c, ".rc4Resume%u:", $label) if ($pByp); - if ($byte_num == 0 && $iteration >= $phases) { - &I(\$c, "st8 [OutPtr] = OutWord[%u], 8", - $iw1 % $NOutWord) if ($p & $pOut); - if ($iteration == (1 + $unroll_count) * $phases - 1) { - if ($unroll_count == 6) { - &I(\$c, "mov OutWord[%u] = OutWord[%u]", - $iw1 % $NOutWord, $iw0 % $NOutWord); - } - &I(\$c, "lfetch.nt1 [InPrefetch], %u", - $unroll_count * $phases); - &I(\$c, "lfetch.excl.nt1 [OutPrefetch], %u", - $unroll_count * $phases); - &I(\$c, "br.cloop.sptk.few .rc4Loop"); - } - } - - if ($pByp) { - &P(\$bypass, ".rc4Bypass%u:", $label); - &I(\$bypass, "sub J = J, SI[%u]", $i0 % $NSI); - &I(\$bypass, "nop 0"); - &I(\$bypass, "nop 0"); - &I(\$bypass, ";;"); - &I(\$bypass, "add J = J, SI[%u]", $i1 % $NSI); - &I(\$bypass, "mov SI[%u] = SI[%u]", $i0 % $NSI, $i1 % $NSI); - &I(\$bypass, "br.sptk.many .rc4Resume%u\n", $label); - &I(\$bypass, ";;"); - } -} - -$code=<<___; -.ident \"rc4-ia64.s, version 3.0\" -.ident \"Copyright (c) 2005 Hewlett-Packard Development Company, L.P.\" - -#define LCSave r8 -#define PRSave r9 - -/* Inputs become invalid once rotation begins! */ - -#define StateTable in0 -#define DataLen in1 -#define InputBuffer in2 -#define OutputBuffer in3 - -#define KTable r14 -#define J r15 -#define InPtr r16 -#define OutPtr r17 -#define InPrefetch r18 -#define OutPrefetch r19 -#define One r20 -#define LoopCount r21 -#define Remainder r22 -#define IFinal r23 -#define EndPtr r24 - -#define tmp0 r25 -#define tmp1 r26 - -#define pBypass p6 -#define pDone p7 -#define pSmall p8 -#define pAligned p9 -#define pUnaligned p10 - -#define pComputeI pPhase[0] -#define pComputeJ pPhase[1] -#define pComputeT pPhase[2] -#define pOutput pPhase[3] - -#define RetVal r8 -#define L_OK p7 -#define L_NOK p8 - -#define _NINPUTS 4 -#define _NOUTPUT 0 - -#define _NROTATE 24 -#define _NLOCALS (_NROTATE - _NINPUTS - _NOUTPUT) - -#ifndef SZ -# define SZ 4 // this must be set to sizeof(RC4_INT) -#endif - -#if SZ == 1 -# define LKEY ld1 -# define SKEY st1 -# define KEYADDR(dst, i) add dst = i, KTable -#elif SZ == 2 -# define LKEY ld2 -# define SKEY st2 -# define KEYADDR(dst, i) shladd dst = i, 1, KTable -#elif SZ == 4 -# define LKEY ld4 -# define SKEY st4 -# define KEYADDR(dst, i) shladd dst = i, 2, KTable -#else -# define LKEY ld8 -# define SKEY st8 -# define KEYADDR(dst, i) shladd dst = i, 3, KTable -#endif - -#if defined(_HPUX_SOURCE) && !defined(_LP64) -# define ADDP addp4 -#else -# define ADDP add -#endif - -/* Define a macro for the bit number of the n-th byte: */ - -#if defined(_HPUX_SOURCE) || defined(B_ENDIAN) -# define HOST_IS_BIG_ENDIAN -# define BYTE_POS(n) (56 - (8 * (n))) -#else -# define BYTE_POS(n) (8 * (n)) -#endif - -/* - We must perform the first phase of the pipeline explicitly since - we will always load from the stable the first time. The br.cexit - will never be taken since regardless of the number of bytes because - the epilogue count is 4. -*/ -/* MODSCHED_RC4 macro was split to _PROLOGUE and _LOOP, because HP-UX - assembler failed on original macro with syntax error. */ -#define MODSCHED_RC4_PROLOGUE \\ - { \\ - ld1 Data[0] = [InPtr], 1; \\ - add IFinal = 1, I[1]; \\ - KEYADDR(IPr[0], I[1]); \\ - } ;; \\ - { \\ - LKEY SI[0] = [IPr[0]]; \\ - mov pr.rot = 0x10000; \\ - mov ar.ec = 4; \\ - } ;; \\ - { \\ - add J = J, SI[0]; \\ - zxt1 I[0] = IFinal; \\ - br.cexit.spnt.few .+16; /* never taken */ \\ - } ;; -#define MODSCHED_RC4_LOOP(label) \\ -label: \\ - { .mmi; \\ - (pComputeI) ld1 Data[0] = [InPtr], 1; \\ - (pComputeI) add IFinal = 1, I[1]; \\ - (pComputeJ) zxt1 J = J; \\ - }{ .mmi; \\ - (pOutput) LKEY T[1] = [T[1]]; \\ - (pComputeT) add T[0] = SI[2], SJ[1]; \\ - (pComputeI) KEYADDR(IPr[0], I[1]); \\ - } ;; \\ - { .mmi; \\ - (pComputeT) SKEY [IPr[2]] = SJ[1]; \\ - (pComputeT) SKEY [JP[1]] = SI[2]; \\ - (pComputeT) zxt1 T[0] = T[0]; \\ - }{ .mmi; \\ - (pComputeI) LKEY SI[0] = [IPr[0]]; \\ - (pComputeJ) KEYADDR(JP[0], J); \\ - (pComputeI) cmp.eq.unc pBypass, p0 = I[1], J; \\ - } ;; \\ - { .mmi; \\ - (pComputeJ) LKEY SJ[0] = [JP[0]]; \\ - (pOutput) xor Data[3] = Data[3], T[1]; \\ - nop 0x0; \\ - }{ .mmi; \\ - (pComputeT) KEYADDR(T[0], T[0]); \\ - (pBypass) mov SI[0] = SI[1]; \\ - (pComputeI) zxt1 I[0] = IFinal; \\ - } ;; \\ - { .mmb; \\ - (pOutput) st1 [OutPtr] = Data[3], 1; \\ - (pComputeI) add J = J, SI[0]; \\ - br.ctop.sptk.few label; \\ - } ;; - - .text - - .align 32 - - .type RC4, \@function - .global RC4 - - .proc RC4 - .prologue - -RC4: - { - .mmi - alloc r2 = ar.pfs, _NINPUTS, _NLOCALS, _NOUTPUT, _NROTATE - - .rotr Data[4], I[2], IPr[3], SI[3], JP[2], SJ[2], T[2], \\ - OutWord[2] - .rotp pPhase[4] - - ADDP InPrefetch = 0, InputBuffer - ADDP KTable = 0, StateTable - } - { - .mmi - ADDP InPtr = 0, InputBuffer - ADDP OutPtr = 0, OutputBuffer - mov RetVal = r0 - } - ;; - { - .mmi - lfetch.nt1 [InPrefetch], 0x80 - ADDP OutPrefetch = 0, OutputBuffer - } - { // Return 0 if the input length is nonsensical - .mib - ADDP StateTable = 0, StateTable - cmp.ge.unc L_NOK, L_OK = r0, DataLen - (L_NOK) br.ret.sptk.few rp - } - ;; - { - .mib - cmp.eq.or L_NOK, L_OK = r0, InPtr - cmp.eq.or L_NOK, L_OK = r0, OutPtr - nop 0x0 - } - { - .mib - cmp.eq.or L_NOK, L_OK = r0, StateTable - nop 0x0 - (L_NOK) br.ret.sptk.few rp - } - ;; - LKEY I[1] = [KTable], SZ -/* Prefetch the state-table. It contains 256 elements of size SZ */ - -#if SZ == 1 - ADDP tmp0 = 1*128, StateTable -#elif SZ == 2 - ADDP tmp0 = 3*128, StateTable - ADDP tmp1 = 2*128, StateTable -#elif SZ == 4 - ADDP tmp0 = 7*128, StateTable - ADDP tmp1 = 6*128, StateTable -#elif SZ == 8 - ADDP tmp0 = 15*128, StateTable - ADDP tmp1 = 14*128, StateTable -#endif - ;; -#if SZ >= 8 - lfetch.fault.nt1 [tmp0], -256 // 15 - lfetch.fault.nt1 [tmp1], -256;; - lfetch.fault.nt1 [tmp0], -256 // 13 - lfetch.fault.nt1 [tmp1], -256;; - lfetch.fault.nt1 [tmp0], -256 // 11 - lfetch.fault.nt1 [tmp1], -256;; - lfetch.fault.nt1 [tmp0], -256 // 9 - lfetch.fault.nt1 [tmp1], -256;; -#endif -#if SZ >= 4 - lfetch.fault.nt1 [tmp0], -256 // 7 - lfetch.fault.nt1 [tmp1], -256;; - lfetch.fault.nt1 [tmp0], -256 // 5 - lfetch.fault.nt1 [tmp1], -256;; -#endif -#if SZ >= 2 - lfetch.fault.nt1 [tmp0], -256 // 3 - lfetch.fault.nt1 [tmp1], -256;; -#endif - { - .mii - lfetch.fault.nt1 [tmp0] // 1 - add I[1]=1,I[1];; - zxt1 I[1]=I[1] - } - { - .mmi - lfetch.nt1 [InPrefetch], 0x80 - lfetch.excl.nt1 [OutPrefetch], 0x80 - .save pr, PRSave - mov PRSave = pr - } ;; - { - .mmi - lfetch.excl.nt1 [OutPrefetch], 0x80 - LKEY J = [KTable], SZ - ADDP EndPtr = DataLen, InPtr - } ;; - { - .mmi - ADDP EndPtr = -1, EndPtr // Make it point to - // last data byte. - mov One = 1 - .save ar.lc, LCSave - mov LCSave = ar.lc - .body - } ;; - { - .mmb - sub Remainder = 0, OutPtr - cmp.gtu pSmall, p0 = $threshold, DataLen -(pSmall) br.cond.dpnt .rc4Remainder // Data too small for - // big loop. - } ;; - { - .mmi - and Remainder = 0x7, Remainder - ;; - cmp.eq pAligned, pUnaligned = Remainder, r0 - nop 0x0 - } ;; - { - .mmb -.pred.rel "mutex",pUnaligned,pAligned -(pUnaligned) add Remainder = -1, Remainder -(pAligned) sub Remainder = EndPtr, InPtr -(pAligned) br.cond.dptk.many .rc4Aligned - } ;; - { - .mmi - nop 0x0 - nop 0x0 - mov.i ar.lc = Remainder - } - -/* Do the initial few bytes via the compact, modulo-scheduled loop - until the output pointer is 8-byte-aligned. */ - - MODSCHED_RC4_PROLOGUE - MODSCHED_RC4_LOOP(.RC4AlignLoop) - - { - .mib - sub Remainder = EndPtr, InPtr - zxt1 IFinal = IFinal - clrrrb // Clear CFM.rrb.pr so - ;; // next "mov pr.rot = N" - // does the right thing. - } - { - .mmi - mov I[1] = IFinal - nop 0x0 - nop 0x0 - } ;; - - -.rc4Aligned: - -/* - Unrolled loop count = (Remainder - ($unroll_count+1)*$phases)/($unroll_count*$phases) - */ - - { - .mlx - add LoopCount = 1 - ($unroll_count + 1)*$phases, Remainder - movl Remainder = 0xaaaaaaaaaaaaaaab - } ;; - { - .mmi - setf.sig f6 = LoopCount // M2, M3 6 cyc - setf.sig f7 = Remainder // M2, M3 6 cyc - nop 0x0 - } ;; - { - .mfb - nop 0x0 - xmpy.hu f6 = f6, f7 - nop 0x0 - } ;; - { - .mmi - getf.sig LoopCount = f6;; // M2 5 cyc - nop 0x0 - shr.u LoopCount = LoopCount, 4 - } ;; - { - .mmi - nop 0x0 - nop 0x0 - mov.i ar.lc = LoopCount - } ;; - -/* Now comes the unrolled loop: */ - -.rc4Prologue: -___ - -$iteration = 0; - -# Generate the prologue: -$predicates = 1; -for ($i = 0; $i < $phases; ++$i) { - &emit_body (\$code, \$bypass, $iteration++, $predicates); - $predicates = ($predicates << 1) | 1; -} - -$code.=<<___; -.rc4Loop: -___ - -# Generate the body: -for ($i = 0; $i < $unroll_count*$phases; ++$i) { - &emit_body (\$code, \$bypass, $iteration++, $predicates); -} - -$code.=<<___; -.rc4Epilogue: -___ - -# Generate the epilogue: -for ($i = 0; $i < $phases; ++$i) { - $predicates <<= 1; - &emit_body (\$code, \$bypass, $iteration++, $predicates); -} - -$code.=<<___; - { - .mmi - lfetch.nt1 [EndPtr] // fetch line with last byte - mov IFinal = I[1] - nop 0x0 - } - -.rc4Remainder: - { - .mmi - sub Remainder = EndPtr, InPtr // Calculate - // # of bytes - // left - 1 - nop 0x0 - nop 0x0 - } ;; - { - .mib - cmp.eq pDone, p0 = -1, Remainder // done already? - mov.i ar.lc = Remainder -(pDone) br.cond.dptk.few .rc4Complete - } - -/* Do the remaining bytes via the compact, modulo-scheduled loop */ - - MODSCHED_RC4_PROLOGUE - MODSCHED_RC4_LOOP(.RC4RestLoop) - -.rc4Complete: - { - .mmi - add KTable = -SZ, KTable - add IFinal = -1, IFinal - mov ar.lc = LCSave - } ;; - { - .mii - SKEY [KTable] = J,-SZ - zxt1 IFinal = IFinal - mov pr = PRSave, 0x1FFFF - } ;; - { - .mib - SKEY [KTable] = IFinal - add RetVal = 1, r0 - br.ret.sptk.few rp - } ;; -___ - -# Last but not least, emit the code for the bypass-code of the unrolled loop: - -$code.=$bypass; - -$code.=<<___; - .endp RC4 -___ - -print $code; - -close STDOUT; diff --git a/crypto/rc4/asm/rc4-md5-x86_64.pl b/crypto/rc4/asm/rc4-md5-x86_64.pl index 890161ba..74e51910 100644 --- a/crypto/rc4/asm/rc4-md5-x86_64.pl +++ b/crypto/rc4/asm/rc4-md5-x86_64.pl @@ -51,7 +51,7 @@ my ($rc4,$md5)=(1,1); # what to generate? my $D="#" if (!$md5); # if set to "#", MD5 is stitched into RC4(), # but its result is discarded. Idea here is # to be able to use 'openssl speed rc4' for - # benchmarking the stitched subroutine... + # benchmarking the stitched subroutine... my $flavour = shift; my $output = shift; @@ -124,15 +124,23 @@ $code.=<<___; .globl $func .type $func,\@function,$nargs $func: +.cfi_startproc cmp \$0,$len je .Labort push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 sub \$40,%rsp +.cfi_adjust_cfa_offset 40 .Lbody: ___ if ($rc4) { @@ -419,7 +427,7 @@ $code.=<<___ if ($rc4 && (!$md5 || $D)); and \$63,$len # remaining bytes jnz .Loop1 jmp .Ldone - + .align 16 .Loop1: add $TX[0]#b,$YY#b @@ -444,15 +452,23 @@ $code.=<<___; #rc4# movl $YY#d,-4($dat) mov 40(%rsp),%r15 +.cfi_restore %r15 mov 48(%rsp),%r14 +.cfi_restore %r14 mov 56(%rsp),%r13 +.cfi_restore %r13 mov 64(%rsp),%r12 +.cfi_restore %r12 mov 72(%rsp),%rbp +.cfi_restore %rbp mov 80(%rsp),%rbx +.cfi_restore %rbx lea 88(%rsp),%rsp +.cfi_adjust_cfa_offset -88 .Lepilogue: .Labort: ret +.cfi_endproc .size $func,.-$func ___ diff --git a/crypto/rc4/asm/rc4-parisc.pl b/crypto/rc4/asm/rc4-parisc.pl index 006b6b01..229c6c7d 100644 --- a/crypto/rc4/asm/rc4-parisc.pl +++ b/crypto/rc4/asm/rc4-parisc.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -98,7 +98,7 @@ sub unrolledloopbody { for ($i=0;$i<4;$i++) { $code.=<<___; ldo 1($XX[0]),$XX[1] - `sprintf("$LDX %$TY(%$key),%$dat1") if ($i>0)` + `sprintf("$LDX %$TY(%$key),%$dat1") if ($i>0)` and $mask,$XX[1],$XX[1] $LDX $YY($key),$TY $MKX $YY,$key,$ix @@ -166,7 +166,7 @@ RC4 ldo `2*$SZ`($key),$key ldi 0xff,$mask - ldi 3,$dat0 + ldi 3,$dat0 ldo 1($XX[0]),$XX[0] ; warm up loop and $mask,$XX[0],$XX[0] diff --git a/crypto/rc4/asm/rc4-s390x.pl b/crypto/rc4/asm/rc4-s390x.pl index 5589503a..469f110f 100644 --- a/crypto/rc4/asm/rc4-s390x.pl +++ b/crypto/rc4/asm/rc4-s390x.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. diff --git a/crypto/rc4/asm/rc4-x86_64.pl b/crypto/rc4/asm/rc4-x86_64.pl index aaed2b1e..1a9cc47d 100755 --- a/crypto/rc4/asm/rc4-x86_64.pl +++ b/crypto/rc4/asm/rc4-x86_64.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -48,7 +48,7 @@ # April 2005 # -# P4 EM64T core appears to be "allergic" to 64-bit inc/dec. Replacing +# P4 EM64T core appears to be "allergic" to 64-bit inc/dec. Replacing # those with add/sub results in 50% performance improvement of folded # loop... @@ -88,7 +88,7 @@ # The only code path that was not modified is P4-specific one. Non-P4 # Intel code path optimization is heavily based on submission by Maxim # Perminov, Maxim Locktyukhin and Jim Guilford of Intel. I've used -# some of the ideas even in attempt to optmize the original RC4_INT +# some of the ideas even in attempt to optimize the original RC4_INT # code path... Current performance in cycles per processed byte (less # is better) and improvement coefficients relative to previous # version of this module are: @@ -142,9 +142,13 @@ RC4: or $len,$len jne .Lentry ret .Lentry: +.cfi_startproc push %rbx +.cfi_push %rbx push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 .Lprologue: mov $len,%r11 mov $inp,%r12 @@ -427,11 +431,16 @@ $code.=<<___; movl $YY#d,-4($dat) mov (%rsp),%r13 +.cfi_restore %r13 mov 8(%rsp),%r12 +.cfi_restore %r12 mov 16(%rsp),%rbx +.cfi_restore %rbx add \$24,%rsp +.cfi_adjust_cfa_offset -24 .Lepilogue: ret +.cfi_endproc .size RC4,.-RC4 ___ } diff --git a/crypto/rc4/build.info b/crypto/rc4/build.info index 8659526d..46ee66b6 100644 --- a/crypto/rc4/build.info +++ b/crypto/rc4/build.info @@ -2,7 +2,8 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ {- $target{rc4_asm_src} -} -GENERATE[rc4-586.s]=asm/rc4-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[rc4-586.s]=asm/rc4-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[rc4-586.s]=../perlasm/x86asm.pl GENERATE[rc4-x86_64.s]=asm/rc4-x86_64.pl $(PERLASM_SCHEME) @@ -10,23 +11,7 @@ GENERATE[rc4-md5-x86_64.s]=asm/rc4-md5-x86_64.pl $(PERLASM_SCHEME) GENERATE[rc4-parisc.s]=asm/rc4-parisc.pl $(PERLASM_SCHEME) -BEGINRAW[makefile(windows)] -{- $builddir -}\rc4-ia64.asm: {- $sourcedir -}\asm\rc4-ia64.pl - $(PERL) {- $sourcedir -}\asm\rc4-ia64.pl $@.S - $(CC) -DSZ=4 -EP $@.S > $@.i && move /Y $@.i $@ - del /Q $@.S -ENDRAW[makefile(windows)] - BEGINRAW[Makefile] -{- $builddir -}/rc4-ia64.s: {- $sourcedir -}/asm/rc4-ia64.pl - @(trap "rm $@.*" INT 0; \ - $(PERL) {- $sourcedir -}/asm/rc4-ia64.pl $(CFLAGS) $(LIB_CFLAGS) $@.S; \ - case `awk '/^#define RC4_INT/{print$$NF}' $(BLDDIR)/include/openssl/opensslconf.h` in \ - int) set -x; $(CC) $(CFLAGS) $(LIB_CFLAGS) -DSZ=4 -E $@.S > $@.i && mv -f $@.i $@;; \ - char) set -x; $(CC) $(CFLAGS) $(LIB_CFLAGS) -DSZ=1 -E $@.S > $@.i && mv -f $@.i $@;; \ - *) exit 1 ;; \ - esac ) - # GNU make "catch all" {- $builddir -}/rc4-%.s: {- $sourcedir -}/asm/rc4-%.pl CC="$(CC)" $(PERL) $< $(PERLASM_SCHEME) $@ diff --git a/crypto/rc4/rc4_enc.c b/crypto/rc4/rc4_enc.c index be11bade..638a75bb 100644 --- a/crypto/rc4/rc4_enc.c +++ b/crypto/rc4/rc4_enc.c @@ -13,7 +13,6 @@ /*- * RC4 as implemented from a posting from * Newsgroups: sci.crypt - * From: sterndark@netcom.com (David Sterndark) * Subject: RC4 Algorithm revealed. * Message-ID: * Date: Wed, 14 Sep 1994 06:35:31 GMT diff --git a/crypto/rc4/rc4_skey.c b/crypto/rc4/rc4_skey.c index 16f81a4d..e9007331 100644 --- a/crypto/rc4/rc4_skey.c +++ b/crypto/rc4/rc4_skey.c @@ -14,15 +14,14 @@ const char *RC4_options(void) { if (sizeof(RC4_INT) == 1) - return ("rc4(char)"); + return "rc4(char)"; else - return ("rc4(int)"); + return "rc4(int)"; } /*- * RC4 as implemented from a posting from * Newsgroups: sci.crypt - * From: sterndark@netcom.com (David Sterndark) * Subject: RC4 Algorithm revealed. * Message-ID: * Date: Wed, 14 Sep 1994 06:35:31 GMT diff --git a/crypto/rc5/asm/rc5-586.pl b/crypto/rc5/asm/rc5-586.pl index e3e1c642..e58a98bc 100644 --- a/crypto/rc5/asm/rc5-586.pl +++ b/crypto/rc5/asm/rc5-586.pl @@ -15,7 +15,7 @@ require "cbc.pl"; $output = pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"rc5-586.pl"); +&asm_init($ARGV[0]); $RC5_MAX_ROUNDS=16; $RC5_32_OFF=($RC5_MAX_ROUNDS+2)*4; diff --git a/crypto/rc5/build.info b/crypto/rc5/build.info index baf8a0ef..928a62cd 100644 --- a/crypto/rc5/build.info +++ b/crypto/rc5/build.info @@ -2,5 +2,6 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ rc5_skey.c rc5_ecb.c {- $target{rc5_asm_src} -} rc5cfb64.c rc5ofb64.c -GENERATE[rc5-586.s]=asm/rc5-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) +GENERATE[rc5-586.s]=asm/rc5-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) DEPEND[rc5-586.s]=../perlasm/x86asm.pl ../perlasm/cbc.pl diff --git a/crypto/ripemd/asm/rmd-586.pl b/crypto/ripemd/asm/rmd-586.pl index 544c496f..84aa7ced 100644 --- a/crypto/ripemd/asm/rmd-586.pl +++ b/crypto/ripemd/asm/rmd-586.pl @@ -19,7 +19,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],$0); +&asm_init($ARGV[0]); $A="ecx"; $B="esi"; @@ -34,7 +34,7 @@ $KL2=0x6ED9EBA1; $KL3=0x8F1BBCDC; $KL4=0xA953FD4E; $KR0=0x50A28BE6; -$KR1=0x5C4DD124; +$KR1=0x5C4DD124; $KR2=0x6D703EF3; $KR3=0x7A6D76E9; @@ -339,7 +339,6 @@ sub ripemd160_block # aligned. The good news are that gcc-2.95 # and later does keep first argument at # least double-wise aligned. - # &set_label("start") unless $normal; &comment(""); @@ -543,28 +542,28 @@ sub ripemd160_block # &mov($tmp2, &wparam(0)); # Moved into last round &mov($tmp1, &DWP( 4,$tmp2,"",0)); # ctx->B - &add($D, $tmp1); + &add($D, $tmp1); &mov($tmp1, &swtmp(16+2)); # $c &add($D, $tmp1); &mov($tmp1, &DWP( 8,$tmp2,"",0)); # ctx->C - &add($E, $tmp1); + &add($E, $tmp1); &mov($tmp1, &swtmp(16+3)); # $d &add($E, $tmp1); &mov($tmp1, &DWP(12,$tmp2,"",0)); # ctx->D - &add($A, $tmp1); + &add($A, $tmp1); &mov($tmp1, &swtmp(16+4)); # $e &add($A, $tmp1); &mov($tmp1, &DWP(16,$tmp2,"",0)); # ctx->E - &add($B, $tmp1); + &add($B, $tmp1); &mov($tmp1, &swtmp(16+0)); # $a &add($B, $tmp1); &mov($tmp1, &DWP( 0,$tmp2,"",0)); # ctx->A - &add($C, $tmp1); + &add($C, $tmp1); &mov($tmp1, &swtmp(16+1)); # $b &add($C, $tmp1); diff --git a/crypto/ripemd/build.info b/crypto/ripemd/build.info index c45050cb..a4a894e2 100644 --- a/crypto/ripemd/build.info +++ b/crypto/ripemd/build.info @@ -2,5 +2,6 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ rmd_dgst.c rmd_one.c {- $target{rmd160_asm_src} -} -GENERATE[rmd-586.s]=asm/rmd-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) +GENERATE[rmd-586.s]=asm/rmd-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) DEPEND[rmd-586.s]=../perlasm/x86asm.pl diff --git a/crypto/ripemd/rmd_locl.h b/crypto/ripemd/rmd_locl.h index 9c5ba151..f1ae4323 100644 --- a/crypto/ripemd/rmd_locl.h +++ b/crypto/ripemd/rmd_locl.h @@ -15,7 +15,6 @@ /* * DO EXAMINE COMMENTS IN crypto/md5/md5_locl.h & crypto/md5/md5_dgst.c * FOR EXPLANATIONS ON FOLLOWING "CODE." - * */ #ifdef RMD160_ASM # if defined(__i386) || defined(__i386__) || defined(_M_IX86) @@ -46,7 +45,7 @@ void ripemd160_block_data_order(RIPEMD160_CTX *c, const void *p, size_t num); #include "internal/md32_common.h" /* - * Transformed F2 and F4 are courtesy of Wei Dai + * Transformed F2 and F4 are courtesy of Wei Dai */ #define F1(x,y,z) ((x) ^ (y) ^ (z)) #define F2(x,y,z) ((((y) ^ (z)) & (x)) ^ (z)) diff --git a/crypto/ripemd/rmd_one.c b/crypto/ripemd/rmd_one.c index c3193bd7..cc01f15c 100644 --- a/crypto/ripemd/rmd_one.c +++ b/crypto/ripemd/rmd_one.c @@ -24,5 +24,5 @@ unsigned char *RIPEMD160(const unsigned char *d, size_t n, unsigned char *md) RIPEMD160_Update(&c, d, n); RIPEMD160_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* security consideration */ - return (md); + return md; } diff --git a/crypto/rsa/build.info b/crypto/rsa/build.info index 39b7464b..87f92492 100644 --- a/crypto/rsa/build.info +++ b/crypto/rsa/build.info @@ -1,6 +1,6 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ rsa_ossl.c rsa_gen.c rsa_lib.c rsa_sign.c rsa_saos.c rsa_err.c \ - rsa_pk1.c rsa_ssl.c rsa_none.c rsa_oaep.c rsa_chk.c rsa_null.c \ + rsa_pk1.c rsa_ssl.c rsa_none.c rsa_oaep.c rsa_chk.c \ rsa_pss.c rsa_x931.c rsa_asn1.c rsa_depr.c rsa_ameth.c rsa_prn.c \ - rsa_pmeth.c rsa_crpt.c rsa_x931g.c rsa_meth.c + rsa_pmeth.c rsa_crpt.c rsa_x931g.c rsa_meth.c rsa_mp.c diff --git a/crypto/rsa/rsa_ameth.c b/crypto/rsa/rsa_ameth.c index 4a12276a..98121b5e 100644 --- a/crypto/rsa/rsa_ameth.c +++ b/crypto/rsa/rsa_ameth.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-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 @@ -24,15 +24,68 @@ static int rsa_cms_decrypt(CMS_RecipientInfo *ri); static int rsa_cms_encrypt(CMS_RecipientInfo *ri); #endif +static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg); + +/* Set any parameters associated with pkey */ +static int rsa_param_encode(const EVP_PKEY *pkey, + ASN1_STRING **pstr, int *pstrtype) +{ + const RSA *rsa = pkey->pkey.rsa; + + *pstr = NULL; + /* If RSA it's just NULL type */ + if (pkey->ameth->pkey_id == EVP_PKEY_RSA) { + *pstrtype = V_ASN1_NULL; + return 1; + } + /* If no PSS parameters we omit parameters entirely */ + if (rsa->pss == NULL) { + *pstrtype = V_ASN1_UNDEF; + return 1; + } + /* Encode PSS parameters */ + if (ASN1_item_pack(rsa->pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), pstr) == NULL) + return 0; + + *pstrtype = V_ASN1_SEQUENCE; + return 1; +} +/* Decode any parameters and set them in RSA structure */ +static int rsa_param_decode(RSA *rsa, const X509_ALGOR *alg) +{ + const ASN1_OBJECT *algoid; + const void *algp; + int algptype; + + X509_ALGOR_get0(&algoid, &algptype, &algp, alg); + if (OBJ_obj2nid(algoid) == EVP_PKEY_RSA) + return 1; + if (algptype == V_ASN1_UNDEF) + return 1; + if (algptype != V_ASN1_SEQUENCE) { + RSAerr(RSA_F_RSA_PARAM_DECODE, RSA_R_INVALID_PSS_PARAMETERS); + return 0; + } + rsa->pss = rsa_pss_decode(alg); + if (rsa->pss == NULL) + return 0; + return 1; +} + static int rsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey) { unsigned char *penc = NULL; int penclen; + ASN1_STRING *str; + int strtype; + + if (!rsa_param_encode(pkey, &str, &strtype)) + return 0; penclen = i2d_RSAPublicKey(pkey->pkey.rsa, &penc); if (penclen <= 0) return 0; - if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_RSA), - V_ASN1_NULL, NULL, penc, penclen)) + if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(pkey->ameth->pkey_id), + strtype, str, penc, penclen)) return 1; OPENSSL_free(penc); @@ -43,15 +96,20 @@ static int rsa_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey) { const unsigned char *p; int pklen; + X509_ALGOR *alg; RSA *rsa = NULL; - if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, NULL, pubkey)) + if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &alg, pubkey)) return 0; if ((rsa = d2i_RSAPublicKey(NULL, &p, pklen)) == NULL) { RSAerr(RSA_F_RSA_PUB_DECODE, ERR_R_RSA_LIB); return 0; } - EVP_PKEY_assign_RSA(pkey, rsa); + if (!rsa_param_decode(rsa, alg)) { + RSA_free(rsa); + return 0; + } + EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa); return 1; } @@ -72,7 +130,7 @@ static int old_rsa_priv_decode(EVP_PKEY *pkey, RSAerr(RSA_F_OLD_RSA_PRIV_DECODE, ERR_R_RSA_LIB); return 0; } - EVP_PKEY_assign_RSA(pkey, rsa); + EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa); return 1; } @@ -85,16 +143,23 @@ static int rsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) { unsigned char *rk = NULL; int rklen; + ASN1_STRING *str; + int strtype; + + if (!rsa_param_encode(pkey, &str, &strtype)) + return 0; rklen = i2d_RSAPrivateKey(pkey->pkey.rsa, &rk); if (rklen <= 0) { RSAerr(RSA_F_RSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE); + ASN1_STRING_free(str); return 0; } - if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_rsaEncryption), 0, - V_ASN1_NULL, NULL, rk, rklen)) { + if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(pkey->ameth->pkey_id), 0, + strtype, str, rk, rklen)) { RSAerr(RSA_F_RSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE); + ASN1_STRING_free(str); return 0; } @@ -104,10 +169,23 @@ static int rsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey) static int rsa_priv_decode(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8) { const unsigned char *p; + RSA *rsa; int pklen; - if (!PKCS8_pkey_get0(NULL, &p, &pklen, NULL, p8)) + const X509_ALGOR *alg; + + if (!PKCS8_pkey_get0(NULL, &p, &pklen, &alg, p8)) return 0; - return old_rsa_priv_decode(pkey, &p, pklen); + rsa = d2i_RSAPrivateKey(NULL, &p, pklen); + if (rsa == NULL) { + RSAerr(RSA_F_RSA_PRIV_DECODE, ERR_R_RSA_LIB); + return 0; + } + if (!rsa_param_decode(rsa, alg)) { + RSA_free(rsa); + return 0; + } + EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa); + return 1; } static int int_rsa_size(const EVP_PKEY *pkey) @@ -130,104 +208,40 @@ static void int_rsa_free(EVP_PKEY *pkey) RSA_free(pkey->pkey.rsa); } -static int do_rsa_print(BIO *bp, const RSA *x, int off, int priv) -{ - char *str; - const char *s; - int ret = 0, mod_len = 0; - - if (x->n != NULL) - mod_len = BN_num_bits(x->n); - - if (!BIO_indent(bp, off, 128)) - goto err; - - if (priv && x->d) { - if (BIO_printf(bp, "Private-Key: (%d bit)\n", mod_len) <= 0) - goto err; - str = "modulus:"; - s = "publicExponent:"; - } else { - if (BIO_printf(bp, "Public-Key: (%d bit)\n", mod_len) <= 0) - goto err; - str = "Modulus:"; - s = "Exponent:"; - } - if (!ASN1_bn_print(bp, str, x->n, NULL, off)) - goto err; - if (!ASN1_bn_print(bp, s, x->e, NULL, off)) - goto err; - if (priv) { - if (!ASN1_bn_print(bp, "privateExponent:", x->d, NULL, off)) - goto err; - if (!ASN1_bn_print(bp, "prime1:", x->p, NULL, off)) - goto err; - if (!ASN1_bn_print(bp, "prime2:", x->q, NULL, off)) - goto err; - if (!ASN1_bn_print(bp, "exponent1:", x->dmp1, NULL, off)) - goto err; - if (!ASN1_bn_print(bp, "exponent2:", x->dmq1, NULL, off)) - goto err; - if (!ASN1_bn_print(bp, "coefficient:", x->iqmp, NULL, off)) - goto err; - } - ret = 1; - err: - return (ret); -} - -static int rsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent, - ASN1_PCTX *ctx) -{ - return do_rsa_print(bp, pkey->pkey.rsa, indent, 0); -} - -static int rsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent, - ASN1_PCTX *ctx) -{ - return do_rsa_print(bp, pkey->pkey.rsa, indent, 1); -} - -/* Given an MGF1 Algorithm ID decode to an Algorithm Identifier */ static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg) { - if (alg == NULL) - return NULL; if (OBJ_obj2nid(alg->algorithm) != NID_mgf1) return NULL; return ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(X509_ALGOR), alg->parameter); } -static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg, - X509_ALGOR **pmaskHash) -{ - RSA_PSS_PARAMS *pss; - - *pmaskHash = NULL; - - pss = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_PSS_PARAMS), - alg->parameter); - - if (!pss) - return NULL; - - *pmaskHash = rsa_mgf1_decode(pss->maskGenAlgorithm); - - return pss; -} - -static int rsa_pss_param_print(BIO *bp, RSA_PSS_PARAMS *pss, - X509_ALGOR *maskHash, int indent) +static int rsa_pss_param_print(BIO *bp, int pss_key, RSA_PSS_PARAMS *pss, + int indent) { int rv = 0; - if (!pss) { - if (BIO_puts(bp, " (INVALID PSS PARAMETERS)\n") <= 0) + X509_ALGOR *maskHash = NULL; + + if (!BIO_indent(bp, indent, 128)) + goto err; + if (pss_key) { + if (pss == NULL) { + if (BIO_puts(bp, "No PSS parameter restrictions\n") <= 0) + return 0; + return 1; + } else { + if (BIO_puts(bp, "PSS parameter restrictions:") <= 0) + return 0; + } + } else if (pss == NULL) { + if (BIO_puts(bp,"(INVALID PSS PARAMETERS)\n") <= 0) return 0; return 1; } if (BIO_puts(bp, "\n") <= 0) goto err; + if (pss_key) + indent += 2; if (!BIO_indent(bp, indent, 128)) goto err; if (BIO_puts(bp, "Hash Algorithm: ") <= 0) @@ -236,8 +250,9 @@ static int rsa_pss_param_print(BIO *bp, RSA_PSS_PARAMS *pss, if (pss->hashAlgorithm) { if (i2a_ASN1_OBJECT(bp, pss->hashAlgorithm->algorithm) <= 0) goto err; - } else if (BIO_puts(bp, "sha1 (default)") <= 0) + } else if (BIO_puts(bp, "sha1 (default)") <= 0) { goto err; + } if (BIO_puts(bp, "\n") <= 0) goto err; @@ -252,24 +267,28 @@ static int rsa_pss_param_print(BIO *bp, RSA_PSS_PARAMS *pss, goto err; if (BIO_puts(bp, " with ") <= 0) goto err; - if (maskHash) { + maskHash = rsa_mgf1_decode(pss->maskGenAlgorithm); + if (maskHash != NULL) { if (i2a_ASN1_OBJECT(bp, maskHash->algorithm) <= 0) goto err; - } else if (BIO_puts(bp, "INVALID") <= 0) + } else if (BIO_puts(bp, "INVALID") <= 0) { goto err; - } else if (BIO_puts(bp, "mgf1 with sha1 (default)") <= 0) + } + } else if (BIO_puts(bp, "mgf1 with sha1 (default)") <= 0) { goto err; + } BIO_puts(bp, "\n"); if (!BIO_indent(bp, indent, 128)) goto err; - if (BIO_puts(bp, "Salt Length: 0x") <= 0) + if (BIO_printf(bp, "%s Salt Length: 0x", pss_key ? "Minimum" : "") <= 0) goto err; if (pss->saltLength) { if (i2a_ASN1_INTEGER(bp, pss->saltLength) <= 0) goto err; - } else if (BIO_puts(bp, "14 (default)") <= 0) + } else if (BIO_puts(bp, "14 (default)") <= 0) { goto err; + } BIO_puts(bp, "\n"); if (!BIO_indent(bp, indent, 128)) @@ -279,32 +298,155 @@ static int rsa_pss_param_print(BIO *bp, RSA_PSS_PARAMS *pss, if (pss->trailerField) { if (i2a_ASN1_INTEGER(bp, pss->trailerField) <= 0) goto err; - } else if (BIO_puts(bp, "BC (default)") <= 0) + } else if (BIO_puts(bp, "BC (default)") <= 0) { goto err; + } BIO_puts(bp, "\n"); rv = 1; err: + X509_ALGOR_free(maskHash); return rv; } +static int pkey_rsa_print(BIO *bp, const EVP_PKEY *pkey, int off, int priv) +{ + const RSA *x = pkey->pkey.rsa; + char *str; + const char *s; + int ret = 0, mod_len = 0, ex_primes; + + if (x->n != NULL) + mod_len = BN_num_bits(x->n); + ex_primes = sk_RSA_PRIME_INFO_num(x->prime_infos); + + if (!BIO_indent(bp, off, 128)) + goto err; + + if (BIO_printf(bp, "%s ", pkey_is_pss(pkey) ? "RSA-PSS" : "RSA") <= 0) + goto err; + + if (priv && x->d) { + if (BIO_printf(bp, "Private-Key: (%d bit, %d primes)\n", + mod_len, ex_primes <= 0 ? 2 : ex_primes + 2) <= 0) + goto err; + str = "modulus:"; + s = "publicExponent:"; + } else { + if (BIO_printf(bp, "Public-Key: (%d bit)\n", mod_len) <= 0) + goto err; + str = "Modulus:"; + s = "Exponent:"; + } + if (!ASN1_bn_print(bp, str, x->n, NULL, off)) + goto err; + if (!ASN1_bn_print(bp, s, x->e, NULL, off)) + goto err; + if (priv) { + int i; + + if (!ASN1_bn_print(bp, "privateExponent:", x->d, NULL, off)) + goto err; + if (!ASN1_bn_print(bp, "prime1:", x->p, NULL, off)) + goto err; + if (!ASN1_bn_print(bp, "prime2:", x->q, NULL, off)) + goto err; + if (!ASN1_bn_print(bp, "exponent1:", x->dmp1, NULL, off)) + goto err; + if (!ASN1_bn_print(bp, "exponent2:", x->dmq1, NULL, off)) + goto err; + if (!ASN1_bn_print(bp, "coefficient:", x->iqmp, NULL, off)) + goto err; + for (i = 0; i < sk_RSA_PRIME_INFO_num(x->prime_infos); i++) { + /* print multi-prime info */ + BIGNUM *bn = NULL; + RSA_PRIME_INFO *pinfo; + int j; + + pinfo = sk_RSA_PRIME_INFO_value(x->prime_infos, i); + for (j = 0; j < 3; j++) { + if (!BIO_indent(bp, off, 128)) + goto err; + switch (j) { + case 0: + if (BIO_printf(bp, "prime%d:", i + 3) <= 0) + goto err; + bn = pinfo->r; + break; + case 1: + if (BIO_printf(bp, "exponent%d:", i + 3) <= 0) + goto err; + bn = pinfo->d; + break; + case 2: + if (BIO_printf(bp, "coefficient%d:", i + 3) <= 0) + goto err; + bn = pinfo->t; + break; + default: + break; + } + if (!ASN1_bn_print(bp, "", bn, NULL, off)) + goto err; + } + } + } + if (pkey_is_pss(pkey) && !rsa_pss_param_print(bp, 1, x->pss, off)) + goto err; + ret = 1; + err: + return ret; +} + +static int rsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *ctx) +{ + return pkey_rsa_print(bp, pkey, indent, 0); +} + +static int rsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent, + ASN1_PCTX *ctx) +{ + return pkey_rsa_print(bp, pkey, indent, 1); +} + +static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg) +{ + RSA_PSS_PARAMS *pss; + + pss = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_PSS_PARAMS), + alg->parameter); + + if (pss == NULL) + return NULL; + + if (pss->maskGenAlgorithm != NULL) { + pss->maskHash = rsa_mgf1_decode(pss->maskGenAlgorithm); + if (pss->maskHash == NULL) { + RSA_PSS_PARAMS_free(pss); + return NULL; + } + } + + return pss; +} + static int rsa_sig_print(BIO *bp, const X509_ALGOR *sigalg, const ASN1_STRING *sig, int indent, ASN1_PCTX *pctx) { - if (OBJ_obj2nid(sigalg->algorithm) == NID_rsassaPss) { + if (OBJ_obj2nid(sigalg->algorithm) == EVP_PKEY_RSA_PSS) { int rv; - RSA_PSS_PARAMS *pss; - X509_ALGOR *maskHash; - pss = rsa_pss_decode(sigalg, &maskHash); - rv = rsa_pss_param_print(bp, pss, maskHash, indent); + RSA_PSS_PARAMS *pss = rsa_pss_decode(sigalg); + + rv = rsa_pss_param_print(bp, 0, pss, indent); RSA_PSS_PARAMS_free(pss); - X509_ALGOR_free(maskHash); if (!rv) return 0; - } else if (!sig && BIO_puts(bp, "\n") <= 0) + } else if (!sig && BIO_puts(bp, "\n") <= 0) { return 0; + } if (sig) return X509_signature_dump(bp, sig, indent); return 1; @@ -313,6 +455,7 @@ static int rsa_sig_print(BIO *bp, const X509_ALGOR *sigalg, static int rsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) { X509_ALGOR *alg = NULL; + switch (op) { case ASN1_PKEY_CTRL_PKCS7_SIGN: @@ -321,6 +464,8 @@ static int rsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) break; case ASN1_PKEY_CTRL_PKCS7_ENCRYPT: + if (pkey_is_pss(pkey)) + return -2; if (arg1 == 0) PKCS7_RECIP_INFO_get0_alg(arg2, &alg); break; @@ -333,6 +478,8 @@ static int rsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) break; case ASN1_PKEY_CTRL_CMS_ENVELOPE: + if (pkey_is_pss(pkey)) + return -2; if (arg1 == 0) return rsa_cms_encrypt(arg2); else if (arg1 == 1) @@ -340,6 +487,8 @@ static int rsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) break; case ASN1_PKEY_CTRL_CMS_RI_TYPE: + if (pkey_is_pss(pkey)) + return -2; *(int *)arg2 = CMS_RECIPINFO_TRANS; return 1; #endif @@ -363,7 +512,7 @@ static int rsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) /* allocate and set algorithm ID from EVP_MD, default SHA1 */ static int rsa_md_to_algor(X509_ALGOR **palg, const EVP_MD *md) { - if (EVP_MD_type(md) == NID_sha1) + if (md == NULL || EVP_MD_type(md) == NID_sha1) return 1; *palg = X509_ALGOR_new(); if (*palg == NULL) @@ -377,13 +526,14 @@ static int rsa_md_to_mgf1(X509_ALGOR **palg, const EVP_MD *mgf1md) { X509_ALGOR *algtmp = NULL; ASN1_STRING *stmp = NULL; + *palg = NULL; - if (EVP_MD_type(mgf1md) == NID_sha1) + if (mgf1md == NULL || EVP_MD_type(mgf1md) == NID_sha1) return 1; /* need to embed algorithm ID inside another */ if (!rsa_md_to_algor(&algtmp, mgf1md)) goto err; - if (!ASN1_item_pack(algtmp, ASN1_ITEM_rptr(X509_ALGOR), &stmp)) + if (ASN1_item_pack(algtmp, ASN1_ITEM_rptr(X509_ALGOR), &stmp) == NULL) goto err; *palg = X509_ALGOR_new(); if (*palg == NULL) @@ -402,6 +552,7 @@ static int rsa_md_to_mgf1(X509_ALGOR **palg, const EVP_MD *mgf1md) static const EVP_MD *rsa_algor_to_md(X509_ALGOR *alg) { const EVP_MD *md; + if (!alg) return EVP_sha1(); md = EVP_get_digestbyobj(alg->algorithm); @@ -410,55 +561,39 @@ static const EVP_MD *rsa_algor_to_md(X509_ALGOR *alg) return md; } -/* convert MGF1 algorithm ID to EVP_MD, default SHA1 */ -static const EVP_MD *rsa_mgf1_to_md(X509_ALGOR *alg, X509_ALGOR *maskHash) -{ - const EVP_MD *md; - if (!alg) - return EVP_sha1(); - /* Check mask and lookup mask hash algorithm */ - if (OBJ_obj2nid(alg->algorithm) != NID_mgf1) { - RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNSUPPORTED_MASK_ALGORITHM); - return NULL; - } - if (!maskHash) { - RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNSUPPORTED_MASK_PARAMETER); - return NULL; - } - md = EVP_get_digestbyobj(maskHash->algorithm); - if (md == NULL) { - RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNKNOWN_MASK_DIGEST); - return NULL; - } - return md; -} - /* - * Convert EVP_PKEY_CTX is PSS mode into corresponding algorithm parameter, + * Convert EVP_PKEY_CTX in PSS mode into corresponding algorithm parameter, * suitable for setting an AlgorithmIdentifier. */ -static ASN1_STRING *rsa_ctx_to_pss(EVP_PKEY_CTX *pkctx) +static RSA_PSS_PARAMS *rsa_ctx_to_pss(EVP_PKEY_CTX *pkctx) { const EVP_MD *sigmd, *mgf1md; - RSA_PSS_PARAMS *pss = NULL; - ASN1_STRING *os = NULL; EVP_PKEY *pk = EVP_PKEY_CTX_get0_pkey(pkctx); - int saltlen, rv = 0; + int saltlen; + if (EVP_PKEY_CTX_get_signature_md(pkctx, &sigmd) <= 0) - goto err; + return NULL; if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0) - goto err; + return NULL; if (!EVP_PKEY_CTX_get_rsa_pss_saltlen(pkctx, &saltlen)) - goto err; - if (saltlen == -1) + return NULL; + if (saltlen == -1) { saltlen = EVP_MD_size(sigmd); - else if (saltlen == -2) { + } else if (saltlen == -2) { saltlen = EVP_PKEY_size(pk) - EVP_MD_size(sigmd) - 2; - if (((EVP_PKEY_bits(pk) - 1) & 0x7) == 0) + if ((EVP_PKEY_bits(pk) & 0x7) == 1) saltlen--; } - pss = RSA_PSS_PARAMS_new(); + + return rsa_pss_params_create(sigmd, mgf1md, saltlen); +} + +RSA_PSS_PARAMS *rsa_pss_params_create(const EVP_MD *sigmd, + const EVP_MD *mgf1md, int saltlen) +{ + RSA_PSS_PARAMS *pss = RSA_PSS_PARAMS_new(); + if (pss == NULL) goto err; if (saltlen != 20) { @@ -470,20 +605,31 @@ static ASN1_STRING *rsa_ctx_to_pss(EVP_PKEY_CTX *pkctx) } if (!rsa_md_to_algor(&pss->hashAlgorithm, sigmd)) goto err; + if (mgf1md == NULL) + mgf1md = sigmd; if (!rsa_md_to_mgf1(&pss->maskGenAlgorithm, mgf1md)) goto err; - /* Finally create string with pss parameter encoding. */ - if (!ASN1_item_pack(pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), &os)) - goto err; - rv = 1; + if (!rsa_md_to_algor(&pss->maskHash, mgf1md)) + goto err; + return pss; err: RSA_PSS_PARAMS_free(pss); - if (rv) - return os; - ASN1_STRING_free(os); return NULL; } +static ASN1_STRING *rsa_ctx_to_pss_string(EVP_PKEY_CTX *pkctx) +{ + RSA_PSS_PARAMS *pss = rsa_ctx_to_pss(pkctx); + ASN1_STRING *os; + + if (pss == NULL) + return NULL; + + os = ASN1_item_pack(pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), NULL); + RSA_PSS_PARAMS_free(pss); + return os; +} + /* * From PSS AlgorithmIdentifier set public key parameters. If pkey isn't NULL * then the EVP_MD_CTX is setup and initialised. If it is NULL parameters are @@ -497,51 +643,21 @@ static int rsa_pss_to_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pkctx, int saltlen; const EVP_MD *mgf1md = NULL, *md = NULL; RSA_PSS_PARAMS *pss; - X509_ALGOR *maskHash; + /* Sanity check: make sure it is PSS */ - if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) { + if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) { RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } /* Decode PSS parameters */ - pss = rsa_pss_decode(sigalg, &maskHash); + pss = rsa_pss_decode(sigalg); - if (pss == NULL) { + if (!rsa_pss_get_param(pss, &md, &mgf1md, &saltlen)) { RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_INVALID_PSS_PARAMETERS); goto err; } - mgf1md = rsa_mgf1_to_md(pss->maskGenAlgorithm, maskHash); - if (!mgf1md) - goto err; - md = rsa_algor_to_md(pss->hashAlgorithm); - if (!md) - goto err; - - if (pss->saltLength) { - saltlen = ASN1_INTEGER_get(pss->saltLength); - - /* - * Could perform more salt length sanity checks but the main RSA - * routines will trap other invalid values anyway. - */ - if (saltlen < 0) { - RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_INVALID_SALT_LENGTH); - goto err; - } - } else - saltlen = 20; - - /* - * low-level routines support only trailer field 0xbc (value 1) and - * PKCS#1 says we should reject any other value anyway. - */ - if (pss->trailerField && ASN1_INTEGER_get(pss->trailerField) != 1) { - RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_INVALID_TRAILER); - goto err; - } /* We have all parameters now set up context */ - if (pkey) { if (!EVP_DigestVerifyInit(ctx, &pkctx, md, NULL, pkey)) goto err; @@ -568,22 +684,60 @@ static int rsa_pss_to_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pkctx, err: RSA_PSS_PARAMS_free(pss); - X509_ALGOR_free(maskHash); return rv; } +int rsa_pss_get_param(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd, + const EVP_MD **pmgf1md, int *psaltlen) +{ + if (pss == NULL) + return 0; + *pmd = rsa_algor_to_md(pss->hashAlgorithm); + if (*pmd == NULL) + return 0; + *pmgf1md = rsa_algor_to_md(pss->maskHash); + if (*pmgf1md == NULL) + return 0; + if (pss->saltLength) { + *psaltlen = ASN1_INTEGER_get(pss->saltLength); + if (*psaltlen < 0) { + RSAerr(RSA_F_RSA_PSS_GET_PARAM, RSA_R_INVALID_SALT_LENGTH); + return 0; + } + } else { + *psaltlen = 20; + } + + /* + * low-level routines support only trailer field 0xbc (value 1) and + * PKCS#1 says we should reject any other value anyway. + */ + if (pss->trailerField && ASN1_INTEGER_get(pss->trailerField) != 1) { + RSAerr(RSA_F_RSA_PSS_GET_PARAM, RSA_R_INVALID_TRAILER); + return 0; + } + + return 1; +} + #ifndef OPENSSL_NO_CMS static int rsa_cms_verify(CMS_SignerInfo *si) { int nid, nid2; X509_ALGOR *alg; EVP_PKEY_CTX *pkctx = CMS_SignerInfo_get0_pkey_ctx(si); + CMS_SignerInfo_get0_algs(si, NULL, NULL, NULL, &alg); nid = OBJ_obj2nid(alg->algorithm); + if (nid == EVP_PKEY_RSA_PSS) + return rsa_pss_to_ctx(NULL, pkctx, alg, NULL); + /* Only PSS allowed for PSS keys */ + if (pkey_ctx_is_pss(pkctx)) { + RSAerr(RSA_F_RSA_CMS_VERIFY, RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE); + return 0; + } if (nid == NID_rsaEncryption) return 1; - if (nid == NID_rsassaPss) - return rsa_pss_to_ctx(NULL, pkctx, alg, NULL); /* Workaround for some implementation that use a signature OID */ if (OBJ_find_sigid_algs(nid, NULL, &nid2)) { if (nid2 == NID_rsaEncryption) @@ -603,7 +757,7 @@ static int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, EVP_PKEY *pkey) { /* Sanity check: make sure it is PSS */ - if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) { + if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) { RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } @@ -621,6 +775,7 @@ static int rsa_cms_sign(CMS_SignerInfo *si) X509_ALGOR *alg; EVP_PKEY_CTX *pkctx = CMS_SignerInfo_get0_pkey_ctx(si); ASN1_STRING *os = NULL; + CMS_SignerInfo_get0_algs(si, NULL, NULL, NULL, &alg); if (pkctx) { if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0) @@ -633,10 +788,10 @@ static int rsa_cms_sign(CMS_SignerInfo *si) /* We don't support it */ if (pad_mode != RSA_PKCS1_PSS_PADDING) return 0; - os = rsa_ctx_to_pss(pkctx); + os = rsa_ctx_to_pss_string(pkctx); if (!os) return 0; - X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsassaPss), V_ASN1_SEQUENCE, os); + X509_ALGOR_set0(alg, OBJ_nid2obj(EVP_PKEY_RSA_PSS), V_ASN1_SEQUENCE, os); return 1; } #endif @@ -647,13 +802,14 @@ static int rsa_item_sign(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, { int pad_mode; EVP_PKEY_CTX *pkctx = EVP_MD_CTX_pkey_ctx(ctx); + if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0) return 0; if (pad_mode == RSA_PKCS1_PADDING) return 2; if (pad_mode == RSA_PKCS1_PSS_PADDING) { ASN1_STRING *os1 = NULL; - os1 = rsa_ctx_to_pss(pkctx); + os1 = rsa_ctx_to_pss_string(pkctx); if (!os1) return 0; /* Duplicate parameters if we have to */ @@ -663,33 +819,70 @@ static int rsa_item_sign(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, ASN1_STRING_free(os1); return 0; } - X509_ALGOR_set0(alg2, OBJ_nid2obj(NID_rsassaPss), + X509_ALGOR_set0(alg2, OBJ_nid2obj(EVP_PKEY_RSA_PSS), V_ASN1_SEQUENCE, os2); } - X509_ALGOR_set0(alg1, OBJ_nid2obj(NID_rsassaPss), + X509_ALGOR_set0(alg1, OBJ_nid2obj(EVP_PKEY_RSA_PSS), V_ASN1_SEQUENCE, os1); return 3; } return 2; } -#ifndef OPENSSL_NO_CMS -static RSA_OAEP_PARAMS *rsa_oaep_decode(const X509_ALGOR *alg, - X509_ALGOR **pmaskHash) +static int rsa_sig_info_set(X509_SIG_INFO *siginf, const X509_ALGOR *sigalg, + const ASN1_STRING *sig) { - RSA_OAEP_PARAMS *pss; + int rv = 0; + int mdnid, saltlen; + uint32_t flags; + const EVP_MD *mgf1md = NULL, *md = NULL; + RSA_PSS_PARAMS *pss; - *pmaskHash = NULL; + /* Sanity check: make sure it is PSS */ + if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) + return 0; + /* Decode PSS parameters */ + pss = rsa_pss_decode(sigalg); + if (!rsa_pss_get_param(pss, &md, &mgf1md, &saltlen)) + goto err; + mdnid = EVP_MD_type(md); + /* + * For TLS need SHA256, SHA384 or SHA512, digest and MGF1 digest must + * match and salt length must equal digest size + */ + if ((mdnid == NID_sha256 || mdnid == NID_sha384 || mdnid == NID_sha512) + && mdnid == EVP_MD_type(mgf1md) && saltlen == EVP_MD_size(md)) + flags = X509_SIG_INFO_TLS; + else + flags = 0; + /* Note: security bits half number of digest bits */ + X509_SIG_INFO_set(siginf, mdnid, EVP_PKEY_RSA_PSS, EVP_MD_size(md) * 4, + flags); + rv = 1; + err: + RSA_PSS_PARAMS_free(pss); + return rv; +} - pss = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_OAEP_PARAMS), - alg->parameter); +#ifndef OPENSSL_NO_CMS +static RSA_OAEP_PARAMS *rsa_oaep_decode(const X509_ALGOR *alg) +{ + RSA_OAEP_PARAMS *oaep; - if (!pss) + oaep = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_OAEP_PARAMS), + alg->parameter); + + if (oaep == NULL) return NULL; - *pmaskHash = rsa_mgf1_decode(pss->maskGenFunc); - - return pss; + if (oaep->maskGenFunc != NULL) { + oaep->maskHash = rsa_mgf1_decode(oaep->maskGenFunc); + if (oaep->maskHash == NULL) { + RSA_OAEP_PARAMS_free(oaep); + return NULL; + } + } + return oaep; } static int rsa_cms_decrypt(CMS_RecipientInfo *ri) @@ -702,9 +895,9 @@ static int rsa_cms_decrypt(CMS_RecipientInfo *ri) int labellen = 0; const EVP_MD *mgf1md = NULL, *md = NULL; RSA_OAEP_PARAMS *oaep; - X509_ALGOR *maskHash; + pkctx = CMS_RecipientInfo_get0_pkey_ctx(ri); - if (!pkctx) + if (pkctx == NULL) return 0; if (!CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &cmsalg)) return -1; @@ -716,22 +909,23 @@ static int rsa_cms_decrypt(CMS_RecipientInfo *ri) return -1; } /* Decode OAEP parameters */ - oaep = rsa_oaep_decode(cmsalg, &maskHash); + oaep = rsa_oaep_decode(cmsalg); if (oaep == NULL) { RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_INVALID_OAEP_PARAMETERS); goto err; } - mgf1md = rsa_mgf1_to_md(oaep->maskGenFunc, maskHash); - if (!mgf1md) + mgf1md = rsa_algor_to_md(oaep->maskHash); + if (mgf1md == NULL) goto err; md = rsa_algor_to_md(oaep->hashFunc); - if (!md) + if (md == NULL) goto err; - if (oaep->pSourceFunc) { + if (oaep->pSourceFunc != NULL) { X509_ALGOR *plab = oaep->pSourceFunc; + if (OBJ_obj2nid(plab->algorithm) != NID_pSpecified) { RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_UNSUPPORTED_LABEL_SOURCE); goto err; @@ -760,7 +954,6 @@ static int rsa_cms_decrypt(CMS_RecipientInfo *ri) err: RSA_OAEP_PARAMS_free(oaep); - X509_ALGOR_free(maskHash); return rv; } @@ -773,8 +966,8 @@ static int rsa_cms_encrypt(CMS_RecipientInfo *ri) EVP_PKEY_CTX *pkctx = CMS_RecipientInfo_get0_pkey_ctx(ri); int pad_mode = RSA_PKCS1_PADDING, rv = 0, labellen; unsigned char *label; - if (CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &alg) <= 0) - return 0; + + CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &alg); if (pkctx) { if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0) return 0; @@ -828,6 +1021,11 @@ static int rsa_cms_encrypt(CMS_RecipientInfo *ri) } #endif +static int rsa_pkey_check(const EVP_PKEY *pkey) +{ + return RSA_check_key_ex(pkey->pkey.rsa, NULL); +} + const EVP_PKEY_ASN1_METHOD rsa_asn1_meths[2] = { { EVP_PKEY_RSA, @@ -858,10 +1056,46 @@ const EVP_PKEY_ASN1_METHOD rsa_asn1_meths[2] = { old_rsa_priv_decode, old_rsa_priv_encode, rsa_item_verify, - rsa_item_sign}, + rsa_item_sign, + rsa_sig_info_set, + rsa_pkey_check + }, { EVP_PKEY_RSA2, EVP_PKEY_RSA, ASN1_PKEY_ALIAS} }; + +const EVP_PKEY_ASN1_METHOD rsa_pss_asn1_meth = { + EVP_PKEY_RSA_PSS, + EVP_PKEY_RSA_PSS, + ASN1_PKEY_SIGPARAM_NULL, + + "RSA-PSS", + "OpenSSL RSA-PSS method", + + rsa_pub_decode, + rsa_pub_encode, + rsa_pub_cmp, + rsa_pub_print, + + rsa_priv_decode, + rsa_priv_encode, + rsa_priv_print, + + int_rsa_size, + rsa_bits, + rsa_security_bits, + + 0, 0, 0, 0, 0, 0, + + rsa_sig_print, + int_rsa_free, + rsa_pkey_ctrl, + 0, 0, + rsa_item_verify, + rsa_item_sign, + 0, + rsa_pkey_check +}; diff --git a/crypto/rsa/rsa_asn1.c b/crypto/rsa/rsa_asn1.c index 20f8ebfa..9fe62c82 100644 --- a/crypto/rsa/rsa_asn1.c +++ b/crypto/rsa/rsa_asn1.c @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2000-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 @@ -14,7 +14,11 @@ #include #include "rsa_locl.h" -/* Override the default free and new methods */ +/* + * Override the default free and new methods, + * and calculate helper products for multi-prime + * RSA keys. + */ static int rsa_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { @@ -27,12 +31,25 @@ static int rsa_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, RSA_free((RSA *)*pval); *pval = NULL; return 2; + } else if (operation == ASN1_OP_D2I_POST) { + if (((RSA *)*pval)->version != RSA_ASN1_VERSION_MULTI) { + /* not a multi-prime key, skip */ + return 1; + } + return (rsa_multip_calc_product((RSA *)*pval) == 1) ? 2 : 0; } return 1; } +/* Based on definitions in RFC 8017 appendix A.1.2 */ +ASN1_SEQUENCE(RSA_PRIME_INFO) = { + ASN1_SIMPLE(RSA_PRIME_INFO, r, CBIGNUM), + ASN1_SIMPLE(RSA_PRIME_INFO, d, CBIGNUM), + ASN1_SIMPLE(RSA_PRIME_INFO, t, CBIGNUM), +} ASN1_SEQUENCE_END(RSA_PRIME_INFO) + ASN1_SEQUENCE_cb(RSAPrivateKey, rsa_cb) = { - ASN1_SIMPLE(RSA, version, LONG), + ASN1_EMBED(RSA, version, INT32), ASN1_SIMPLE(RSA, n, BIGNUM), ASN1_SIMPLE(RSA, e, BIGNUM), ASN1_SIMPLE(RSA, d, CBIGNUM), @@ -40,7 +57,8 @@ ASN1_SEQUENCE_cb(RSAPrivateKey, rsa_cb) = { ASN1_SIMPLE(RSA, q, CBIGNUM), ASN1_SIMPLE(RSA, dmp1, CBIGNUM), ASN1_SIMPLE(RSA, dmq1, CBIGNUM), - ASN1_SIMPLE(RSA, iqmp, CBIGNUM) + ASN1_SIMPLE(RSA, iqmp, CBIGNUM), + ASN1_SEQUENCE_OF_OPT(RSA, prime_infos, RSA_PRIME_INFO) } ASN1_SEQUENCE_END_cb(RSA, RSAPrivateKey) @@ -49,20 +67,42 @@ ASN1_SEQUENCE_cb(RSAPublicKey, rsa_cb) = { ASN1_SIMPLE(RSA, e, BIGNUM), } ASN1_SEQUENCE_END_cb(RSA, RSAPublicKey) -ASN1_SEQUENCE(RSA_PSS_PARAMS) = { +/* Free up maskHash */ +static int rsa_pss_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, + void *exarg) +{ + if (operation == ASN1_OP_FREE_PRE) { + RSA_PSS_PARAMS *pss = (RSA_PSS_PARAMS *)*pval; + X509_ALGOR_free(pss->maskHash); + } + return 1; +} + +ASN1_SEQUENCE_cb(RSA_PSS_PARAMS, rsa_pss_cb) = { ASN1_EXP_OPT(RSA_PSS_PARAMS, hashAlgorithm, X509_ALGOR,0), ASN1_EXP_OPT(RSA_PSS_PARAMS, maskGenAlgorithm, X509_ALGOR,1), ASN1_EXP_OPT(RSA_PSS_PARAMS, saltLength, ASN1_INTEGER,2), ASN1_EXP_OPT(RSA_PSS_PARAMS, trailerField, ASN1_INTEGER,3) -} ASN1_SEQUENCE_END(RSA_PSS_PARAMS) +} ASN1_SEQUENCE_END_cb(RSA_PSS_PARAMS, RSA_PSS_PARAMS) IMPLEMENT_ASN1_FUNCTIONS(RSA_PSS_PARAMS) -ASN1_SEQUENCE(RSA_OAEP_PARAMS) = { +/* Free up maskHash */ +static int rsa_oaep_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, + void *exarg) +{ + if (operation == ASN1_OP_FREE_PRE) { + RSA_OAEP_PARAMS *oaep = (RSA_OAEP_PARAMS *)*pval; + X509_ALGOR_free(oaep->maskHash); + } + return 1; +} + +ASN1_SEQUENCE_cb(RSA_OAEP_PARAMS, rsa_oaep_cb) = { ASN1_EXP_OPT(RSA_OAEP_PARAMS, hashFunc, X509_ALGOR, 0), ASN1_EXP_OPT(RSA_OAEP_PARAMS, maskGenFunc, X509_ALGOR, 1), ASN1_EXP_OPT(RSA_OAEP_PARAMS, pSourceFunc, X509_ALGOR, 2), -} ASN1_SEQUENCE_END(RSA_OAEP_PARAMS) +} ASN1_SEQUENCE_END_cb(RSA_OAEP_PARAMS, RSA_OAEP_PARAMS) IMPLEMENT_ASN1_FUNCTIONS(RSA_OAEP_PARAMS) diff --git a/crypto/rsa/rsa_chk.c b/crypto/rsa/rsa_chk.c index 00260fb1..1b69be30 100644 --- a/crypto/rsa/rsa_chk.c +++ b/crypto/rsa/rsa_chk.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-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 @@ -20,7 +20,8 @@ int RSA_check_key_ex(const RSA *key, BN_GENCB *cb) { BIGNUM *i, *j, *k, *l, *m; BN_CTX *ctx; - int ret = 1; + int ret = 1, ex_primes = 0, idx; + RSA_PRIME_INFO *pinfo; if (key->p == NULL || key->q == NULL || key->n == NULL || key->e == NULL || key->d == NULL) { @@ -28,6 +29,16 @@ int RSA_check_key_ex(const RSA *key, BN_GENCB *cb) return 0; } + /* multi-prime? */ + if (key->version == RSA_ASN1_VERSION_MULTI) { + ex_primes = sk_RSA_PRIME_INFO_num(key->prime_infos); + if (ex_primes <= 0 + || (ex_primes + 2) > rsa_multip_cap(BN_num_bits(key->n))) { + RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_INVALID_MULTI_PRIME_KEY); + return 0; + } + } + i = BN_new(); j = BN_new(); k = BN_new(); @@ -62,17 +73,37 @@ int RSA_check_key_ex(const RSA *key, BN_GENCB *cb) RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_Q_NOT_PRIME); } - /* n = p*q? */ + /* r_i prime? */ + for (idx = 0; idx < ex_primes; idx++) { + pinfo = sk_RSA_PRIME_INFO_value(key->prime_infos, idx); + if (BN_is_prime_ex(pinfo->r, BN_prime_checks, NULL, cb) != 1) { + ret = 0; + RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_MP_R_NOT_PRIME); + } + } + + /* n = p*q * r_3...r_i? */ if (!BN_mul(i, key->p, key->q, ctx)) { ret = -1; goto err; } + for (idx = 0; idx < ex_primes; idx++) { + pinfo = sk_RSA_PRIME_INFO_value(key->prime_infos, idx); + if (!BN_mul(i, i, pinfo->r, ctx)) { + ret = -1; + goto err; + } + } if (BN_cmp(i, key->n) != 0) { ret = 0; - RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_N_DOES_NOT_EQUAL_P_Q); + if (ex_primes) + RSAerr(RSA_F_RSA_CHECK_KEY_EX, + RSA_R_N_DOES_NOT_EQUAL_PRODUCT_OF_PRIMES); + else + RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_N_DOES_NOT_EQUAL_P_Q); } - /* d*e = 1 mod lcm(p-1,q-1)? */ + /* d*e = 1 mod \lambda(n)? */ if (!BN_sub(i, key->p, BN_value_one())) { ret = -1; goto err; @@ -82,7 +113,7 @@ int RSA_check_key_ex(const RSA *key, BN_GENCB *cb) goto err; } - /* now compute k = lcm(i,j) */ + /* now compute k = \lambda(n) = LCM(i, j, r_3 - 1...) */ if (!BN_mul(l, i, j, ctx)) { ret = -1; goto err; @@ -91,6 +122,21 @@ int RSA_check_key_ex(const RSA *key, BN_GENCB *cb) ret = -1; goto err; } + for (idx = 0; idx < ex_primes; idx++) { + pinfo = sk_RSA_PRIME_INFO_value(key->prime_infos, idx); + if (!BN_sub(k, pinfo->r, BN_value_one())) { + ret = -1; + goto err; + } + if (!BN_mul(l, l, k, ctx)) { + ret = -1; + goto err; + } + if (!BN_gcd(m, m, k, ctx)) { + ret = -1; + goto err; + } + } if (!BN_div(k, NULL, l, m, ctx)) { /* remainder is 0 */ ret = -1; goto err; @@ -145,6 +191,32 @@ int RSA_check_key_ex(const RSA *key, BN_GENCB *cb) } } + for (idx = 0; idx < ex_primes; idx++) { + pinfo = sk_RSA_PRIME_INFO_value(key->prime_infos, idx); + /* d_i = d mod (r_i - 1)? */ + if (!BN_sub(i, pinfo->r, BN_value_one())) { + ret = -1; + goto err; + } + if (!BN_mod(j, key->d, i, ctx)) { + ret = -1; + goto err; + } + if (BN_cmp(j, pinfo->d) != 0) { + ret = 0; + RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_MP_EXPONENT_NOT_CONGRUENT_TO_D); + } + /* t_i = R_i ^ -1 mod r_i ? */ + if (!BN_mod_inverse(i, pinfo->pp, pinfo->r, ctx)) { + ret = -1; + goto err; + } + if (BN_cmp(i, pinfo->t) != 0) { + ret = 0; + RSAerr(RSA_F_RSA_CHECK_KEY_EX, RSA_R_MP_COEFFICIENT_NOT_INVERSE_OF_R); + } + } + err: BN_free(i); BN_free(j); diff --git a/crypto/rsa/rsa_crpt.c b/crypto/rsa/rsa_crpt.c index 9cd733b2..f4ef8b43 100644 --- a/crypto/rsa/rsa_crpt.c +++ b/crypto/rsa/rsa_crpt.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -10,48 +10,47 @@ #include #include #include "internal/cryptlib.h" -#include #include "internal/bn_int.h" #include #include "rsa_locl.h" int RSA_bits(const RSA *r) { - return (BN_num_bits(r->n)); + return BN_num_bits(r->n); } int RSA_size(const RSA *r) { - return (BN_num_bytes(r->n)); + return BN_num_bytes(r->n); } int RSA_public_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { - return (rsa->meth->rsa_pub_enc(flen, from, to, rsa, padding)); + 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) { - return (rsa->meth->rsa_priv_enc(flen, from, to, rsa, padding)); + 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) { - return (rsa->meth->rsa_priv_dec(flen, from, to, rsa, padding)); + 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) { - return (rsa->meth->rsa_pub_dec(flen, from, to, rsa, padding)); + return rsa->meth->rsa_pub_dec(flen, from, to, rsa, padding); } int RSA_flags(const RSA *r) { - return ((r == NULL) ? 0 : r->meth->flags); + return r == NULL ? 0 : r->meth->flags; } void RSA_blinding_off(RSA *rsa) @@ -77,7 +76,7 @@ int RSA_blinding_on(RSA *rsa, BN_CTX *ctx) rsa->flags &= ~RSA_FLAG_NO_BLINDING; ret = 1; err: - return (ret); + return ret; } static BIGNUM *rsa_get_public_exp(const BIGNUM *d, const BIGNUM *p, @@ -117,8 +116,9 @@ BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *in_ctx) if (in_ctx == NULL) { if ((ctx = BN_CTX_new()) == NULL) return 0; - } else + } else { ctx = in_ctx; + } BN_CTX_start(ctx); e = BN_CTX_get(ctx); @@ -133,17 +133,8 @@ BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *in_ctx) RSAerr(RSA_F_RSA_SETUP_BLINDING, RSA_R_NO_PUBLIC_EXPONENT); goto err; } - } else + } else { e = rsa->e; - - if ((RAND_status() == 0) && rsa->d != NULL - && bn_get_words(rsa->d) != NULL) { - /* - * if PRNG is not properly seeded, resort to secret exponent as - * unpredictable seed - */ - RAND_add(bn_get_words(rsa->d), bn_get_dmax(rsa->d) * sizeof(BN_ULONG), - 0.0); } { diff --git a/crypto/rsa/rsa_err.c b/crypto/rsa/rsa_err.c index bf54095b..f7d29e19 100644 --- a/crypto/rsa/rsa_err.c +++ b/crypto/rsa/rsa_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,165 +8,224 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_RSA,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_RSA,0,reason) - -static ERR_STRING_DATA RSA_str_functs[] = { - {ERR_FUNC(RSA_F_CHECK_PADDING_MD), "check_padding_md"}, - {ERR_FUNC(RSA_F_ENCODE_PKCS1), "encode_pkcs1"}, - {ERR_FUNC(RSA_F_INT_RSA_VERIFY), "int_rsa_verify"}, - {ERR_FUNC(RSA_F_OLD_RSA_PRIV_DECODE), "old_rsa_priv_decode"}, - {ERR_FUNC(RSA_F_PKEY_RSA_CTRL), "pkey_rsa_ctrl"}, - {ERR_FUNC(RSA_F_PKEY_RSA_CTRL_STR), "pkey_rsa_ctrl_str"}, - {ERR_FUNC(RSA_F_PKEY_RSA_SIGN), "pkey_rsa_sign"}, - {ERR_FUNC(RSA_F_PKEY_RSA_VERIFY), "pkey_rsa_verify"}, - {ERR_FUNC(RSA_F_PKEY_RSA_VERIFYRECOVER), "pkey_rsa_verifyrecover"}, - {ERR_FUNC(RSA_F_RSA_ALGOR_TO_MD), "rsa_algor_to_md"}, - {ERR_FUNC(RSA_F_RSA_BUILTIN_KEYGEN), "rsa_builtin_keygen"}, - {ERR_FUNC(RSA_F_RSA_CHECK_KEY), "RSA_check_key"}, - {ERR_FUNC(RSA_F_RSA_CHECK_KEY_EX), "RSA_check_key_ex"}, - {ERR_FUNC(RSA_F_RSA_CMS_DECRYPT), "rsa_cms_decrypt"}, - {ERR_FUNC(RSA_F_RSA_ITEM_VERIFY), "rsa_item_verify"}, - {ERR_FUNC(RSA_F_RSA_METH_DUP), "RSA_meth_dup"}, - {ERR_FUNC(RSA_F_RSA_METH_NEW), "RSA_meth_new"}, - {ERR_FUNC(RSA_F_RSA_METH_SET1_NAME), "RSA_meth_set1_name"}, - {ERR_FUNC(RSA_F_RSA_MGF1_TO_MD), "rsa_mgf1_to_md"}, - {ERR_FUNC(RSA_F_RSA_NEW_METHOD), "RSA_new_method"}, - {ERR_FUNC(RSA_F_RSA_NULL), "RSA_NULL"}, - {ERR_FUNC(RSA_F_RSA_NULL_PRIVATE_DECRYPT), "RSA_null_private_decrypt"}, - {ERR_FUNC(RSA_F_RSA_NULL_PRIVATE_ENCRYPT), "RSA_null_private_encrypt"}, - {ERR_FUNC(RSA_F_RSA_NULL_PUBLIC_DECRYPT), "RSA_null_public_decrypt"}, - {ERR_FUNC(RSA_F_RSA_NULL_PUBLIC_ENCRYPT), "RSA_null_public_encrypt"}, - {ERR_FUNC(RSA_F_RSA_OSSL_PRIVATE_DECRYPT), "rsa_ossl_private_decrypt"}, - {ERR_FUNC(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT), "rsa_ossl_private_encrypt"}, - {ERR_FUNC(RSA_F_RSA_OSSL_PUBLIC_DECRYPT), "rsa_ossl_public_decrypt"}, - {ERR_FUNC(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT), "rsa_ossl_public_encrypt"}, - {ERR_FUNC(RSA_F_RSA_PADDING_ADD_NONE), "RSA_padding_add_none"}, - {ERR_FUNC(RSA_F_RSA_PADDING_ADD_PKCS1_OAEP), +static const ERR_STRING_DATA RSA_str_functs[] = { + {ERR_PACK(ERR_LIB_RSA, RSA_F_CHECK_PADDING_MD, 0), "check_padding_md"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_ENCODE_PKCS1, 0), "encode_pkcs1"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_INT_RSA_VERIFY, 0), "int_rsa_verify"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_OLD_RSA_PRIV_DECODE, 0), + "old_rsa_priv_decode"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_PKEY_PSS_INIT, 0), "pkey_pss_init"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_PKEY_RSA_CTRL, 0), "pkey_rsa_ctrl"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_PKEY_RSA_CTRL_STR, 0), "pkey_rsa_ctrl_str"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_PKEY_RSA_SIGN, 0), "pkey_rsa_sign"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_PKEY_RSA_VERIFY, 0), "pkey_rsa_verify"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_PKEY_RSA_VERIFYRECOVER, 0), + "pkey_rsa_verifyrecover"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_ALGOR_TO_MD, 0), "rsa_algor_to_md"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_BUILTIN_KEYGEN, 0), "rsa_builtin_keygen"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_CHECK_KEY, 0), "RSA_check_key"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_CHECK_KEY_EX, 0), "RSA_check_key_ex"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_CMS_DECRYPT, 0), "rsa_cms_decrypt"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_CMS_VERIFY, 0), "rsa_cms_verify"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_ITEM_VERIFY, 0), "rsa_item_verify"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_METH_DUP, 0), "RSA_meth_dup"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_METH_NEW, 0), "RSA_meth_new"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_METH_SET1_NAME, 0), "RSA_meth_set1_name"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_MGF1_TO_MD, 0), ""}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_NEW_METHOD, 0), "RSA_new_method"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_NULL, 0), ""}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_NULL_PRIVATE_DECRYPT, 0), ""}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_NULL_PRIVATE_ENCRYPT, 0), ""}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_NULL_PUBLIC_DECRYPT, 0), ""}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_NULL_PUBLIC_ENCRYPT, 0), ""}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_OSSL_PRIVATE_DECRYPT, 0), + "rsa_ossl_private_decrypt"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, 0), + "rsa_ossl_private_encrypt"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_OSSL_PUBLIC_DECRYPT, 0), + "rsa_ossl_public_decrypt"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, 0), + "rsa_ossl_public_encrypt"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_ADD_NONE, 0), + "RSA_padding_add_none"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_ADD_PKCS1_OAEP, 0), "RSA_padding_add_PKCS1_OAEP"}, - {ERR_FUNC(RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1), + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1, 0), "RSA_padding_add_PKCS1_OAEP_mgf1"}, - {ERR_FUNC(RSA_F_RSA_PADDING_ADD_PKCS1_PSS), "RSA_padding_add_PKCS1_PSS"}, - {ERR_FUNC(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1), + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_ADD_PKCS1_PSS, 0), + "RSA_padding_add_PKCS1_PSS"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1, 0), "RSA_padding_add_PKCS1_PSS_mgf1"}, - {ERR_FUNC(RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_1), + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_1, 0), "RSA_padding_add_PKCS1_type_1"}, - {ERR_FUNC(RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_2), + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_2, 0), "RSA_padding_add_PKCS1_type_2"}, - {ERR_FUNC(RSA_F_RSA_PADDING_ADD_SSLV23), "RSA_padding_add_SSLv23"}, - {ERR_FUNC(RSA_F_RSA_PADDING_ADD_X931), "RSA_padding_add_X931"}, - {ERR_FUNC(RSA_F_RSA_PADDING_CHECK_NONE), "RSA_padding_check_none"}, - {ERR_FUNC(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP), + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_ADD_SSLV23, 0), + "RSA_padding_add_SSLv23"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_ADD_X931, 0), + "RSA_padding_add_X931"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_CHECK_NONE, 0), + "RSA_padding_check_none"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP, 0), "RSA_padding_check_PKCS1_OAEP"}, - {ERR_FUNC(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1), + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1, 0), "RSA_padding_check_PKCS1_OAEP_mgf1"}, - {ERR_FUNC(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1), + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, 0), "RSA_padding_check_PKCS1_type_1"}, - {ERR_FUNC(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2), + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2, 0), "RSA_padding_check_PKCS1_type_2"}, - {ERR_FUNC(RSA_F_RSA_PADDING_CHECK_SSLV23), "RSA_padding_check_SSLv23"}, - {ERR_FUNC(RSA_F_RSA_PADDING_CHECK_X931), "RSA_padding_check_X931"}, - {ERR_FUNC(RSA_F_RSA_PRINT), "RSA_print"}, - {ERR_FUNC(RSA_F_RSA_PRINT_FP), "RSA_print_fp"}, - {ERR_FUNC(RSA_F_RSA_PRIV_ENCODE), "rsa_priv_encode"}, - {ERR_FUNC(RSA_F_RSA_PSS_TO_CTX), "rsa_pss_to_ctx"}, - {ERR_FUNC(RSA_F_RSA_PUB_DECODE), "rsa_pub_decode"}, - {ERR_FUNC(RSA_F_RSA_SETUP_BLINDING), "RSA_setup_blinding"}, - {ERR_FUNC(RSA_F_RSA_SIGN), "RSA_sign"}, - {ERR_FUNC(RSA_F_RSA_SIGN_ASN1_OCTET_STRING), + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_CHECK_SSLV23, 0), + "RSA_padding_check_SSLv23"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PADDING_CHECK_X931, 0), + "RSA_padding_check_X931"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PARAM_DECODE, 0), "rsa_param_decode"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PRINT, 0), "RSA_print"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PRINT_FP, 0), "RSA_print_fp"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PRIV_DECODE, 0), "rsa_priv_decode"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PRIV_ENCODE, 0), "rsa_priv_encode"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PSS_GET_PARAM, 0), "rsa_pss_get_param"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PSS_TO_CTX, 0), "rsa_pss_to_ctx"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_PUB_DECODE, 0), "rsa_pub_decode"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_SETUP_BLINDING, 0), "RSA_setup_blinding"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_SIGN, 0), "RSA_sign"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_SIGN_ASN1_OCTET_STRING, 0), "RSA_sign_ASN1_OCTET_STRING"}, - {ERR_FUNC(RSA_F_RSA_VERIFY), "RSA_verify"}, - {ERR_FUNC(RSA_F_RSA_VERIFY_ASN1_OCTET_STRING), + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_VERIFY, 0), "RSA_verify"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_VERIFY_ASN1_OCTET_STRING, 0), "RSA_verify_ASN1_OCTET_STRING"}, - {ERR_FUNC(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1), "RSA_verify_PKCS1_PSS_mgf1"}, + {ERR_PACK(ERR_LIB_RSA, RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, 0), + "RSA_verify_PKCS1_PSS_mgf1"}, {0, NULL} }; -static ERR_STRING_DATA RSA_str_reasons[] = { - {ERR_REASON(RSA_R_ALGORITHM_MISMATCH), "algorithm mismatch"}, - {ERR_REASON(RSA_R_BAD_E_VALUE), "bad e value"}, - {ERR_REASON(RSA_R_BAD_FIXED_HEADER_DECRYPT), "bad fixed header decrypt"}, - {ERR_REASON(RSA_R_BAD_PAD_BYTE_COUNT), "bad pad byte count"}, - {ERR_REASON(RSA_R_BAD_SIGNATURE), "bad signature"}, - {ERR_REASON(RSA_R_BLOCK_TYPE_IS_NOT_01), "block type is not 01"}, - {ERR_REASON(RSA_R_BLOCK_TYPE_IS_NOT_02), "block type is not 02"}, - {ERR_REASON(RSA_R_DATA_GREATER_THAN_MOD_LEN), - "data greater than mod len"}, - {ERR_REASON(RSA_R_DATA_TOO_LARGE), "data too large"}, - {ERR_REASON(RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE), - "data too large for key size"}, - {ERR_REASON(RSA_R_DATA_TOO_LARGE_FOR_MODULUS), - "data too large for modulus"}, - {ERR_REASON(RSA_R_DATA_TOO_SMALL), "data too small"}, - {ERR_REASON(RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE), - "data too small for key size"}, - {ERR_REASON(RSA_R_DIGEST_DOES_NOT_MATCH), "digest does not match"}, - {ERR_REASON(RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY), - "digest too big for rsa key"}, - {ERR_REASON(RSA_R_DMP1_NOT_CONGRUENT_TO_D), "dmp1 not congruent to d"}, - {ERR_REASON(RSA_R_DMQ1_NOT_CONGRUENT_TO_D), "dmq1 not congruent to d"}, - {ERR_REASON(RSA_R_D_E_NOT_CONGRUENT_TO_1), "d e not congruent to 1"}, - {ERR_REASON(RSA_R_FIRST_OCTET_INVALID), "first octet invalid"}, - {ERR_REASON(RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE), - "illegal or unsupported padding mode"}, - {ERR_REASON(RSA_R_INVALID_DIGEST), "invalid digest"}, - {ERR_REASON(RSA_R_INVALID_DIGEST_LENGTH), "invalid digest length"}, - {ERR_REASON(RSA_R_INVALID_HEADER), "invalid header"}, - {ERR_REASON(RSA_R_INVALID_LABEL), "invalid label"}, - {ERR_REASON(RSA_R_INVALID_MESSAGE_LENGTH), "invalid message length"}, - {ERR_REASON(RSA_R_INVALID_MGF1_MD), "invalid mgf1 md"}, - {ERR_REASON(RSA_R_INVALID_OAEP_PARAMETERS), "invalid oaep parameters"}, - {ERR_REASON(RSA_R_INVALID_PADDING), "invalid padding"}, - {ERR_REASON(RSA_R_INVALID_PADDING_MODE), "invalid padding mode"}, - {ERR_REASON(RSA_R_INVALID_PSS_PARAMETERS), "invalid pss parameters"}, - {ERR_REASON(RSA_R_INVALID_PSS_SALTLEN), "invalid pss saltlen"}, - {ERR_REASON(RSA_R_INVALID_SALT_LENGTH), "invalid salt length"}, - {ERR_REASON(RSA_R_INVALID_TRAILER), "invalid trailer"}, - {ERR_REASON(RSA_R_INVALID_X931_DIGEST), "invalid x931 digest"}, - {ERR_REASON(RSA_R_IQMP_NOT_INVERSE_OF_Q), "iqmp not inverse of q"}, - {ERR_REASON(RSA_R_KEY_SIZE_TOO_SMALL), "key size too small"}, - {ERR_REASON(RSA_R_LAST_OCTET_INVALID), "last octet invalid"}, - {ERR_REASON(RSA_R_MODULUS_TOO_LARGE), "modulus too large"}, - {ERR_REASON(RSA_R_NO_PUBLIC_EXPONENT), "no public exponent"}, - {ERR_REASON(RSA_R_NULL_BEFORE_BLOCK_MISSING), - "null before block missing"}, - {ERR_REASON(RSA_R_N_DOES_NOT_EQUAL_P_Q), "n does not equal p q"}, - {ERR_REASON(RSA_R_OAEP_DECODING_ERROR), "oaep decoding error"}, - {ERR_REASON(RSA_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE), - "operation not supported for this keytype"}, - {ERR_REASON(RSA_R_PADDING_CHECK_FAILED), "padding check failed"}, - {ERR_REASON(RSA_R_PKCS_DECODING_ERROR), "pkcs decoding error"}, - {ERR_REASON(RSA_R_P_NOT_PRIME), "p not prime"}, - {ERR_REASON(RSA_R_Q_NOT_PRIME), "q not prime"}, - {ERR_REASON(RSA_R_RSA_OPERATIONS_NOT_SUPPORTED), - "rsa operations not supported"}, - {ERR_REASON(RSA_R_SLEN_CHECK_FAILED), "salt length check failed"}, - {ERR_REASON(RSA_R_SLEN_RECOVERY_FAILED), "salt length recovery failed"}, - {ERR_REASON(RSA_R_SSLV3_ROLLBACK_ATTACK), "sslv3 rollback attack"}, - {ERR_REASON(RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD), - "the asn1 object identifier is not known for this md"}, - {ERR_REASON(RSA_R_UNKNOWN_ALGORITHM_TYPE), "unknown algorithm type"}, - {ERR_REASON(RSA_R_UNKNOWN_DIGEST), "unknown digest"}, - {ERR_REASON(RSA_R_UNKNOWN_MASK_DIGEST), "unknown mask digest"}, - {ERR_REASON(RSA_R_UNKNOWN_PADDING_TYPE), "unknown padding type"}, - {ERR_REASON(RSA_R_UNSUPPORTED_ENCRYPTION_TYPE), - "unsupported encryption type"}, - {ERR_REASON(RSA_R_UNSUPPORTED_LABEL_SOURCE), "unsupported label source"}, - {ERR_REASON(RSA_R_UNSUPPORTED_MASK_ALGORITHM), - "unsupported mask algorithm"}, - {ERR_REASON(RSA_R_UNSUPPORTED_MASK_PARAMETER), - "unsupported mask parameter"}, - {ERR_REASON(RSA_R_UNSUPPORTED_SIGNATURE_TYPE), - "unsupported signature type"}, - {ERR_REASON(RSA_R_VALUE_MISSING), "value missing"}, - {ERR_REASON(RSA_R_WRONG_SIGNATURE_LENGTH), "wrong signature length"}, +static const ERR_STRING_DATA RSA_str_reasons[] = { + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_ALGORITHM_MISMATCH), "algorithm mismatch"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_E_VALUE), "bad e value"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_FIXED_HEADER_DECRYPT), + "bad fixed header decrypt"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_PAD_BYTE_COUNT), "bad pad byte count"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BAD_SIGNATURE), "bad signature"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BLOCK_TYPE_IS_NOT_01), + "block type is not 01"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_BLOCK_TYPE_IS_NOT_02), + "block type is not 02"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_GREATER_THAN_MOD_LEN), + "data greater than mod len"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_LARGE), "data too large"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE), + "data too large for key size"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_LARGE_FOR_MODULUS), + "data too large for modulus"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_SMALL), "data too small"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE), + "data too small for key size"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DIGEST_DOES_NOT_MATCH), + "digest does not match"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DIGEST_NOT_ALLOWED), "digest not allowed"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY), + "digest too big for rsa key"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DMP1_NOT_CONGRUENT_TO_D), + "dmp1 not congruent to d"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_DMQ1_NOT_CONGRUENT_TO_D), + "dmq1 not congruent to d"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_D_E_NOT_CONGRUENT_TO_1), + "d e not congruent to 1"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_FIRST_OCTET_INVALID), + "first octet invalid"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE), + "illegal or unsupported padding mode"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_DIGEST), "invalid digest"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_DIGEST_LENGTH), + "invalid digest length"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_HEADER), "invalid header"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_LABEL), "invalid label"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MESSAGE_LENGTH), + "invalid message length"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MGF1_MD), "invalid mgf1 md"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_MULTI_PRIME_KEY), + "invalid multi prime key"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_OAEP_PARAMETERS), + "invalid oaep parameters"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PADDING), "invalid padding"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PADDING_MODE), + "invalid padding mode"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PSS_PARAMETERS), + "invalid pss parameters"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_PSS_SALTLEN), + "invalid pss saltlen"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_SALT_LENGTH), + "invalid salt length"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_TRAILER), "invalid trailer"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_INVALID_X931_DIGEST), + "invalid x931 digest"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_IQMP_NOT_INVERSE_OF_Q), + "iqmp not inverse of q"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_KEY_PRIME_NUM_INVALID), + "key prime num invalid"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_KEY_SIZE_TOO_SMALL), "key size too small"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_LAST_OCTET_INVALID), "last octet invalid"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MGF1_DIGEST_NOT_ALLOWED), + "mgf1 digest not allowed"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MODULUS_TOO_LARGE), "modulus too large"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MP_COEFFICIENT_NOT_INVERSE_OF_R), + "mp coefficient not inverse of r"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MP_EXPONENT_NOT_CONGRUENT_TO_D), + "mp exponent not congruent to d"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_MP_R_NOT_PRIME), "mp r not prime"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_NO_PUBLIC_EXPONENT), "no public exponent"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_NULL_BEFORE_BLOCK_MISSING), + "null before block missing"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_N_DOES_NOT_EQUAL_PRODUCT_OF_PRIMES), + "n does not equal product of primes"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_N_DOES_NOT_EQUAL_P_Q), + "n does not equal p q"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_OAEP_DECODING_ERROR), + "oaep decoding error"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE), + "operation not supported for this keytype"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PADDING_CHECK_FAILED), + "padding check failed"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PKCS_DECODING_ERROR), + "pkcs decoding error"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_PSS_SALTLEN_TOO_SMALL), + "pss saltlen too small"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_P_NOT_PRIME), "p not prime"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_Q_NOT_PRIME), "q not prime"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED), + "rsa operations not supported"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_SLEN_CHECK_FAILED), + "salt length check failed"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_SLEN_RECOVERY_FAILED), + "salt length recovery failed"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_SSLV3_ROLLBACK_ATTACK), + "sslv3 rollback attack"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD), + "the asn1 object identifier is not known for this md"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_ALGORITHM_TYPE), + "unknown algorithm type"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_DIGEST), "unknown digest"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_MASK_DIGEST), + "unknown mask digest"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNKNOWN_PADDING_TYPE), + "unknown padding type"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_ENCRYPTION_TYPE), + "unsupported encryption type"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_LABEL_SOURCE), + "unsupported label source"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_MASK_ALGORITHM), + "unsupported mask algorithm"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_MASK_PARAMETER), + "unsupported mask parameter"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_UNSUPPORTED_SIGNATURE_TYPE), + "unsupported signature type"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_VALUE_MISSING), "value missing"}, + {ERR_PACK(ERR_LIB_RSA, 0, RSA_R_WRONG_SIGNATURE_LENGTH), + "wrong signature length"}, {0, NULL} }; @@ -175,10 +234,9 @@ static ERR_STRING_DATA RSA_str_reasons[] = { int ERR_load_RSA_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(RSA_str_functs[0].error) == NULL) { - ERR_load_strings(0, RSA_str_functs); - ERR_load_strings(0, RSA_str_reasons); + ERR_load_strings_const(RSA_str_functs); + ERR_load_strings_const(RSA_str_reasons); } #endif return 1; diff --git a/crypto/rsa/rsa_gen.c b/crypto/rsa/rsa_gen.c index 9af43e05..d8ef3c7e 100644 --- a/crypto/rsa/rsa_gen.c +++ b/crypto/rsa/rsa_gen.c @@ -19,7 +19,7 @@ #include #include "rsa_locl.h" -static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, +static int rsa_builtin_keygen(RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb); /* @@ -31,29 +31,60 @@ static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, */ int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { - if (rsa->meth->rsa_keygen) + if (rsa->meth->rsa_keygen != NULL) return rsa->meth->rsa_keygen(rsa, bits, e_value, cb); - return rsa_builtin_keygen(rsa, bits, e_value, cb); + + return RSA_generate_multi_prime_key(rsa, bits, RSA_DEFAULT_PRIME_NUM, + e_value, cb); } -static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, +int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes, + BIGNUM *e_value, BN_GENCB *cb) +{ + /* multi-prime is only supported with the builtin key generation */ + if (rsa->meth->rsa_multi_prime_keygen != NULL) { + return rsa->meth->rsa_multi_prime_keygen(rsa, bits, primes, + e_value, cb); + } else if (rsa->meth->rsa_keygen != NULL) { + /* + * However, if rsa->meth implements only rsa_keygen, then we + * have to honour it in 2-prime case and assume that it wouldn't + * know what to do with multi-prime key generated by builtin + * subroutine... + */ + if (primes == 2) + return rsa->meth->rsa_keygen(rsa, bits, e_value, cb); + else + return 0; + } + + return rsa_builtin_keygen(rsa, bits, primes, e_value, cb); +} + +static int rsa_builtin_keygen(RSA *rsa, int bits, int primes, BIGNUM *e_value, BN_GENCB *cb) { - BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp; - int bitsp, bitsq, ok = -1, n = 0; + BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *tmp, *prime; + int ok = -1, n = 0, bitsr[RSA_MAX_PRIME_NUM], bitse = 0; + int i = 0, quo = 0, rmd = 0, adj = 0, retries = 0; + RSA_PRIME_INFO *pinfo = NULL; + STACK_OF(RSA_PRIME_INFO) *prime_infos = NULL; BN_CTX *ctx = NULL; + BN_ULONG bitst = 0; unsigned long error = 0; - /* - * When generating ridiculously small keys, we can get stuck - * continually regenerating the same prime values. - */ - if (bits < 16) { + if (bits < RSA_MIN_MODULUS_BITS) { ok = 0; /* we set our own err */ RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL); goto err; } + if (primes < RSA_DEFAULT_PRIME_NUM || primes > rsa_multip_cap(bits)) { + ok = 0; /* we set our own err */ + RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_PRIME_NUM_INVALID); + goto err; + } + ctx = BN_CTX_new(); if (ctx == NULL) goto err; @@ -61,12 +92,15 @@ static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); - r3 = BN_CTX_get(ctx); - if (r3 == NULL) + if (r2 == NULL) goto err; - bitsp = (bits + 1) / 2; - bitsq = bits - bitsp; + /* divide bits into 'primes' pieces evenly */ + quo = bits / primes; + rmd = bits % primes; + + for (i = 0; i < primes; i++) + bitsr[i] = (i < rmd) ? quo + 1 : quo; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) @@ -86,81 +120,201 @@ static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL)) goto err; + /* initialize multi-prime components */ + if (primes > RSA_DEFAULT_PRIME_NUM) { + rsa->version = RSA_ASN1_VERSION_MULTI; + prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, primes - 2); + if (prime_infos == NULL) + goto err; + if (rsa->prime_infos != NULL) { + /* could this happen? */ + sk_RSA_PRIME_INFO_pop_free(rsa->prime_infos, rsa_multip_info_free); + } + rsa->prime_infos = prime_infos; + + /* prime_info from 2 to |primes| -1 */ + for (i = 2; i < primes; i++) { + pinfo = rsa_multip_info_new(); + if (pinfo == NULL) + goto err; + (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo); + } + } + if (BN_copy(rsa->e, e_value) == NULL) goto err; - 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; - 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(); + /* generate p, q and other primes (if any) */ + for (i = 0; i < primes; i++) { + adj = 0; + retries = 0; + + if (i == 0) { + prime = rsa->p; + } else if (i == 1) { + prime = rsa->q; } else { - goto err; + pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); + prime = pinfo->r; } - 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)) + + for (;;) { + redo: + if (!BN_generate_prime_ex(prime, bitsr[i] + adj, 0, NULL, NULL, cb)) + goto err; + /* + * prime should not be equal to p, q, r_3... + * (those primes prior to this one) + */ + { + int j; + + for (j = 0; j < i; j++) { + BIGNUM *prev_prime; + + if (j == 0) + prev_prime = rsa->p; + else if (j == 1) + prev_prime = rsa->q; + else + prev_prime = sk_RSA_PRIME_INFO_value(prime_infos, + j - 2)->r; + + if (!BN_cmp(prime, prev_prime)) { + goto redo; + } + } + } + if (!BN_sub(r2, prime, BN_value_one())) + goto err; + ERR_set_mark(); + BN_set_flags(r2, BN_FLG_CONSTTIME); + if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { + /* GCD == 1 since inverse exists */ + break; + } + error = ERR_peek_last_error(); + if (ERR_GET_LIB(error) == ERR_LIB_BN + && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { + /* GCD != 1 */ + ERR_pop_to_mark(); + } else { + goto err; + } + if (!BN_GENCB_call(cb, 2, n++)) goto err; - } while (BN_cmp(rsa->p, rsa->q) == 0); - if (!BN_sub(r2, rsa->q, BN_value_one())) - goto err; - 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(); + + bitse += bitsr[i]; + + /* calculate n immediately to see if it's sufficient */ + if (i == 1) { + /* we get at least 2 primes */ + if (!BN_mul(r1, rsa->p, rsa->q, ctx)) + goto err; + } else if (i != 0) { + /* modulus n = p * q * r_3 * r_4 ... */ + if (!BN_mul(r1, rsa->n, prime, ctx)) + goto err; } else { - goto err; + /* i == 0, do nothing */ + if (!BN_GENCB_call(cb, 3, i)) + goto err; + continue; } - if (!BN_GENCB_call(cb, 2, n++)) + /* + * if |r1|, product of factors so far, is not as long as expected + * (by checking the first 4 bits are less than 0x9 or greater than + * 0xF). If so, re-generate the last prime. + * + * NOTE: This actually can't happen in two-prime case, because of + * the way factors are generated. + * + * Besides, another consideration is, for multi-prime case, even the + * length modulus is as long as expected, the modulus could start at + * 0x8, which could be utilized to distinguish a multi-prime private + * key by using the modulus in a certificate. This is also covered + * by checking the length should not be less than 0x9. + */ + if (!BN_rshift(r2, r1, bitse - 4)) + goto err; + bitst = BN_get_word(r2); + + if (bitst < 0x9 || bitst > 0xF) { + /* + * For keys with more than 4 primes, we attempt longer factor to + * meet length requirement. + * + * Otherwise, we just re-generate the prime with the same length. + * + * This strategy has the following goals: + * + * 1. 1024-bit factors are effcient when using 3072 and 4096-bit key + * 2. stay the same logic with normal 2-prime key + */ + bitse -= bitsr[i]; + if (!BN_GENCB_call(cb, 2, n++)) + goto err; + if (primes > 4) { + if (bitst < 0x9) + adj++; + else + adj--; + } else if (retries == 4) { + /* + * re-generate all primes from scratch, mainly used + * in 4 prime case to avoid long loop. Max retry times + * is set to 4. + */ + i = -1; + bitse = 0; + continue; + } + retries++; + goto redo; + } + /* save product of primes for further use, for multi-prime only */ + if (i > 1 && BN_copy(pinfo->pp, rsa->n) == NULL) + goto err; + if (BN_copy(rsa->n, r1) == NULL) + goto err; + if (!BN_GENCB_call(cb, 3, i)) goto err; } - 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 */ + + /* p - 1 */ if (!BN_sub(r1, rsa->p, BN_value_one())) - goto err; /* p-1 */ + goto err; + /* q - 1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) - goto err; /* q-1 */ + goto err; + /* (p - 1)(q - 1) */ if (!BN_mul(r0, r1, r2, ctx)) - goto err; /* (p-1)(q-1) */ + goto err; + /* multi-prime */ + for (i = 2; i < primes; i++) { + pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); + /* save r_i - 1 to pinfo->d temporarily */ + if (!BN_sub(pinfo->d, pinfo->r, BN_value_one())) + goto err; + if (!BN_mul(r0, r0, pinfo->d, ctx)) + goto err; + } + { BIGNUM *pr0 = BN_new(); if (pr0 == NULL) goto err; + BN_with_flags(pr0, r0, BN_FLG_CONSTTIME); if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) { BN_free(pr0); @@ -175,15 +329,26 @@ static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, if (d == NULL) goto err; + BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME); - if ( /* calculate d mod (p-1) */ - !BN_mod(rsa->dmp1, d, r1, ctx) - /* calculate d mod (q-1) */ + /* calculate d mod (p-1) and d mod (q - 1) */ + if (!BN_mod(rsa->dmp1, d, r1, ctx) || !BN_mod(rsa->dmq1, d, r2, ctx)) { BN_free(d); goto err; } + + /* calculate CRT exponents */ + for (i = 2; i < primes; i++) { + pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); + /* pinfo->d == r_i - 1 */ + if (!BN_mod(pinfo->d, d, pinfo->d, ctx)) { + BN_free(d); + goto err; + } + } + /* We MUST free d before any further use of rsa->d */ BN_free(d); } @@ -200,6 +365,17 @@ static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, BN_free(p); goto err; } + + /* calculate CRT coefficient for other primes */ + for (i = 2; i < primes; i++) { + pinfo = sk_RSA_PRIME_INFO_value(prime_infos, i - 2); + BN_with_flags(p, pinfo->r, BN_FLG_CONSTTIME); + if (!BN_mod_inverse(pinfo->t, pinfo->pp, p, ctx)) { + BN_free(p); + goto err; + } + } + /* We MUST free p before any further use of rsa->p */ BN_free(p); } @@ -213,6 +389,5 @@ static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, if (ctx != NULL) BN_CTX_end(ctx); BN_CTX_free(ctx); - return ok; } diff --git a/crypto/rsa/rsa_lib.c b/crypto/rsa/rsa_lib.c index e1377a06..133ba218 100644 --- a/crypto/rsa/rsa_lib.c +++ b/crypto/rsa/rsa_lib.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -10,9 +10,11 @@ #include #include #include "internal/cryptlib.h" -#include +#include "internal/refcount.h" #include "internal/bn_int.h" #include +#include +#include "internal/evp_int.h" #include "rsa_locl.h" RSA *RSA_new(void) @@ -71,8 +73,9 @@ RSA *RSA_new_method(ENGINE *engine) goto err; } ret->engine = engine; - } else + } else { ret->engine = ENGINE_get_default_RSA(); + } if (ret->engine) { ret->meth = ENGINE_get_RSA(ret->engine); if (ret->meth == NULL) { @@ -106,7 +109,7 @@ void RSA_free(RSA *r) if (r == NULL) return; - CRYPTO_atomic_add(&r->references, -1, &i, r->lock); + CRYPTO_DOWN_REF(&r->references, &i, r->lock); REF_PRINT_COUNT("RSA", r); if (i > 0) return; @@ -130,6 +133,8 @@ void RSA_free(RSA *r) BN_clear_free(r->dmp1); BN_clear_free(r->dmq1); BN_clear_free(r->iqmp); + RSA_PSS_PARAMS_free(r->pss); + sk_RSA_PRIME_INFO_pop_free(r->prime_infos, rsa_multip_info_free); BN_BLINDING_free(r->blinding); BN_BLINDING_free(r->mt_blinding); OPENSSL_free(r->bignum_data); @@ -140,27 +145,36 @@ int RSA_up_ref(RSA *r) { int i; - if (CRYPTO_atomic_add(&r->references, 1, &i, r->lock) <= 0) + if (CRYPTO_UP_REF(&r->references, &i, r->lock) <= 0) return 0; REF_PRINT_COUNT("RSA", r); REF_ASSERT_ISNT(i < 2); - return ((i > 1) ? 1 : 0); + return i > 1 ? 1 : 0; } int RSA_set_ex_data(RSA *r, int idx, void *arg) { - return (CRYPTO_set_ex_data(&r->ex_data, idx, arg)); + return CRYPTO_set_ex_data(&r->ex_data, idx, arg); } void *RSA_get_ex_data(const RSA *r, int idx) { - return (CRYPTO_get_ex_data(&r->ex_data, idx)); + return CRYPTO_get_ex_data(&r->ex_data, idx); } int RSA_security_bits(const RSA *rsa) { - return BN_security_bits(BN_num_bits(rsa->n), -1); + int bits = BN_num_bits(rsa->n); + + if (rsa->version == RSA_ASN1_VERSION_MULTI) { + /* This ought to mean that we have private key at hand. */ + int ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos); + + if (ex_primes <= 0 || (ex_primes + 2) > rsa_multip_cap(bits)) + return 0; + } + return BN_security_bits(bits, -1); } int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d) @@ -236,6 +250,71 @@ int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) return 1; } +/* + * Is it better to export RSA_PRIME_INFO structure + * and related functions to let user pass a triplet? + */ +int RSA_set0_multi_prime_params(RSA *r, BIGNUM *primes[], BIGNUM *exps[], + BIGNUM *coeffs[], int pnum) +{ + STACK_OF(RSA_PRIME_INFO) *prime_infos, *old = NULL; + RSA_PRIME_INFO *pinfo; + int i; + + if (primes == NULL || exps == NULL || coeffs == NULL || pnum == 0) + return 0; + + prime_infos = sk_RSA_PRIME_INFO_new_reserve(NULL, pnum); + if (prime_infos == NULL) + return 0; + + if (r->prime_infos != NULL) + old = r->prime_infos; + + for (i = 0; i < pnum; i++) { + pinfo = rsa_multip_info_new(); + if (pinfo == NULL) + goto err; + if (primes[i] != NULL && exps[i] != NULL && coeffs[i] != NULL) { + BN_free(pinfo->r); + BN_free(pinfo->d); + BN_free(pinfo->t); + pinfo->r = primes[i]; + pinfo->d = exps[i]; + pinfo->t = coeffs[i]; + } else { + rsa_multip_info_free(pinfo); + goto err; + } + (void)sk_RSA_PRIME_INFO_push(prime_infos, pinfo); + } + + r->prime_infos = prime_infos; + + if (!rsa_multip_calc_product(r)) { + r->prime_infos = old; + goto err; + } + + if (old != NULL) { + /* + * This is hard to deal with, since the old infos could + * also be set by this function and r, d, t should not + * be freed in that case. So currently, stay consistent + * with other *set0* functions: just free it... + */ + sk_RSA_PRIME_INFO_pop_free(old, rsa_multip_info_free); + } + + r->version = RSA_ASN1_VERSION_MULTI; + + return 1; + err: + /* r, d, t should not be freed */ + sk_RSA_PRIME_INFO_pop_free(prime_infos, rsa_multip_info_free_ex); + return 0; +} + void RSA_get0_key(const RSA *r, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d) { @@ -255,6 +334,36 @@ void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q) *q = r->q; } +int RSA_get_multi_prime_extra_count(const RSA *r) +{ + int pnum; + + pnum = sk_RSA_PRIME_INFO_num(r->prime_infos); + if (pnum <= 0) + pnum = 0; + return pnum; +} + +int RSA_get0_multi_prime_factors(const RSA *r, const BIGNUM *primes[]) +{ + int pnum, i; + RSA_PRIME_INFO *pinfo; + + if ((pnum = RSA_get_multi_prime_extra_count(r)) == 0) + return 0; + + /* + * return other primes + * it's caller's responsibility to allocate oth_primes[pnum] + */ + for (i = 0; i < pnum; i++) { + pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i); + primes[i] = pinfo->r; + } + + return 1; +} + void RSA_get0_crt_params(const RSA *r, const BIGNUM **dmp1, const BIGNUM **dmq1, const BIGNUM **iqmp) @@ -267,6 +376,32 @@ void RSA_get0_crt_params(const RSA *r, *iqmp = r->iqmp; } +int RSA_get0_multi_prime_crt_params(const RSA *r, const BIGNUM *exps[], + const BIGNUM *coeffs[]) +{ + int pnum; + + if ((pnum = RSA_get_multi_prime_extra_count(r)) == 0) + return 0; + + /* return other primes */ + if (exps != NULL || coeffs != NULL) { + RSA_PRIME_INFO *pinfo; + int i; + + /* it's the user's job to guarantee the buffer length */ + for (i = 0; i < pnum; i++) { + pinfo = sk_RSA_PRIME_INFO_value(r->prime_infos, i); + if (exps != NULL) + exps[i] = pinfo->d; + if (coeffs != NULL) + coeffs[i] = pinfo->t; + } + } + + return 1; +} + void RSA_clear_flags(RSA *r, int flags) { r->flags &= ~flags; @@ -282,7 +417,23 @@ void RSA_set_flags(RSA *r, int flags) r->flags |= flags; } +int RSA_get_version(RSA *r) +{ + /* { two-prime(0), multi(1) } */ + return r->version; +} + ENGINE *RSA_get0_engine(const RSA *r) { return r->engine; } + +int RSA_pkey_ctx_ctrl(EVP_PKEY_CTX *ctx, int optype, int cmd, int p1, void *p2) +{ + /* If key type not RSA or RSA-PSS return error */ + if (ctx != NULL && ctx->pmeth != NULL + && ctx->pmeth->pkey_id != EVP_PKEY_RSA + && ctx->pmeth->pkey_id != EVP_PKEY_RSA_PSS) + return -1; + return EVP_PKEY_CTX_ctrl(ctx, -1, optype, cmd, p1, p2); +} diff --git a/crypto/rsa/rsa_locl.h b/crypto/rsa/rsa_locl.h index 5d16aa6f..2b94462a 100644 --- a/crypto/rsa/rsa_locl.h +++ b/crypto/rsa/rsa_locl.h @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-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 @@ -8,14 +8,30 @@ */ #include +#include "internal/refcount.h" + +#define RSA_MAX_PRIME_NUM 5 +#define RSA_MIN_MODULUS_BITS 512 + +typedef struct rsa_prime_info_st { + BIGNUM *r; + BIGNUM *d; + BIGNUM *t; + /* save product of primes prior to this one */ + BIGNUM *pp; + BN_MONT_CTX *m; +} RSA_PRIME_INFO; + +DECLARE_ASN1_ITEM(RSA_PRIME_INFO) +DEFINE_STACK_OF(RSA_PRIME_INFO) struct rsa_st { /* * The first parameter is used to pickup errors where this is passed - * instead of aEVP_PKEY, it is set to 0 + * instead of an EVP_PKEY, it is set to 0 */ int pad; - long version; + int32_t version; const RSA_METHOD *meth; /* functional reference if 'meth' is ENGINE-provided */ ENGINE *engine; @@ -27,9 +43,13 @@ struct rsa_st { BIGNUM *dmp1; BIGNUM *dmq1; BIGNUM *iqmp; + /* for multi-prime RSA, defined in RFC 8017 */ + STACK_OF(RSA_PRIME_INFO) *prime_infos; + /* If a PSS only key this contains the parameter restrictions */ + RSA_PSS_PARAMS *pss; /* be careful using this if the RSA structure is shared */ CRYPTO_EX_DATA ex_data; - int references; + CRYPTO_REF_COUNT references; int flags; /* Used to cache montgomery values */ BN_MONT_CTX *_method_mod_n; @@ -88,9 +108,25 @@ struct rsa_meth_st { * things as "builtin software" implementations. */ int (*rsa_keygen) (RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); + int (*rsa_multi_prime_keygen) (RSA *rsa, int bits, int primes, + BIGNUM *e, BN_GENCB *cb); }; extern int int_rsa_verify(int dtype, const unsigned char *m, unsigned int m_len, unsigned char *rm, size_t *prm_len, const unsigned char *sigbuf, size_t siglen, RSA *rsa); +/* Macros to test if a pkey or ctx is for a PSS key */ +#define pkey_is_pss(pkey) (pkey->ameth->pkey_id == EVP_PKEY_RSA_PSS) +#define pkey_ctx_is_pss(ctx) (ctx->pmeth->pkey_id == EVP_PKEY_RSA_PSS) + +RSA_PSS_PARAMS *rsa_pss_params_create(const EVP_MD *sigmd, + const EVP_MD *mgf1md, int saltlen); +int rsa_pss_get_param(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd, + const EVP_MD **pmgf1md, int *psaltlen); +/* internal function to clear and free multi-prime parameters */ +void rsa_multip_info_free_ex(RSA_PRIME_INFO *pinfo); +void rsa_multip_info_free(RSA_PRIME_INFO *pinfo); +RSA_PRIME_INFO *rsa_multip_info_new(void); +int rsa_multip_calc_product(RSA *rsa); +int rsa_multip_cap(int bits); diff --git a/crypto/rsa/rsa_meth.c b/crypto/rsa/rsa_meth.c index 9480abd7..5dccc330 100644 --- a/crypto/rsa/rsa_meth.c +++ b/crypto/rsa/rsa_meth.c @@ -271,3 +271,17 @@ int RSA_meth_set_keygen(RSA_METHOD *meth, return 1; } +int (*RSA_meth_get_multi_prime_keygen(const RSA_METHOD *meth)) + (RSA *rsa, int bits, int primes, BIGNUM *e, BN_GENCB *cb) +{ + return meth->rsa_multi_prime_keygen; +} + +int RSA_meth_set_multi_prime_keygen(RSA_METHOD *meth, + int (*keygen) (RSA *rsa, int bits, + int primes, BIGNUM *e, + BN_GENCB *cb)) +{ + meth->rsa_multi_prime_keygen = keygen; + return 1; +} diff --git a/crypto/rsa/rsa_mp.c b/crypto/rsa/rsa_mp.c new file mode 100644 index 00000000..b8727fa2 --- /dev/null +++ b/crypto/rsa/rsa_mp.c @@ -0,0 +1,113 @@ +/* + * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 BaishanCloud. 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 +#include "rsa_locl.h" + +void rsa_multip_info_free_ex(RSA_PRIME_INFO *pinfo) +{ + /* free pp and pinfo only */ + BN_clear_free(pinfo->pp); + OPENSSL_free(pinfo); +} + +void rsa_multip_info_free(RSA_PRIME_INFO *pinfo) +{ + /* free a RSA_PRIME_INFO structure */ + BN_clear_free(pinfo->r); + BN_clear_free(pinfo->d); + BN_clear_free(pinfo->t); + rsa_multip_info_free_ex(pinfo); +} + +RSA_PRIME_INFO *rsa_multip_info_new(void) +{ + RSA_PRIME_INFO *pinfo; + + /* create a RSA_PRIME_INFO structure */ + pinfo = OPENSSL_zalloc(sizeof(RSA_PRIME_INFO)); + if (pinfo == NULL) + return NULL; + if ((pinfo->r = BN_secure_new()) == NULL) + goto err; + if ((pinfo->d = BN_secure_new()) == NULL) + goto err; + if ((pinfo->t = BN_secure_new()) == NULL) + goto err; + if ((pinfo->pp = BN_secure_new()) == NULL) + goto err; + + return pinfo; + + err: + BN_free(pinfo->r); + BN_free(pinfo->d); + BN_free(pinfo->t); + BN_free(pinfo->pp); + OPENSSL_free(pinfo); + return NULL; +} + +/* Refill products of primes */ +int rsa_multip_calc_product(RSA *rsa) +{ + RSA_PRIME_INFO *pinfo; + BIGNUM *p1 = NULL, *p2 = NULL; + BN_CTX *ctx = NULL; + int i, rv = 0, ex_primes; + + if ((ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos)) <= 0) { + /* invalid */ + goto err; + } + + if ((ctx = BN_CTX_new()) == NULL) + goto err; + + /* calculate pinfo->pp = p * q for first 'extra' prime */ + p1 = rsa->p; + p2 = rsa->q; + + for (i = 0; i < ex_primes; i++) { + pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i); + if (pinfo->pp == NULL) { + pinfo->pp = BN_secure_new(); + if (pinfo->pp == NULL) + goto err; + } + if (!BN_mul(pinfo->pp, p1, p2, ctx)) + goto err; + /* save previous one */ + p1 = pinfo->pp; + p2 = pinfo->r; + } + + rv = 1; + err: + BN_CTX_free(ctx); + return rv; +} + +int rsa_multip_cap(int bits) +{ + int cap = 5; + + if (bits < 1024) + cap = 2; + else if (bits < 4096) + cap = 3; + else if (bits < 8192) + cap = 4; + + if (cap > RSA_MAX_PRIME_NUM) + cap = RSA_MAX_PRIME_NUM; + + return cap; +} diff --git a/crypto/rsa/rsa_none.c b/crypto/rsa/rsa_none.c index b78756d1..f16cc670 100644 --- a/crypto/rsa/rsa_none.c +++ b/crypto/rsa/rsa_none.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -16,16 +16,16 @@ int RSA_padding_add_none(unsigned char *to, int tlen, { if (flen > tlen) { RSAerr(RSA_F_RSA_PADDING_ADD_NONE, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); - return (0); + return 0; } if (flen < tlen) { RSAerr(RSA_F_RSA_PADDING_ADD_NONE, RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE); - return (0); + return 0; } memcpy(to, from, (unsigned int)flen); - return (1); + return 1; } int RSA_padding_check_none(unsigned char *to, int tlen, @@ -34,10 +34,10 @@ int RSA_padding_check_none(unsigned char *to, int tlen, if (flen > tlen) { RSAerr(RSA_F_RSA_PADDING_CHECK_NONE, RSA_R_DATA_TOO_LARGE); - return (-1); + return -1; } memset(to, 0, tlen - flen); memcpy(to + tlen - flen, from, flen); - return (tlen); + return tlen; } diff --git a/crypto/rsa/rsa_null.c b/crypto/rsa/rsa_null.c deleted file mode 100644 index d3394941..00000000 --- a/crypto/rsa/rsa_null.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 1999-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 - */ - -#include -#include "internal/cryptlib.h" -#include -#include "rsa_locl.h" - -/* - * This is a dummy RSA implementation that just returns errors when called. - * It is designed to allow some RSA functions to work while stopping those - * covered by the RSA patent. That is RSA, encryption, decryption, signing - * and verify is not allowed but RSA key generation, key checking and other - * operations (like storing RSA keys) are permitted. - */ - -static int RSA_null_public_encrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); -static int RSA_null_private_encrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); -static int RSA_null_public_decrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); -static int RSA_null_private_decrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); -static int RSA_null_init(RSA *rsa); -static int RSA_null_finish(RSA *rsa); -static RSA_METHOD rsa_null_meth = { - "Null RSA", - RSA_null_public_encrypt, - RSA_null_public_decrypt, - RSA_null_private_encrypt, - RSA_null_private_decrypt, - NULL, - NULL, - RSA_null_init, - RSA_null_finish, - 0, - NULL, - NULL, - NULL, - NULL -}; - -const RSA_METHOD *RSA_null_method(void) -{ - return (&rsa_null_meth); -} - -static int RSA_null_public_encrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding) -{ - RSAerr(RSA_F_RSA_NULL_PUBLIC_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); - return -1; -} - -static int RSA_null_private_encrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding) -{ - RSAerr(RSA_F_RSA_NULL_PRIVATE_ENCRYPT, - RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); - return -1; -} - -static int RSA_null_private_decrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding) -{ - RSAerr(RSA_F_RSA_NULL_PRIVATE_DECRYPT, - RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); - return -1; -} - -static int RSA_null_public_decrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding) -{ - RSAerr(RSA_F_RSA_NULL_PUBLIC_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED); - return -1; -} - -static int RSA_null_init(RSA *rsa) -{ - return (1); -} - -static int RSA_null_finish(RSA *rsa) -{ - return (1); -} diff --git a/crypto/rsa/rsa_oaep.c b/crypto/rsa/rsa_oaep.c index 4878d495..d4de71df 100644 --- a/crypto/rsa/rsa_oaep.c +++ b/crypto/rsa/rsa_oaep.c @@ -78,11 +78,6 @@ int RSA_padding_add_PKCS1_OAEP_mgf1(unsigned char *to, int tlen, memcpy(db + emlen - flen - mdlen, from, (unsigned int)flen); if (RAND_bytes(seed, mdlen) <= 0) return 0; -#ifdef PKCS_TESTVECT - memcpy(seed, - "\xaa\xfd\x12\xf6\x59\xca\xe6\x34\x89\xb4\x79\xe5\x07\x6d\xde\xc2\xf0\x6c\xb5\x8f", - 20); -#endif dbmask = OPENSSL_malloc(emlen - mdlen); if (dbmask == NULL) { diff --git a/crypto/rsa/rsa_ossl.c b/crypto/rsa/rsa_ossl.c index 62a88959..f7b5cdca 100644 --- a/crypto/rsa/rsa_ossl.c +++ b/crypto/rsa/rsa_ossl.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -38,7 +38,8 @@ static RSA_METHOD rsa_pkcs1_ossl_meth = { NULL, 0, /* rsa_sign */ 0, /* rsa_verify */ - NULL /* rsa_keygen */ + NULL, /* rsa_keygen */ + NULL /* rsa_multi_prime_keygen */ }; static const RSA_METHOD *default_RSA_meth = &rsa_pkcs1_ossl_meth; @@ -58,6 +59,11 @@ const RSA_METHOD *RSA_PKCS1_OpenSSL(void) return &rsa_pkcs1_ossl_meth; } +const RSA_METHOD *RSA_null_method(void) +{ + return NULL; +} + static int rsa_ossl_public_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { @@ -91,7 +97,7 @@ static int rsa_ossl_public_encrypt(int flen, const unsigned char *from, ret = BN_CTX_get(ctx); num = BN_num_bytes(rsa->n); buf = OPENSSL_malloc(num); - if (f == NULL || ret == NULL || buf == NULL) { + if (ret == NULL || buf == NULL) { RSAerr(RSA_F_RSA_OSSL_PUBLIC_ENCRYPT, ERR_R_MALLOC_FAILURE); goto err; } @@ -150,7 +156,7 @@ static int rsa_ossl_public_encrypt(int flen, const unsigned char *from, BN_CTX_end(ctx); BN_CTX_free(ctx); OPENSSL_clear_free(buf, num); - return (r); + return r; } static BN_BLINDING *rsa_get_blinding(RSA *rsa, int *local, BN_CTX *ctx) @@ -195,12 +201,12 @@ static BN_BLINDING *rsa_get_blinding(RSA *rsa, int *local, BN_CTX *ctx) static int rsa_blinding_convert(BN_BLINDING *b, BIGNUM *f, BIGNUM *unblind, BN_CTX *ctx) { - if (unblind == NULL) + if (unblind == NULL) { /* * Local blinding: store the unblinding factor in BN_BLINDING. */ return BN_BLINDING_convert_ex(f, NULL, b, ctx); - else { + } else { /* * Shared blinding: store the unblinding factor outside BN_BLINDING. */ @@ -252,7 +258,7 @@ static int rsa_ossl_private_encrypt(int flen, const unsigned char *from, ret = BN_CTX_get(ctx); num = BN_num_bytes(rsa->n); buf = OPENSSL_malloc(num); - if (f == NULL || ret == NULL || buf == NULL) { + if (ret == NULL || buf == NULL) { RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE); goto err; } @@ -303,6 +309,7 @@ static int rsa_ossl_private_encrypt(int flen, const unsigned char *from, } if ((rsa->flags & RSA_FLAG_EXT_PKEY) || + (rsa->version == RSA_ASN1_VERSION_MULTI) || ((rsa->p != NULL) && (rsa->q != NULL) && (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) { @@ -342,8 +349,9 @@ static int rsa_ossl_private_encrypt(int flen, const unsigned char *from, res = f; else res = ret; - } else + } else { res = ret; + } /* * put in leading 0 bytes if the number is less than the length of the @@ -360,7 +368,7 @@ static int rsa_ossl_private_encrypt(int flen, const unsigned char *from, BN_CTX_end(ctx); BN_CTX_free(ctx); OPENSSL_clear_free(buf, num); - return (r); + return r; } static int rsa_ossl_private_decrypt(int flen, const unsigned char *from, @@ -387,7 +395,7 @@ static int rsa_ossl_private_decrypt(int flen, const unsigned char *from, ret = BN_CTX_get(ctx); num = BN_num_bytes(rsa->n); buf = OPENSSL_malloc(num); - if (f == NULL || ret == NULL || buf == NULL) { + if (ret == NULL || buf == NULL) { RSAerr(RSA_F_RSA_OSSL_PRIVATE_DECRYPT, ERR_R_MALLOC_FAILURE); goto err; } @@ -431,6 +439,7 @@ static int rsa_ossl_private_decrypt(int flen, const unsigned char *from, /* do the decrypt */ if ((rsa->flags & RSA_FLAG_EXT_PKEY) || + (rsa->version == RSA_ASN1_VERSION_MULTI) || ((rsa->p != NULL) && (rsa->q != NULL) && (rsa->dmp1 != NULL) && (rsa->dmq1 != NULL) && (rsa->iqmp != NULL))) { @@ -491,7 +500,7 @@ static int rsa_ossl_private_decrypt(int flen, const unsigned char *from, BN_CTX_end(ctx); BN_CTX_free(ctx); OPENSSL_clear_free(buf, num); - return (r); + return r; } /* signature verification */ @@ -529,7 +538,7 @@ static int rsa_ossl_public_decrypt(int flen, const unsigned char *from, ret = BN_CTX_get(ctx); num = BN_num_bytes(rsa->n); buf = OPENSSL_malloc(num); - if (f == NULL || ret == NULL || buf == NULL) { + if (ret == NULL || buf == NULL) { RSAerr(RSA_F_RSA_OSSL_PUBLIC_DECRYPT, ERR_R_MALLOC_FAILURE); goto err; } @@ -590,22 +599,29 @@ static int rsa_ossl_public_decrypt(int flen, const unsigned char *from, BN_CTX_end(ctx); BN_CTX_free(ctx); OPENSSL_clear_free(buf, num); - return (r); + return r; } static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) { - BIGNUM *r1, *m1, *vrfy; - int ret = 0; + BIGNUM *r1, *m1, *vrfy, *r2, *m[RSA_MAX_PRIME_NUM - 2]; + int ret = 0, i, ex_primes = 0; + RSA_PRIME_INFO *pinfo; BN_CTX_start(ctx); r1 = BN_CTX_get(ctx); + r2 = BN_CTX_get(ctx); m1 = BN_CTX_get(ctx); vrfy = BN_CTX_get(ctx); if (vrfy == NULL) goto err; + if (rsa->version == RSA_ASN1_VERSION_MULTI + && ((ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos)) <= 0 + || ex_primes > RSA_MAX_PRIME_NUM - 2)) + goto err; + { BIGNUM *p = BN_new(), *q = BN_new(); @@ -630,6 +646,28 @@ static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) BN_free(q); goto err; } + if (ex_primes > 0) { + /* cache BN_MONT_CTX for other primes */ + BIGNUM *r = BN_new(); + + if (r == NULL) { + BN_free(p); + BN_free(q); + goto err; + } + + for (i = 0; i < ex_primes; i++) { + pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i); + BN_with_flags(r, pinfo->r, BN_FLG_CONSTTIME); + if (!BN_MONT_CTX_set_locked(&pinfo->m, rsa->lock, r, ctx)) { + BN_free(p); + BN_free(q); + BN_free(r); + goto err; + } + } + BN_free(r); + } } /* * We MUST free p and q before any further use of rsa->p and rsa->q @@ -699,6 +737,56 @@ static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) BN_free(dmp1); } + /* + * calculate m_i in multi-prime case + * + * TODO: + * 1. squash the following two loops and calculate |m_i| there. + * 2. remove cc and reuse |c|. + * 3. remove |dmq1| and |dmp1| in previous block and use |di|. + * + * If these things are done, the code will be more readable. + */ + if (ex_primes > 0) { + BIGNUM *di = BN_new(), *cc = BN_new(); + + if (cc == NULL || di == NULL) { + BN_free(cc); + BN_free(di); + goto err; + } + + for (i = 0; i < ex_primes; i++) { + /* prepare m_i */ + if ((m[i] = BN_CTX_get(ctx)) == NULL) { + BN_free(cc); + BN_free(di); + goto err; + } + + pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i); + + /* prepare c and d_i */ + BN_with_flags(cc, I, BN_FLG_CONSTTIME); + BN_with_flags(di, pinfo->d, BN_FLG_CONSTTIME); + + if (!BN_mod(r1, cc, pinfo->r, ctx)) { + BN_free(cc); + BN_free(di); + goto err; + } + /* compute r1 ^ d_i mod r_i */ + if (!rsa->meth->bn_mod_exp(m[i], r1, di, pinfo->r, ctx, pinfo->m)) { + BN_free(cc); + BN_free(di); + goto err; + } + } + + BN_free(cc); + BN_free(di); + } + if (!BN_sub(r0, r0, m1)) goto err; /* @@ -741,6 +829,49 @@ static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) if (!BN_add(r0, r1, m1)) goto err; + /* add m_i to m in multi-prime case */ + if (ex_primes > 0) { + BIGNUM *pr2 = BN_new(); + + if (pr2 == NULL) + goto err; + + for (i = 0; i < ex_primes; i++) { + pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i); + if (!BN_sub(r1, m[i], r0)) { + BN_free(pr2); + goto err; + } + + if (!BN_mul(r2, r1, pinfo->t, ctx)) { + BN_free(pr2); + goto err; + } + + BN_with_flags(pr2, r2, BN_FLG_CONSTTIME); + + if (!BN_mod(r1, pr2, pinfo->r, ctx)) { + BN_free(pr2); + goto err; + } + + if (BN_is_negative(r1)) + if (!BN_add(r1, r1, pinfo->r)) { + BN_free(pr2); + goto err; + } + if (!BN_mul(r1, r1, pinfo->pp, ctx)) { + BN_free(pr2); + goto err; + } + if (!BN_add(r0, r0, r1)) { + BN_free(pr2); + goto err; + } + } + BN_free(pr2); + } + if (rsa->e && rsa->n) { if (!rsa->meth->bn_mod_exp(vrfy, r0, rsa->e, rsa->n, ctx, rsa->_method_mod_n)) @@ -782,19 +913,26 @@ static int rsa_ossl_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) ret = 1; err: BN_CTX_end(ctx); - return (ret); + return ret; } static int rsa_ossl_init(RSA *rsa) { rsa->flags |= RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE; - return (1); + return 1; } static int rsa_ossl_finish(RSA *rsa) { + int i; + RSA_PRIME_INFO *pinfo; + BN_MONT_CTX_free(rsa->_method_mod_n); BN_MONT_CTX_free(rsa->_method_mod_p); BN_MONT_CTX_free(rsa->_method_mod_q); - return (1); + for (i = 0; i < sk_RSA_PRIME_INFO_num(rsa->prime_infos); i++) { + pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i); + BN_MONT_CTX_free(pinfo->m); + } + return 1; } diff --git a/crypto/rsa/rsa_pk1.c b/crypto/rsa/rsa_pk1.c index aeeb32c2..7d453ff9 100644 --- a/crypto/rsa/rsa_pk1.c +++ b/crypto/rsa/rsa_pk1.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -24,7 +24,7 @@ int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen, if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_1, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); - return (0); + return 0; } p = (unsigned char *)to; @@ -38,7 +38,7 @@ int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen, p += j; *(p++) = '\0'; memcpy(p, from, (unsigned int)flen); - return (1); + return 1; } int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen, @@ -73,7 +73,7 @@ int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen, if ((num != (flen + 1)) || (*(p++) != 0x01)) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, RSA_R_BLOCK_TYPE_IS_NOT_01); - return (-1); + return -1; } /* scan over padding data */ @@ -86,7 +86,7 @@ int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen, } else { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, RSA_R_BAD_FIXED_HEADER_DECRYPT); - return (-1); + return -1; } } p++; @@ -95,23 +95,23 @@ int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen, if (i == j) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, RSA_R_NULL_BEFORE_BLOCK_MISSING); - return (-1); + return -1; } if (i < 8) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, RSA_R_BAD_PAD_BYTE_COUNT); - return (-1); + return -1; } i++; /* Skip over the '\0' */ j -= i; if (j > tlen) { RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1, RSA_R_DATA_TOO_LARGE); - return (-1); + return -1; } memcpy(to, p, (unsigned int)j); - return (j); + return j; } int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen, @@ -123,7 +123,7 @@ int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen, if (flen > (tlen - 11)) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_2, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); - return (0); + return 0; } p = (unsigned char *)to; @@ -135,12 +135,12 @@ int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen, j = tlen - 3 - flen; if (RAND_bytes(p, j) <= 0) - return (0); + return 0; for (i = 0; i < j; i++) { if (*p == '\0') do { if (RAND_bytes(p, 1) <= 0) - return (0); + return 0; } while (*p == '\0'); p++; } @@ -148,7 +148,7 @@ int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen, *(p++) = '\0'; memcpy(p, from, (unsigned int)flen); - return (1); + return 1; } int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen, diff --git a/crypto/rsa/rsa_pmeth.c b/crypto/rsa/rsa_pmeth.c index 2d1dffbb..e11ed1f0 100644 --- a/crypto/rsa/rsa_pmeth.c +++ b/crypto/rsa/rsa_pmeth.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-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 @@ -25,6 +25,7 @@ typedef struct { /* Key gen parameters */ int nbits; BIGNUM *pub_exp; + int primes; /* Keygen callback info */ int gentmp[2]; /* RSA padding mode */ @@ -35,6 +36,8 @@ typedef struct { const EVP_MD *mgf1md; /* PSS salt length */ int saltlen; + /* Minimum salt length or -1 if no PSS parameter restriction */ + int min_saltlen; /* Temp buffer */ unsigned char *tbuf; /* OAEP label */ @@ -42,15 +45,24 @@ typedef struct { size_t oaep_labellen; } RSA_PKEY_CTX; +/* True if PSS parameters are restricted */ +#define rsa_pss_restricted(rctx) (rctx->min_saltlen != -1) + static int pkey_rsa_init(EVP_PKEY_CTX *ctx) { - RSA_PKEY_CTX *rctx; - rctx = OPENSSL_zalloc(sizeof(*rctx)); + RSA_PKEY_CTX *rctx = OPENSSL_zalloc(sizeof(*rctx)); + if (rctx == NULL) return 0; rctx->nbits = 1024; - rctx->pad_mode = RSA_PKCS1_PADDING; - rctx->saltlen = -2; + rctx->primes = RSA_DEFAULT_PRIME_NUM; + if (pkey_ctx_is_pss(ctx)) + rctx->pad_mode = RSA_PKCS1_PSS_PADDING; + else + rctx->pad_mode = RSA_PKCS1_PADDING; + /* Maximum for sign, auto for verify */ + rctx->saltlen = RSA_PSS_SALTLEN_AUTO; + rctx->min_saltlen = -1; ctx->data = rctx; ctx->keygen_info = rctx->gentmp; ctx->keygen_info_count = 2; @@ -61,6 +73,7 @@ static int pkey_rsa_init(EVP_PKEY_CTX *ctx) static int pkey_rsa_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { RSA_PKEY_CTX *dctx, *sctx; + if (!pkey_rsa_init(dst)) return 0; sctx = src->data; @@ -86,7 +99,7 @@ static int pkey_rsa_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) static int setup_tbuf(RSA_PKEY_CTX *ctx, EVP_PKEY_CTX *pk) { - if (ctx->tbuf) + if (ctx->tbuf != NULL) return 1; ctx->tbuf = OPENSSL_malloc(EVP_PKEY_size(pk->pkey)); if (ctx->tbuf == NULL) @@ -159,11 +172,13 @@ static int pkey_rsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig, return -1; ret = RSA_private_encrypt(RSA_size(rsa), rctx->tbuf, sig, rsa, RSA_NO_PADDING); - } else + } else { return -1; - } else + } + } else { ret = RSA_private_encrypt(tbslen, tbs, sig, ctx->pkey->pkey.rsa, rctx->pad_mode); + } if (ret < 0) return ret; *siglen = ret; @@ -207,11 +222,13 @@ static int pkey_rsa_verifyrecover(EVP_PKEY_CTX *ctx, if (ret <= 0) return 0; ret = sltmp; - } else + } else { return -1; - } else + } + } else { ret = RSA_public_decrypt(siglen, sig, rout, ctx->pkey->pkey.rsa, rctx->pad_mode); + } if (ret < 0) return ret; *routlen = ret; @@ -225,6 +242,7 @@ static int pkey_rsa_verify(EVP_PKEY_CTX *ctx, RSA_PKEY_CTX *rctx = ctx->data; RSA *rsa = ctx->pkey->pkey.rsa; size_t rslen; + if (rctx->md) { if (rctx->pad_mode == RSA_PKCS1_PADDING) return RSA_verify(EVP_MD_type(rctx->md), tbs, tbslen, @@ -250,8 +268,9 @@ static int pkey_rsa_verify(EVP_PKEY_CTX *ctx, if (ret <= 0) return 0; return 1; - } else + } else { return -1; + } } else { if (!setup_tbuf(rctx, ctx)) return -1; @@ -274,6 +293,7 @@ static int pkey_rsa_encrypt(EVP_PKEY_CTX *ctx, { int ret; RSA_PKEY_CTX *rctx = ctx->data; + if (rctx->pad_mode == RSA_PKCS1_OAEP_PADDING) { int klen = RSA_size(ctx->pkey->pkey.rsa); if (!setup_tbuf(rctx, ctx)) @@ -286,9 +306,10 @@ static int pkey_rsa_encrypt(EVP_PKEY_CTX *ctx, return -1; ret = RSA_public_encrypt(klen, rctx->tbuf, out, ctx->pkey->pkey.rsa, RSA_NO_PADDING); - } else + } else { ret = RSA_public_encrypt(inlen, in, out, ctx->pkey->pkey.rsa, rctx->pad_mode); + } if (ret < 0) return ret; *outlen = ret; @@ -301,6 +322,7 @@ static int pkey_rsa_decrypt(EVP_PKEY_CTX *ctx, { int ret; RSA_PKEY_CTX *rctx = ctx->data; + if (rctx->pad_mode == RSA_PKCS1_OAEP_PADDING) { if (!setup_tbuf(rctx, ctx)) return -1; @@ -313,9 +335,10 @@ static int pkey_rsa_decrypt(EVP_PKEY_CTX *ctx, rctx->oaep_label, rctx->oaep_labellen, rctx->md, rctx->mgf1md); - } else + } else { ret = RSA_private_decrypt(inlen, in, out, ctx->pkey->pkey.rsa, rctx->pad_mode); + } if (ret < 0) return ret; *outlen = ret; @@ -325,6 +348,7 @@ static int pkey_rsa_decrypt(EVP_PKEY_CTX *ctx, static int check_padding_md(const EVP_MD *md, int padding) { int mdnid; + if (!md) return 1; @@ -354,6 +378,10 @@ static int check_padding_md(const EVP_MD *md, int padding) case NID_md4: case NID_mdc2: case NID_ripemd160: + case NID_sha3_224: + case NID_sha3_256: + case NID_sha3_384: + case NID_sha3_512: return 1; default: @@ -369,6 +397,7 @@ static int check_padding_md(const EVP_MD *md, int padding) static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { RSA_PKEY_CTX *rctx = ctx->data; + switch (type) { case EVP_PKEY_CTRL_RSA_PADDING: if ((p1 >= RSA_PKCS1_PADDING) && (p1 <= RSA_PKCS1_PSS_PADDING)) { @@ -380,6 +409,8 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) goto bad_pad; if (!rctx->md) rctx->md = EVP_sha1(); + } else if (pkey_ctx_is_pss(ctx)) { + goto bad_pad; } if (p1 == RSA_PKCS1_OAEP_PADDING) { if (!(ctx->operation & EVP_PKEY_OP_TYPE_CRYPT)) @@ -405,17 +436,30 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_INVALID_PSS_SALTLEN); return -2; } - if (type == EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN) + if (type == EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN) { *(int *)p2 = rctx->saltlen; - else { - if (p1 < -2) + } else { + if (p1 < RSA_PSS_SALTLEN_MAX) return -2; + if (rsa_pss_restricted(rctx)) { + if (p1 == RSA_PSS_SALTLEN_AUTO + && ctx->operation == EVP_PKEY_OP_VERIFY) { + RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_INVALID_PSS_SALTLEN); + return -2; + } + if ((p1 == RSA_PSS_SALTLEN_DIGEST + && rctx->min_saltlen > EVP_MD_size(rctx->md)) + || (p1 >= 0 && p1 < rctx->min_saltlen)) { + RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_PSS_SALTLEN_TOO_SMALL); + return 0; + } + } rctx->saltlen = p1; } return 1; case EVP_PKEY_CTRL_RSA_KEYGEN_BITS: - if (p1 < 512) { + if (p1 < RSA_MIN_MODULUS_BITS) { RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_KEY_SIZE_TOO_SMALL); return -2; } @@ -431,6 +475,14 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) rctx->pub_exp = p2; return 1; + case EVP_PKEY_CTRL_RSA_KEYGEN_PRIMES: + if (p1 < RSA_DEFAULT_PRIME_NUM || p1 > RSA_MAX_PRIME_NUM) { + RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_KEY_PRIME_NUM_INVALID); + return -2; + } + rctx->primes = p1; + return 1; + case EVP_PKEY_CTRL_RSA_OAEP_MD: case EVP_PKEY_CTRL_GET_RSA_OAEP_MD: if (rctx->pad_mode != RSA_PKCS1_OAEP_PADDING) { @@ -446,6 +498,12 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) case EVP_PKEY_CTRL_MD: if (!check_padding_md(p2, rctx->pad_mode)) return 0; + if (rsa_pss_restricted(rctx)) { + if (EVP_MD_type(rctx->md) == EVP_MD_type(p2)) + return 1; + RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_DIGEST_NOT_ALLOWED); + return 0; + } rctx->md = p2; return 1; @@ -465,8 +523,15 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) *(const EVP_MD **)p2 = rctx->mgf1md; else *(const EVP_MD **)p2 = rctx->md; - } else + } else { + if (rsa_pss_restricted(rctx)) { + if (EVP_MD_type(rctx->mgf1md) == EVP_MD_type(p2)) + return 1; + RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_MGF1_DIGEST_NOT_ALLOWED); + return 0; + } rctx->mgf1md = p2; + } return 1; case EVP_PKEY_CTRL_RSA_OAEP_LABEL: @@ -493,16 +558,21 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) return rctx->oaep_labellen; case EVP_PKEY_CTRL_DIGESTINIT: + case EVP_PKEY_CTRL_PKCS7_SIGN: +#ifndef OPENSSL_NO_CMS + case EVP_PKEY_CTRL_CMS_SIGN: +#endif + return 1; + case EVP_PKEY_CTRL_PKCS7_ENCRYPT: case EVP_PKEY_CTRL_PKCS7_DECRYPT: - case EVP_PKEY_CTRL_PKCS7_SIGN: - return 1; #ifndef OPENSSL_NO_CMS case EVP_PKEY_CTRL_CMS_DECRYPT: case EVP_PKEY_CTRL_CMS_ENCRYPT: - case EVP_PKEY_CTRL_CMS_SIGN: - return 1; #endif + if (!pkey_ctx_is_pss(ctx)) + return 1; + /* fall through */ case EVP_PKEY_CTRL_PEER_KEY: RSAerr(RSA_F_PKEY_RSA_CTRL, RSA_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE); @@ -517,27 +587,28 @@ static int pkey_rsa_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) static int pkey_rsa_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { - if (!value) { + if (value == NULL) { RSAerr(RSA_F_PKEY_RSA_CTRL_STR, RSA_R_VALUE_MISSING); return 0; } if (strcmp(type, "rsa_padding_mode") == 0) { int pm; - if (strcmp(value, "pkcs1") == 0) + + if (strcmp(value, "pkcs1") == 0) { pm = RSA_PKCS1_PADDING; - else if (strcmp(value, "sslv23") == 0) + } else if (strcmp(value, "sslv23") == 0) { pm = RSA_SSLV23_PADDING; - else if (strcmp(value, "none") == 0) + } else if (strcmp(value, "none") == 0) { pm = RSA_NO_PADDING; - else if (strcmp(value, "oeap") == 0) + } else if (strcmp(value, "oeap") == 0) { pm = RSA_PKCS1_OAEP_PADDING; - else if (strcmp(value, "oaep") == 0) + } else if (strcmp(value, "oaep") == 0) { pm = RSA_PKCS1_OAEP_PADDING; - else if (strcmp(value, "x931") == 0) + } else if (strcmp(value, "x931") == 0) { pm = RSA_X931_PADDING; - else if (strcmp(value, "pss") == 0) + } else if (strcmp(value, "pss") == 0) { pm = RSA_PKCS1_PSS_PADDING; - else { + } else { RSAerr(RSA_F_PKEY_RSA_CTRL_STR, RSA_R_UNKNOWN_PADDING_TYPE); return -2; } @@ -546,18 +617,27 @@ static int pkey_rsa_ctrl_str(EVP_PKEY_CTX *ctx, if (strcmp(type, "rsa_pss_saltlen") == 0) { int saltlen; - saltlen = atoi(value); + + if (!strcmp(value, "digest")) + saltlen = RSA_PSS_SALTLEN_DIGEST; + else if (!strcmp(value, "max")) + saltlen = RSA_PSS_SALTLEN_MAX; + else if (!strcmp(value, "auto")) + saltlen = RSA_PSS_SALTLEN_AUTO; + else + saltlen = atoi(value); return EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, saltlen); } if (strcmp(type, "rsa_keygen_bits") == 0) { - int nbits; - nbits = atoi(value); + int nbits = atoi(value); + return EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, nbits); } if (strcmp(type, "rsa_keygen_pubexp") == 0) { int ret; + BIGNUM *pubexp = NULL; if (!BN_asc2bn(&pubexp, value)) return 0; @@ -567,27 +647,43 @@ static int pkey_rsa_ctrl_str(EVP_PKEY_CTX *ctx, return ret; } - if (strcmp(type, "rsa_mgf1_md") == 0) { - const EVP_MD *md; - if ((md = EVP_get_digestbyname(value)) == NULL) { - RSAerr(RSA_F_PKEY_RSA_CTRL_STR, RSA_R_INVALID_DIGEST); - return 0; - } - return EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, md); + if (strcmp(type, "rsa_keygen_primes") == 0) { + int nprimes = atoi(value); + + return EVP_PKEY_CTX_set_rsa_keygen_primes(ctx, nprimes); } - if (strcmp(type, "rsa_oaep_md") == 0) { - const EVP_MD *md; - if ((md = EVP_get_digestbyname(value)) == NULL) { - RSAerr(RSA_F_PKEY_RSA_CTRL_STR, RSA_R_INVALID_DIGEST); - return 0; + if (strcmp(type, "rsa_mgf1_md") == 0) + return EVP_PKEY_CTX_md(ctx, + EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, + EVP_PKEY_CTRL_RSA_MGF1_MD, value); + + if (pkey_ctx_is_pss(ctx)) { + + if (strcmp(type, "rsa_pss_keygen_mgf1_md") == 0) + return EVP_PKEY_CTX_md(ctx, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_RSA_MGF1_MD, value); + + if (strcmp(type, "rsa_pss_keygen_md") == 0) + return EVP_PKEY_CTX_md(ctx, EVP_PKEY_OP_KEYGEN, + EVP_PKEY_CTRL_MD, value); + + if (strcmp(type, "rsa_pss_keygen_saltlen") == 0) { + int saltlen = atoi(value); + + return EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(ctx, saltlen); } - return EVP_PKEY_CTX_set_rsa_oaep_md(ctx, md); } + + if (strcmp(type, "rsa_oaep_md") == 0) + return EVP_PKEY_CTX_md(ctx, EVP_PKEY_OP_TYPE_CRYPT, + EVP_PKEY_CTRL_RSA_OAEP_MD, value); + if (strcmp(type, "rsa_oaep_label") == 0) { unsigned char *lab; long lablen; int ret; + lab = OPENSSL_hexstr2buf(value, &lablen); if (!lab) return 0; @@ -600,12 +696,30 @@ static int pkey_rsa_ctrl_str(EVP_PKEY_CTX *ctx, return -2; } +/* Set PSS parameters when generating a key, if necessary */ +static int rsa_set_pss_param(RSA *rsa, EVP_PKEY_CTX *ctx) +{ + RSA_PKEY_CTX *rctx = ctx->data; + + if (!pkey_ctx_is_pss(ctx)) + return 1; + /* If all parameters are default values don't set pss */ + if (rctx->md == NULL && rctx->mgf1md == NULL && rctx->saltlen == -2) + return 1; + rsa->pss = rsa_pss_params_create(rctx->md, rctx->mgf1md, + rctx->saltlen == -2 ? 0 : rctx->saltlen); + if (rsa->pss == NULL) + return 0; + return 1; +} + static int pkey_rsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { RSA *rsa = NULL; RSA_PKEY_CTX *rctx = ctx->data; BN_GENCB *pcb; int ret; + if (rctx->pub_exp == NULL) { rctx->pub_exp = BN_new(); if (rctx->pub_exp == NULL || !BN_set_word(rctx->pub_exp, RSA_F4)) @@ -621,12 +735,18 @@ static int pkey_rsa_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) return 0; } evp_pkey_set_cb_translate(pcb, ctx); - } else + } else { pcb = NULL; - ret = RSA_generate_key_ex(rsa, rctx->nbits, rctx->pub_exp, pcb); + } + ret = RSA_generate_multi_prime_key(rsa, rctx->nbits, rctx->primes, + rctx->pub_exp, pcb); BN_GENCB_free(pcb); + if (ret > 0 && !rsa_set_pss_param(rsa, ctx)) { + RSA_free(rsa); + return 0; + } if (ret > 0) - EVP_PKEY_assign_RSA(pkey, rsa); + EVP_PKEY_assign(pkey, ctx->pmeth->pkey_id, rsa); else RSA_free(rsa); return ret; @@ -666,3 +786,74 @@ const EVP_PKEY_METHOD rsa_pkey_meth = { pkey_rsa_ctrl, pkey_rsa_ctrl_str }; + +/* + * Called for PSS sign or verify initialisation: checks PSS parameter + * sanity and sets any restrictions on key usage. + */ + +static int pkey_pss_init(EVP_PKEY_CTX *ctx) +{ + RSA *rsa; + RSA_PKEY_CTX *rctx = ctx->data; + const EVP_MD *md; + const EVP_MD *mgf1md; + int min_saltlen, max_saltlen; + + /* Should never happen */ + if (!pkey_ctx_is_pss(ctx)) + return 0; + rsa = ctx->pkey->pkey.rsa; + /* If no restrictions just return */ + if (rsa->pss == NULL) + return 1; + /* Get and check parameters */ + if (!rsa_pss_get_param(rsa->pss, &md, &mgf1md, &min_saltlen)) + return 0; + + /* See if minimum salt length exceeds maximum possible */ + max_saltlen = RSA_size(rsa) - EVP_MD_size(md); + if ((RSA_bits(rsa) & 0x7) == 1) + max_saltlen--; + if (min_saltlen > max_saltlen) { + RSAerr(RSA_F_PKEY_PSS_INIT, RSA_R_INVALID_SALT_LENGTH); + return 0; + } + + rctx->min_saltlen = min_saltlen; + + /* + * Set PSS restrictions as defaults: we can then block any attempt to + * use invalid values in pkey_rsa_ctrl + */ + + rctx->md = md; + rctx->mgf1md = mgf1md; + rctx->saltlen = min_saltlen; + + return 1; +} + +const EVP_PKEY_METHOD rsa_pss_pkey_meth = { + EVP_PKEY_RSA_PSS, + EVP_PKEY_FLAG_AUTOARGLEN, + pkey_rsa_init, + pkey_rsa_copy, + pkey_rsa_cleanup, + + 0, 0, + + 0, + pkey_rsa_keygen, + + pkey_pss_init, + pkey_rsa_sign, + + pkey_pss_init, + pkey_rsa_verify, + + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + + pkey_rsa_ctrl, + pkey_rsa_ctrl_str +}; diff --git a/crypto/rsa/rsa_prn.c b/crypto/rsa/rsa_prn.c index 5e6c599e..b5f4bce2 100644 --- a/crypto/rsa/rsa_prn.c +++ b/crypto/rsa/rsa_prn.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-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 @@ -20,12 +20,12 @@ int RSA_print_fp(FILE *fp, const RSA *x, int off) if ((b = BIO_new(BIO_s_file())) == NULL) { RSAerr(RSA_F_RSA_PRINT_FP, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = RSA_print(b, x, off); BIO_free(b); - return (ret); + return ret; } #endif diff --git a/crypto/rsa/rsa_pss.c b/crypto/rsa/rsa_pss.c index f8143387..4484ff28 100644 --- a/crypto/rsa/rsa_pss.c +++ b/crypto/rsa/rsa_pss.c @@ -1,5 +1,5 @@ /* - * Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2005-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 @@ -41,7 +41,6 @@ int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash, EVP_MD_CTX *ctx = EVP_MD_CTX_new(); unsigned char H_[EVP_MAX_MD_SIZE]; - if (ctx == NULL) goto err; @@ -55,13 +54,12 @@ int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash, * Negative sLen has special meanings: * -1 sLen == hLen * -2 salt length is autorecovered from signature + * -3 salt length is maximized * -N reserved */ - if (sLen == -1) + if (sLen == RSA_PSS_SALTLEN_DIGEST) { sLen = hLen; - else if (sLen == -2) - sLen = -2; - else if (sLen < -2) { + } else if (sLen < RSA_PSS_SALTLEN_MAX) { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED); goto err; } @@ -80,7 +78,9 @@ int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash, 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 */ + if (sLen == RSA_PSS_SALTLEN_MAX) { + sLen = emLen - hLen - 2; + } else 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; } @@ -106,7 +106,7 @@ int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash, RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_RECOVERY_FAILED); goto err; } - if (sLen >= 0 && (maskedDBLen - i) != sLen) { + if (sLen != RSA_PSS_SALTLEN_AUTO && (maskedDBLen - i) != sLen) { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED); goto err; } @@ -123,8 +123,9 @@ int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash, if (memcmp(H_, H, hLen)) { RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_BAD_SIGNATURE); ret = 0; - } else + } else { ret = 1; + } err: OPENSSL_free(DB); @@ -162,13 +163,14 @@ int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM, * Negative sLen has special meanings: * -1 sLen == hLen * -2 salt length is maximized + * -3 same as above (on signing) * -N reserved */ - if (sLen == -1) + if (sLen == RSA_PSS_SALTLEN_DIGEST) { sLen = hLen; - else if (sLen == -2) - sLen = -2; - else if (sLen < -2) { + } else if (sLen == RSA_PSS_SALTLEN_MAX_SIGN) { + sLen = RSA_PSS_SALTLEN_MAX; + } else if (sLen < RSA_PSS_SALTLEN_MAX) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED); goto err; } @@ -184,7 +186,7 @@ int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); goto err; } - if (sLen == -2) { + if (sLen == RSA_PSS_SALTLEN_MAX) { sLen = emLen - hLen - 2; } else if (sLen > emLen - hLen - 2) { RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1, diff --git a/crypto/rsa/rsa_saos.c b/crypto/rsa/rsa_saos.c index 9e5fff45..8336f32f 100644 --- a/crypto/rsa/rsa_saos.c +++ b/crypto/rsa/rsa_saos.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -32,12 +32,12 @@ int RSA_sign_ASN1_OCTET_STRING(int type, if (i > (j - RSA_PKCS1_PADDING_SIZE)) { RSAerr(RSA_F_RSA_SIGN_ASN1_OCTET_STRING, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY); - return (0); + return 0; } s = OPENSSL_malloc((unsigned int)j + 1); if (s == NULL) { RSAerr(RSA_F_RSA_SIGN_ASN1_OCTET_STRING, ERR_R_MALLOC_FAILURE); - return (0); + return 0; } p = s; i2d_ASN1_OCTET_STRING(&sig, &p); @@ -48,7 +48,7 @@ int RSA_sign_ASN1_OCTET_STRING(int type, *siglen = i; OPENSSL_clear_free(s, (unsigned int)j + 1); - return (ret); + return ret; } int RSA_verify_ASN1_OCTET_STRING(int dtype, @@ -64,7 +64,7 @@ int RSA_verify_ASN1_OCTET_STRING(int dtype, if (siglen != (unsigned int)RSA_size(rsa)) { RSAerr(RSA_F_RSA_VERIFY_ASN1_OCTET_STRING, RSA_R_WRONG_SIGNATURE_LENGTH); - return (0); + return 0; } s = OPENSSL_malloc((unsigned int)siglen); @@ -85,10 +85,11 @@ int RSA_verify_ASN1_OCTET_STRING(int dtype, if (((unsigned int)sig->length != m_len) || (memcmp(m, sig->data, m_len) != 0)) { RSAerr(RSA_F_RSA_VERIFY_ASN1_OCTET_STRING, RSA_R_BAD_SIGNATURE); - } else + } else { ret = 1; + } err: ASN1_OCTET_STRING_free(sig); OPENSSL_clear_free(s, (unsigned int)siglen); - return (ret); + return ret; } diff --git a/crypto/rsa/rsa_ssl.c b/crypto/rsa/rsa_ssl.c index 9ef6b80e..cd98584b 100644 --- a/crypto/rsa/rsa_ssl.c +++ b/crypto/rsa/rsa_ssl.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -22,7 +22,7 @@ int RSA_padding_add_SSLv23(unsigned char *to, int tlen, if (flen > (tlen - 11)) { RSAerr(RSA_F_RSA_PADDING_ADD_SSLV23, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); - return (0); + return 0; } p = (unsigned char *)to; @@ -34,12 +34,12 @@ int RSA_padding_add_SSLv23(unsigned char *to, int tlen, j = tlen - 3 - 8 - flen; if (RAND_bytes(p, j) <= 0) - return (0); + return 0; for (i = 0; i < j; i++) { if (*p == '\0') do { if (RAND_bytes(p, 1) <= 0) - return (0); + return 0; } while (*p == '\0'); p++; } @@ -49,7 +49,7 @@ int RSA_padding_add_SSLv23(unsigned char *to, int tlen, *(p++) = '\0'; memcpy(p, from, (unsigned int)flen); - return (1); + return 1; } int RSA_padding_check_SSLv23(unsigned char *to, int tlen, @@ -61,11 +61,11 @@ int RSA_padding_check_SSLv23(unsigned char *to, int tlen, p = from; if (flen < 10) { RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_DATA_TOO_SMALL); - return (-1); + return -1; } if ((num != (flen + 1)) || (*(p++) != 02)) { RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_BLOCK_TYPE_IS_NOT_02); - return (-1); + return -1; } /* scan over padding data */ @@ -77,7 +77,7 @@ int RSA_padding_check_SSLv23(unsigned char *to, int tlen, if ((i == j) || (i < 8)) { RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_NULL_BEFORE_BLOCK_MISSING); - return (-1); + return -1; } for (k = -9; k < -1; k++) { if (p[k] != 0x03) @@ -85,16 +85,16 @@ int RSA_padding_check_SSLv23(unsigned char *to, int tlen, } if (k == -1) { RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_SSLV3_ROLLBACK_ATTACK); - return (-1); + return -1; } i++; /* Skip over the '\0' */ j -= i; if (j > tlen) { RSAerr(RSA_F_RSA_PADDING_CHECK_SSLV23, RSA_R_DATA_TOO_LARGE); - return (-1); + return -1; } memcpy(to, p, (unsigned int)j); - return (j); + return j; } diff --git a/crypto/rsa/rsa_x931.c b/crypto/rsa/rsa_x931.c index b9301f37..7b0486c0 100644 --- a/crypto/rsa/rsa_x931.c +++ b/crypto/rsa/rsa_x931.c @@ -1,5 +1,5 @@ /* - * Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2005-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 @@ -34,9 +34,9 @@ int RSA_padding_add_X931(unsigned char *to, int tlen, p = (unsigned char *)to; /* If no padding start and end nibbles are in one byte */ - if (j == 0) + if (j == 0) { *p++ = 0x6A; - else { + } else { *p++ = 0x6B; if (j > 1) { memset(p, 0xBB, j - 1); @@ -47,7 +47,7 @@ int RSA_padding_add_X931(unsigned char *to, int tlen, memcpy(p, from, (unsigned int)flen); p += flen; *p = 0xCC; - return (1); + return 1; } int RSA_padding_check_X931(unsigned char *to, int tlen, @@ -81,8 +81,9 @@ int RSA_padding_check_X931(unsigned char *to, int tlen, return -1; } - } else + } else { j = flen - 2; + } if (p[j] != 0xCC) { RSAerr(RSA_F_RSA_PADDING_CHECK_X931, RSA_R_INVALID_TRAILER); @@ -91,7 +92,7 @@ int RSA_padding_check_X931(unsigned char *to, int tlen, memcpy(to, p, (unsigned int)j); - return (j); + return j; } /* Translate between X931 hash ids and NIDs */ diff --git a/crypto/rsa/rsa_x931g.c b/crypto/rsa/rsa_x931g.c index 877ee221..3563670a 100644 --- a/crypto/rsa/rsa_x931g.c +++ b/crypto/rsa/rsa_x931g.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -44,8 +44,9 @@ int RSA_X931_derive_ex(RSA *rsa, BIGNUM *p1, BIGNUM *p2, BIGNUM *q1, rsa->e = BN_dup(e); if (!rsa->e) goto err; - } else + } else { e = rsa->e; + } /* * If not all parameters present only calculate what we can. This allows diff --git a/crypto/s390x_arch.h b/crypto/s390x_arch.h new file mode 100644 index 00000000..57443182 --- /dev/null +++ b/crypto/s390x_arch.h @@ -0,0 +1,95 @@ +/* + * Copyright 2017-2018 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 + */ + +#ifndef S390X_ARCH_H +# define S390X_ARCH_H + +# ifndef __ASSEMBLER__ + +void s390x_km(const unsigned char *in, size_t len, unsigned char *out, + unsigned int fc, void *param); +void s390x_kmac(const unsigned char *in, size_t len, unsigned int fc, + void *param); +void s390x_kma(const unsigned char *aad, size_t alen, const unsigned char *in, + size_t len, unsigned char *out, unsigned int fc, void *param); + +/* + * The field elements of OPENSSL_s390xcap_P are the 64-bit words returned by + * the STFLE instruction followed by the 64-bit word pairs returned by + * instructions' QUERY functions. If STFLE returns fewer data or an instruction + * is not supported, the corresponding field elements are zero. + */ +struct OPENSSL_s390xcap_st { + unsigned long long stfle[4]; + unsigned long long kimd[2]; + unsigned long long klmd[2]; + unsigned long long km[2]; + unsigned long long kmc[2]; + unsigned long long kmac[2]; + unsigned long long kmctr[2]; + unsigned long long kmo[2]; + unsigned long long kmf[2]; + unsigned long long prno[2]; + unsigned long long kma[2]; +}; + +extern struct OPENSSL_s390xcap_st OPENSSL_s390xcap_P; + +/* convert facility bit number or function code to bit mask */ +# define S390X_CAPBIT(i) (1ULL << (63 - (i) % 64)) + +# endif + +/* OPENSSL_s390xcap_P offsets [bytes] */ +# define S390X_STFLE 0x00 +# define S390X_KIMD 0x20 +# define S390X_KLMD 0x30 +# define S390X_KM 0x40 +# define S390X_KMC 0x50 +# define S390X_KMAC 0x60 +# define S390X_KMCTR 0x70 +# define S390X_KMO 0x80 +# define S390X_KMF 0x90 +# define S390X_PRNO 0xa0 +# define S390X_KMA 0xb0 + +/* Facility Bit Numbers */ +# define S390X_VX 129 +# define S390X_VXD 134 +# define S390X_VXE 135 + +/* Function Codes */ + +/* all instructions */ +# define S390X_QUERY 0 + +/* kimd/klmd */ +# define S390X_SHA3_224 32 +# define S390X_SHA3_256 33 +# define S390X_SHA3_384 34 +# define S390X_SHA3_512 35 +# define S390X_SHAKE_128 36 +# define S390X_SHAKE_256 37 +# define S390X_GHASH 65 + +/* km/kmc/kmac/kmctr/kmo/kmf/kma */ +# define S390X_AES_128 18 +# define S390X_AES_192 19 +# define S390X_AES_256 20 + +/* prno */ +# define S390X_TRNG 114 + +/* Register 0 Flags */ +# define S390X_DECRYPT 0x80 +# define S390X_KMA_LPC 0x100 +# define S390X_KMA_LAAD 0x200 +# define S390X_KMA_HS 0x400 + +#endif diff --git a/crypto/s390xcap.c b/crypto/s390xcap.c index 272c5517..e7c7f0a3 100644 --- a/crypto/s390xcap.c +++ b/crypto/s390xcap.c @@ -1,5 +1,5 @@ /* - * Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2010-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 @@ -12,8 +12,8 @@ #include #include #include - -unsigned long long OPENSSL_s390xcap_P[10]; +#include "internal/cryptlib.h" +#include "s390x_arch.h" static sigjmp_buf ill_jmp; static void ill_handler(int sig) @@ -21,30 +21,47 @@ static void ill_handler(int sig) siglongjmp(ill_jmp, sig); } -unsigned long OPENSSL_s390x_facilities(void); +void OPENSSL_s390x_facilities(void); +void OPENSSL_vx_probe(void); + +struct OPENSSL_s390xcap_st OPENSSL_s390xcap_P; void OPENSSL_cpuid_setup(void) { sigset_t oset; struct sigaction ill_act, oact; - if (OPENSSL_s390xcap_P[0]) + if (OPENSSL_s390xcap_P.stfle[0]) return; - OPENSSL_s390xcap_P[0] = 1UL << (8 * sizeof(unsigned long) - 1); + /* set a bit that will not be tested later */ + OPENSSL_s390xcap_P.stfle[0] |= S390X_CAPBIT(0); memset(&ill_act, 0, sizeof(ill_act)); ill_act.sa_handler = ill_handler; sigfillset(&ill_act.sa_mask); sigdelset(&ill_act.sa_mask, SIGILL); + sigdelset(&ill_act.sa_mask, SIGFPE); sigdelset(&ill_act.sa_mask, SIGTRAP); sigprocmask(SIG_SETMASK, &ill_act.sa_mask, &oset); sigaction(SIGILL, &ill_act, &oact); + sigaction(SIGFPE, &ill_act, &oact); /* protection against missing store-facility-list-extended */ if (sigsetjmp(ill_jmp, 1) == 0) OPENSSL_s390x_facilities(); + /* protection against disabled vector facility */ + if ((OPENSSL_s390xcap_P.stfle[2] & S390X_CAPBIT(S390X_VX)) + && (sigsetjmp(ill_jmp, 1) == 0)) { + OPENSSL_vx_probe(); + } else { + OPENSSL_s390xcap_P.stfle[2] &= ~(S390X_CAPBIT(S390X_VX) + | S390X_CAPBIT(S390X_VXD) + | S390X_CAPBIT(S390X_VXE)); + } + + sigaction(SIGFPE, &oact, NULL); sigaction(SIGILL, &oact, NULL); sigprocmask(SIG_SETMASK, &oset, NULL); } diff --git a/crypto/s390xcpuid.S b/crypto/s390xcpuid.S deleted file mode 100644 index fc141d92..00000000 --- a/crypto/s390xcpuid.S +++ /dev/null @@ -1,178 +0,0 @@ -.text -// Copyright 2009-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 - -.globl OPENSSL_s390x_facilities -.type OPENSSL_s390x_facilities,@function -.align 16 -OPENSSL_s390x_facilities: - lghi %r0,0 - larl %r4,OPENSSL_s390xcap_P - stg %r0,8(%r4) # wipe capability vectors - stg %r0,16(%r4) - stg %r0,24(%r4) - stg %r0,32(%r4) - stg %r0,40(%r4) - stg %r0,48(%r4) - stg %r0,56(%r4) - stg %r0,64(%r4) - stg %r0,72(%r4) - - .long 0xb2b04000 # stfle 0(%r4) - brc 8,.Ldone - lghi %r0,1 - .long 0xb2b04000 # stfle 0(%r4) -.Ldone: - lmg %r2,%r3,0(%r4) - tmhl %r2,0x4000 # check for message-security-assist - jz .Lret - - lghi %r0,0 # query kimd capabilities - la %r1,16(%r4) - .long 0xb93e0002 # kimd %r0,%r2 - - lghi %r0,0 # query km capability vector - la %r1,32(%r4) - .long 0xb92e0042 # km %r4,%r2 - - lghi %r0,0 # query kmc capability vector - la %r1,48(%r4) - .long 0xb92f0042 # kmc %r4,%r2 - - tmhh %r3,0x0004 # check for message-security-assist-4 - jz .Lret - - lghi %r0,0 # query kmctr capability vector - la %r1,64(%r4) - .long 0xb92d2042 # kmctr %r4,%r2,%r2 - -.Lret: - br %r14 -.size OPENSSL_s390x_facilities,.-OPENSSL_s390x_facilities - -.globl OPENSSL_rdtsc -.type OPENSSL_rdtsc,@function -.align 16 -OPENSSL_rdtsc: - stck 16(%r15) - lg %r2,16(%r15) - br %r14 -.size OPENSSL_rdtsc,.-OPENSSL_rdtsc - -.globl OPENSSL_atomic_add -.type OPENSSL_atomic_add,@function -.align 16 -OPENSSL_atomic_add: - l %r1,0(%r2) -.Lspin: lr %r0,%r1 - ar %r0,%r3 - cs %r1,%r0,0(%r2) - brc 4,.Lspin - lgfr %r2,%r0 # OpenSSL expects the new value - br %r14 -.size OPENSSL_atomic_add,.-OPENSSL_atomic_add - -.globl OPENSSL_wipe_cpu -.type OPENSSL_wipe_cpu,@function -.align 16 -OPENSSL_wipe_cpu: - xgr %r0,%r0 - xgr %r1,%r1 - lgr %r2,%r15 - xgr %r3,%r3 - xgr %r4,%r4 - lzdr %f0 - lzdr %f1 - lzdr %f2 - lzdr %f3 - lzdr %f4 - lzdr %f5 - lzdr %f6 - lzdr %f7 - br %r14 -.size OPENSSL_wipe_cpu,.-OPENSSL_wipe_cpu - -.globl OPENSSL_cleanse -.type OPENSSL_cleanse,@function -.align 16 -OPENSSL_cleanse: -#if !defined(__s390x__) && !defined(__s390x) - llgfr %r3,%r3 -#endif - lghi %r4,15 - lghi %r0,0 - clgr %r3,%r4 - jh .Lot - clgr %r3,%r0 - bcr 8,%r14 -.Little: - stc %r0,0(%r2) - la %r2,1(%r2) - brctg %r3,.Little - br %r14 -.align 4 -.Lot: tmll %r2,7 - jz .Laligned - stc %r0,0(%r2) - la %r2,1(%r2) - brctg %r3,.Lot -.Laligned: - srlg %r4,%r3,3 -.Loop: stg %r0,0(%r2) - la %r2,8(%r2) - brctg %r4,.Loop - lghi %r4,7 - ngr %r3,%r4 - jnz .Little - br %r14 -.size OPENSSL_cleanse,.-OPENSSL_cleanse - -.globl CRYPTO_memcmp -.type CRYPTO_memcmp,@function -.align 16 -CRYPTO_memcmp: -#if !defined(__s390x__) && !defined(__s390x) - llgfr %r4,%r4 -#endif - lghi %r5,0 - clgr %r4,%r5 - je .Lno_data - -.Loop_cmp: - llgc %r0,0(%r2) - la %r2,1(%r2) - llgc %r1,0(%r3) - la %r3,1(%r3) - xr %r1,%r0 - or %r5,%r1 - brctg %r4,.Loop_cmp - - lnr %r5,%r5 - srl %r5,31 -.Lno_data: - lgr %r2,%r5 - br %r14 -.size CRYPTO_memcmp,.-CRYPTO_memcmp - -.globl OPENSSL_instrument_bus -.type OPENSSL_instrument_bus,@function -.align 16 -OPENSSL_instrument_bus: - lghi %r2,0 - br %r14 -.size OPENSSL_instrument_bus,.-OPENSSL_instrument_bus - -.globl OPENSSL_instrument_bus2 -.type OPENSSL_instrument_bus2,@function -.align 16 -OPENSSL_instrument_bus2: - lghi %r2,0 - br %r14 -.size OPENSSL_instrument_bus2,.-OPENSSL_instrument_bus2 - -.section .init - brasl %r14,OPENSSL_cpuid_setup diff --git a/crypto/s390xcpuid.pl b/crypto/s390xcpuid.pl new file mode 100755 index 00000000..b0ed9e06 --- /dev/null +++ b/crypto/s390xcpuid.pl @@ -0,0 +1,337 @@ +#! /usr/bin/env perl +# Copyright 2009-2018 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 + +$flavour = shift; + +if ($flavour =~ /3[12]/) { + $SIZE_T=4; + $g=""; +} else { + $SIZE_T=8; + $g="g"; +} + +while (($output=shift) && ($output!~/\w[\w\-]*\.\w+$/)) {} +open STDOUT,">$output"; + +$ra="%r14"; +$sp="%r15"; +$stdframe=16*$SIZE_T+4*8; + +$code=<<___; +#include "s390x_arch.h" + +.text + +.globl OPENSSL_s390x_facilities +.type OPENSSL_s390x_facilities,\@function +.align 16 +OPENSSL_s390x_facilities: + lghi %r0,0 + larl %r4,OPENSSL_s390xcap_P + + stg %r0,S390X_STFLE+8(%r4) # wipe capability vectors + stg %r0,S390X_STFLE+16(%r4) + stg %r0,S390X_STFLE+24(%r4) + stg %r0,S390X_KIMD(%r4) + stg %r0,S390X_KIMD+8(%r4) + stg %r0,S390X_KLMD(%r4) + stg %r0,S390X_KLMD+8(%r4) + stg %r0,S390X_KM(%r4) + stg %r0,S390X_KM+8(%r4) + stg %r0,S390X_KMC(%r4) + stg %r0,S390X_KMC+8(%r4) + stg %r0,S390X_KMAC(%r4) + stg %r0,S390X_KMAC+8(%r4) + stg %r0,S390X_KMCTR(%r4) + stg %r0,S390X_KMCTR+8(%r4) + stg %r0,S390X_KMO(%r4) + stg %r0,S390X_KMO+8(%r4) + stg %r0,S390X_KMF(%r4) + stg %r0,S390X_KMF+8(%r4) + stg %r0,S390X_PRNO(%r4) + stg %r0,S390X_PRNO+8(%r4) + stg %r0,S390X_KMA(%r4) + stg %r0,S390X_KMA+8(%r4) + + .long 0xb2b04000 # stfle 0(%r4) + brc 8,.Ldone + lghi %r0,1 + .long 0xb2b04000 # stfle 0(%r4) + brc 8,.Ldone + lghi %r0,2 + .long 0xb2b04000 # stfle 0(%r4) +.Ldone: + lmg %r2,%r3,S390X_STFLE(%r4) + tmhl %r2,0x4000 # check for message-security-assist + jz .Lret + + lghi %r0,S390X_QUERY # query kimd capabilities + la %r1,S390X_KIMD(%r4) + .long 0xb93e0002 # kimd %r0,%r2 + + lghi %r0,S390X_QUERY # query klmd capabilities + la %r1,S390X_KLMD(%r4) + .long 0xb93f0002 # klmd %r0,%r2 + + lghi %r0,S390X_QUERY # query km capability vector + la %r1,S390X_KM(%r4) + .long 0xb92e0042 # km %r4,%r2 + + lghi %r0,S390X_QUERY # query kmc capability vector + la %r1,S390X_KMC(%r4) + .long 0xb92f0042 # kmc %r4,%r2 + + lghi %r0,S390X_QUERY # query kmac capability vector + la %r1,S390X_KMAC(%r4) + .long 0xb91e0042 # kmac %r4,%r2 + + tmhh %r3,0x0004 # check for message-security-assist-4 + jz .Lret + + lghi %r0,S390X_QUERY # query kmctr capability vector + la %r1,S390X_KMCTR(%r4) + .long 0xb92d2042 # kmctr %r4,%r2,%r2 + + lghi %r0,S390X_QUERY # query kmo capability vector + la %r1,S390X_KMO(%r4) + .long 0xb92b0042 # kmo %r4,%r2 + + lghi %r0,S390X_QUERY # query kmf capability vector + la %r1,S390X_KMF(%r4) + .long 0xb92a0042 # kmf %r4,%r2 + + tml %r2,0x40 # check for message-security-assist-5 + jz .Lret + + lghi %r0,S390X_QUERY # query prno capability vector + la %r1,S390X_PRNO(%r4) + .long 0xb93c0042 # prno %r4,%r2 + + lg %r2,S390X_STFLE+16(%r4) + tmhl %r2,0x2000 # check for message-security-assist-8 + jz .Lret + + lghi %r0,S390X_QUERY # query kma capability vector + la %r1,S390X_KMA(%r4) + .long 0xb9294022 # kma %r2,%r4,%r2 + +.Lret: + br $ra +.size OPENSSL_s390x_facilities,.-OPENSSL_s390x_facilities + +.globl OPENSSL_rdtsc +.type OPENSSL_rdtsc,\@function +.align 16 +OPENSSL_rdtsc: + larl %r4,OPENSSL_s390xcap_P + tm S390X_STFLE+3(%r4),0x40 # check for store-clock-fast facility + jz .Lstck + + .long 0xb27cf010 # stckf 16($sp) + lg %r2,16($sp) + br $ra +.Lstck: + stck 16($sp) + lg %r2,16($sp) + br $ra +.size OPENSSL_rdtsc,.-OPENSSL_rdtsc + +.globl OPENSSL_atomic_add +.type OPENSSL_atomic_add,\@function +.align 16 +OPENSSL_atomic_add: + l %r1,0(%r2) +.Lspin: lr %r0,%r1 + ar %r0,%r3 + cs %r1,%r0,0(%r2) + brc 4,.Lspin + lgfr %r2,%r0 # OpenSSL expects the new value + br $ra +.size OPENSSL_atomic_add,.-OPENSSL_atomic_add + +.globl OPENSSL_wipe_cpu +.type OPENSSL_wipe_cpu,\@function +.align 16 +OPENSSL_wipe_cpu: + xgr %r0,%r0 + xgr %r1,%r1 + lgr %r2,$sp + xgr %r3,%r3 + xgr %r4,%r4 + lzdr %f0 + lzdr %f1 + lzdr %f2 + lzdr %f3 + lzdr %f4 + lzdr %f5 + lzdr %f6 + lzdr %f7 + br $ra +.size OPENSSL_wipe_cpu,.-OPENSSL_wipe_cpu + +.globl OPENSSL_cleanse +.type OPENSSL_cleanse,\@function +.align 16 +OPENSSL_cleanse: +#if !defined(__s390x__) && !defined(__s390x) + llgfr %r3,%r3 +#endif + lghi %r4,15 + lghi %r0,0 + clgr %r3,%r4 + jh .Lot + clgr %r3,%r0 + bcr 8,%r14 +.Little: + stc %r0,0(%r2) + la %r2,1(%r2) + brctg %r3,.Little + br %r14 +.align 4 +.Lot: tmll %r2,7 + jz .Laligned + stc %r0,0(%r2) + la %r2,1(%r2) + brctg %r3,.Lot +.Laligned: + srlg %r4,%r3,3 +.Loop: stg %r0,0(%r2) + la %r2,8(%r2) + brctg %r4,.Loop + lghi %r4,7 + ngr %r3,%r4 + jnz .Little + br $ra +.size OPENSSL_cleanse,.-OPENSSL_cleanse + +.globl CRYPTO_memcmp +.type CRYPTO_memcmp,\@function +.align 16 +CRYPTO_memcmp: +#if !defined(__s390x__) && !defined(__s390x) + llgfr %r4,%r4 +#endif + lghi %r5,0 + clgr %r4,%r5 + je .Lno_data + +.Loop_cmp: + llgc %r0,0(%r2) + la %r2,1(%r2) + llgc %r1,0(%r3) + la %r3,1(%r3) + xr %r1,%r0 + or %r5,%r1 + brctg %r4,.Loop_cmp + + lnr %r5,%r5 + srl %r5,31 +.Lno_data: + lgr %r2,%r5 + br $ra +.size CRYPTO_memcmp,.-CRYPTO_memcmp + +.globl OPENSSL_instrument_bus +.type OPENSSL_instrument_bus,\@function +.align 16 +OPENSSL_instrument_bus: + lghi %r2,0 + br %r14 +.size OPENSSL_instrument_bus,.-OPENSSL_instrument_bus + +.globl OPENSSL_instrument_bus2 +.type OPENSSL_instrument_bus2,\@function +.align 16 +OPENSSL_instrument_bus2: + lghi %r2,0 + br $ra +.size OPENSSL_instrument_bus2,.-OPENSSL_instrument_bus2 + +.globl OPENSSL_vx_probe +.type OPENSSL_vx_probe,\@function +.align 16 +OPENSSL_vx_probe: + .word 0xe700,0x0000,0x0044 # vzero %v0 + br $ra +.size OPENSSL_vx_probe,.-OPENSSL_vx_probe +___ + +################ +# void s390x_km(const unsigned char *in, size_t len, unsigned char *out, +# unsigned int fc, void *param) +{ +my ($in,$len,$out,$fc,$param) = map("%r$_",(2..6)); +$code.=<<___; +.globl s390x_km +.type s390x_km,\@function +.align 16 +s390x_km: + lr %r0,$fc + l${g}r %r1,$param + + .long 0xb92e0042 # km $out,$in + brc 1,.-4 # pay attention to "partial completion" + + br $ra +.size s390x_km,.-s390x_km +___ +} + +################ +# void s390x_kmac(const unsigned char *in, size_t len, unsigned int fc, +# void *param) +{ +my ($in,$len,$fc,$param) = map("%r$_",(2..5)); +$code.=<<___; +.globl s390x_kmac +.type s390x_kmac,\@function +.align 16 +s390x_kmac: + lr %r0,$fc + l${g}r %r1,$param + + .long 0xb91e0002 # kmac %r0,$in + brc 1,.-4 # pay attention to "partial completion" + + br $ra +.size s390x_kmac,.-s390x_kmac +___ +} + +################ +# void s390x_kma(const unsigned char *aad, size_t alen, +# const unsigned char *in, size_t len, +# unsigned char *out, unsigned int fc, void *param) +{ +my ($aad,$alen,$in,$len,$out) = map("%r$_",(2..6)); +$code.=<<___; +.globl s390x_kma +.type s390x_kma,\@function +.align 16 +s390x_kma: + st${g} $out,6*$SIZE_T($sp) + lm${g} %r0,%r1,$stdframe($sp) + + .long 0xb9292064 # kma $out,$aad,$in + brc 1,.-4 # pay attention to "partial completion" + + l${g} $out,6*$SIZE_T($sp) + br $ra +.size s390x_kma,.-s390x_kma +___ +} + +$code.=<<___; +.section .init + brasl $ra,OPENSSL_cpuid_setup +___ + +$code =~ s/\`([^\`]*)\`/eval $1/gem; +print $code; +close STDOUT; # force flush diff --git a/crypto/sha/asm/keccak1600-armv4.pl b/crypto/sha/asm/keccak1600-armv4.pl new file mode 100755 index 00000000..16d23931 --- /dev/null +++ b/crypto/sha/asm/keccak1600-armv4.pl @@ -0,0 +1,1586 @@ +#!/usr/bin/env perl +# 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# Keccak-1600 for ARMv4. +# +# June 2017. +# +# Non-NEON code is KECCAK_1X variant (see sha/keccak1600.c) with bit +# interleaving. How does it compare to Keccak Code Package? It's as +# fast, but several times smaller, and is endian- and ISA-neutral. ISA +# neutrality means that minimum ISA requirement is ARMv4, yet it can +# be assembled even as Thumb-2. NEON code path is KECCAK_1X_ALT with +# register layout taken from Keccak Code Package. It's also as fast, +# in fact faster by 10-15% on some processors, and endian-neutral. +# +# August 2017. +# +# Switch to KECCAK_2X variant for non-NEON code and merge almost 1/2 +# of rotate instructions with logical ones. This resulted in ~10% +# improvement on most processors. Switch to KECCAK_2X effectively +# minimizes re-loads from temporary storage, and merged rotates just +# eliminate corresponding instructions. As for latter. When examining +# code you'll notice commented ror instructions. These are eliminated +# ones, and you should trace destination register below to see what's +# going on. Just in case, why not all rotates are eliminated. Trouble +# is that you have operations that require both inputs to be rotated, +# e.g. 'eor a,b>>>x,c>>>y'. This conundrum is resolved by using +# 'eor a,b,c>>>(x-y)' and then merge-rotating 'a' in next operation +# that takes 'a' as input. And thing is that this next operation can +# be in next round. It's totally possible to "carry" rotate "factors" +# to the next round, but it makes code more complex. And the last word +# is the keyword, i.e. "almost 1/2" is kind of complexity cap [for the +# time being]... +# +# Reduce per-round instruction count in Thumb-2 case by 16%. This is +# achieved by folding ldr/str pairs to their double-word counterparts. +# Theoretically this should have improved performance on single-issue +# cores, such as Cortex-A5/A7, by 19%. Reality is a bit different, as +# usual... +# +######################################################################## +# Numbers are cycles per processed byte. Non-NEON results account even +# for input bit interleaving. +# +# r=1088(*) Thumb-2(**) NEON +# +# ARM11xx 82/+150% +# Cortex-A5 88/+160%, 86, 36 +# Cortex-A7 78/+160%, 68, 34 +# Cortex-A8 51/+230%, 57, 30 +# Cortex-A9 53/+210%, 51, 26 +# Cortex-A15 42/+160%, 38, 18 +# Snapdragon S4 43/+210%, 38, 24 +# +# (*) Corresponds to SHA3-256. Percentage after slash is improvement +# over compiler-generated KECCAK_2X reference code. +# (**) Thumb-2 results for Cortex-A5/A7 are likely to apply even to +# Cortex-Mx, x>=3. Otherwise, non-NEON results for NEON-capable +# processors are presented mostly for reference purposes. + +my @C = map("r$_",(0..9)); +my @E = map("r$_",(10..12,14)); + +######################################################################## +# Stack layout +# ----->+-----------------------+ +# | uint64_t A[5][5] | +# | ... | +# +200->+-----------------------+ +# | uint64_t D[5] | +# | ... | +# +240->+-----------------------+ +# | uint64_t T[5][5] | +# | ... | +# +440->+-----------------------+ +# | saved lr | +# +444->+-----------------------+ +# | loop counter | +# +448->+-----------------------+ +# | ... + +my @A = map([ 8*$_, 8*($_+1), 8*($_+2), 8*($_+3), 8*($_+4) ], (0,5,10,15,20)); +my @D = map(8*$_, (25..29)); +my @T = map([ 8*$_, 8*($_+1), 8*($_+2), 8*($_+3), 8*($_+4) ], (30,35,40,45,50)); + +$code.=<<___; +.text + +#if defined(__thumb2__) +.syntax unified +.thumb +#else +.code 32 +#endif + +.type iotas32, %object +.align 5 +iotas32: + .long 0x00000001, 0x00000000 + .long 0x00000000, 0x00000089 + .long 0x00000000, 0x8000008b + .long 0x00000000, 0x80008080 + .long 0x00000001, 0x0000008b + .long 0x00000001, 0x00008000 + .long 0x00000001, 0x80008088 + .long 0x00000001, 0x80000082 + .long 0x00000000, 0x0000000b + .long 0x00000000, 0x0000000a + .long 0x00000001, 0x00008082 + .long 0x00000000, 0x00008003 + .long 0x00000001, 0x0000808b + .long 0x00000001, 0x8000000b + .long 0x00000001, 0x8000008a + .long 0x00000001, 0x80000081 + .long 0x00000000, 0x80000081 + .long 0x00000000, 0x80000008 + .long 0x00000000, 0x00000083 + .long 0x00000000, 0x80008003 + .long 0x00000001, 0x80008088 + .long 0x00000000, 0x80000088 + .long 0x00000001, 0x00008000 + .long 0x00000000, 0x80008082 +.size iotas32,.-iotas32 + +.type KeccakF1600_int, %function +.align 5 +KeccakF1600_int: + add @C[9],sp,#$A[4][2] + add @E[2],sp,#$A[0][0] + add @E[0],sp,#$A[1][0] + ldmia @C[9],{@C[4]-@C[9]} @ A[4][2..4] +KeccakF1600_enter: + str lr,[sp,#440] + eor @E[1],@E[1],@E[1] + str @E[1],[sp,#444] + b .Lround2x + +.align 4 +.Lround2x: +___ +sub Round { +my (@A,@R); (@A[0..4],@R) = @_; + +$code.=<<___; + ldmia @E[2],{@C[0]-@C[3]} @ A[0][0..1] + ldmia @E[0],{@E[0]-@E[2],@E[3]} @ A[1][0..1] +#ifdef __thumb2__ + eor @C[0],@C[0],@E[0] + eor @C[1],@C[1],@E[1] + eor @C[2],@C[2],@E[2] + ldrd @E[0],@E[1],[sp,#$A[1][2]] + eor @C[3],@C[3],@E[3] + ldrd @E[2],@E[3],[sp,#$A[1][3]] + eor @C[4],@C[4],@E[0] + eor @C[5],@C[5],@E[1] + eor @C[6],@C[6],@E[2] + ldrd @E[0],@E[1],[sp,#$A[1][4]] + eor @C[7],@C[7],@E[3] + ldrd @E[2],@E[3],[sp,#$A[2][0]] + eor @C[8],@C[8],@E[0] + eor @C[9],@C[9],@E[1] + eor @C[0],@C[0],@E[2] + ldrd @E[0],@E[1],[sp,#$A[2][1]] + eor @C[1],@C[1],@E[3] + ldrd @E[2],@E[3],[sp,#$A[2][2]] + eor @C[2],@C[2],@E[0] + eor @C[3],@C[3],@E[1] + eor @C[4],@C[4],@E[2] + ldrd @E[0],@E[1],[sp,#$A[2][3]] + eor @C[5],@C[5],@E[3] + ldrd @E[2],@E[3],[sp,#$A[2][4]] + eor @C[6],@C[6],@E[0] + eor @C[7],@C[7],@E[1] + eor @C[8],@C[8],@E[2] + ldrd @E[0],@E[1],[sp,#$A[3][0]] + eor @C[9],@C[9],@E[3] + ldrd @E[2],@E[3],[sp,#$A[3][1]] + eor @C[0],@C[0],@E[0] + eor @C[1],@C[1],@E[1] + eor @C[2],@C[2],@E[2] + ldrd @E[0],@E[1],[sp,#$A[3][2]] + eor @C[3],@C[3],@E[3] + ldrd @E[2],@E[3],[sp,#$A[3][3]] + eor @C[4],@C[4],@E[0] + eor @C[5],@C[5],@E[1] + eor @C[6],@C[6],@E[2] + ldrd @E[0],@E[1],[sp,#$A[3][4]] + eor @C[7],@C[7],@E[3] + ldrd @E[2],@E[3],[sp,#$A[4][0]] + eor @C[8],@C[8],@E[0] + eor @C[9],@C[9],@E[1] + eor @C[0],@C[0],@E[2] + ldrd @E[0],@E[1],[sp,#$A[4][1]] + eor @C[1],@C[1],@E[3] + ldrd @E[2],@E[3],[sp,#$A[0][2]] + eor @C[2],@C[2],@E[0] + eor @C[3],@C[3],@E[1] + eor @C[4],@C[4],@E[2] + ldrd @E[0],@E[1],[sp,#$A[0][3]] + eor @C[5],@C[5],@E[3] + ldrd @E[2],@E[3],[sp,#$A[0][4]] +#else + eor @C[0],@C[0],@E[0] + add @E[0],sp,#$A[1][2] + eor @C[1],@C[1],@E[1] + eor @C[2],@C[2],@E[2] + eor @C[3],@C[3],@E[3] + ldmia @E[0],{@E[0]-@E[2],@E[3]} @ A[1][2..3] + eor @C[4],@C[4],@E[0] + add @E[0],sp,#$A[1][4] + eor @C[5],@C[5],@E[1] + eor @C[6],@C[6],@E[2] + eor @C[7],@C[7],@E[3] + ldmia @E[0],{@E[0]-@E[2],@E[3]} @ A[1][4]..A[2][0] + eor @C[8],@C[8],@E[0] + add @E[0],sp,#$A[2][1] + eor @C[9],@C[9],@E[1] + eor @C[0],@C[0],@E[2] + eor @C[1],@C[1],@E[3] + ldmia @E[0],{@E[0]-@E[2],@E[3]} @ A[2][1..2] + eor @C[2],@C[2],@E[0] + add @E[0],sp,#$A[2][3] + eor @C[3],@C[3],@E[1] + eor @C[4],@C[4],@E[2] + eor @C[5],@C[5],@E[3] + ldmia @E[0],{@E[0]-@E[2],@E[3]} @ A[2][3..4] + eor @C[6],@C[6],@E[0] + add @E[0],sp,#$A[3][0] + eor @C[7],@C[7],@E[1] + eor @C[8],@C[8],@E[2] + eor @C[9],@C[9],@E[3] + ldmia @E[0],{@E[0]-@E[2],@E[3]} @ A[3][0..1] + eor @C[0],@C[0],@E[0] + add @E[0],sp,#$A[3][2] + eor @C[1],@C[1],@E[1] + eor @C[2],@C[2],@E[2] + eor @C[3],@C[3],@E[3] + ldmia @E[0],{@E[0]-@E[2],@E[3]} @ A[3][2..3] + eor @C[4],@C[4],@E[0] + add @E[0],sp,#$A[3][4] + eor @C[5],@C[5],@E[1] + eor @C[6],@C[6],@E[2] + eor @C[7],@C[7],@E[3] + ldmia @E[0],{@E[0]-@E[2],@E[3]} @ A[3][4]..A[4][0] + eor @C[8],@C[8],@E[0] + ldr @E[0],[sp,#$A[4][1]] @ A[4][1] + eor @C[9],@C[9],@E[1] + ldr @E[1],[sp,#$A[4][1]+4] + eor @C[0],@C[0],@E[2] + ldr @E[2],[sp,#$A[0][2]] @ A[0][2] + eor @C[1],@C[1],@E[3] + ldr @E[3],[sp,#$A[0][2]+4] + eor @C[2],@C[2],@E[0] + add @E[0],sp,#$A[0][3] + eor @C[3],@C[3],@E[1] + eor @C[4],@C[4],@E[2] + eor @C[5],@C[5],@E[3] + ldmia @E[0],{@E[0]-@E[2],@E[3]} @ A[0][3..4] +#endif + eor @C[6],@C[6],@E[0] + eor @C[7],@C[7],@E[1] + eor @C[8],@C[8],@E[2] + eor @C[9],@C[9],@E[3] + + eor @E[0],@C[0],@C[5],ror#32-1 @ E[0] = ROL64(C[2], 1) ^ C[0]; + str.l @E[0],[sp,#$D[1]] @ D[1] = E[0] + eor @E[1],@C[1],@C[4] + str.h @E[1],[sp,#$D[1]+4] + eor @E[2],@C[6],@C[1],ror#32-1 @ E[1] = ROL64(C[0], 1) ^ C[3]; + eor @E[3],@C[7],@C[0] + str.l @E[2],[sp,#$D[4]] @ D[4] = E[1] + eor @C[0],@C[8],@C[3],ror#32-1 @ C[0] = ROL64(C[1], 1) ^ C[4]; + str.h @E[3],[sp,#$D[4]+4] + eor @C[1],@C[9],@C[2] + str.l @C[0],[sp,#$D[0]] @ D[0] = C[0] + eor @C[2],@C[2],@C[7],ror#32-1 @ C[1] = ROL64(C[3], 1) ^ C[1]; + ldr.l @C[7],[sp,#$A[3][3]] + eor @C[3],@C[3],@C[6] + str.h @C[1],[sp,#$D[0]+4] + ldr.h @C[6],[sp,#$A[3][3]+4] + str.l @C[2],[sp,#$D[2]] @ D[2] = C[1] + eor @C[4],@C[4],@C[9],ror#32-1 @ C[2] = ROL64(C[4], 1) ^ C[2]; + str.h @C[3],[sp,#$D[2]+4] + eor @C[5],@C[5],@C[8] + + ldr.l @C[8],[sp,#$A[4][4]] + ldr.h @C[9],[sp,#$A[4][4]+4] + str.l @C[4],[sp,#$D[3]] @ D[3] = C[2] + eor @C[7],@C[7],@C[4] + str.h @C[5],[sp,#$D[3]+4] + eor @C[6],@C[6],@C[5] + ldr.l @C[4],[sp,#$A[0][0]] + @ ror @C[7],@C[7],#32-10 @ C[3] = ROL64(A[3][3] ^ C[2], rhotates[3][3]); /* D[3] */ + @ ror @C[6],@C[6],#32-11 + ldr.h @C[5],[sp,#$A[0][0]+4] + eor @C[8],@C[8],@E[2] + eor @C[9],@C[9],@E[3] + ldr.l @E[2],[sp,#$A[2][2]] + eor @C[0],@C[0],@C[4] + ldr.h @E[3],[sp,#$A[2][2]+4] + @ ror @C[8],@C[8],#32-7 @ C[4] = ROL64(A[4][4] ^ E[1], rhotates[4][4]); /* D[4] */ + @ ror @C[9],@C[9],#32-7 + eor @C[1],@C[1],@C[5] @ C[0] = A[0][0] ^ C[0]; /* rotate by 0 */ /* D[0] */ + eor @E[2],@E[2],@C[2] + ldr.l @C[2],[sp,#$A[1][1]] + eor @E[3],@E[3],@C[3] + ldr.h @C[3],[sp,#$A[1][1]+4] + ror @C[5],@E[2],#32-21 @ C[2] = ROL64(A[2][2] ^ C[1], rhotates[2][2]); /* D[2] */ + ldr @E[2],[sp,#444] @ load counter + eor @C[2],@C[2],@E[0] + adr @E[0],iotas32 + ror @C[4],@E[3],#32-22 + add @E[3],@E[0],@E[2] + eor @C[3],@C[3],@E[1] +___ +$code.=<<___ if ($A[0][0] != $T[0][0]); + ldmia @E[3],{@E[0],@E[1]} @ iotas[i] +___ +$code.=<<___ if ($A[0][0] == $T[0][0]); + ldr.l @E[0],[@E[3],#8] @ iotas[i].lo + add @E[2],@E[2],#16 + ldr.h @E[1],[@E[3],#12] @ iotas[i].hi + cmp @E[2],#192 + str @E[2],[sp,#444] @ store counter +___ +$code.=<<___; + bic @E[2],@C[4],@C[2],ror#32-22 + bic @E[3],@C[5],@C[3],ror#32-22 + ror @C[2],@C[2],#32-22 @ C[1] = ROL64(A[1][1] ^ E[0], rhotates[1][1]); /* D[1] */ + ror @C[3],@C[3],#32-22 + eor @E[2],@E[2],@C[0] + eor @E[3],@E[3],@C[1] + eor @E[0],@E[0],@E[2] + eor @E[1],@E[1],@E[3] + str.l @E[0],[sp,#$R[0][0]] @ R[0][0] = C[0] ^ (~C[1] & C[2]) ^ iotas[i]; + bic @E[2],@C[6],@C[4],ror#11 + str.h @E[1],[sp,#$R[0][0]+4] + bic @E[3],@C[7],@C[5],ror#10 + bic @E[0],@C[8],@C[6],ror#32-(11-7) + bic @E[1],@C[9],@C[7],ror#32-(10-7) + eor @E[2],@C[2],@E[2],ror#32-11 + str.l @E[2],[sp,#$R[0][1]] @ R[0][1] = C[1] ^ (~C[2] & C[3]); + eor @E[3],@C[3],@E[3],ror#32-10 + str.h @E[3],[sp,#$R[0][1]+4] + eor @E[0],@C[4],@E[0],ror#32-7 + eor @E[1],@C[5],@E[1],ror#32-7 + str.l @E[0],[sp,#$R[0][2]] @ R[0][2] = C[2] ^ (~C[3] & C[4]); + bic @E[2],@C[0],@C[8],ror#32-7 + str.h @E[1],[sp,#$R[0][2]+4] + bic @E[3],@C[1],@C[9],ror#32-7 + eor @E[2],@E[2],@C[6],ror#32-11 + str.l @E[2],[sp,#$R[0][3]] @ R[0][3] = C[3] ^ (~C[4] & C[0]); + eor @E[3],@E[3],@C[7],ror#32-10 + str.h @E[3],[sp,#$R[0][3]+4] + bic @E[0],@C[2],@C[0] + add @E[3],sp,#$D[3] + ldr.l @C[0],[sp,#$A[0][3]] @ A[0][3] + bic @E[1],@C[3],@C[1] + ldr.h @C[1],[sp,#$A[0][3]+4] + eor @E[0],@E[0],@C[8],ror#32-7 + eor @E[1],@E[1],@C[9],ror#32-7 + str.l @E[0],[sp,#$R[0][4]] @ R[0][4] = C[4] ^ (~C[0] & C[1]); + add @C[9],sp,#$D[0] + str.h @E[1],[sp,#$R[0][4]+4] + + ldmia @E[3],{@E[0]-@E[2],@E[3]} @ D[3..4] + ldmia @C[9],{@C[6]-@C[9]} @ D[0..1] + + ldr.l @C[2],[sp,#$A[1][4]] @ A[1][4] + eor @C[0],@C[0],@E[0] + ldr.h @C[3],[sp,#$A[1][4]+4] + eor @C[1],@C[1],@E[1] + @ ror @C[0],@C[0],#32-14 @ C[0] = ROL64(A[0][3] ^ D[3], rhotates[0][3]); + ldr.l @E[0],[sp,#$A[3][1]] @ A[3][1] + @ ror @C[1],@C[1],#32-14 + ldr.h @E[1],[sp,#$A[3][1]+4] + + eor @C[2],@C[2],@E[2] + ldr.l @C[4],[sp,#$A[2][0]] @ A[2][0] + eor @C[3],@C[3],@E[3] + ldr.h @C[5],[sp,#$A[2][0]+4] + @ ror @C[2],@C[2],#32-10 @ C[1] = ROL64(A[1][4] ^ D[4], rhotates[1][4]); + @ ror @C[3],@C[3],#32-10 + + eor @C[6],@C[6],@C[4] + ldr.l @E[2],[sp,#$D[2]] @ D[2] + eor @C[7],@C[7],@C[5] + ldr.h @E[3],[sp,#$D[2]+4] + ror @C[5],@C[6],#32-1 @ C[2] = ROL64(A[2][0] ^ D[0], rhotates[2][0]); + ror @C[4],@C[7],#32-2 + + eor @E[0],@E[0],@C[8] + ldr.l @C[8],[sp,#$A[4][2]] @ A[4][2] + eor @E[1],@E[1],@C[9] + ldr.h @C[9],[sp,#$A[4][2]+4] + ror @C[7],@E[0],#32-22 @ C[3] = ROL64(A[3][1] ^ D[1], rhotates[3][1]); + ror @C[6],@E[1],#32-23 + + bic @E[0],@C[4],@C[2],ror#32-10 + bic @E[1],@C[5],@C[3],ror#32-10 + eor @E[2],@E[2],@C[8] + eor @E[3],@E[3],@C[9] + ror @C[9],@E[2],#32-30 @ C[4] = ROL64(A[4][2] ^ D[2], rhotates[4][2]); + ror @C[8],@E[3],#32-31 + eor @E[0],@E[0],@C[0],ror#32-14 + eor @E[1],@E[1],@C[1],ror#32-14 + str.l @E[0],[sp,#$R[1][0]] @ R[1][0] = C[0] ^ (~C[1] & C[2]) + bic @E[2],@C[6],@C[4] + str.h @E[1],[sp,#$R[1][0]+4] + bic @E[3],@C[7],@C[5] + eor @E[2],@E[2],@C[2],ror#32-10 + str.l @E[2],[sp,#$R[1][1]] @ R[1][1] = C[1] ^ (~C[2] & C[3]); + eor @E[3],@E[3],@C[3],ror#32-10 + str.h @E[3],[sp,#$R[1][1]+4] + bic @E[0],@C[8],@C[6] + bic @E[1],@C[9],@C[7] + bic @E[2],@C[0],@C[8],ror#14 + bic @E[3],@C[1],@C[9],ror#14 + eor @E[0],@E[0],@C[4] + eor @E[1],@E[1],@C[5] + str.l @E[0],[sp,#$R[1][2]] @ R[1][2] = C[2] ^ (~C[3] & C[4]); + bic @C[2],@C[2],@C[0],ror#32-(14-10) + str.h @E[1],[sp,#$R[1][2]+4] + eor @E[2],@C[6],@E[2],ror#32-14 + bic @E[1],@C[3],@C[1],ror#32-(14-10) + str.l @E[2],[sp,#$R[1][3]] @ R[1][3] = C[3] ^ (~C[4] & C[0]); + eor @E[3],@C[7],@E[3],ror#32-14 + str.h @E[3],[sp,#$R[1][3]+4] + add @E[2],sp,#$D[1] + ldr.l @C[1],[sp,#$A[0][1]] @ A[0][1] + eor @E[0],@C[8],@C[2],ror#32-10 + ldr.h @C[0],[sp,#$A[0][1]+4] + eor @E[1],@C[9],@E[1],ror#32-10 + str.l @E[0],[sp,#$R[1][4]] @ R[1][4] = C[4] ^ (~C[0] & C[1]); + str.h @E[1],[sp,#$R[1][4]+4] + + add @C[9],sp,#$D[3] + ldmia @E[2],{@E[0]-@E[2],@E[3]} @ D[1..2] + ldr.l @C[2],[sp,#$A[1][2]] @ A[1][2] + ldr.h @C[3],[sp,#$A[1][2]+4] + ldmia @C[9],{@C[6]-@C[9]} @ D[3..4] + + eor @C[1],@C[1],@E[0] + ldr.l @C[4],[sp,#$A[2][3]] @ A[2][3] + eor @C[0],@C[0],@E[1] + ldr.h @C[5],[sp,#$A[2][3]+4] + ror @C[0],@C[0],#32-1 @ C[0] = ROL64(A[0][1] ^ D[1], rhotates[0][1]); + + eor @C[2],@C[2],@E[2] + ldr.l @E[0],[sp,#$A[3][4]] @ A[3][4] + eor @C[3],@C[3],@E[3] + ldr.h @E[1],[sp,#$A[3][4]+4] + @ ror @C[2],@C[2],#32-3 @ C[1] = ROL64(A[1][2] ^ D[2], rhotates[1][2]); + ldr.l @E[2],[sp,#$D[0]] @ D[0] + @ ror @C[3],@C[3],#32-3 + ldr.h @E[3],[sp,#$D[0]+4] + + eor @C[4],@C[4],@C[6] + eor @C[5],@C[5],@C[7] + @ ror @C[5],@C[6],#32-12 @ C[2] = ROL64(A[2][3] ^ D[3], rhotates[2][3]); + @ ror @C[4],@C[7],#32-13 @ [track reverse order below] + + eor @E[0],@E[0],@C[8] + ldr.l @C[8],[sp,#$A[4][0]] @ A[4][0] + eor @E[1],@E[1],@C[9] + ldr.h @C[9],[sp,#$A[4][0]+4] + ror @C[6],@E[0],#32-4 @ C[3] = ROL64(A[3][4] ^ D[4], rhotates[3][4]); + ror @C[7],@E[1],#32-4 + + eor @E[2],@E[2],@C[8] + eor @E[3],@E[3],@C[9] + ror @C[8],@E[2],#32-9 @ C[4] = ROL64(A[4][0] ^ D[0], rhotates[4][0]); + ror @C[9],@E[3],#32-9 + + bic @E[0],@C[5],@C[2],ror#13-3 + bic @E[1],@C[4],@C[3],ror#12-3 + bic @E[2],@C[6],@C[5],ror#32-13 + bic @E[3],@C[7],@C[4],ror#32-12 + eor @E[0],@C[0],@E[0],ror#32-13 + eor @E[1],@C[1],@E[1],ror#32-12 + str.l @E[0],[sp,#$R[2][0]] @ R[2][0] = C[0] ^ (~C[1] & C[2]) + eor @E[2],@E[2],@C[2],ror#32-3 + str.h @E[1],[sp,#$R[2][0]+4] + eor @E[3],@E[3],@C[3],ror#32-3 + str.l @E[2],[sp,#$R[2][1]] @ R[2][1] = C[1] ^ (~C[2] & C[3]); + bic @E[0],@C[8],@C[6] + bic @E[1],@C[9],@C[7] + str.h @E[3],[sp,#$R[2][1]+4] + eor @E[0],@E[0],@C[5],ror#32-13 + eor @E[1],@E[1],@C[4],ror#32-12 + str.l @E[0],[sp,#$R[2][2]] @ R[2][2] = C[2] ^ (~C[3] & C[4]); + bic @E[2],@C[0],@C[8] + str.h @E[1],[sp,#$R[2][2]+4] + bic @E[3],@C[1],@C[9] + eor @E[2],@E[2],@C[6] + eor @E[3],@E[3],@C[7] + str.l @E[2],[sp,#$R[2][3]] @ R[2][3] = C[3] ^ (~C[4] & C[0]); + bic @E[0],@C[2],@C[0],ror#3 + str.h @E[3],[sp,#$R[2][3]+4] + bic @E[1],@C[3],@C[1],ror#3 + ldr.l @C[1],[sp,#$A[0][4]] @ A[0][4] [in reverse order] + eor @E[0],@C[8],@E[0],ror#32-3 + ldr.h @C[0],[sp,#$A[0][4]+4] + eor @E[1],@C[9],@E[1],ror#32-3 + str.l @E[0],[sp,#$R[2][4]] @ R[2][4] = C[4] ^ (~C[0] & C[1]); + add @C[9],sp,#$D[1] + str.h @E[1],[sp,#$R[2][4]+4] + + ldr.l @E[0],[sp,#$D[4]] @ D[4] + ldr.h @E[1],[sp,#$D[4]+4] + ldr.l @E[2],[sp,#$D[0]] @ D[0] + ldr.h @E[3],[sp,#$D[0]+4] + + ldmia @C[9],{@C[6]-@C[9]} @ D[1..2] + + eor @C[1],@C[1],@E[0] + ldr.l @C[2],[sp,#$A[1][0]] @ A[1][0] + eor @C[0],@C[0],@E[1] + ldr.h @C[3],[sp,#$A[1][0]+4] + @ ror @C[1],@E[0],#32-13 @ C[0] = ROL64(A[0][4] ^ D[4], rhotates[0][4]); + ldr.l @C[4],[sp,#$A[2][1]] @ A[2][1] + @ ror @C[0],@E[1],#32-14 @ [was loaded in reverse order] + ldr.h @C[5],[sp,#$A[2][1]+4] + + eor @C[2],@C[2],@E[2] + ldr.l @E[0],[sp,#$A[3][2]] @ A[3][2] + eor @C[3],@C[3],@E[3] + ldr.h @E[1],[sp,#$A[3][2]+4] + @ ror @C[2],@C[2],#32-18 @ C[1] = ROL64(A[1][0] ^ D[0], rhotates[1][0]); + ldr.l @E[2],[sp,#$D[3]] @ D[3] + @ ror @C[3],@C[3],#32-18 + ldr.h @E[3],[sp,#$D[3]+4] + + eor @C[6],@C[6],@C[4] + eor @C[7],@C[7],@C[5] + ror @C[4],@C[6],#32-5 @ C[2] = ROL64(A[2][1] ^ D[1], rhotates[2][1]); + ror @C[5],@C[7],#32-5 + + eor @E[0],@E[0],@C[8] + ldr.l @C[8],[sp,#$A[4][3]] @ A[4][3] + eor @E[1],@E[1],@C[9] + ldr.h @C[9],[sp,#$A[4][3]+4] + ror @C[7],@E[0],#32-7 @ C[3] = ROL64(A[3][2] ^ D[2], rhotates[3][2]); + ror @C[6],@E[1],#32-8 + + eor @E[2],@E[2],@C[8] + eor @E[3],@E[3],@C[9] + ror @C[8],@E[2],#32-28 @ C[4] = ROL64(A[4][3] ^ D[3], rhotates[4][3]); + ror @C[9],@E[3],#32-28 + + bic @E[0],@C[4],@C[2],ror#32-18 + bic @E[1],@C[5],@C[3],ror#32-18 + eor @E[0],@E[0],@C[0],ror#32-14 + eor @E[1],@E[1],@C[1],ror#32-13 + str.l @E[0],[sp,#$R[3][0]] @ R[3][0] = C[0] ^ (~C[1] & C[2]) + bic @E[2],@C[6],@C[4] + str.h @E[1],[sp,#$R[3][0]+4] + bic @E[3],@C[7],@C[5] + eor @E[2],@E[2],@C[2],ror#32-18 + str.l @E[2],[sp,#$R[3][1]] @ R[3][1] = C[1] ^ (~C[2] & C[3]); + eor @E[3],@E[3],@C[3],ror#32-18 + str.h @E[3],[sp,#$R[3][1]+4] + bic @E[0],@C[8],@C[6] + bic @E[1],@C[9],@C[7] + bic @E[2],@C[0],@C[8],ror#14 + bic @E[3],@C[1],@C[9],ror#13 + eor @E[0],@E[0],@C[4] + eor @E[1],@E[1],@C[5] + str.l @E[0],[sp,#$R[3][2]] @ R[3][2] = C[2] ^ (~C[3] & C[4]); + bic @C[2],@C[2],@C[0],ror#18-14 + str.h @E[1],[sp,#$R[3][2]+4] + eor @E[2],@C[6],@E[2],ror#32-14 + bic @E[1],@C[3],@C[1],ror#18-13 + eor @E[3],@C[7],@E[3],ror#32-13 + str.l @E[2],[sp,#$R[3][3]] @ R[3][3] = C[3] ^ (~C[4] & C[0]); + str.h @E[3],[sp,#$R[3][3]+4] + add @E[3],sp,#$D[2] + ldr.l @C[0],[sp,#$A[0][2]] @ A[0][2] + eor @E[0],@C[8],@C[2],ror#32-18 + ldr.h @C[1],[sp,#$A[0][2]+4] + eor @E[1],@C[9],@E[1],ror#32-18 + str.l @E[0],[sp,#$R[3][4]] @ R[3][4] = C[4] ^ (~C[0] & C[1]); + str.h @E[1],[sp,#$R[3][4]+4] + + ldmia @E[3],{@E[0]-@E[2],@E[3]} @ D[2..3] + ldr.l @C[2],[sp,#$A[1][3]] @ A[1][3] + ldr.h @C[3],[sp,#$A[1][3]+4] + ldr.l @C[6],[sp,#$D[4]] @ D[4] + ldr.h @C[7],[sp,#$D[4]+4] + + eor @C[0],@C[0],@E[0] + ldr.l @C[4],[sp,#$A[2][4]] @ A[2][4] + eor @C[1],@C[1],@E[1] + ldr.h @C[5],[sp,#$A[2][4]+4] + @ ror @C[0],@C[0],#32-31 @ C[0] = ROL64(A[0][2] ^ D[2], rhotates[0][2]); + ldr.l @C[8],[sp,#$D[0]] @ D[0] + @ ror @C[1],@C[1],#32-31 + ldr.h @C[9],[sp,#$D[0]+4] + + eor @E[2],@E[2],@C[2] + ldr.l @E[0],[sp,#$A[3][0]] @ A[3][0] + eor @E[3],@E[3],@C[3] + ldr.h @E[1],[sp,#$A[3][0]+4] + ror @C[3],@E[2],#32-27 @ C[1] = ROL64(A[1][3] ^ D[3], rhotates[1][3]); + ldr.l @E[2],[sp,#$D[1]] @ D[1] + ror @C[2],@E[3],#32-28 + ldr.h @E[3],[sp,#$D[1]+4] + + eor @C[6],@C[6],@C[4] + eor @C[7],@C[7],@C[5] + ror @C[5],@C[6],#32-19 @ C[2] = ROL64(A[2][4] ^ D[4], rhotates[2][4]); + ror @C[4],@C[7],#32-20 + + eor @E[0],@E[0],@C[8] + ldr.l @C[8],[sp,#$A[4][1]] @ A[4][1] + eor @E[1],@E[1],@C[9] + ldr.h @C[9],[sp,#$A[4][1]+4] + ror @C[7],@E[0],#32-20 @ C[3] = ROL64(A[3][0] ^ D[0], rhotates[3][0]); + ror @C[6],@E[1],#32-21 + + eor @C[8],@C[8],@E[2] + eor @C[9],@C[9],@E[3] + @ ror @C[8],@C[2],#32-1 @ C[4] = ROL64(A[4][1] ^ D[1], rhotates[4][1]); + @ ror @C[9],@C[3],#32-1 + + bic @E[0],@C[4],@C[2] + bic @E[1],@C[5],@C[3] + eor @E[0],@E[0],@C[0],ror#32-31 + str.l @E[0],[sp,#$R[4][0]] @ R[4][0] = C[0] ^ (~C[1] & C[2]) + eor @E[1],@E[1],@C[1],ror#32-31 + str.h @E[1],[sp,#$R[4][0]+4] + bic @E[2],@C[6],@C[4] + bic @E[3],@C[7],@C[5] + eor @E[2],@E[2],@C[2] + eor @E[3],@E[3],@C[3] + str.l @E[2],[sp,#$R[4][1]] @ R[4][1] = C[1] ^ (~C[2] & C[3]); + bic @E[0],@C[8],@C[6],ror#1 + str.h @E[3],[sp,#$R[4][1]+4] + bic @E[1],@C[9],@C[7],ror#1 + bic @E[2],@C[0],@C[8],ror#31-1 + bic @E[3],@C[1],@C[9],ror#31-1 + eor @C[4],@C[4],@E[0],ror#32-1 + str.l @C[4],[sp,#$R[4][2]] @ R[4][2] = C[2] ^= (~C[3] & C[4]); + eor @C[5],@C[5],@E[1],ror#32-1 + str.h @C[5],[sp,#$R[4][2]+4] + eor @C[6],@C[6],@E[2],ror#32-31 + eor @C[7],@C[7],@E[3],ror#32-31 + str.l @C[6],[sp,#$R[4][3]] @ R[4][3] = C[3] ^= (~C[4] & C[0]); + bic @E[0],@C[2],@C[0],ror#32-31 + str.h @C[7],[sp,#$R[4][3]+4] + bic @E[1],@C[3],@C[1],ror#32-31 + add @E[2],sp,#$R[0][0] + eor @C[8],@E[0],@C[8],ror#32-1 + add @E[0],sp,#$R[1][0] + eor @C[9],@E[1],@C[9],ror#32-1 + str.l @C[8],[sp,#$R[4][4]] @ R[4][4] = C[4] ^= (~C[0] & C[1]); + str.h @C[9],[sp,#$R[4][4]+4] +___ +} + Round(@A,@T); + Round(@T,@A); +$code.=<<___; + blo .Lround2x + + ldr pc,[sp,#440] +.size KeccakF1600_int,.-KeccakF1600_int + +.type KeccakF1600, %function +.align 5 +KeccakF1600: + stmdb sp!,{r0,r4-r11,lr} + sub sp,sp,#440+16 @ space for A[5][5],D[5],T[5][5],... + + add @E[0],r0,#$A[1][0] + add @E[1],sp,#$A[1][0] + ldmia r0, {@C[0]-@C[9]} @ copy A[5][5] to stack + stmia sp, {@C[0]-@C[9]} + ldmia @E[0]!,{@C[0]-@C[9]} + stmia @E[1]!,{@C[0]-@C[9]} + ldmia @E[0]!,{@C[0]-@C[9]} + stmia @E[1]!,{@C[0]-@C[9]} + ldmia @E[0]!,{@C[0]-@C[9]} + stmia @E[1]!,{@C[0]-@C[9]} + ldmia @E[0], {@C[0]-@C[9]} + add @E[2],sp,#$A[0][0] + add @E[0],sp,#$A[1][0] + stmia @E[1], {@C[0]-@C[9]} + + bl KeccakF1600_enter + + ldr @E[1], [sp,#440+16] @ restore pointer to A + ldmia sp, {@C[0]-@C[9]} + stmia @E[1]!,{@C[0]-@C[9]} @ return A[5][5] + ldmia @E[0]!,{@C[0]-@C[9]} + stmia @E[1]!,{@C[0]-@C[9]} + ldmia @E[0]!,{@C[0]-@C[9]} + stmia @E[1]!,{@C[0]-@C[9]} + ldmia @E[0]!,{@C[0]-@C[9]} + stmia @E[1]!,{@C[0]-@C[9]} + ldmia @E[0], {@C[0]-@C[9]} + stmia @E[1], {@C[0]-@C[9]} + + add sp,sp,#440+20 + ldmia sp!,{r4-r11,pc} +.size KeccakF1600,.-KeccakF1600 +___ +{ my ($A_flat,$inp,$len,$bsz) = map("r$_",(10..12,14)); + +######################################################################## +# Stack layout +# ----->+-----------------------+ +# | uint64_t A[5][5] | +# | ... | +# | ... | +# +456->+-----------------------+ +# | 0x55555555 | +# +460->+-----------------------+ +# | 0x33333333 | +# +464->+-----------------------+ +# | 0x0f0f0f0f | +# +468->+-----------------------+ +# | 0x00ff00ff | +# +472->+-----------------------+ +# | uint64_t *A | +# +476->+-----------------------+ +# | const void *inp | +# +480->+-----------------------+ +# | size_t len | +# +484->+-----------------------+ +# | size_t bs | +# +488->+-----------------------+ +# | .... + +$code.=<<___; +.global SHA3_absorb +.type SHA3_absorb,%function +.align 5 +SHA3_absorb: + stmdb sp!,{r0-r12,lr} + sub sp,sp,#456+16 + + add $A_flat,r0,#$A[1][0] + @ mov $inp,r1 + mov $len,r2 + mov $bsz,r3 + cmp r2,r3 + blo .Labsorb_abort + + add $inp,sp,#0 + ldmia r0, {@C[0]-@C[9]} @ copy A[5][5] to stack + stmia $inp!, {@C[0]-@C[9]} + ldmia $A_flat!,{@C[0]-@C[9]} + stmia $inp!, {@C[0]-@C[9]} + ldmia $A_flat!,{@C[0]-@C[9]} + stmia $inp!, {@C[0]-@C[9]} + ldmia $A_flat!,{@C[0]-@C[9]} + stmia $inp!, {@C[0]-@C[9]} + ldmia $A_flat!,{@C[0]-@C[9]} + stmia $inp, {@C[0]-@C[9]} + + ldr $inp,[sp,#476] @ restore $inp +#ifdef __thumb2__ + mov r9,#0x00ff00ff + mov r8,#0x0f0f0f0f + mov r7,#0x33333333 + mov r6,#0x55555555 +#else + mov r6,#0x11 @ compose constants + mov r8,#0x0f + mov r9,#0xff + orr r6,r6,r6,lsl#8 + orr r8,r8,r8,lsl#8 + orr r6,r6,r6,lsl#16 @ 0x11111111 + orr r9,r9,r9,lsl#16 @ 0x00ff00ff + orr r8,r8,r8,lsl#16 @ 0x0f0f0f0f + orr r7,r6,r6,lsl#1 @ 0x33333333 + orr r6,r6,r6,lsl#2 @ 0x55555555 +#endif + str r9,[sp,#468] + str r8,[sp,#464] + str r7,[sp,#460] + str r6,[sp,#456] + b .Loop_absorb + +.align 4 +.Loop_absorb: + subs r0,$len,$bsz + blo .Labsorbed + add $A_flat,sp,#0 + str r0,[sp,#480] @ save len - bsz + +.align 4 +.Loop_block: + ldrb r0,[$inp],#1 + ldrb r1,[$inp],#1 + ldrb r2,[$inp],#1 + ldrb r3,[$inp],#1 + ldrb r4,[$inp],#1 + orr r0,r0,r1,lsl#8 + ldrb r1,[$inp],#1 + orr r0,r0,r2,lsl#16 + ldrb r2,[$inp],#1 + orr r0,r0,r3,lsl#24 @ lo + ldrb r3,[$inp],#1 + orr r1,r4,r1,lsl#8 + orr r1,r1,r2,lsl#16 + orr r1,r1,r3,lsl#24 @ hi + + and r2,r0,r6 @ &=0x55555555 + and r0,r0,r6,lsl#1 @ &=0xaaaaaaaa + and r3,r1,r6 @ &=0x55555555 + and r1,r1,r6,lsl#1 @ &=0xaaaaaaaa + orr r2,r2,r2,lsr#1 + orr r0,r0,r0,lsl#1 + orr r3,r3,r3,lsr#1 + orr r1,r1,r1,lsl#1 + and r2,r2,r7 @ &=0x33333333 + and r0,r0,r7,lsl#2 @ &=0xcccccccc + and r3,r3,r7 @ &=0x33333333 + and r1,r1,r7,lsl#2 @ &=0xcccccccc + orr r2,r2,r2,lsr#2 + orr r0,r0,r0,lsl#2 + orr r3,r3,r3,lsr#2 + orr r1,r1,r1,lsl#2 + and r2,r2,r8 @ &=0x0f0f0f0f + and r0,r0,r8,lsl#4 @ &=0xf0f0f0f0 + and r3,r3,r8 @ &=0x0f0f0f0f + and r1,r1,r8,lsl#4 @ &=0xf0f0f0f0 + ldmia $A_flat,{r4-r5} @ A_flat[i] + orr r2,r2,r2,lsr#4 + orr r0,r0,r0,lsl#4 + orr r3,r3,r3,lsr#4 + orr r1,r1,r1,lsl#4 + and r2,r2,r9 @ &=0x00ff00ff + and r0,r0,r9,lsl#8 @ &=0xff00ff00 + and r3,r3,r9 @ &=0x00ff00ff + and r1,r1,r9,lsl#8 @ &=0xff00ff00 + orr r2,r2,r2,lsr#8 + orr r0,r0,r0,lsl#8 + orr r3,r3,r3,lsr#8 + orr r1,r1,r1,lsl#8 + + lsl r2,r2,#16 + lsr r1,r1,#16 + eor r4,r4,r3,lsl#16 + eor r5,r5,r0,lsr#16 + eor r4,r4,r2,lsr#16 + eor r5,r5,r1,lsl#16 + stmia $A_flat!,{r4-r5} @ A_flat[i++] ^= BitInterleave(inp[0..7]) + + subs $bsz,$bsz,#8 + bhi .Loop_block + + str $inp,[sp,#476] + + bl KeccakF1600_int + + add r14,sp,#456 + ldmia r14,{r6-r12,r14} @ restore constants and variables + b .Loop_absorb + +.align 4 +.Labsorbed: + add $inp,sp,#$A[1][0] + ldmia sp, {@C[0]-@C[9]} + stmia $A_flat!,{@C[0]-@C[9]} @ return A[5][5] + ldmia $inp!, {@C[0]-@C[9]} + stmia $A_flat!,{@C[0]-@C[9]} + ldmia $inp!, {@C[0]-@C[9]} + stmia $A_flat!,{@C[0]-@C[9]} + ldmia $inp!, {@C[0]-@C[9]} + stmia $A_flat!,{@C[0]-@C[9]} + ldmia $inp, {@C[0]-@C[9]} + stmia $A_flat, {@C[0]-@C[9]} + +.Labsorb_abort: + add sp,sp,#456+32 + mov r0,$len @ return value + ldmia sp!,{r4-r12,pc} +.size SHA3_absorb,.-SHA3_absorb +___ +} +{ my ($out,$len,$A_flat,$bsz) = map("r$_", (4,5,10,12)); + +$code.=<<___; +.global SHA3_squeeze +.type SHA3_squeeze,%function +.align 5 +SHA3_squeeze: + stmdb sp!,{r0,r3-r10,lr} + + mov $A_flat,r0 + mov $out,r1 + mov $len,r2 + mov $bsz,r3 + +#ifdef __thumb2__ + mov r9,#0x00ff00ff + mov r8,#0x0f0f0f0f + mov r7,#0x33333333 + mov r6,#0x55555555 +#else + mov r6,#0x11 @ compose constants + mov r8,#0x0f + mov r9,#0xff + orr r6,r6,r6,lsl#8 + orr r8,r8,r8,lsl#8 + orr r6,r6,r6,lsl#16 @ 0x11111111 + orr r9,r9,r9,lsl#16 @ 0x00ff00ff + orr r8,r8,r8,lsl#16 @ 0x0f0f0f0f + orr r7,r6,r6,lsl#1 @ 0x33333333 + orr r6,r6,r6,lsl#2 @ 0x55555555 +#endif + stmdb sp!,{r6-r9} + + mov r14,$A_flat + b .Loop_squeeze + +.align 4 +.Loop_squeeze: + ldmia $A_flat!,{r0,r1} @ A_flat[i++] + + lsl r2,r0,#16 + lsl r3,r1,#16 @ r3 = r1 << 16 + lsr r2,r2,#16 @ r2 = r0 & 0x0000ffff + lsr r1,r1,#16 + lsr r0,r0,#16 @ r0 = r0 >> 16 + lsl r1,r1,#16 @ r1 = r1 & 0xffff0000 + + orr r2,r2,r2,lsl#8 + orr r3,r3,r3,lsr#8 + orr r0,r0,r0,lsl#8 + orr r1,r1,r1,lsr#8 + and r2,r2,r9 @ &=0x00ff00ff + and r3,r3,r9,lsl#8 @ &=0xff00ff00 + and r0,r0,r9 @ &=0x00ff00ff + and r1,r1,r9,lsl#8 @ &=0xff00ff00 + orr r2,r2,r2,lsl#4 + orr r3,r3,r3,lsr#4 + orr r0,r0,r0,lsl#4 + orr r1,r1,r1,lsr#4 + and r2,r2,r8 @ &=0x0f0f0f0f + and r3,r3,r8,lsl#4 @ &=0xf0f0f0f0 + and r0,r0,r8 @ &=0x0f0f0f0f + and r1,r1,r8,lsl#4 @ &=0xf0f0f0f0 + orr r2,r2,r2,lsl#2 + orr r3,r3,r3,lsr#2 + orr r0,r0,r0,lsl#2 + orr r1,r1,r1,lsr#2 + and r2,r2,r7 @ &=0x33333333 + and r3,r3,r7,lsl#2 @ &=0xcccccccc + and r0,r0,r7 @ &=0x33333333 + and r1,r1,r7,lsl#2 @ &=0xcccccccc + orr r2,r2,r2,lsl#1 + orr r3,r3,r3,lsr#1 + orr r0,r0,r0,lsl#1 + orr r1,r1,r1,lsr#1 + and r2,r2,r6 @ &=0x55555555 + and r3,r3,r6,lsl#1 @ &=0xaaaaaaaa + and r0,r0,r6 @ &=0x55555555 + and r1,r1,r6,lsl#1 @ &=0xaaaaaaaa + + orr r2,r2,r3 + orr r0,r0,r1 + + cmp $len,#8 + blo .Lsqueeze_tail + lsr r1,r2,#8 + strb r2,[$out],#1 + lsr r3,r2,#16 + strb r1,[$out],#1 + lsr r2,r2,#24 + strb r3,[$out],#1 + strb r2,[$out],#1 + + lsr r1,r0,#8 + strb r0,[$out],#1 + lsr r3,r0,#16 + strb r1,[$out],#1 + lsr r0,r0,#24 + strb r3,[$out],#1 + strb r0,[$out],#1 + subs $len,$len,#8 + beq .Lsqueeze_done + + subs $bsz,$bsz,#8 @ bsz -= 8 + bhi .Loop_squeeze + + mov r0,r14 @ original $A_flat + + bl KeccakF1600 + + ldmia sp,{r6-r10,r12} @ restore constants and variables + mov r14,$A_flat + b .Loop_squeeze + +.align 4 +.Lsqueeze_tail: + strb r2,[$out],#1 + lsr r2,r2,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb r2,[$out],#1 + lsr r2,r2,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb r2,[$out],#1 + lsr r2,r2,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb r2,[$out],#1 + subs $len,$len,#1 + beq .Lsqueeze_done + + strb r0,[$out],#1 + lsr r0,r0,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb r0,[$out],#1 + lsr r0,r0,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb r0,[$out] + b .Lsqueeze_done + +.align 4 +.Lsqueeze_done: + add sp,sp,#24 + ldmia sp!,{r4-r10,pc} +.size SHA3_squeeze,.-SHA3_squeeze +___ +} + +$code.=<<___; +.fpu neon + +.type iotas64, %object +.align 5 +iotas64: + .quad 0x0000000000000001 + .quad 0x0000000000008082 + .quad 0x800000000000808a + .quad 0x8000000080008000 + .quad 0x000000000000808b + .quad 0x0000000080000001 + .quad 0x8000000080008081 + .quad 0x8000000000008009 + .quad 0x000000000000008a + .quad 0x0000000000000088 + .quad 0x0000000080008009 + .quad 0x000000008000000a + .quad 0x000000008000808b + .quad 0x800000000000008b + .quad 0x8000000000008089 + .quad 0x8000000000008003 + .quad 0x8000000000008002 + .quad 0x8000000000000080 + .quad 0x000000000000800a + .quad 0x800000008000000a + .quad 0x8000000080008081 + .quad 0x8000000000008080 + .quad 0x0000000080000001 + .quad 0x8000000080008008 +.size iotas64,.-iotas64 + +.type KeccakF1600_neon, %function +.align 5 +KeccakF1600_neon: + add r1, r0, #16 + adr r2, iotas64 + mov r3, #24 @ loop counter + b .Loop_neon + +.align 4 +.Loop_neon: + @ Theta + vst1.64 {q4}, [r0:64] @ offload A[0..1][4] + veor q13, q0, q5 @ A[0..1][0]^A[2..3][0] + vst1.64 {d18}, [r1:64] @ offload A[2][4] + veor q14, q1, q6 @ A[0..1][1]^A[2..3][1] + veor q15, q2, q7 @ A[0..1][2]^A[2..3][2] + veor d26, d26, d27 @ C[0]=A[0][0]^A[1][0]^A[2][0]^A[3][0] + veor d27, d28, d29 @ C[1]=A[0][1]^A[1][1]^A[2][1]^A[3][1] + veor q14, q3, q8 @ A[0..1][3]^A[2..3][3] + veor q4, q4, q9 @ A[0..1][4]^A[2..3][4] + veor d30, d30, d31 @ C[2]=A[0][2]^A[1][2]^A[2][2]^A[3][2] + veor d31, d28, d29 @ C[3]=A[0][3]^A[1][3]^A[2][3]^A[3][3] + veor d25, d8, d9 @ C[4]=A[0][4]^A[1][4]^A[2][4]^A[3][4] + veor q13, q13, q10 @ C[0..1]^=A[4][0..1] + veor q14, q15, q11 @ C[2..3]^=A[4][2..3] + veor d25, d25, d24 @ C[4]^=A[4][4] + + vadd.u64 q4, q13, q13 @ C[0..1]<<1 + vadd.u64 q15, q14, q14 @ C[2..3]<<1 + vadd.u64 d18, d25, d25 @ C[4]<<1 + vsri.u64 q4, q13, #63 @ ROL64(C[0..1],1) + vsri.u64 q15, q14, #63 @ ROL64(C[2..3],1) + vsri.u64 d18, d25, #63 @ ROL64(C[4],1) + veor d25, d25, d9 @ D[0] = C[4] ^= ROL64(C[1],1) + veor q13, q13, q15 @ D[1..2] = C[0..1] ^ ROL64(C[2..3],1) + veor d28, d28, d18 @ D[3] = C[2] ^= ROL64(C[4],1) + veor d29, d29, d8 @ D[4] = C[3] ^= ROL64(C[0],1) + + veor d0, d0, d25 @ A[0][0] ^= C[4] + veor d1, d1, d25 @ A[1][0] ^= C[4] + veor d10, d10, d25 @ A[2][0] ^= C[4] + veor d11, d11, d25 @ A[3][0] ^= C[4] + veor d20, d20, d25 @ A[4][0] ^= C[4] + + veor d2, d2, d26 @ A[0][1] ^= D[1] + veor d3, d3, d26 @ A[1][1] ^= D[1] + veor d12, d12, d26 @ A[2][1] ^= D[1] + veor d13, d13, d26 @ A[3][1] ^= D[1] + veor d21, d21, d26 @ A[4][1] ^= D[1] + vmov d26, d27 + + veor d6, d6, d28 @ A[0][3] ^= C[2] + veor d7, d7, d28 @ A[1][3] ^= C[2] + veor d16, d16, d28 @ A[2][3] ^= C[2] + veor d17, d17, d28 @ A[3][3] ^= C[2] + veor d23, d23, d28 @ A[4][3] ^= C[2] + vld1.64 {q4}, [r0:64] @ restore A[0..1][4] + vmov d28, d29 + + vld1.64 {d18}, [r1:64] @ restore A[2][4] + veor q2, q2, q13 @ A[0..1][2] ^= D[2] + veor q7, q7, q13 @ A[2..3][2] ^= D[2] + veor d22, d22, d27 @ A[4][2] ^= D[2] + + veor q4, q4, q14 @ A[0..1][4] ^= C[3] + veor q9, q9, q14 @ A[2..3][4] ^= C[3] + veor d24, d24, d29 @ A[4][4] ^= C[3] + + @ Rho + Pi + vmov d26, d2 @ C[1] = A[0][1] + vshl.u64 d2, d3, #44 + vmov d27, d4 @ C[2] = A[0][2] + vshl.u64 d4, d14, #43 + vmov d28, d6 @ C[3] = A[0][3] + vshl.u64 d6, d17, #21 + vmov d29, d8 @ C[4] = A[0][4] + vshl.u64 d8, d24, #14 + vsri.u64 d2, d3, #64-44 @ A[0][1] = ROL64(A[1][1], rhotates[1][1]) + vsri.u64 d4, d14, #64-43 @ A[0][2] = ROL64(A[2][2], rhotates[2][2]) + vsri.u64 d6, d17, #64-21 @ A[0][3] = ROL64(A[3][3], rhotates[3][3]) + vsri.u64 d8, d24, #64-14 @ A[0][4] = ROL64(A[4][4], rhotates[4][4]) + + vshl.u64 d3, d9, #20 + vshl.u64 d14, d16, #25 + vshl.u64 d17, d15, #15 + vshl.u64 d24, d21, #2 + vsri.u64 d3, d9, #64-20 @ A[1][1] = ROL64(A[1][4], rhotates[1][4]) + vsri.u64 d14, d16, #64-25 @ A[2][2] = ROL64(A[2][3], rhotates[2][3]) + vsri.u64 d17, d15, #64-15 @ A[3][3] = ROL64(A[3][2], rhotates[3][2]) + vsri.u64 d24, d21, #64-2 @ A[4][4] = ROL64(A[4][1], rhotates[4][1]) + + vshl.u64 d9, d22, #61 + @ vshl.u64 d16, d19, #8 + vshl.u64 d15, d12, #10 + vshl.u64 d21, d7, #55 + vsri.u64 d9, d22, #64-61 @ A[1][4] = ROL64(A[4][2], rhotates[4][2]) + vext.8 d16, d19, d19, #8-1 @ A[2][3] = ROL64(A[3][4], rhotates[3][4]) + vsri.u64 d15, d12, #64-10 @ A[3][2] = ROL64(A[2][1], rhotates[2][1]) + vsri.u64 d21, d7, #64-55 @ A[4][1] = ROL64(A[1][3], rhotates[1][3]) + + vshl.u64 d22, d18, #39 + @ vshl.u64 d19, d23, #56 + vshl.u64 d12, d5, #6 + vshl.u64 d7, d13, #45 + vsri.u64 d22, d18, #64-39 @ A[4][2] = ROL64(A[2][4], rhotates[2][4]) + vext.8 d19, d23, d23, #8-7 @ A[3][4] = ROL64(A[4][3], rhotates[4][3]) + vsri.u64 d12, d5, #64-6 @ A[2][1] = ROL64(A[1][2], rhotates[1][2]) + vsri.u64 d7, d13, #64-45 @ A[1][3] = ROL64(A[3][1], rhotates[3][1]) + + vshl.u64 d18, d20, #18 + vshl.u64 d23, d11, #41 + vshl.u64 d5, d10, #3 + vshl.u64 d13, d1, #36 + vsri.u64 d18, d20, #64-18 @ A[2][4] = ROL64(A[4][0], rhotates[4][0]) + vsri.u64 d23, d11, #64-41 @ A[4][3] = ROL64(A[3][0], rhotates[3][0]) + vsri.u64 d5, d10, #64-3 @ A[1][2] = ROL64(A[2][0], rhotates[2][0]) + vsri.u64 d13, d1, #64-36 @ A[3][1] = ROL64(A[1][0], rhotates[1][0]) + + vshl.u64 d1, d28, #28 + vshl.u64 d10, d26, #1 + vshl.u64 d11, d29, #27 + vshl.u64 d20, d27, #62 + vsri.u64 d1, d28, #64-28 @ A[1][0] = ROL64(C[3], rhotates[0][3]) + vsri.u64 d10, d26, #64-1 @ A[2][0] = ROL64(C[1], rhotates[0][1]) + vsri.u64 d11, d29, #64-27 @ A[3][0] = ROL64(C[4], rhotates[0][4]) + vsri.u64 d20, d27, #64-62 @ A[4][0] = ROL64(C[2], rhotates[0][2]) + + @ Chi + Iota + vbic q13, q2, q1 + vbic q14, q3, q2 + vbic q15, q4, q3 + veor q13, q13, q0 @ A[0..1][0] ^ (~A[0..1][1] & A[0..1][2]) + veor q14, q14, q1 @ A[0..1][1] ^ (~A[0..1][2] & A[0..1][3]) + veor q2, q2, q15 @ A[0..1][2] ^= (~A[0..1][3] & A[0..1][4]) + vst1.64 {q13}, [r0:64] @ offload A[0..1][0] + vbic q13, q0, q4 + vbic q15, q1, q0 + vmov q1, q14 @ A[0..1][1] + veor q3, q3, q13 @ A[0..1][3] ^= (~A[0..1][4] & A[0..1][0]) + veor q4, q4, q15 @ A[0..1][4] ^= (~A[0..1][0] & A[0..1][1]) + + vbic q13, q7, q6 + vmov q0, q5 @ A[2..3][0] + vbic q14, q8, q7 + vmov q15, q6 @ A[2..3][1] + veor q5, q5, q13 @ A[2..3][0] ^= (~A[2..3][1] & A[2..3][2]) + vbic q13, q9, q8 + veor q6, q6, q14 @ A[2..3][1] ^= (~A[2..3][2] & A[2..3][3]) + vbic q14, q0, q9 + veor q7, q7, q13 @ A[2..3][2] ^= (~A[2..3][3] & A[2..3][4]) + vbic q13, q15, q0 + veor q8, q8, q14 @ A[2..3][3] ^= (~A[2..3][4] & A[2..3][0]) + vmov q14, q10 @ A[4][0..1] + veor q9, q9, q13 @ A[2..3][4] ^= (~A[2..3][0] & A[2..3][1]) + + vld1.64 d25, [r2:64]! @ Iota[i++] + vbic d26, d22, d21 + vbic d27, d23, d22 + vld1.64 {q0}, [r0:64] @ restore A[0..1][0] + veor d20, d20, d26 @ A[4][0] ^= (~A[4][1] & A[4][2]) + vbic d26, d24, d23 + veor d21, d21, d27 @ A[4][1] ^= (~A[4][2] & A[4][3]) + vbic d27, d28, d24 + veor d22, d22, d26 @ A[4][2] ^= (~A[4][3] & A[4][4]) + vbic d26, d29, d28 + veor d23, d23, d27 @ A[4][3] ^= (~A[4][4] & A[4][0]) + veor d0, d0, d25 @ A[0][0] ^= Iota[i] + veor d24, d24, d26 @ A[4][4] ^= (~A[4][0] & A[4][1]) + + subs r3, r3, #1 + bne .Loop_neon + + bx lr +.size KeccakF1600_neon,.-KeccakF1600_neon + +.global SHA3_absorb_neon +.type SHA3_absorb_neon, %function +.align 5 +SHA3_absorb_neon: + stmdb sp!, {r4-r6,lr} + vstmdb sp!, {d8-d15} + + mov r4, r1 @ inp + mov r5, r2 @ len + mov r6, r3 @ bsz + + vld1.32 {d0}, [r0:64]! @ A[0][0] + vld1.32 {d2}, [r0:64]! @ A[0][1] + vld1.32 {d4}, [r0:64]! @ A[0][2] + vld1.32 {d6}, [r0:64]! @ A[0][3] + vld1.32 {d8}, [r0:64]! @ A[0][4] + + vld1.32 {d1}, [r0:64]! @ A[1][0] + vld1.32 {d3}, [r0:64]! @ A[1][1] + vld1.32 {d5}, [r0:64]! @ A[1][2] + vld1.32 {d7}, [r0:64]! @ A[1][3] + vld1.32 {d9}, [r0:64]! @ A[1][4] + + vld1.32 {d10}, [r0:64]! @ A[2][0] + vld1.32 {d12}, [r0:64]! @ A[2][1] + vld1.32 {d14}, [r0:64]! @ A[2][2] + vld1.32 {d16}, [r0:64]! @ A[2][3] + vld1.32 {d18}, [r0:64]! @ A[2][4] + + vld1.32 {d11}, [r0:64]! @ A[3][0] + vld1.32 {d13}, [r0:64]! @ A[3][1] + vld1.32 {d15}, [r0:64]! @ A[3][2] + vld1.32 {d17}, [r0:64]! @ A[3][3] + vld1.32 {d19}, [r0:64]! @ A[3][4] + + vld1.32 {d20-d23}, [r0:64]! @ A[4][0..3] + vld1.32 {d24}, [r0:64] @ A[4][4] + sub r0, r0, #24*8 @ rewind + b .Loop_absorb_neon + +.align 4 +.Loop_absorb_neon: + subs r12, r5, r6 @ len - bsz + blo .Labsorbed_neon + mov r5, r12 + + vld1.8 {d31}, [r4]! @ endian-neutral loads... + cmp r6, #8*2 + veor d0, d0, d31 @ A[0][0] ^= *inp++ + blo .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d2, d2, d31 @ A[0][1] ^= *inp++ + beq .Lprocess_neon + vld1.8 {d31}, [r4]! + cmp r6, #8*4 + veor d4, d4, d31 @ A[0][2] ^= *inp++ + blo .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d6, d6, d31 @ A[0][3] ^= *inp++ + beq .Lprocess_neon + vld1.8 {d31},[r4]! + cmp r6, #8*6 + veor d8, d8, d31 @ A[0][4] ^= *inp++ + blo .Lprocess_neon + + vld1.8 {d31}, [r4]! + veor d1, d1, d31 @ A[1][0] ^= *inp++ + beq .Lprocess_neon + vld1.8 {d31}, [r4]! + cmp r6, #8*8 + veor d3, d3, d31 @ A[1][1] ^= *inp++ + blo .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d5, d5, d31 @ A[1][2] ^= *inp++ + beq .Lprocess_neon + vld1.8 {d31}, [r4]! + cmp r6, #8*10 + veor d7, d7, d31 @ A[1][3] ^= *inp++ + blo .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d9, d9, d31 @ A[1][4] ^= *inp++ + beq .Lprocess_neon + + vld1.8 {d31}, [r4]! + cmp r6, #8*12 + veor d10, d10, d31 @ A[2][0] ^= *inp++ + blo .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d12, d12, d31 @ A[2][1] ^= *inp++ + beq .Lprocess_neon + vld1.8 {d31}, [r4]! + cmp r6, #8*14 + veor d14, d14, d31 @ A[2][2] ^= *inp++ + blo .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d16, d16, d31 @ A[2][3] ^= *inp++ + beq .Lprocess_neon + vld1.8 {d31}, [r4]! + cmp r6, #8*16 + veor d18, d18, d31 @ A[2][4] ^= *inp++ + blo .Lprocess_neon + + vld1.8 {d31}, [r4]! + veor d11, d11, d31 @ A[3][0] ^= *inp++ + beq .Lprocess_neon + vld1.8 {d31}, [r4]! + cmp r6, #8*18 + veor d13, d13, d31 @ A[3][1] ^= *inp++ + blo .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d15, d15, d31 @ A[3][2] ^= *inp++ + beq .Lprocess_neon + vld1.8 {d31}, [r4]! + cmp r6, #8*20 + veor d17, d17, d31 @ A[3][3] ^= *inp++ + blo .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d19, d19, d31 @ A[3][4] ^= *inp++ + beq .Lprocess_neon + + vld1.8 {d31}, [r4]! + cmp r6, #8*22 + veor d20, d20, d31 @ A[4][0] ^= *inp++ + blo .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d21, d21, d31 @ A[4][1] ^= *inp++ + beq .Lprocess_neon + vld1.8 {d31}, [r4]! + cmp r6, #8*24 + veor d22, d22, d31 @ A[4][2] ^= *inp++ + blo .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d23, d23, d31 @ A[4][3] ^= *inp++ + beq .Lprocess_neon + vld1.8 {d31}, [r4]! + veor d24, d24, d31 @ A[4][4] ^= *inp++ + +.Lprocess_neon: + bl KeccakF1600_neon + b .Loop_absorb_neon + +.align 4 +.Labsorbed_neon: + vst1.32 {d0}, [r0:64]! @ A[0][0..4] + vst1.32 {d2}, [r0:64]! + vst1.32 {d4}, [r0:64]! + vst1.32 {d6}, [r0:64]! + vst1.32 {d8}, [r0:64]! + + vst1.32 {d1}, [r0:64]! @ A[1][0..4] + vst1.32 {d3}, [r0:64]! + vst1.32 {d5}, [r0:64]! + vst1.32 {d7}, [r0:64]! + vst1.32 {d9}, [r0:64]! + + vst1.32 {d10}, [r0:64]! @ A[2][0..4] + vst1.32 {d12}, [r0:64]! + vst1.32 {d14}, [r0:64]! + vst1.32 {d16}, [r0:64]! + vst1.32 {d18}, [r0:64]! + + vst1.32 {d11}, [r0:64]! @ A[3][0..4] + vst1.32 {d13}, [r0:64]! + vst1.32 {d15}, [r0:64]! + vst1.32 {d17}, [r0:64]! + vst1.32 {d19}, [r0:64]! + + vst1.32 {d20-d23}, [r0:64]! @ A[4][0..4] + vst1.32 {d24}, [r0:64] + + mov r0, r5 @ return value + vldmia sp!, {d8-d15} + ldmia sp!, {r4-r6,pc} +.size SHA3_absorb_neon,.-SHA3_absorb_neon + +.global SHA3_squeeze_neon +.type SHA3_squeeze_neon, %function +.align 5 +SHA3_squeeze_neon: + stmdb sp!, {r4-r6,lr} + + mov r4, r1 @ out + mov r5, r2 @ len + mov r6, r3 @ bsz + mov r12, r0 @ A_flat + mov r14, r3 @ bsz + b .Loop_squeeze_neon + +.align 4 +.Loop_squeeze_neon: + cmp r5, #8 + blo .Lsqueeze_neon_tail + vld1.32 {d0}, [r12]! + vst1.8 {d0}, [r4]! @ endian-neutral store + + subs r5, r5, #8 @ len -= 8 + beq .Lsqueeze_neon_done + + subs r14, r14, #8 @ bsz -= 8 + bhi .Loop_squeeze_neon + + vstmdb sp!, {d8-d15} + + vld1.32 {d0}, [r0:64]! @ A[0][0..4] + vld1.32 {d2}, [r0:64]! + vld1.32 {d4}, [r0:64]! + vld1.32 {d6}, [r0:64]! + vld1.32 {d8}, [r0:64]! + + vld1.32 {d1}, [r0:64]! @ A[1][0..4] + vld1.32 {d3}, [r0:64]! + vld1.32 {d5}, [r0:64]! + vld1.32 {d7}, [r0:64]! + vld1.32 {d9}, [r0:64]! + + vld1.32 {d10}, [r0:64]! @ A[2][0..4] + vld1.32 {d12}, [r0:64]! + vld1.32 {d14}, [r0:64]! + vld1.32 {d16}, [r0:64]! + vld1.32 {d18}, [r0:64]! + + vld1.32 {d11}, [r0:64]! @ A[3][0..4] + vld1.32 {d13}, [r0:64]! + vld1.32 {d15}, [r0:64]! + vld1.32 {d17}, [r0:64]! + vld1.32 {d19}, [r0:64]! + + vld1.32 {d20-d23}, [r0:64]! @ A[4][0..4] + vld1.32 {d24}, [r0:64] + sub r0, r0, #24*8 @ rewind + + bl KeccakF1600_neon + + mov r12, r0 @ A_flat + vst1.32 {d0}, [r0:64]! @ A[0][0..4] + vst1.32 {d2}, [r0:64]! + vst1.32 {d4}, [r0:64]! + vst1.32 {d6}, [r0:64]! + vst1.32 {d8}, [r0:64]! + + vst1.32 {d1}, [r0:64]! @ A[1][0..4] + vst1.32 {d3}, [r0:64]! + vst1.32 {d5}, [r0:64]! + vst1.32 {d7}, [r0:64]! + vst1.32 {d9}, [r0:64]! + + vst1.32 {d10}, [r0:64]! @ A[2][0..4] + vst1.32 {d12}, [r0:64]! + vst1.32 {d14}, [r0:64]! + vst1.32 {d16}, [r0:64]! + vst1.32 {d18}, [r0:64]! + + vst1.32 {d11}, [r0:64]! @ A[3][0..4] + vst1.32 {d13}, [r0:64]! + vst1.32 {d15}, [r0:64]! + vst1.32 {d17}, [r0:64]! + vst1.32 {d19}, [r0:64]! + + vst1.32 {d20-d23}, [r0:64]! @ A[4][0..4] + mov r14, r6 @ bsz + vst1.32 {d24}, [r0:64] + mov r0, r12 @ rewind + + vldmia sp!, {d8-d15} + b .Loop_squeeze_neon + +.align 4 +.Lsqueeze_neon_tail: + ldmia r12, {r2,r3} + cmp r5, #2 + strb r2, [r4],#1 @ endian-neutral store + lsr r2, r2, #8 + blo .Lsqueeze_neon_done + strb r2, [r4], #1 + lsr r2, r2, #8 + beq .Lsqueeze_neon_done + strb r2, [r4], #1 + lsr r2, r2, #8 + cmp r5, #4 + blo .Lsqueeze_neon_done + strb r2, [r4], #1 + beq .Lsqueeze_neon_done + + strb r3, [r4], #1 + lsr r3, r3, #8 + cmp r5, #6 + blo .Lsqueeze_neon_done + strb r3, [r4], #1 + lsr r3, r3, #8 + beq .Lsqueeze_neon_done + strb r3, [r4], #1 + +.Lsqueeze_neon_done: + ldmia sp!, {r4-r6,pc} +.size SHA3_squeeze_neon,.-SHA3_squeeze_neon +.asciz "Keccak-1600 absorb and squeeze for ARMv4/NEON, CRYPTOGAMS by " +.align 2 +___ + +{ + my %ldr, %str; + + sub ldrd { + my ($mnemonic,$half,$reg,$ea) = @_; + my $op = $mnemonic eq "ldr" ? \%ldr : \%str; + + if ($half eq "l") { + $$op{reg} = $reg; + $$op{ea} = $ea; + sprintf "#ifndef __thumb2__\n" . + " %s\t%s,%s\n" . + "#endif", $mnemonic,$reg,$ea; + } else { + sprintf "#ifndef __thumb2__\n" . + " %s\t%s,%s\n" . + "#else\n" . + " %sd\t%s,%s,%s\n" . + "#endif", $mnemonic,$reg,$ea, + $mnemonic,$$op{reg},$reg,$$op{ea}; + } + } +} + +foreach (split($/,$code)) { + s/\`([^\`]*)\`/eval $1/ge; + + s/^\s+(ldr|str)\.([lh])\s+(r[0-9]+),\s*(\[.*)/ldrd($1,$2,$3,$4)/ge or + s/\bret\b/bx lr/g or + s/\bbx\s+lr\b/.word\t0xe12fff1e/g; # make it possible to compile with -march=armv4 + + print $_,"\n"; +} + +close STDOUT; # enforce flush diff --git a/crypto/sha/asm/keccak1600-armv8.pl b/crypto/sha/asm/keccak1600-armv8.pl new file mode 100755 index 00000000..a32b8bae --- /dev/null +++ b/crypto/sha/asm/keccak1600-armv8.pl @@ -0,0 +1,866 @@ +#!/usr/bin/env perl +# Copyright 2017-2018 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# Keccak-1600 for ARMv8. +# +# June 2017. +# +# This is straightforward KECCAK_1X_ALT implementation. It makes no +# sense to attempt SIMD/NEON implementation for following reason. +# 64-bit lanes of vector registers can't be addressed as easily as in +# 32-bit mode. This means that 64-bit NEON is bound to be slower than +# 32-bit NEON, and this implementation is faster than 32-bit NEON on +# same processor. Even though it takes more scalar xor's and andn's, +# it gets compensated by availability of rotate. Not to forget that +# most processors achieve higher issue rate with scalar instructions. +# +# February 2018. +# +# Add hardware-assisted ARMv8.2 implementation. It's KECCAK_1X_ALT +# variant with register permutation/rotation twist that allows to +# eliminate copies to temporary registers. If you look closely you'll +# notice that it uses only one lane of vector registers. The new +# instructions effectively facilitate parallel hashing, which we don't +# support [yet?]. But lowest-level core procedure is prepared for it. +# The inner round is 67 [vector] instructions, so it's not actually +# obvious that it will provide performance improvement [in serial +# hash] as long as vector instructions issue rate is limited to 1 per +# cycle... +# +###################################################################### +# Numbers are cycles per processed byte. +# +# r=1088(*) +# +# Cortex-A53 13 +# Cortex-A57 12 +# X-Gene 14 +# Mongoose 10 +# Kryo 12 +# Denver 7.8 +# Apple A7 7.2 +# +# (*) Corresponds to SHA3-256. No improvement coefficients are listed +# because they vary too much from compiler to compiler. Newer +# compiler does much better and improvement varies from 5% on +# Cortex-A57 to 25% on Cortex-A53. While in comparison to older +# compiler this code is at least 2x faster... + +$flavour = shift; +$output = shift; + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../perlasm/arm-xlate.pl" and -f $xlate) or +die "can't locate arm-xlate.pl"; + +open OUT,"| \"$^X\" $xlate $flavour $output"; +*STDOUT=*OUT; + +my @rhotates = ([ 0, 1, 62, 28, 27 ], + [ 36, 44, 6, 55, 20 ], + [ 3, 10, 43, 25, 39 ], + [ 41, 45, 15, 21, 8 ], + [ 18, 2, 61, 56, 14 ]); + +$code.=<<___; +.text + +.align 8 // strategic alignment and padding that allows to use + // address value as loop termination condition... + .quad 0,0,0,0,0,0,0,0 +.type iotas,%object +iotas: + .quad 0x0000000000000001 + .quad 0x0000000000008082 + .quad 0x800000000000808a + .quad 0x8000000080008000 + .quad 0x000000000000808b + .quad 0x0000000080000001 + .quad 0x8000000080008081 + .quad 0x8000000000008009 + .quad 0x000000000000008a + .quad 0x0000000000000088 + .quad 0x0000000080008009 + .quad 0x000000008000000a + .quad 0x000000008000808b + .quad 0x800000000000008b + .quad 0x8000000000008089 + .quad 0x8000000000008003 + .quad 0x8000000000008002 + .quad 0x8000000000000080 + .quad 0x000000000000800a + .quad 0x800000008000000a + .quad 0x8000000080008081 + .quad 0x8000000000008080 + .quad 0x0000000080000001 + .quad 0x8000000080008008 +.size iotas,.-iotas +___ + {{{ +my @A = map([ "x$_", "x".($_+1), "x".($_+2), "x".($_+3), "x".($_+4) ], + (0, 5, 10, 15, 20)); + $A[3][3] = "x25"; # x18 is reserved + +my @C = map("x$_", (26,27,28,30)); + +$code.=<<___; +.type KeccakF1600_int,%function +.align 5 +KeccakF1600_int: + adr $C[2],iotas + stp $C[2],x30,[sp,#16] // 32 bytes on top are mine + b .Loop +.align 4 +.Loop: + ////////////////////////////////////////// Theta + eor $C[0],$A[0][0],$A[1][0] + stp $A[0][4],$A[1][4],[sp,#0] // offload pair... + eor $C[1],$A[0][1],$A[1][1] + eor $C[2],$A[0][2],$A[1][2] + eor $C[3],$A[0][3],$A[1][3] +___ + $C[4]=$A[0][4]; + $C[5]=$A[1][4]; +$code.=<<___; + eor $C[4],$A[0][4],$A[1][4] + eor $C[0],$C[0],$A[2][0] + eor $C[1],$C[1],$A[2][1] + eor $C[2],$C[2],$A[2][2] + eor $C[3],$C[3],$A[2][3] + eor $C[4],$C[4],$A[2][4] + eor $C[0],$C[0],$A[3][0] + eor $C[1],$C[1],$A[3][1] + eor $C[2],$C[2],$A[3][2] + eor $C[3],$C[3],$A[3][3] + eor $C[4],$C[4],$A[3][4] + eor $C[0],$C[0],$A[4][0] + eor $C[2],$C[2],$A[4][2] + eor $C[1],$C[1],$A[4][1] + eor $C[3],$C[3],$A[4][3] + eor $C[4],$C[4],$A[4][4] + + eor $C[5],$C[0],$C[2],ror#63 + + eor $A[0][1],$A[0][1],$C[5] + eor $A[1][1],$A[1][1],$C[5] + eor $A[2][1],$A[2][1],$C[5] + eor $A[3][1],$A[3][1],$C[5] + eor $A[4][1],$A[4][1],$C[5] + + eor $C[5],$C[1],$C[3],ror#63 + eor $C[2],$C[2],$C[4],ror#63 + eor $C[3],$C[3],$C[0],ror#63 + eor $C[4],$C[4],$C[1],ror#63 + + eor $C[1], $A[0][2],$C[5] // mov $C[1],$A[0][2] + eor $A[1][2],$A[1][2],$C[5] + eor $A[2][2],$A[2][2],$C[5] + eor $A[3][2],$A[3][2],$C[5] + eor $A[4][2],$A[4][2],$C[5] + + eor $A[0][0],$A[0][0],$C[4] + eor $A[1][0],$A[1][0],$C[4] + eor $A[2][0],$A[2][0],$C[4] + eor $A[3][0],$A[3][0],$C[4] + eor $A[4][0],$A[4][0],$C[4] +___ + $C[4]=undef; + $C[5]=undef; +$code.=<<___; + ldp $A[0][4],$A[1][4],[sp,#0] // re-load offloaded data + eor $C[0], $A[0][3],$C[2] // mov $C[0],$A[0][3] + eor $A[1][3],$A[1][3],$C[2] + eor $A[2][3],$A[2][3],$C[2] + eor $A[3][3],$A[3][3],$C[2] + eor $A[4][3],$A[4][3],$C[2] + + eor $C[2], $A[0][4],$C[3] // mov $C[2],$A[0][4] + eor $A[1][4],$A[1][4],$C[3] + eor $A[2][4],$A[2][4],$C[3] + eor $A[3][4],$A[3][4],$C[3] + eor $A[4][4],$A[4][4],$C[3] + + ////////////////////////////////////////// Rho+Pi + mov $C[3],$A[0][1] + ror $A[0][1],$A[1][1],#64-$rhotates[1][1] + //mov $C[1],$A[0][2] + ror $A[0][2],$A[2][2],#64-$rhotates[2][2] + //mov $C[0],$A[0][3] + ror $A[0][3],$A[3][3],#64-$rhotates[3][3] + //mov $C[2],$A[0][4] + ror $A[0][4],$A[4][4],#64-$rhotates[4][4] + + ror $A[1][1],$A[1][4],#64-$rhotates[1][4] + ror $A[2][2],$A[2][3],#64-$rhotates[2][3] + ror $A[3][3],$A[3][2],#64-$rhotates[3][2] + ror $A[4][4],$A[4][1],#64-$rhotates[4][1] + + ror $A[1][4],$A[4][2],#64-$rhotates[4][2] + ror $A[2][3],$A[3][4],#64-$rhotates[3][4] + ror $A[3][2],$A[2][1],#64-$rhotates[2][1] + ror $A[4][1],$A[1][3],#64-$rhotates[1][3] + + ror $A[4][2],$A[2][4],#64-$rhotates[2][4] + ror $A[3][4],$A[4][3],#64-$rhotates[4][3] + ror $A[2][1],$A[1][2],#64-$rhotates[1][2] + ror $A[1][3],$A[3][1],#64-$rhotates[3][1] + + ror $A[2][4],$A[4][0],#64-$rhotates[4][0] + ror $A[4][3],$A[3][0],#64-$rhotates[3][0] + ror $A[1][2],$A[2][0],#64-$rhotates[2][0] + ror $A[3][1],$A[1][0],#64-$rhotates[1][0] + + ror $A[1][0],$C[0],#64-$rhotates[0][3] + ror $A[2][0],$C[3],#64-$rhotates[0][1] + ror $A[3][0],$C[2],#64-$rhotates[0][4] + ror $A[4][0],$C[1],#64-$rhotates[0][2] + + ////////////////////////////////////////// Chi+Iota + bic $C[0],$A[0][2],$A[0][1] + bic $C[1],$A[0][3],$A[0][2] + bic $C[2],$A[0][0],$A[0][4] + bic $C[3],$A[0][1],$A[0][0] + eor $A[0][0],$A[0][0],$C[0] + bic $C[0],$A[0][4],$A[0][3] + eor $A[0][1],$A[0][1],$C[1] + ldr $C[1],[sp,#16] + eor $A[0][3],$A[0][3],$C[2] + eor $A[0][4],$A[0][4],$C[3] + eor $A[0][2],$A[0][2],$C[0] + ldr $C[3],[$C[1]],#8 // Iota[i++] + + bic $C[0],$A[1][2],$A[1][1] + tst $C[1],#255 // are we done? + str $C[1],[sp,#16] + bic $C[1],$A[1][3],$A[1][2] + bic $C[2],$A[1][0],$A[1][4] + eor $A[0][0],$A[0][0],$C[3] // A[0][0] ^= Iota + bic $C[3],$A[1][1],$A[1][0] + eor $A[1][0],$A[1][0],$C[0] + bic $C[0],$A[1][4],$A[1][3] + eor $A[1][1],$A[1][1],$C[1] + eor $A[1][3],$A[1][3],$C[2] + eor $A[1][4],$A[1][4],$C[3] + eor $A[1][2],$A[1][2],$C[0] + + bic $C[0],$A[2][2],$A[2][1] + bic $C[1],$A[2][3],$A[2][2] + bic $C[2],$A[2][0],$A[2][4] + bic $C[3],$A[2][1],$A[2][0] + eor $A[2][0],$A[2][0],$C[0] + bic $C[0],$A[2][4],$A[2][3] + eor $A[2][1],$A[2][1],$C[1] + eor $A[2][3],$A[2][3],$C[2] + eor $A[2][4],$A[2][4],$C[3] + eor $A[2][2],$A[2][2],$C[0] + + bic $C[0],$A[3][2],$A[3][1] + bic $C[1],$A[3][3],$A[3][2] + bic $C[2],$A[3][0],$A[3][4] + bic $C[3],$A[3][1],$A[3][0] + eor $A[3][0],$A[3][0],$C[0] + bic $C[0],$A[3][4],$A[3][3] + eor $A[3][1],$A[3][1],$C[1] + eor $A[3][3],$A[3][3],$C[2] + eor $A[3][4],$A[3][4],$C[3] + eor $A[3][2],$A[3][2],$C[0] + + bic $C[0],$A[4][2],$A[4][1] + bic $C[1],$A[4][3],$A[4][2] + bic $C[2],$A[4][0],$A[4][4] + bic $C[3],$A[4][1],$A[4][0] + eor $A[4][0],$A[4][0],$C[0] + bic $C[0],$A[4][4],$A[4][3] + eor $A[4][1],$A[4][1],$C[1] + eor $A[4][3],$A[4][3],$C[2] + eor $A[4][4],$A[4][4],$C[3] + eor $A[4][2],$A[4][2],$C[0] + + bne .Loop + + ldr x30,[sp,#24] + ret +.size KeccakF1600_int,.-KeccakF1600_int + +.type KeccakF1600,%function +.align 5 +KeccakF1600: + stp x29,x30,[sp,#-128]! + add x29,sp,#0 + stp x19,x20,[sp,#16] + stp x21,x22,[sp,#32] + stp x23,x24,[sp,#48] + stp x25,x26,[sp,#64] + stp x27,x28,[sp,#80] + sub sp,sp,#48 + + str x0,[sp,#32] // offload argument + mov $C[0],x0 + ldp $A[0][0],$A[0][1],[x0,#16*0] + ldp $A[0][2],$A[0][3],[$C[0],#16*1] + ldp $A[0][4],$A[1][0],[$C[0],#16*2] + ldp $A[1][1],$A[1][2],[$C[0],#16*3] + ldp $A[1][3],$A[1][4],[$C[0],#16*4] + ldp $A[2][0],$A[2][1],[$C[0],#16*5] + ldp $A[2][2],$A[2][3],[$C[0],#16*6] + ldp $A[2][4],$A[3][0],[$C[0],#16*7] + ldp $A[3][1],$A[3][2],[$C[0],#16*8] + ldp $A[3][3],$A[3][4],[$C[0],#16*9] + ldp $A[4][0],$A[4][1],[$C[0],#16*10] + ldp $A[4][2],$A[4][3],[$C[0],#16*11] + ldr $A[4][4],[$C[0],#16*12] + + bl KeccakF1600_int + + ldr $C[0],[sp,#32] + stp $A[0][0],$A[0][1],[$C[0],#16*0] + stp $A[0][2],$A[0][3],[$C[0],#16*1] + stp $A[0][4],$A[1][0],[$C[0],#16*2] + stp $A[1][1],$A[1][2],[$C[0],#16*3] + stp $A[1][3],$A[1][4],[$C[0],#16*4] + stp $A[2][0],$A[2][1],[$C[0],#16*5] + stp $A[2][2],$A[2][3],[$C[0],#16*6] + stp $A[2][4],$A[3][0],[$C[0],#16*7] + stp $A[3][1],$A[3][2],[$C[0],#16*8] + stp $A[3][3],$A[3][4],[$C[0],#16*9] + stp $A[4][0],$A[4][1],[$C[0],#16*10] + stp $A[4][2],$A[4][3],[$C[0],#16*11] + str $A[4][4],[$C[0],#16*12] + + ldp x19,x20,[x29,#16] + add sp,sp,#48 + ldp x21,x22,[x29,#32] + ldp x23,x24,[x29,#48] + ldp x25,x26,[x29,#64] + ldp x27,x28,[x29,#80] + ldp x29,x30,[sp],#128 + ret +.size KeccakF1600,.-KeccakF1600 + +.globl SHA3_absorb +.type SHA3_absorb,%function +.align 5 +SHA3_absorb: + stp x29,x30,[sp,#-128]! + add x29,sp,#0 + stp x19,x20,[sp,#16] + stp x21,x22,[sp,#32] + stp x23,x24,[sp,#48] + stp x25,x26,[sp,#64] + stp x27,x28,[sp,#80] + sub sp,sp,#64 + + stp x0,x1,[sp,#32] // offload arguments + stp x2,x3,[sp,#48] + + mov $C[0],x0 // uint64_t A[5][5] + mov $C[1],x1 // const void *inp + mov $C[2],x2 // size_t len + mov $C[3],x3 // size_t bsz + ldp $A[0][0],$A[0][1],[$C[0],#16*0] + ldp $A[0][2],$A[0][3],[$C[0],#16*1] + ldp $A[0][4],$A[1][0],[$C[0],#16*2] + ldp $A[1][1],$A[1][2],[$C[0],#16*3] + ldp $A[1][3],$A[1][4],[$C[0],#16*4] + ldp $A[2][0],$A[2][1],[$C[0],#16*5] + ldp $A[2][2],$A[2][3],[$C[0],#16*6] + ldp $A[2][4],$A[3][0],[$C[0],#16*7] + ldp $A[3][1],$A[3][2],[$C[0],#16*8] + ldp $A[3][3],$A[3][4],[$C[0],#16*9] + ldp $A[4][0],$A[4][1],[$C[0],#16*10] + ldp $A[4][2],$A[4][3],[$C[0],#16*11] + ldr $A[4][4],[$C[0],#16*12] + b .Loop_absorb + +.align 4 +.Loop_absorb: + subs $C[0],$C[2],$C[3] // len - bsz + blo .Labsorbed + + str $C[0],[sp,#48] // save len - bsz +___ +for (my $i=0; $i<24; $i+=2) { +my $j = $i+1; +$code.=<<___; + ldr $C[0],[$C[1]],#8 // *inp++ +#ifdef __AARCH64EB__ + rev $C[0],$C[0] +#endif + eor $A[$i/5][$i%5],$A[$i/5][$i%5],$C[0] + cmp $C[3],#8*($i+2) + blo .Lprocess_block + ldr $C[0],[$C[1]],#8 // *inp++ +#ifdef __AARCH64EB__ + rev $C[0],$C[0] +#endif + eor $A[$j/5][$j%5],$A[$j/5][$j%5],$C[0] + beq .Lprocess_block +___ +} +$code.=<<___; + ldr $C[0],[$C[1]],#8 // *inp++ +#ifdef __AARCH64EB__ + rev $C[0],$C[0] +#endif + eor $A[4][4],$A[4][4],$C[0] + +.Lprocess_block: + str $C[1],[sp,#40] // save inp + + bl KeccakF1600_int + + ldr $C[1],[sp,#40] // restore arguments + ldp $C[2],$C[3],[sp,#48] + b .Loop_absorb + +.align 4 +.Labsorbed: + ldr $C[1],[sp,#32] + stp $A[0][0],$A[0][1],[$C[1],#16*0] + stp $A[0][2],$A[0][3],[$C[1],#16*1] + stp $A[0][4],$A[1][0],[$C[1],#16*2] + stp $A[1][1],$A[1][2],[$C[1],#16*3] + stp $A[1][3],$A[1][4],[$C[1],#16*4] + stp $A[2][0],$A[2][1],[$C[1],#16*5] + stp $A[2][2],$A[2][3],[$C[1],#16*6] + stp $A[2][4],$A[3][0],[$C[1],#16*7] + stp $A[3][1],$A[3][2],[$C[1],#16*8] + stp $A[3][3],$A[3][4],[$C[1],#16*9] + stp $A[4][0],$A[4][1],[$C[1],#16*10] + stp $A[4][2],$A[4][3],[$C[1],#16*11] + str $A[4][4],[$C[1],#16*12] + + mov x0,$C[2] // return value + ldp x19,x20,[x29,#16] + add sp,sp,#64 + ldp x21,x22,[x29,#32] + ldp x23,x24,[x29,#48] + ldp x25,x26,[x29,#64] + ldp x27,x28,[x29,#80] + ldp x29,x30,[sp],#128 + ret +.size SHA3_absorb,.-SHA3_absorb +___ +{ +my ($A_flat,$out,$len,$bsz) = map("x$_",(19..22)); +$code.=<<___; +.globl SHA3_squeeze +.type SHA3_squeeze,%function +.align 5 +SHA3_squeeze: + stp x29,x30,[sp,#-48]! + add x29,sp,#0 + stp x19,x20,[sp,#16] + stp x21,x22,[sp,#32] + + mov $A_flat,x0 // put aside arguments + mov $out,x1 + mov $len,x2 + mov $bsz,x3 + +.Loop_squeeze: + ldr x4,[x0],#8 + cmp $len,#8 + blo .Lsqueeze_tail +#ifdef __AARCH64EB__ + rev x4,x4 +#endif + str x4,[$out],#8 + subs $len,$len,#8 + beq .Lsqueeze_done + + subs x3,x3,#8 + bhi .Loop_squeeze + + mov x0,$A_flat + bl KeccakF1600 + mov x0,$A_flat + mov x3,$bsz + b .Loop_squeeze + +.align 4 +.Lsqueeze_tail: + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done + strb w4,[$out],#1 + +.Lsqueeze_done: + ldp x19,x20,[sp,#16] + ldp x21,x22,[sp,#32] + ldp x29,x30,[sp],#48 + ret +.size SHA3_squeeze,.-SHA3_squeeze +___ +} }}} + {{{ +my @A = map([ "v".$_.".16b", "v".($_+1).".16b", "v".($_+2).".16b", + "v".($_+3).".16b", "v".($_+4).".16b" ], + (0, 5, 10, 15, 20)); + +my @C = map("v$_.16b", (25..31)); + +$code.=<<___; +.type KeccakF1600_ce,%function +.align 5 +KeccakF1600_ce: + mov x9,#6 + adr x10,iotas + b .Loop_ce +.align 4 +.Loop_ce: +___ +for($i=0; $i<4; $i++) { +$code.=<<___; + ////////////////////////////////////////////////// Theta + eor3 $C[0],$A[0][0],$A[1][0],$A[2][0] + eor3 $C[1],$A[0][1],$A[1][1],$A[2][1] + eor3 $C[2],$A[0][2],$A[1][2],$A[2][2] + eor3 $C[3],$A[0][3],$A[1][3],$A[2][3] + eor3 $C[4],$A[0][4],$A[1][4],$A[2][4] + eor3 $C[0],$C[0], $A[3][0],$A[4][0] + eor3 $C[1],$C[1], $A[3][1],$A[4][1] + eor3 $C[2],$C[2], $A[3][2],$A[4][2] + eor3 $C[3],$C[3], $A[3][3],$A[4][3] + eor3 $C[4],$C[4], $A[3][4],$A[4][4] + + rax1 $C[5],$C[0],$C[2] // D[1] + rax1 $C[6],$C[1],$C[3] // D[2] + rax1 $C[2],$C[2],$C[4] // D[3] + rax1 $C[3],$C[3],$C[0] // D[4] + rax1 $C[4],$C[4],$C[1] // D[0] + + ////////////////////////////////////////////////// Theta+Rho+Pi + xar $C[0], $A[1][1],$C[5],#64-$rhotates[1][1] // C[0]=A[0][1] + xar $A[1][1],$A[1][4],$C[3],#64-$rhotates[1][4] + xar $A[1][4],$A[4][2],$C[6],#64-$rhotates[4][2] + xar $A[4][2],$A[2][4],$C[3],#64-$rhotates[2][4] + xar $A[2][4],$A[4][0],$C[4],#64-$rhotates[4][0] + + xar $A[4][0],$A[0][2],$C[6],#64-$rhotates[0][2] + + xar $A[0][2],$A[2][2],$C[6],#64-$rhotates[2][2] + xar $A[2][2],$A[2][3],$C[2],#64-$rhotates[2][3] + xar $A[2][3],$A[3][4],$C[3],#64-$rhotates[3][4] + xar $A[3][4],$A[4][3],$C[2],#64-$rhotates[4][3] + xar $A[4][3],$A[3][0],$C[4],#64-$rhotates[3][0] + + xar $A[3][0],$A[0][4],$C[3],#64-$rhotates[0][4] + + eor $A[0][0],$A[0][0],$C[4] + ldr x11,[x10],#8 + + xar $C[1] ,$A[3][3],$C[2],#64-$rhotates[3][3] // C[1]=A[0][3] + xar $A[3][3],$A[3][2],$C[6],#64-$rhotates[3][2] + xar $A[3][2],$A[2][1],$C[5],#64-$rhotates[2][1] + xar $A[2][1],$A[1][2],$C[6],#64-$rhotates[1][2] + xar $A[1][2],$A[2][0],$C[4],#64-$rhotates[2][0] + + xar $A[2][0],$A[0][1],$C[5],#64-$rhotates[0][1] // * + + xar $A[0][4],$A[4][4],$C[3],#64-$rhotates[4][4] + xar $A[4][4],$A[4][1],$C[5],#64-$rhotates[4][1] + xar $A[4][1],$A[1][3],$C[2],#64-$rhotates[1][3] + xar $A[1][3],$A[3][1],$C[5],#64-$rhotates[3][1] + xar $A[3][1],$A[1][0],$C[4],#64-$rhotates[1][0] + + xar $A[1][0],$A[0][3],$C[2],#64-$rhotates[0][3] // * + + ////////////////////////////////////////////////// Chi+Iota + dup $C[6],x11 // borrow C[6] + bcax $C[3], $A[0][0],$A[0][2],$C[0] // * + bcax $A[0][1],$C[0], $C[1], $A[0][2] // * + bcax $A[0][2],$A[0][2],$A[0][4],$C[1] + bcax $A[0][3],$C[1], $A[0][0],$A[0][4] + bcax $A[0][4],$A[0][4],$C[0], $A[0][0] + + bcax $C[0], $A[1][0],$A[1][2],$A[1][1] // * + bcax $C[1], $A[1][1],$A[1][3],$A[1][2] // * + bcax $A[1][2],$A[1][2],$A[1][4],$A[1][3] + bcax $A[1][3],$A[1][3],$A[1][0],$A[1][4] + bcax $A[1][4],$A[1][4],$A[1][1],$A[1][0] + + eor $A[0][0],$C[3],$C[6] // Iota + + bcax $C[2], $A[2][0],$A[2][2],$A[2][1] // * + bcax $C[3], $A[2][1],$A[2][3],$A[2][2] // * + bcax $A[2][2],$A[2][2],$A[2][4],$A[2][3] + bcax $A[2][3],$A[2][3],$A[2][0],$A[2][4] + bcax $A[2][4],$A[2][4],$A[2][1],$A[2][0] + + bcax $A[2][0],$A[3][0],$A[3][2],$A[3][1] // * + bcax $A[2][1],$A[3][1],$A[3][3],$A[3][2] // * + bcax $A[3][2],$A[3][2],$A[3][4],$A[3][3] + bcax $A[3][3],$A[3][3],$A[3][0],$A[3][4] + bcax $A[3][4],$A[3][4],$A[3][1],$A[3][0] + + bcax $A[3][0],$A[4][0],$A[4][2],$A[4][1] // * + bcax $A[3][1],$A[4][1],$A[4][3],$A[4][2] // * + bcax $A[4][2],$A[4][2],$A[4][4],$A[4][3] + bcax $A[4][3],$A[4][3],$A[4][0],$A[4][4] + bcax $A[4][4],$A[4][4],$A[4][1],$A[4][0] +___ + ($A[1][0],$A[1][1], $C[0],$C[1]) + = ($C[0],$C[1], $A[1][0],$A[1][1]); + ($A[2][0],$A[2][1], $A[3][0],$A[3][1], $A[4][0],$A[4][1], $C[2],$C[3]) + = ($C[2],$C[3], $A[2][0],$A[2][1], $A[3][0],$A[3][1], $A[4][0],$A[4][1]); +} +$code.=<<___; + subs x9,x9,#1 + bne .Loop_ce + + ret +.size KeccakF1600_ce,.-KeccakF1600_ce + +.type KeccakF1600_cext,%function +.align 5 +KeccakF1600_cext: + stp x29,x30,[sp,#-80]! + add x29,sp,#0 + stp d8,d9,[sp,#16] // per ABI requirement + stp d10,d11,[sp,#32] + stp d12,d13,[sp,#48] + stp d14,d15,[sp,#64] +___ +for($i=0; $i<24; $i+=2) { # load A[5][5] +my $j=$i+1; +$code.=<<___; + ldp d$i,d$j,[x0,#8*$i] +___ +} +$code.=<<___; + ldr d24,[x0,#8*$i] + bl KeccakF1600_ce + ldr x30,[sp,#8] +___ +for($i=0; $i<24; $i+=2) { # store A[5][5] +my $j=$i+1; +$code.=<<___; + stp d$i,d$j,[x0,#8*$i] +___ +} +$code.=<<___; + str d24,[x0,#8*$i] + + ldp d8,d9,[sp,#16] + ldp d10,d11,[sp,#32] + ldp d12,d13,[sp,#48] + ldp d14,d15,[sp,#64] + ldr x29,[sp],#80 + ret +.size KeccakF1600_cext,.-KeccakF1600_cext +___ + +{ +my ($ctx,$inp,$len,$bsz) = map("x$_",(0..3)); + +$code.=<<___; +.globl SHA3_absorb_cext +.type SHA3_absorb_cext,%function +.align 5 +SHA3_absorb_cext: + stp x29,x30,[sp,#-80]! + add x29,sp,#0 + stp d8,d9,[sp,#16] // per ABI requirement + stp d10,d11,[sp,#32] + stp d12,d13,[sp,#48] + stp d14,d15,[sp,#64] +___ +for($i=0; $i<24; $i+=2) { # load A[5][5] +my $j=$i+1; +$code.=<<___; + ldp d$i,d$j,[x0,#8*$i] +___ +} +$code.=<<___; + ldr d24,[x0,#8*$i] + b .Loop_absorb_ce + +.align 4 +.Loop_absorb_ce: + subs $len,$len,$bsz // len - bsz + blo .Labsorbed_ce +___ +for (my $i=0; $i<24; $i+=2) { +my $j = $i+1; +$code.=<<___; + ldr d31,[$inp],#8 // *inp++ +#ifdef __AARCH64EB__ + rev64 v31.16b,v31.16b +#endif + eor $A[$i/5][$i%5],$A[$i/5][$i%5],v31.16b + cmp $bsz,#8*($i+2) + blo .Lprocess_block_ce + ldr d31,[$inp],#8 // *inp++ +#ifdef __AARCH64EB__ + rev v31.16b,v31.16b +#endif + eor $A[$j/5][$j%5],$A[$j/5][$j%5],v31.16b + beq .Lprocess_block_ce +___ +} +$code.=<<___; + ldr d31,[$inp],#8 // *inp++ +#ifdef __AARCH64EB__ + rev v31.16b,v31.16b +#endif + eor $A[4][4],$A[4][4],v31.16b + +.Lprocess_block_ce: + + bl KeccakF1600_ce + + b .Loop_absorb_ce + +.align 4 +.Labsorbed_ce: +___ +for($i=0; $i<24; $i+=2) { # store A[5][5] +my $j=$i+1; +$code.=<<___; + stp d$i,d$j,[x0,#8*$i] +___ +} +$code.=<<___; + str d24,[x0,#8*$i] + add x0,$len,$bsz // return value + + ldp d8,d9,[sp,#16] + ldp d10,d11,[sp,#32] + ldp d12,d13,[sp,#48] + ldp d14,d15,[sp,#64] + ldp x29,x30,[sp],#80 + ret +.size SHA3_absorb_cext,.-SHA3_absorb_cext +___ +} +{ +my ($ctx,$out,$len,$bsz) = map("x$_",(0..3)); +$code.=<<___; +.globl SHA3_squeeze_cext +.type SHA3_squeeze_cext,%function +.align 5 +SHA3_squeeze_cext: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + mov x9,$ctx + mov x10,$bsz + +.Loop_squeeze_ce: + ldr x4,[x9],#8 + cmp $len,#8 + blo .Lsqueeze_tail_ce +#ifdef __AARCH64EB__ + rev x4,x4 +#endif + str x4,[$out],#8 + beq .Lsqueeze_done_ce + + sub $len,$len,#8 + subs x10,x10,#8 + bhi .Loop_squeeze_ce + + bl KeccakF1600_cext + ldr x30,[sp,#8] + mov x9,$ctx + mov x10,$bsz + b .Loop_squeeze_ce + +.align 4 +.Lsqueeze_tail_ce: + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done_ce + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done_ce + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done_ce + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done_ce + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done_ce + strb w4,[$out],#1 + lsr x4,x4,#8 + subs $len,$len,#1 + beq .Lsqueeze_done_ce + strb w4,[$out],#1 + +.Lsqueeze_done_ce: + ldr x29,[sp],#16 + ret +.size SHA3_squeeze_cext,.-SHA3_squeeze_cext +___ +} }}} +$code.=<<___; +.asciz "Keccak-1600 absorb and squeeze for ARMv8, CRYPTOGAMS by " +___ + +{ my %opcode = ( + "rax1" => 0xce608c00, "eor3" => 0xce000000, + "bcax" => 0xce200000, "xar" => 0xce800000 ); + + sub unsha3 { + my ($mnemonic,$arg)=@_; + + $arg =~ m/[qv]([0-9]+)[^,]*,\s*[qv]([0-9]+)[^,]*(?:,\s*[qv]([0-9]+)[^,]*(?:,\s*[qv#]([0-9\-]+))?)?/ + && + sprintf ".inst\t0x%08x\t//%s %s", + $opcode{$mnemonic}|$1|($2<<5)|($3<<16)|(eval($4)<<10), + $mnemonic,$arg; + } +} + +foreach(split("\n",$code)) { + + s/\`([^\`]*)\`/eval($1)/ge; + + m/\bdup\b/ and s/\.16b/.2d/g or + s/\b(eor3|rax1|xar|bcax)\s+(v.*)/unsha3($1,$2)/ge; + + print $_,"\n"; +} + +close STDOUT; diff --git a/crypto/sha/asm/keccak1600-avx2.pl b/crypto/sha/asm/keccak1600-avx2.pl new file mode 100755 index 00000000..82ca6728 --- /dev/null +++ b/crypto/sha/asm/keccak1600-avx2.pl @@ -0,0 +1,480 @@ +#!/usr/bin/env perl +# 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# Keccak-1600 for AVX2. +# +# July 2017. +# +# To paraphrase Gilles Van Assche, if you contemplate Fig. 2.3 on page +# 20 of The Keccak reference [or Fig. 5 of FIPS PUB 202], and load data +# other than A[0][0] in magic order into 6 [256-bit] registers, *each +# dedicated to one axis*, Pi permutation is reduced to intra-register +# shuffles... +# +# It makes other steps more intricate, but overall, is it a win? To be +# more specific index permutations organized by quadruples are: +# +# [4][4] [3][3] [2][2] [1][1]<-+ +# [0][4] [0][3] [0][2] [0][1]<-+ +# [3][0] [1][0] [4][0] [2][0] | +# [4][3] [3][1] [2][4] [1][2] | +# [3][4] [1][3] [4][2] [2][1] | +# [2][3] [4][1] [1][4] [3][2] | +# [2][2] [4][4] [1][1] [3][3] -+ +# +# This however is highly impractical for Theta and Chi. What would help +# Theta is if x indices were aligned column-wise, or in other words: +# +# [0][4] [0][3] [0][2] [0][1] +# [3][0] [1][0] [4][0] [2][0] +#vpermq([4][3] [3][1] [2][4] [1][2], 0b01110010) +# [2][4] [4][3] [1][2] [3][1] +#vpermq([4][2] [3][4] [2][1] [1][3], 0b10001101) +# [3][4] [1][3] [4][2] [2][1] +#vpermq([2][3] [4][1] [1][4] [3][2], 0b01110010) +# [1][4] [2][3] [3][2] [4][1] +#vpermq([1][1] [2][2] [3][3] [4][4], 0b00011011) +# [4][4] [3][3] [2][2] [1][1] +# +# So here we have it, lines not marked with vpermq() represent the magic +# order in which data is to be loaded and maintained. [And lines marked +# with vpermq() represent Pi circular permutation in chosen layout. Note +# that first step is permutation-free.] A[0][0] is loaded to register of +# its own, to all lanes. [A[0][0] is not part of Pi permutation or Rho.] +# Digits in variables' names denote right-most coordinates: + +my ($A00, # [0][0] [0][0] [0][0] [0][0] # %ymm0 + $A01, # [0][4] [0][3] [0][2] [0][1] # %ymm1 + $A20, # [3][0] [1][0] [4][0] [2][0] # %ymm2 + $A31, # [2][4] [4][3] [1][2] [3][1] # %ymm3 + $A21, # [3][4] [1][3] [4][2] [2][1] # %ymm4 + $A41, # [1][4] [2][3] [3][2] [4][1] # %ymm5 + $A11) = # [4][4] [3][3] [2][2] [1][1] # %ymm6 + map("%ymm$_",(0..6)); + +# We also need to map the magic order into offsets within structure: + +my @A_jagged = ([0,0], [1,0], [1,1], [1,2], [1,3], # [0][0..4] + [2,2], [6,0], [3,1], [4,2], [5,3], # [1][0..4] + [2,0], [4,0], [6,1], [5,2], [3,3], # [2][0..4] + [2,3], [3,0], [5,1], [6,2], [4,3], # [3][0..4] + [2,1], [5,0], [4,1], [3,2], [6,3]); # [4][0..4] + @A_jagged = map(8*($$_[0]*4+$$_[1]), @A_jagged); # ... and now linear + +# But on the other hand Chi is much better off if y indices were aligned +# column-wise, not x. For this reason we have to shuffle data prior +# Chi and revert it afterwards. Prior shuffle is naturally merged with +# Pi itself: +# +# [0][4] [0][3] [0][2] [0][1] +# [3][0] [1][0] [4][0] [2][0] +#vpermq([4][3] [3][1] [2][4] [1][2], 0b01110010) +#vpermq([2][4] [4][3] [1][2] [3][1], 0b00011011) = 0b10001101 +# [3][1] [1][2] [4][3] [2][4] +#vpermq([4][2] [3][4] [2][1] [1][3], 0b10001101) +#vpermq([3][4] [1][3] [4][2] [2][1], 0b11100100) = 0b10001101 +# [3][4] [1][3] [4][2] [2][1] +#vpermq([2][3] [4][1] [1][4] [3][2], 0b01110010) +#vpermq([1][4] [2][3] [3][2] [4][1], 0b01110010) = 0b00011011 +# [3][2] [1][4] [4][1] [2][3] +#vpermq([1][1] [2][2] [3][3] [4][4], 0b00011011) +#vpermq([4][4] [3][3] [2][2] [1][1], 0b10001101) = 0b01110010 +# [3][3] [1][1] [4][4] [2][2] +# +# And reverse post-Chi permutation: +# +# [0][4] [0][3] [0][2] [0][1] +# [3][0] [1][0] [4][0] [2][0] +#vpermq([3][1] [1][2] [4][3] [2][4], 0b00011011) +# [2][4] [4][3] [1][2] [3][1] +#vpermq([3][4] [1][3] [4][2] [2][1], 0b11100100) = nop :-) +# [3][4] [1][3] [4][2] [2][1] +#vpermq([3][2] [1][4] [4][1] [2][3], 0b10001101) +# [1][4] [2][3] [3][2] [4][1] +#vpermq([3][3] [1][1] [4][4] [2][2], 0b01110010) +# [4][4] [3][3] [2][2] [1][1] +# +######################################################################## +# Numbers are cycles per processed byte out of large message. +# +# r=1088(*) +# +# Haswell 8.7/+10% +# Skylake 7.8/+20% +# Ryzen 17(**) +# +# (*) Corresponds to SHA3-256. Percentage after slash is improvement +# coefficient in comparison to scalar keccak1600-x86_64.pl. +# (**) It's expected that Ryzen performs poorly, because instruction +# issue rate is limited to two AVX2 instructions per cycle and +# in addition vpblendd is reportedly bound to specific port. +# Obviously this code path should not be executed on Ryzen. + +my @T = map("%ymm$_",(7..15)); +my ($C14,$C00,$D00,$D14) = @T[5..8]; + +$code.=<<___; +.text + +.type __KeccakF1600,\@function +.align 32 +__KeccakF1600: + lea rhotates_left+96(%rip),%r8 + lea rhotates_right+96(%rip),%r9 + lea iotas(%rip),%r10 + mov \$24,%eax + jmp .Loop_avx2 + +.align 32 +.Loop_avx2: + ######################################### Theta + vpshufd \$0b01001110,$A20,$C00 + vpxor $A31,$A41,$C14 + vpxor $A11,$A21,@T[2] + vpxor $A01,$C14,$C14 + vpxor @T[2],$C14,$C14 # C[1..4] + + vpermq \$0b10010011,$C14,@T[4] + vpxor $A20,$C00,$C00 + vpermq \$0b01001110,$C00,@T[0] + + vpsrlq \$63,$C14,@T[1] + vpaddq $C14,$C14,@T[2] + vpor @T[2],@T[1],@T[1] # ROL64(C[1..4],1) + + vpermq \$0b00111001,@T[1],$D14 + vpxor @T[4],@T[1],$D00 + vpermq \$0b00000000,$D00,$D00 # D[0..0] = ROL64(C[1],1) ^ C[4] + + vpxor $A00,$C00,$C00 + vpxor @T[0],$C00,$C00 # C[0..0] + + vpsrlq \$63,$C00,@T[0] + vpaddq $C00,$C00,@T[1] + vpor @T[0],@T[1],@T[1] # ROL64(C[0..0],1) + + vpxor $D00,$A20,$A20 # ^= D[0..0] + vpxor $D00,$A00,$A00 # ^= D[0..0] + + vpblendd \$0b11000000,@T[1],$D14,$D14 + vpblendd \$0b00000011,$C00,@T[4],@T[4] + vpxor @T[4],$D14,$D14 # D[1..4] = ROL64(C[2..4,0),1) ^ C[0..3] + + ######################################### Rho + Pi + pre-Chi shuffle + vpsllvq 0*32-96(%r8),$A20,@T[3] + vpsrlvq 0*32-96(%r9),$A20,$A20 + vpor @T[3],$A20,$A20 + + vpxor $D14,$A31,$A31 # ^= D[1..4] from Theta + vpsllvq 2*32-96(%r8),$A31,@T[4] + vpsrlvq 2*32-96(%r9),$A31,$A31 + vpor @T[4],$A31,$A31 + + vpxor $D14,$A21,$A21 # ^= D[1..4] from Theta + vpsllvq 3*32-96(%r8),$A21,@T[5] + vpsrlvq 3*32-96(%r9),$A21,$A21 + vpor @T[5],$A21,$A21 + + vpxor $D14,$A41,$A41 # ^= D[1..4] from Theta + vpsllvq 4*32-96(%r8),$A41,@T[6] + vpsrlvq 4*32-96(%r9),$A41,$A41 + vpor @T[6],$A41,$A41 + + vpxor $D14,$A11,$A11 # ^= D[1..4] from Theta + vpermq \$0b10001101,$A20,@T[3] # $A20 -> future $A31 + vpermq \$0b10001101,$A31,@T[4] # $A31 -> future $A21 + vpsllvq 5*32-96(%r8),$A11,@T[7] + vpsrlvq 5*32-96(%r9),$A11,@T[1] + vpor @T[7],@T[1],@T[1] # $A11 -> future $A01 + + vpxor $D14,$A01,$A01 # ^= D[1..4] from Theta + vpermq \$0b00011011,$A21,@T[5] # $A21 -> future $A41 + vpermq \$0b01110010,$A41,@T[6] # $A41 -> future $A11 + vpsllvq 1*32-96(%r8),$A01,@T[8] + vpsrlvq 1*32-96(%r9),$A01,@T[2] + vpor @T[8],@T[2],@T[2] # $A01 -> future $A20 + + ######################################### Chi + vpsrldq \$8,@T[1],@T[7] + vpandn @T[7],@T[1],@T[0] # tgting [0][0] [0][0] [0][0] [0][0] + + vpblendd \$0b00001100,@T[6],@T[2],$A31 # [4][4] [2][0] + vpblendd \$0b00001100,@T[2],@T[4],@T[8] # [4][0] [2][1] + vpblendd \$0b00001100,@T[4],@T[3],$A41 # [4][2] [2][4] + vpblendd \$0b00001100,@T[3],@T[2],@T[7] # [4][3] [2][0] + vpblendd \$0b00110000,@T[4],$A31,$A31 # [1][3] [4][4] [2][0] + vpblendd \$0b00110000,@T[5],@T[8],@T[8] # [1][4] [4][0] [2][1] + vpblendd \$0b00110000,@T[2],$A41,$A41 # [1][0] [4][2] [2][4] + vpblendd \$0b00110000,@T[6],@T[7],@T[7] # [1][1] [4][3] [2][0] + vpblendd \$0b11000000,@T[5],$A31,$A31 # [3][2] [1][3] [4][4] [2][0] + vpblendd \$0b11000000,@T[6],@T[8],@T[8] # [3][3] [1][4] [4][0] [2][1] + vpblendd \$0b11000000,@T[6],$A41,$A41 # [3][3] [1][0] [4][2] [2][4] + vpblendd \$0b11000000,@T[4],@T[7],@T[7] # [3][4] [1][1] [4][3] [2][0] + vpandn @T[8],$A31,$A31 # tgting [3][1] [1][2] [4][3] [2][4] + vpandn @T[7],$A41,$A41 # tgting [3][2] [1][4] [4][1] [2][3] + + vpblendd \$0b00001100,@T[2],@T[5],$A11 # [4][0] [2][3] + vpblendd \$0b00001100,@T[5],@T[3],@T[8] # [4][1] [2][4] + vpxor @T[3],$A31,$A31 + vpblendd \$0b00110000,@T[3],$A11,$A11 # [1][2] [4][0] [2][3] + vpblendd \$0b00110000,@T[4],@T[8],@T[8] # [1][3] [4][1] [2][4] + vpxor @T[5],$A41,$A41 + vpblendd \$0b11000000,@T[4],$A11,$A11 # [3][4] [1][2] [4][0] [2][3] + vpblendd \$0b11000000,@T[2],@T[8],@T[8] # [3][0] [1][3] [4][1] [2][4] + vpandn @T[8],$A11,$A11 # tgting [3][3] [1][1] [4][4] [2][2] + vpxor @T[6],$A11,$A11 + + vpermq \$0b00011110,@T[1],$A21 # [0][1] [0][2] [0][4] [0][3] + vpblendd \$0b00110000,$A00,$A21,@T[8] # [0][1] [0][0] [0][4] [0][3] + vpermq \$0b00111001,@T[1],$A01 # [0][1] [0][4] [0][3] [0][2] + vpblendd \$0b11000000,$A00,$A01,$A01 # [0][0] [0][4] [0][3] [0][2] + vpandn @T[8],$A01,$A01 # tgting [0][4] [0][3] [0][2] [0][1] + + vpblendd \$0b00001100,@T[5],@T[4],$A20 # [4][1] [2][1] + vpblendd \$0b00001100,@T[4],@T[6],@T[7] # [4][2] [2][2] + vpblendd \$0b00110000,@T[6],$A20,$A20 # [1][1] [4][1] [2][1] + vpblendd \$0b00110000,@T[3],@T[7],@T[7] # [1][2] [4][2] [2][2] + vpblendd \$0b11000000,@T[3],$A20,$A20 # [3][1] [1][1] [4][1] [2][1] + vpblendd \$0b11000000,@T[5],@T[7],@T[7] # [3][2] [1][2] [4][2] [2][2] + vpandn @T[7],$A20,$A20 # tgting [3][0] [1][0] [4][0] [2][0] + vpxor @T[2],$A20,$A20 + + vpermq \$0b00000000,@T[0],@T[0] # [0][0] [0][0] [0][0] [0][0] + vpermq \$0b00011011,$A31,$A31 # post-Chi shuffle + vpermq \$0b10001101,$A41,$A41 + vpermq \$0b01110010,$A11,$A11 + + vpblendd \$0b00001100,@T[3],@T[6],$A21 # [4][3] [2][2] + vpblendd \$0b00001100,@T[6],@T[5],@T[7] # [4][4] [2][3] + vpblendd \$0b00110000,@T[5],$A21,$A21 # [1][4] [4][3] [2][2] + vpblendd \$0b00110000,@T[2],@T[7],@T[7] # [1][0] [4][4] [2][3] + vpblendd \$0b11000000,@T[2],$A21,$A21 # [3][0] [1][4] [4][3] [2][2] + vpblendd \$0b11000000,@T[3],@T[7],@T[7] # [3][1] [1][0] [4][4] [2][3] + vpandn @T[7],$A21,$A21 # tgting [3][4] [1][3] [4][2] [2][1] + + vpxor @T[0],$A00,$A00 + vpxor @T[1],$A01,$A01 + vpxor @T[4],$A21,$A21 + + ######################################### Iota + vpxor (%r10),$A00,$A00 + lea 32(%r10),%r10 + + dec %eax + jnz .Loop_avx2 + + ret +.size __KeccakF1600,.-__KeccakF1600 +___ +my ($A_flat,$inp,$len,$bsz) = ("%rdi","%rsi","%rdx","%rcx"); +my $out = $inp; # in squeeze + +$code.=<<___; +.globl SHA3_absorb +.type SHA3_absorb,\@function +.align 32 +SHA3_absorb: + mov %rsp,%r11 + + lea -240(%rsp),%rsp + and \$-32,%rsp + + lea 96($A_flat),$A_flat + lea 96($inp),$inp + lea 96(%rsp),%r10 + + vzeroupper + + vpbroadcastq -96($A_flat),$A00 # load A[5][5] + vmovdqu 8+32*0-96($A_flat),$A01 + vmovdqu 8+32*1-96($A_flat),$A20 + vmovdqu 8+32*2-96($A_flat),$A31 + vmovdqu 8+32*3-96($A_flat),$A21 + vmovdqu 8+32*4-96($A_flat),$A41 + vmovdqu 8+32*5-96($A_flat),$A11 + + vpxor @T[0],@T[0],@T[0] + vmovdqa @T[0],32*2-96(%r10) # zero transfer area on stack + vmovdqa @T[0],32*3-96(%r10) + vmovdqa @T[0],32*4-96(%r10) + vmovdqa @T[0],32*5-96(%r10) + vmovdqa @T[0],32*6-96(%r10) + +.Loop_absorb_avx2: + mov $bsz,%rax + sub $bsz,$len + jc .Ldone_absorb_avx2 + + shr \$3,%eax + vpbroadcastq 0-96($inp),@T[0] + vmovdqu 8-96($inp),@T[1] + sub \$4,%eax +___ +for(my $i=5; $i<25; $i++) { +$code.=<<___ + dec %eax + jz .Labsorved_avx2 + mov 8*$i-96($inp),%r8 + mov %r8,$A_jagged[$i]-96(%r10) +___ +} +$code.=<<___; +.Labsorved_avx2: + lea ($inp,$bsz),$inp + + vpxor @T[0],$A00,$A00 + vpxor @T[1],$A01,$A01 + vpxor 32*2-96(%r10),$A20,$A20 + vpxor 32*3-96(%r10),$A31,$A31 + vpxor 32*4-96(%r10),$A21,$A21 + vpxor 32*5-96(%r10),$A41,$A41 + vpxor 32*6-96(%r10),$A11,$A11 + + call __KeccakF1600 + + lea 96(%rsp),%r10 + jmp .Loop_absorb_avx2 + +.Ldone_absorb_avx2: + vmovq %xmm0,-96($A_flat) + vmovdqu $A01,8+32*0-96($A_flat) + vmovdqu $A20,8+32*1-96($A_flat) + vmovdqu $A31,8+32*2-96($A_flat) + vmovdqu $A21,8+32*3-96($A_flat) + vmovdqu $A41,8+32*4-96($A_flat) + vmovdqu $A11,8+32*5-96($A_flat) + + vzeroupper + + lea (%r11),%rsp + lea ($len,$bsz),%rax # return value + ret +.size SHA3_absorb,.-SHA3_absorb + +.globl SHA3_squeeze +.type SHA3_squeeze,\@function +.align 32 +SHA3_squeeze: + mov %rsp,%r11 + + lea 96($A_flat),$A_flat + shr \$3,$bsz + + vzeroupper + + vpbroadcastq -96($A_flat),$A00 + vpxor @T[0],@T[0],@T[0] + vmovdqu 8+32*0-96($A_flat),$A01 + vmovdqu 8+32*1-96($A_flat),$A20 + vmovdqu 8+32*2-96($A_flat),$A31 + vmovdqu 8+32*3-96($A_flat),$A21 + vmovdqu 8+32*4-96($A_flat),$A41 + vmovdqu 8+32*5-96($A_flat),$A11 + + mov $bsz,%rax + +.Loop_squeeze_avx2: + mov @A_jagged[$i]-96($A_flat),%r8 +___ +for (my $i=0; $i<25; $i++) { +$code.=<<___; + sub \$8,$len + jc .Ltail_squeeze_avx2 + mov %r8,($out) + lea 8($out),$out + je .Ldone_squeeze_avx2 + dec %eax + je .Lextend_output_avx2 + mov @A_jagged[$i+1]-120($A_flat),%r8 +___ +} +$code.=<<___; +.Lextend_output_avx2: + call __KeccakF1600 + + vmovq %xmm0,-96($A_flat) + vmovdqu $A01,8+32*0-96($A_flat) + vmovdqu $A20,8+32*1-96($A_flat) + vmovdqu $A31,8+32*2-96($A_flat) + vmovdqu $A21,8+32*3-96($A_flat) + vmovdqu $A41,8+32*4-96($A_flat) + vmovdqu $A11,8+32*5-96($A_flat) + + mov $bsz,%rax + jmp .Loop_squeeze_avx2 + + +.Ltail_squeeze_avx2: + add \$8,$len +.Loop_tail_avx2: + mov %r8b,($out) + lea 1($out),$out + shr \$8,%r8 + dec $len + jnz .Loop_tail_avx2 + +.Ldone_squeeze_avx2: + vzeroupper + + lea (%r11),%rsp + ret +.size SHA3_squeeze,.-SHA3_squeeze + +.align 64 +rhotates_left: + .quad 3, 18, 36, 41 # [2][0] [4][0] [1][0] [3][0] + .quad 1, 62, 28, 27 # [0][1] [0][2] [0][3] [0][4] + .quad 45, 6, 56, 39 # [3][1] [1][2] [4][3] [2][4] + .quad 10, 61, 55, 8 # [2][1] [4][2] [1][3] [3][4] + .quad 2, 15, 25, 20 # [4][1] [3][2] [2][3] [1][4] + .quad 44, 43, 21, 14 # [1][1] [2][2] [3][3] [4][4] +rhotates_right: + .quad 64-3, 64-18, 64-36, 64-41 + .quad 64-1, 64-62, 64-28, 64-27 + .quad 64-45, 64-6, 64-56, 64-39 + .quad 64-10, 64-61, 64-55, 64-8 + .quad 64-2, 64-15, 64-25, 64-20 + .quad 64-44, 64-43, 64-21, 64-14 +iotas: + .quad 0x0000000000000001, 0x0000000000000001, 0x0000000000000001, 0x0000000000000001 + .quad 0x0000000000008082, 0x0000000000008082, 0x0000000000008082, 0x0000000000008082 + .quad 0x800000000000808a, 0x800000000000808a, 0x800000000000808a, 0x800000000000808a + .quad 0x8000000080008000, 0x8000000080008000, 0x8000000080008000, 0x8000000080008000 + .quad 0x000000000000808b, 0x000000000000808b, 0x000000000000808b, 0x000000000000808b + .quad 0x0000000080000001, 0x0000000080000001, 0x0000000080000001, 0x0000000080000001 + .quad 0x8000000080008081, 0x8000000080008081, 0x8000000080008081, 0x8000000080008081 + .quad 0x8000000000008009, 0x8000000000008009, 0x8000000000008009, 0x8000000000008009 + .quad 0x000000000000008a, 0x000000000000008a, 0x000000000000008a, 0x000000000000008a + .quad 0x0000000000000088, 0x0000000000000088, 0x0000000000000088, 0x0000000000000088 + .quad 0x0000000080008009, 0x0000000080008009, 0x0000000080008009, 0x0000000080008009 + .quad 0x000000008000000a, 0x000000008000000a, 0x000000008000000a, 0x000000008000000a + .quad 0x000000008000808b, 0x000000008000808b, 0x000000008000808b, 0x000000008000808b + .quad 0x800000000000008b, 0x800000000000008b, 0x800000000000008b, 0x800000000000008b + .quad 0x8000000000008089, 0x8000000000008089, 0x8000000000008089, 0x8000000000008089 + .quad 0x8000000000008003, 0x8000000000008003, 0x8000000000008003, 0x8000000000008003 + .quad 0x8000000000008002, 0x8000000000008002, 0x8000000000008002, 0x8000000000008002 + .quad 0x8000000000000080, 0x8000000000000080, 0x8000000000000080, 0x8000000000000080 + .quad 0x000000000000800a, 0x000000000000800a, 0x000000000000800a, 0x000000000000800a + .quad 0x800000008000000a, 0x800000008000000a, 0x800000008000000a, 0x800000008000000a + .quad 0x8000000080008081, 0x8000000080008081, 0x8000000080008081, 0x8000000080008081 + .quad 0x8000000000008080, 0x8000000000008080, 0x8000000000008080, 0x8000000000008080 + .quad 0x0000000080000001, 0x0000000080000001, 0x0000000080000001, 0x0000000080000001 + .quad 0x8000000080008008, 0x8000000080008008, 0x8000000080008008, 0x8000000080008008 + +.asciz "Keccak-1600 absorb and squeeze for AVX2, CRYPTOGAMS by " +___ + +print $code; +close STDOUT; diff --git a/crypto/sha/asm/keccak1600-avx512.pl b/crypto/sha/asm/keccak1600-avx512.pl new file mode 100755 index 00000000..6766f975 --- /dev/null +++ b/crypto/sha/asm/keccak1600-avx512.pl @@ -0,0 +1,549 @@ +#!/usr/bin/env perl +# 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# Keccak-1600 for AVX-512F. +# +# July 2017. +# +# Below code is KECCAK_1X_ALT implementation (see sha/keccak1600.c). +# Pretty straightforward, the only "magic" is data layout in registers. +# It's impossible to have one that is optimal for every step, hence +# it's changing as algorithm progresses. Data is saved in linear order, +# but in-register order morphs between rounds. Even rounds take in +# linear layout, and odd rounds - transposed, or "verticaly-shaped"... +# +######################################################################## +# Numbers are cycles per processed byte out of large message. +# +# r=1088(*) +# +# Knights Landing 7.6 +# Skylake-X 5.7 +# +# (*) Corresponds to SHA3-256. + +######################################################################## +# Below code is combination of two ideas. One is taken from Keccak Code +# Package, hereafter KCP, and another one from initial version of this +# module. What is common is observation that Pi's input and output are +# "mostly transposed", i.e. if input is aligned by x coordinate, then +# output is [mostly] aligned by y. Both versions, KCP and predecessor, +# were trying to use one of them from round to round, which resulted in +# some kind of transposition in each round. This version still does +# transpose data, but only every second round. Another essential factor +# is that KCP transposition has to be performed with instructions that +# turned to be rather expensive on Knights Landing, both latency- and +# throughput-wise. Not to mention that some of them have to depend on +# each other. On the other hand initial version of this module was +# relying heavily on blend instructions. There were lots of them, +# resulting in higher instruction count, yet it performed better on +# Knights Landing, because processor can execute pair of them each +# cycle and they have minimal latency. This module is an attempt to +# bring best parts together:-) +# +# Coordinates below correspond to those in sha/keccak1600.c. Input +# layout is straight linear: +# +# [0][4] [0][3] [0][2] [0][1] [0][0] +# [1][4] [1][3] [1][2] [1][1] [1][0] +# [2][4] [2][3] [2][2] [2][1] [2][0] +# [3][4] [3][3] [3][2] [3][1] [3][0] +# [4][4] [4][3] [4][2] [4][1] [4][0] +# +# It's perfect for Theta, while Pi is reduced to intra-register +# permutations which yield layout perfect for Chi: +# +# [4][0] [3][0] [2][0] [1][0] [0][0] +# [4][1] [3][1] [2][1] [1][1] [0][1] +# [4][2] [3][2] [2][2] [1][2] [0][2] +# [4][3] [3][3] [2][3] [1][3] [0][3] +# [4][4] [3][4] [2][4] [1][4] [0][4] +# +# Now instead of performing full transposition and feeding it to next +# identical round, we perform kind of diagonal transposition to layout +# from initial version of this module, and make it suitable for Theta: +# +# [4][4] [3][3] [2][2] [1][1] [0][0]>4.3.2.1.0>[4][4] [3][3] [2][2] [1][1] [0][0] +# [4][0] [3][4] [2][3] [1][2] [0][1]>3.2.1.0.4>[3][4] [2][3] [1][2] [0][1] [4][0] +# [4][1] [3][0] [2][4] [1][3] [0][2]>2.1.0.4.3>[2][4] [1][3] [0][2] [4][1] [3][0] +# [4][2] [3][1] [2][0] [1][4] [0][3]>1.0.4.3.2>[1][4] [0][3] [4][2] [3][1] [2][0] +# [4][3] [3][2] [2][1] [1][0] [0][4]>0.4.3.2.1>[0][4] [4][3] [3][2] [2][1] [1][0] +# +# Now intra-register permutations yield initial [almost] straight +# linear layout: +# +# [4][4] [3][3] [2][2] [1][1] [0][0] +##[0][4] [0][3] [0][2] [0][1] [0][0] +# [3][4] [2][3] [1][2] [0][1] [4][0] +##[2][3] [2][2] [2][1] [2][0] [2][4] +# [2][4] [1][3] [0][2] [4][1] [3][0] +##[4][2] [4][1] [4][0] [4][4] [4][3] +# [1][4] [0][3] [4][2] [3][1] [2][0] +##[1][1] [1][0] [1][4] [1][3] [1][2] +# [0][4] [4][3] [3][2] [2][1] [1][0] +##[3][0] [3][4] [3][3] [3][2] [3][1] +# +# This means that odd round Chi is performed in less suitable layout, +# with a number of additional permutations. But overall it turned to be +# a win. Permutations are fastest possible on Knights Landing and they +# are laid down to be independent of each other. In the essence I traded +# 20 blend instructions for 3 permutations. The result is 13% faster +# than KCP on Skylake-X, and >40% on Knights Landing. +# +# As implied, data is loaded in straight linear order. Digits in +# variables' names represent coordinates of right-most element of +# loaded data chunk: + +my ($A00, # [0][4] [0][3] [0][2] [0][1] [0][0] + $A10, # [1][4] [1][3] [1][2] [1][1] [1][0] + $A20, # [2][4] [2][3] [2][2] [2][1] [2][0] + $A30, # [3][4] [3][3] [3][2] [3][1] [3][0] + $A40) = # [4][4] [4][3] [4][2] [4][1] [4][0] + map("%zmm$_",(0..4)); + +# We also need to map the magic order into offsets within structure: + +my @A_jagged = ([0,0], [0,1], [0,2], [0,3], [0,4], + [1,0], [1,1], [1,2], [1,3], [1,4], + [2,0], [2,1], [2,2], [2,3], [2,4], + [3,0], [3,1], [3,2], [3,3], [3,4], + [4,0], [4,1], [4,2], [4,3], [4,4]); + @A_jagged = map(8*($$_[0]*8+$$_[1]), @A_jagged); # ... and now linear + +my @T = map("%zmm$_",(5..12)); +my @Theta = map("%zmm$_",(33,13..16)); # invalid @Theta[0] is not typo +my @Pi0 = map("%zmm$_",(17..21)); +my @Rhotate0 = map("%zmm$_",(22..26)); +my @Rhotate1 = map("%zmm$_",(27..31)); + +my ($C00,$D00) = @T[0..1]; +my ($k00001,$k00010,$k00100,$k01000,$k10000,$k11111) = map("%k$_",(1..6)); + +$code.=<<___; +.text + +.type __KeccakF1600,\@function +.align 32 +__KeccakF1600: + lea iotas(%rip),%r10 + mov \$12,%eax + jmp .Loop_avx512 + +.align 32 +.Loop_avx512: + ######################################### Theta, even round + vmovdqa64 $A00,@T[0] # put aside original A00 + vpternlogq \$0x96,$A20,$A10,$A00 # and use it as "C00" + vpternlogq \$0x96,$A40,$A30,$A00 + + vprolq \$1,$A00,$D00 + vpermq $A00,@Theta[1],$A00 + vpermq $D00,@Theta[4],$D00 + + vpternlogq \$0x96,$A00,$D00,@T[0] # T[0] is original A00 + vpternlogq \$0x96,$A00,$D00,$A10 + vpternlogq \$0x96,$A00,$D00,$A20 + vpternlogq \$0x96,$A00,$D00,$A30 + vpternlogq \$0x96,$A00,$D00,$A40 + + ######################################### Rho + vprolvq @Rhotate0[0],@T[0],$A00 # T[0] is original A00 + vprolvq @Rhotate0[1],$A10,$A10 + vprolvq @Rhotate0[2],$A20,$A20 + vprolvq @Rhotate0[3],$A30,$A30 + vprolvq @Rhotate0[4],$A40,$A40 + + ######################################### Pi + vpermq $A00,@Pi0[0],$A00 + vpermq $A10,@Pi0[1],$A10 + vpermq $A20,@Pi0[2],$A20 + vpermq $A30,@Pi0[3],$A30 + vpermq $A40,@Pi0[4],$A40 + + ######################################### Chi + vmovdqa64 $A00,@T[0] + vmovdqa64 $A10,@T[1] + vpternlogq \$0xD2,$A20,$A10,$A00 + vpternlogq \$0xD2,$A30,$A20,$A10 + vpternlogq \$0xD2,$A40,$A30,$A20 + vpternlogq \$0xD2,@T[0],$A40,$A30 + vpternlogq \$0xD2,@T[1],@T[0],$A40 + + ######################################### Iota + vpxorq (%r10),$A00,${A00}{$k00001} + lea 16(%r10),%r10 + + ######################################### Harmonize rounds + vpblendmq $A20,$A10,@{T[1]}{$k00010} + vpblendmq $A30,$A20,@{T[2]}{$k00010} + vpblendmq $A40,$A30,@{T[3]}{$k00010} + vpblendmq $A10,$A00,@{T[0]}{$k00010} + vpblendmq $A00,$A40,@{T[4]}{$k00010} + + vpblendmq $A30,@T[1],@{T[1]}{$k00100} + vpblendmq $A40,@T[2],@{T[2]}{$k00100} + vpblendmq $A20,@T[0],@{T[0]}{$k00100} + vpblendmq $A00,@T[3],@{T[3]}{$k00100} + vpblendmq $A10,@T[4],@{T[4]}{$k00100} + + vpblendmq $A40,@T[1],@{T[1]}{$k01000} + vpblendmq $A30,@T[0],@{T[0]}{$k01000} + vpblendmq $A00,@T[2],@{T[2]}{$k01000} + vpblendmq $A10,@T[3],@{T[3]}{$k01000} + vpblendmq $A20,@T[4],@{T[4]}{$k01000} + + vpblendmq $A40,@T[0],@{T[0]}{$k10000} + vpblendmq $A00,@T[1],@{T[1]}{$k10000} + vpblendmq $A10,@T[2],@{T[2]}{$k10000} + vpblendmq $A20,@T[3],@{T[3]}{$k10000} + vpblendmq $A30,@T[4],@{T[4]}{$k10000} + + #vpermq @T[0],@Theta[0],$A00 # doesn't actually change order + vpermq @T[1],@Theta[1],$A10 + vpermq @T[2],@Theta[2],$A20 + vpermq @T[3],@Theta[3],$A30 + vpermq @T[4],@Theta[4],$A40 + + ######################################### Theta, odd round + vmovdqa64 $T[0],$A00 # real A00 + vpternlogq \$0x96,$A20,$A10,$C00 # C00 is @T[0]'s alias + vpternlogq \$0x96,$A40,$A30,$C00 + + vprolq \$1,$C00,$D00 + vpermq $C00,@Theta[1],$C00 + vpermq $D00,@Theta[4],$D00 + + vpternlogq \$0x96,$C00,$D00,$A00 + vpternlogq \$0x96,$C00,$D00,$A30 + vpternlogq \$0x96,$C00,$D00,$A10 + vpternlogq \$0x96,$C00,$D00,$A40 + vpternlogq \$0x96,$C00,$D00,$A20 + + ######################################### Rho + vprolvq @Rhotate1[0],$A00,$A00 + vprolvq @Rhotate1[3],$A30,@T[1] + vprolvq @Rhotate1[1],$A10,@T[2] + vprolvq @Rhotate1[4],$A40,@T[3] + vprolvq @Rhotate1[2],$A20,@T[4] + + vpermq $A00,@Theta[4],@T[5] + vpermq $A00,@Theta[3],@T[6] + + ######################################### Iota + vpxorq -8(%r10),$A00,${A00}{$k00001} + + ######################################### Pi + vpermq @T[1],@Theta[2],$A10 + vpermq @T[2],@Theta[4],$A20 + vpermq @T[3],@Theta[1],$A30 + vpermq @T[4],@Theta[3],$A40 + + ######################################### Chi + vpternlogq \$0xD2,@T[6],@T[5],$A00 + + vpermq @T[1],@Theta[1],@T[7] + #vpermq @T[1],@Theta[0],@T[1] + vpternlogq \$0xD2,@T[1],@T[7],$A10 + + vpermq @T[2],@Theta[3],@T[0] + vpermq @T[2],@Theta[2],@T[2] + vpternlogq \$0xD2,@T[2],@T[0],$A20 + + #vpermq @T[3],@Theta[0],@T[3] + vpermq @T[3],@Theta[4],@T[1] + vpternlogq \$0xD2,@T[1],@T[3],$A30 + + vpermq @T[4],@Theta[2],@T[0] + vpermq @T[4],@Theta[1],@T[4] + vpternlogq \$0xD2,@T[4],@T[0],$A40 + + dec %eax + jnz .Loop_avx512 + + ret +.size __KeccakF1600,.-__KeccakF1600 +___ + +my ($A_flat,$inp,$len,$bsz) = ("%rdi","%rsi","%rdx","%rcx"); +my $out = $inp; # in squeeze + +$code.=<<___; +.globl SHA3_absorb +.type SHA3_absorb,\@function +.align 32 +SHA3_absorb: + mov %rsp,%r11 + + lea -320(%rsp),%rsp + and \$-64,%rsp + + lea 96($A_flat),$A_flat + lea 96($inp),$inp + lea 128(%rsp),%r9 + + lea theta_perm(%rip),%r8 + + kxnorw $k11111,$k11111,$k11111 + kshiftrw \$15,$k11111,$k00001 + kshiftrw \$11,$k11111,$k11111 + kshiftlw \$1,$k00001,$k00010 + kshiftlw \$2,$k00001,$k00100 + kshiftlw \$3,$k00001,$k01000 + kshiftlw \$4,$k00001,$k10000 + + #vmovdqa64 64*0(%r8),@Theta[0] + vmovdqa64 64*1(%r8),@Theta[1] + vmovdqa64 64*2(%r8),@Theta[2] + vmovdqa64 64*3(%r8),@Theta[3] + vmovdqa64 64*4(%r8),@Theta[4] + + vmovdqa64 64*5(%r8),@Rhotate1[0] + vmovdqa64 64*6(%r8),@Rhotate1[1] + vmovdqa64 64*7(%r8),@Rhotate1[2] + vmovdqa64 64*8(%r8),@Rhotate1[3] + vmovdqa64 64*9(%r8),@Rhotate1[4] + + vmovdqa64 64*10(%r8),@Rhotate0[0] + vmovdqa64 64*11(%r8),@Rhotate0[1] + vmovdqa64 64*12(%r8),@Rhotate0[2] + vmovdqa64 64*13(%r8),@Rhotate0[3] + vmovdqa64 64*14(%r8),@Rhotate0[4] + + vmovdqa64 64*15(%r8),@Pi0[0] + vmovdqa64 64*16(%r8),@Pi0[1] + vmovdqa64 64*17(%r8),@Pi0[2] + vmovdqa64 64*18(%r8),@Pi0[3] + vmovdqa64 64*19(%r8),@Pi0[4] + + vmovdqu64 40*0-96($A_flat),${A00}{$k11111}{z} + vpxorq @T[0],@T[0],@T[0] + vmovdqu64 40*1-96($A_flat),${A10}{$k11111}{z} + vmovdqu64 40*2-96($A_flat),${A20}{$k11111}{z} + vmovdqu64 40*3-96($A_flat),${A30}{$k11111}{z} + vmovdqu64 40*4-96($A_flat),${A40}{$k11111}{z} + + vmovdqa64 @T[0],0*64-128(%r9) # zero transfer area on stack + vmovdqa64 @T[0],1*64-128(%r9) + vmovdqa64 @T[0],2*64-128(%r9) + vmovdqa64 @T[0],3*64-128(%r9) + vmovdqa64 @T[0],4*64-128(%r9) + jmp .Loop_absorb_avx512 + +.align 32 +.Loop_absorb_avx512: + mov $bsz,%rax + sub $bsz,$len + jc .Ldone_absorb_avx512 + + shr \$3,%eax +___ +for(my $i=0; $i<25; $i++) { +$code.=<<___ + mov 8*$i-96($inp),%r8 + mov %r8,$A_jagged[$i]-128(%r9) + dec %eax + jz .Labsorved_avx512 +___ +} +$code.=<<___; +.Labsorved_avx512: + lea ($inp,$bsz),$inp + + vpxorq 64*0-128(%r9),$A00,$A00 + vpxorq 64*1-128(%r9),$A10,$A10 + vpxorq 64*2-128(%r9),$A20,$A20 + vpxorq 64*3-128(%r9),$A30,$A30 + vpxorq 64*4-128(%r9),$A40,$A40 + + call __KeccakF1600 + + jmp .Loop_absorb_avx512 + +.align 32 +.Ldone_absorb_avx512: + vmovdqu64 $A00,40*0-96($A_flat){$k11111} + vmovdqu64 $A10,40*1-96($A_flat){$k11111} + vmovdqu64 $A20,40*2-96($A_flat){$k11111} + vmovdqu64 $A30,40*3-96($A_flat){$k11111} + vmovdqu64 $A40,40*4-96($A_flat){$k11111} + + vzeroupper + + lea (%r11),%rsp + lea ($len,$bsz),%rax # return value + ret +.size SHA3_absorb,.-SHA3_absorb + +.globl SHA3_squeeze +.type SHA3_squeeze,\@function +.align 32 +SHA3_squeeze: + mov %rsp,%r11 + + lea 96($A_flat),$A_flat + cmp $bsz,$len + jbe .Lno_output_extension_avx512 + + lea theta_perm(%rip),%r8 + + kxnorw $k11111,$k11111,$k11111 + kshiftrw \$15,$k11111,$k00001 + kshiftrw \$11,$k11111,$k11111 + kshiftlw \$1,$k00001,$k00010 + kshiftlw \$2,$k00001,$k00100 + kshiftlw \$3,$k00001,$k01000 + kshiftlw \$4,$k00001,$k10000 + + #vmovdqa64 64*0(%r8),@Theta[0] + vmovdqa64 64*1(%r8),@Theta[1] + vmovdqa64 64*2(%r8),@Theta[2] + vmovdqa64 64*3(%r8),@Theta[3] + vmovdqa64 64*4(%r8),@Theta[4] + + vmovdqa64 64*5(%r8),@Rhotate1[0] + vmovdqa64 64*6(%r8),@Rhotate1[1] + vmovdqa64 64*7(%r8),@Rhotate1[2] + vmovdqa64 64*8(%r8),@Rhotate1[3] + vmovdqa64 64*9(%r8),@Rhotate1[4] + + vmovdqa64 64*10(%r8),@Rhotate0[0] + vmovdqa64 64*11(%r8),@Rhotate0[1] + vmovdqa64 64*12(%r8),@Rhotate0[2] + vmovdqa64 64*13(%r8),@Rhotate0[3] + vmovdqa64 64*14(%r8),@Rhotate0[4] + + vmovdqa64 64*15(%r8),@Pi0[0] + vmovdqa64 64*16(%r8),@Pi0[1] + vmovdqa64 64*17(%r8),@Pi0[2] + vmovdqa64 64*18(%r8),@Pi0[3] + vmovdqa64 64*19(%r8),@Pi0[4] + + vmovdqu64 40*0-96($A_flat),${A00}{$k11111}{z} + vmovdqu64 40*1-96($A_flat),${A10}{$k11111}{z} + vmovdqu64 40*2-96($A_flat),${A20}{$k11111}{z} + vmovdqu64 40*3-96($A_flat),${A30}{$k11111}{z} + vmovdqu64 40*4-96($A_flat),${A40}{$k11111}{z} + +.Lno_output_extension_avx512: + shr \$3,$bsz + lea -96($A_flat),%r9 + mov $bsz,%rax + jmp .Loop_squeeze_avx512 + +.align 32 +.Loop_squeeze_avx512: + cmp \$8,$len + jb .Ltail_squeeze_avx512 + + mov (%r9),%r8 + lea 8(%r9),%r9 + mov %r8,($out) + lea 8($out),$out + sub \$8,$len # len -= 8 + jz .Ldone_squeeze_avx512 + + sub \$1,%rax # bsz-- + jnz .Loop_squeeze_avx512 + + #vpermq @Theta[4],@Theta[4],@Theta[3] + #vpermq @Theta[3],@Theta[4],@Theta[2] + #vpermq @Theta[3],@Theta[3],@Theta[1] + + call __KeccakF1600 + + vmovdqu64 $A00,40*0-96($A_flat){$k11111} + vmovdqu64 $A10,40*1-96($A_flat){$k11111} + vmovdqu64 $A20,40*2-96($A_flat){$k11111} + vmovdqu64 $A30,40*3-96($A_flat){$k11111} + vmovdqu64 $A40,40*4-96($A_flat){$k11111} + + lea -96($A_flat),%r9 + mov $bsz,%rax + jmp .Loop_squeeze_avx512 + +.Ltail_squeeze_avx512: + mov $out,%rdi + mov %r9,%rsi + mov $len,%rcx + .byte 0xf3,0xa4 # rep movsb + +.Ldone_squeeze_avx512: + vzeroupper + + lea (%r11),%rsp + ret +.size SHA3_squeeze,.-SHA3_squeeze + +.align 64 +theta_perm: + .quad 0, 1, 2, 3, 4, 5, 6, 7 # [not used] + .quad 4, 0, 1, 2, 3, 5, 6, 7 + .quad 3, 4, 0, 1, 2, 5, 6, 7 + .quad 2, 3, 4, 0, 1, 5, 6, 7 + .quad 1, 2, 3, 4, 0, 5, 6, 7 + +rhotates1: + .quad 0, 44, 43, 21, 14, 0, 0, 0 # [0][0] [1][1] [2][2] [3][3] [4][4] + .quad 18, 1, 6, 25, 8, 0, 0, 0 # [4][0] [0][1] [1][2] [2][3] [3][4] + .quad 41, 2, 62, 55, 39, 0, 0, 0 # [3][0] [4][1] [0][2] [1][3] [2][4] + .quad 3, 45, 61, 28, 20, 0, 0, 0 # [2][0] [3][1] [4][2] [0][3] [1][4] + .quad 36, 10, 15, 56, 27, 0, 0, 0 # [1][0] [2][1] [3][2] [4][3] [0][4] + +rhotates0: + .quad 0, 1, 62, 28, 27, 0, 0, 0 + .quad 36, 44, 6, 55, 20, 0, 0, 0 + .quad 3, 10, 43, 25, 39, 0, 0, 0 + .quad 41, 45, 15, 21, 8, 0, 0, 0 + .quad 18, 2, 61, 56, 14, 0, 0, 0 + +pi0_perm: + .quad 0, 3, 1, 4, 2, 5, 6, 7 + .quad 1, 4, 2, 0, 3, 5, 6, 7 + .quad 2, 0, 3, 1, 4, 5, 6, 7 + .quad 3, 1, 4, 2, 0, 5, 6, 7 + .quad 4, 2, 0, 3, 1, 5, 6, 7 + + +iotas: + .quad 0x0000000000000001 + .quad 0x0000000000008082 + .quad 0x800000000000808a + .quad 0x8000000080008000 + .quad 0x000000000000808b + .quad 0x0000000080000001 + .quad 0x8000000080008081 + .quad 0x8000000000008009 + .quad 0x000000000000008a + .quad 0x0000000000000088 + .quad 0x0000000080008009 + .quad 0x000000008000000a + .quad 0x000000008000808b + .quad 0x800000000000008b + .quad 0x8000000000008089 + .quad 0x8000000000008003 + .quad 0x8000000000008002 + .quad 0x8000000000000080 + .quad 0x000000000000800a + .quad 0x800000008000000a + .quad 0x8000000080008081 + .quad 0x8000000000008080 + .quad 0x0000000080000001 + .quad 0x8000000080008008 + +.asciz "Keccak-1600 absorb and squeeze for AVX-512F, CRYPTOGAMS by " +___ + +print $code; +close STDOUT; diff --git a/crypto/sha/asm/keccak1600-avx512vl.pl b/crypto/sha/asm/keccak1600-avx512vl.pl new file mode 100755 index 00000000..53f1e847 --- /dev/null +++ b/crypto/sha/asm/keccak1600-avx512vl.pl @@ -0,0 +1,390 @@ +#!/usr/bin/env perl +# 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# Keccak-1600 for AVX512VL. +# +# December 2017. +# +# This is an adaptation of AVX2 module that reuses register data +# layout, but utilizes new 256-bit AVX512VL instructions. See AVX2 +# module for further information on layout. +# +######################################################################## +# Numbers are cycles per processed byte out of large message. +# +# r=1088(*) +# +# Skylake-X 6.4/+47% +# +# (*) Corresponds to SHA3-256. Percentage after slash is improvement +# coefficient in comparison to scalar keccak1600-x86_64.pl. + +# Digits in variables' names denote right-most coordinates: + +my ($A00, # [0][0] [0][0] [0][0] [0][0] # %ymm0 + $A01, # [0][4] [0][3] [0][2] [0][1] # %ymm1 + $A20, # [3][0] [1][0] [4][0] [2][0] # %ymm2 + $A31, # [2][4] [4][3] [1][2] [3][1] # %ymm3 + $A21, # [3][4] [1][3] [4][2] [2][1] # %ymm4 + $A41, # [1][4] [2][3] [3][2] [4][1] # %ymm5 + $A11) = # [4][4] [3][3] [2][2] [1][1] # %ymm6 + map("%ymm$_",(0..6)); + +# We also need to map the magic order into offsets within structure: + +my @A_jagged = ([0,0], [1,0], [1,1], [1,2], [1,3], # [0][0..4] + [2,2], [6,0], [3,1], [4,2], [5,3], # [1][0..4] + [2,0], [4,0], [6,1], [5,2], [3,3], # [2][0..4] + [2,3], [3,0], [5,1], [6,2], [4,3], # [3][0..4] + [2,1], [5,0], [4,1], [3,2], [6,3]); # [4][0..4] + @A_jagged = map(8*($$_[0]*4+$$_[1]), @A_jagged); # ... and now linear + +my @T = map("%ymm$_",(7..15)); +my ($C14,$C00,$D00,$D14) = @T[5..8]; +my ($R20,$R01,$R31,$R21,$R41,$R11) = map("%ymm$_",(16..21)); + +$code.=<<___; +.text + +.type __KeccakF1600,\@function +.align 32 +__KeccakF1600: + lea iotas(%rip),%r10 + mov \$24,%eax + jmp .Loop_avx512vl + +.align 32 +.Loop_avx512vl: + ######################################### Theta + vpshufd \$0b01001110,$A20,$C00 + vpxor $A31,$A41,$C14 + vpxor $A11,$A21,@T[2] + vpternlogq \$0x96,$A01,$T[2],$C14 # C[1..4] + + vpxor $A20,$C00,$C00 + vpermq \$0b01001110,$C00,@T[0] + + vpermq \$0b10010011,$C14,@T[4] + vprolq \$1,$C14,@T[1] # ROL64(C[1..4],1) + + vpermq \$0b00111001,@T[1],$D14 + vpxor @T[4],@T[1],$D00 + vpermq \$0b00000000,$D00,$D00 # D[0..0] = ROL64(C[1],1) ^ C[4] + + vpternlogq \$0x96,@T[0],$A00,$C00 # C[0..0] + vprolq \$1,$C00,@T[1] # ROL64(C[0..0],1) + + vpxor $D00,$A00,$A00 # ^= D[0..0] + + vpblendd \$0b11000000,@T[1],$D14,$D14 + vpblendd \$0b00000011,$C00,@T[4],@T[0] + + ######################################### Rho + Pi + pre-Chi shuffle + vpxor $D00,$A20,$A20 # ^= D[0..0] from Theta + vprolvq $R20,$A20,$A20 + + vpternlogq \$0x96,@T[0],$D14,$A31 # ^= D[1..4] from Theta + vprolvq $R31,$A31,$A31 + + vpternlogq \$0x96,@T[0],$D14,$A21 # ^= D[1..4] from Theta + vprolvq $R21,$A21,$A21 + + vpternlogq \$0x96,@T[0],$D14,$A41 # ^= D[1..4] from Theta + vprolvq $R41,$A41,$A41 + + vpermq \$0b10001101,$A20,@T[3] # $A20 -> future $A31 + vpermq \$0b10001101,$A31,@T[4] # $A31 -> future $A21 + vpternlogq \$0x96,@T[0],$D14,$A11 # ^= D[1..4] from Theta + vprolvq $R11,$A11,@T[1] # $A11 -> future $A01 + + vpermq \$0b00011011,$A21,@T[5] # $A21 -> future $A41 + vpermq \$0b01110010,$A41,@T[6] # $A41 -> future $A11 + vpternlogq \$0x96,@T[0],$D14,$A01 # ^= D[1..4] from Theta + vprolvq $R01,$A01,@T[2] # $A01 -> future $A20 + + ######################################### Chi + vpblendd \$0b00001100,@T[6],@T[2],$A31 # [4][4] [2][0] + vpblendd \$0b00001100,@T[2],@T[4],@T[8] # [4][0] [2][1] + vpblendd \$0b00001100,@T[4],@T[3],$A41 # [4][2] [2][4] + vpblendd \$0b00001100,@T[3],@T[2],@T[7] # [4][3] [2][0] + vpblendd \$0b00110000,@T[4],$A31,$A31 # [1][3] [4][4] [2][0] + vpblendd \$0b00110000,@T[5],@T[8],@T[8] # [1][4] [4][0] [2][1] + vpblendd \$0b00110000,@T[2],$A41,$A41 # [1][0] [4][2] [2][4] + vpblendd \$0b00110000,@T[6],@T[7],@T[7] # [1][1] [4][3] [2][0] + vpblendd \$0b11000000,@T[5],$A31,$A31 # [3][2] [1][3] [4][4] [2][0] + vpblendd \$0b11000000,@T[6],@T[8],@T[8] # [3][3] [1][4] [4][0] [2][1] + vpblendd \$0b11000000,@T[6],$A41,$A41 # [3][3] [1][0] [4][2] [2][4] + vpblendd \$0b11000000,@T[4],@T[7],@T[7] # [3][4] [1][1] [4][3] [2][0] + vpternlogq \$0xC6,@T[8],@T[3],$A31 # [3][1] [1][2] [4][3] [2][4] + vpternlogq \$0xC6,@T[7],@T[5],$A41 # [3][2] [1][4] [4][1] [2][3] + + vpsrldq \$8,@T[1],@T[0] + vpandn @T[0],@T[1],@T[0] # tgting [0][0] [0][0] [0][0] [0][0] + + vpblendd \$0b00001100,@T[2],@T[5],$A11 # [4][0] [2][3] + vpblendd \$0b00001100,@T[5],@T[3],@T[8] # [4][1] [2][4] + vpblendd \$0b00110000,@T[3],$A11,$A11 # [1][2] [4][0] [2][3] + vpblendd \$0b00110000,@T[4],@T[8],@T[8] # [1][3] [4][1] [2][4] + vpblendd \$0b11000000,@T[4],$A11,$A11 # [3][4] [1][2] [4][0] [2][3] + vpblendd \$0b11000000,@T[2],@T[8],@T[8] # [3][0] [1][3] [4][1] [2][4] + vpternlogq \$0xC6,@T[8],@T[6],$A11 # [3][3] [1][1] [4][4] [2][2] + + vpermq \$0b00011110,@T[1],$A21 # [0][1] [0][2] [0][4] [0][3] + vpblendd \$0b00110000,$A00,$A21,@T[8] # [0][1] [0][0] [0][4] [0][3] + vpermq \$0b00111001,@T[1],$A01 # [0][1] [0][4] [0][3] [0][2] + vpblendd \$0b11000000,$A00,$A01,$A01 # [0][0] [0][4] [0][3] [0][2] + + vpblendd \$0b00001100,@T[5],@T[4],$A20 # [4][1] [2][1] + vpblendd \$0b00001100,@T[4],@T[6],@T[7] # [4][2] [2][2] + vpblendd \$0b00110000,@T[6],$A20,$A20 # [1][1] [4][1] [2][1] + vpblendd \$0b00110000,@T[3],@T[7],@T[7] # [1][2] [4][2] [2][2] + vpblendd \$0b11000000,@T[3],$A20,$A20 # [3][1] [1][1] [4][1] [2][1] + vpblendd \$0b11000000,@T[5],@T[7],@T[7] # [3][2] [1][2] [4][2] [2][2] + vpternlogq \$0xC6,@T[7],@T[2],$A20 # [3][0] [1][0] [4][0] [2][0] + + vpermq \$0b00000000,@T[0],@T[0] # [0][0] [0][0] [0][0] [0][0] + vpermq \$0b00011011,$A31,$A31 # post-Chi shuffle + vpermq \$0b10001101,$A41,$A41 + vpermq \$0b01110010,$A11,$A11 + + vpblendd \$0b00001100,@T[3],@T[6],$A21 # [4][3] [2][2] + vpblendd \$0b00001100,@T[6],@T[5],@T[7] # [4][4] [2][3] + vpblendd \$0b00110000,@T[5],$A21,$A21 # [1][4] [4][3] [2][2] + vpblendd \$0b00110000,@T[2],@T[7],@T[7] # [1][0] [4][4] [2][3] + vpblendd \$0b11000000,@T[2],$A21,$A21 # [3][0] [1][4] [4][3] [2][2] + vpblendd \$0b11000000,@T[3],@T[7],@T[7] # [3][1] [1][0] [4][4] [2][3] + + vpternlogq \$0xC6,@T[8],@T[1],$A01 # [0][4] [0][3] [0][2] [0][1] + vpternlogq \$0xC6,@T[7],@T[4],$A21 # [3][4] [1][3] [4][2] [2][1] + + ######################################### Iota + vpternlogq \$0x96,(%r10),@T[0],$A00 + lea 32(%r10),%r10 + + dec %eax + jnz .Loop_avx512vl + + ret +.size __KeccakF1600,.-__KeccakF1600 +___ +my ($A_flat,$inp,$len,$bsz) = ("%rdi","%rsi","%rdx","%rcx"); +my $out = $inp; # in squeeze + +$code.=<<___; +.globl SHA3_absorb +.type SHA3_absorb,\@function +.align 32 +SHA3_absorb: + mov %rsp,%r11 + + lea -240(%rsp),%rsp + and \$-32,%rsp + + lea 96($A_flat),$A_flat + lea 96($inp),$inp + lea 96(%rsp),%r10 + lea rhotates_left(%rip),%r8 + + vzeroupper + + vpbroadcastq -96($A_flat),$A00 # load A[5][5] + vmovdqu 8+32*0-96($A_flat),$A01 + vmovdqu 8+32*1-96($A_flat),$A20 + vmovdqu 8+32*2-96($A_flat),$A31 + vmovdqu 8+32*3-96($A_flat),$A21 + vmovdqu 8+32*4-96($A_flat),$A41 + vmovdqu 8+32*5-96($A_flat),$A11 + + vmovdqa64 0*32(%r8),$R20 # load "rhotate" indices + vmovdqa64 1*32(%r8),$R01 + vmovdqa64 2*32(%r8),$R31 + vmovdqa64 3*32(%r8),$R21 + vmovdqa64 4*32(%r8),$R41 + vmovdqa64 5*32(%r8),$R11 + + vpxor @T[0],@T[0],@T[0] + vmovdqa @T[0],32*2-96(%r10) # zero transfer area on stack + vmovdqa @T[0],32*3-96(%r10) + vmovdqa @T[0],32*4-96(%r10) + vmovdqa @T[0],32*5-96(%r10) + vmovdqa @T[0],32*6-96(%r10) + +.Loop_absorb_avx512vl: + mov $bsz,%rax + sub $bsz,$len + jc .Ldone_absorb_avx512vl + + shr \$3,%eax + vpbroadcastq 0-96($inp),@T[0] + vmovdqu 8-96($inp),@T[1] + sub \$4,%eax +___ +for(my $i=5; $i<25; $i++) { +$code.=<<___ + dec %eax + jz .Labsorved_avx512vl + mov 8*$i-96($inp),%r8 + mov %r8,$A_jagged[$i]-96(%r10) +___ +} +$code.=<<___; +.Labsorved_avx512vl: + lea ($inp,$bsz),$inp + + vpxor @T[0],$A00,$A00 + vpxor @T[1],$A01,$A01 + vpxor 32*2-96(%r10),$A20,$A20 + vpxor 32*3-96(%r10),$A31,$A31 + vpxor 32*4-96(%r10),$A21,$A21 + vpxor 32*5-96(%r10),$A41,$A41 + vpxor 32*6-96(%r10),$A11,$A11 + + call __KeccakF1600 + + lea 96(%rsp),%r10 + jmp .Loop_absorb_avx512vl + +.Ldone_absorb_avx512vl: + vmovq %xmm0,-96($A_flat) + vmovdqu $A01,8+32*0-96($A_flat) + vmovdqu $A20,8+32*1-96($A_flat) + vmovdqu $A31,8+32*2-96($A_flat) + vmovdqu $A21,8+32*3-96($A_flat) + vmovdqu $A41,8+32*4-96($A_flat) + vmovdqu $A11,8+32*5-96($A_flat) + + vzeroupper + + lea (%r11),%rsp + lea ($len,$bsz),%rax # return value + ret +.size SHA3_absorb,.-SHA3_absorb + +.globl SHA3_squeeze +.type SHA3_squeeze,\@function +.align 32 +SHA3_squeeze: + mov %rsp,%r11 + + lea 96($A_flat),$A_flat + lea rhotates_left(%rip),%r8 + shr \$3,$bsz + + vzeroupper + + vpbroadcastq -96($A_flat),$A00 + vpxor @T[0],@T[0],@T[0] + vmovdqu 8+32*0-96($A_flat),$A01 + vmovdqu 8+32*1-96($A_flat),$A20 + vmovdqu 8+32*2-96($A_flat),$A31 + vmovdqu 8+32*3-96($A_flat),$A21 + vmovdqu 8+32*4-96($A_flat),$A41 + vmovdqu 8+32*5-96($A_flat),$A11 + + vmovdqa64 0*32(%r8),$R20 # load "rhotate" indices + vmovdqa64 1*32(%r8),$R01 + vmovdqa64 2*32(%r8),$R31 + vmovdqa64 3*32(%r8),$R21 + vmovdqa64 4*32(%r8),$R41 + vmovdqa64 5*32(%r8),$R11 + + mov $bsz,%rax + +.Loop_squeeze_avx512vl: + mov @A_jagged[$i]-96($A_flat),%r8 +___ +for (my $i=0; $i<25; $i++) { +$code.=<<___; + sub \$8,$len + jc .Ltail_squeeze_avx512vl + mov %r8,($out) + lea 8($out),$out + je .Ldone_squeeze_avx512vl + dec %eax + je .Lextend_output_avx512vl + mov @A_jagged[$i+1]-120($A_flat),%r8 +___ +} +$code.=<<___; +.Lextend_output_avx512vl: + call __KeccakF1600 + + vmovq %xmm0,-96($A_flat) + vmovdqu $A01,8+32*0-96($A_flat) + vmovdqu $A20,8+32*1-96($A_flat) + vmovdqu $A31,8+32*2-96($A_flat) + vmovdqu $A21,8+32*3-96($A_flat) + vmovdqu $A41,8+32*4-96($A_flat) + vmovdqu $A11,8+32*5-96($A_flat) + + mov $bsz,%rax + jmp .Loop_squeeze_avx512vl + + +.Ltail_squeeze_avx512vl: + add \$8,$len +.Loop_tail_avx512vl: + mov %r8b,($out) + lea 1($out),$out + shr \$8,%r8 + dec $len + jnz .Loop_tail_avx512vl + +.Ldone_squeeze_avx512vl: + vzeroupper + + lea (%r11),%rsp + ret +.size SHA3_squeeze,.-SHA3_squeeze + +.align 64 +rhotates_left: + .quad 3, 18, 36, 41 # [2][0] [4][0] [1][0] [3][0] + .quad 1, 62, 28, 27 # [0][1] [0][2] [0][3] [0][4] + .quad 45, 6, 56, 39 # [3][1] [1][2] [4][3] [2][4] + .quad 10, 61, 55, 8 # [2][1] [4][2] [1][3] [3][4] + .quad 2, 15, 25, 20 # [4][1] [3][2] [2][3] [1][4] + .quad 44, 43, 21, 14 # [1][1] [2][2] [3][3] [4][4] +iotas: + .quad 0x0000000000000001, 0x0000000000000001, 0x0000000000000001, 0x0000000000000001 + .quad 0x0000000000008082, 0x0000000000008082, 0x0000000000008082, 0x0000000000008082 + .quad 0x800000000000808a, 0x800000000000808a, 0x800000000000808a, 0x800000000000808a + .quad 0x8000000080008000, 0x8000000080008000, 0x8000000080008000, 0x8000000080008000 + .quad 0x000000000000808b, 0x000000000000808b, 0x000000000000808b, 0x000000000000808b + .quad 0x0000000080000001, 0x0000000080000001, 0x0000000080000001, 0x0000000080000001 + .quad 0x8000000080008081, 0x8000000080008081, 0x8000000080008081, 0x8000000080008081 + .quad 0x8000000000008009, 0x8000000000008009, 0x8000000000008009, 0x8000000000008009 + .quad 0x000000000000008a, 0x000000000000008a, 0x000000000000008a, 0x000000000000008a + .quad 0x0000000000000088, 0x0000000000000088, 0x0000000000000088, 0x0000000000000088 + .quad 0x0000000080008009, 0x0000000080008009, 0x0000000080008009, 0x0000000080008009 + .quad 0x000000008000000a, 0x000000008000000a, 0x000000008000000a, 0x000000008000000a + .quad 0x000000008000808b, 0x000000008000808b, 0x000000008000808b, 0x000000008000808b + .quad 0x800000000000008b, 0x800000000000008b, 0x800000000000008b, 0x800000000000008b + .quad 0x8000000000008089, 0x8000000000008089, 0x8000000000008089, 0x8000000000008089 + .quad 0x8000000000008003, 0x8000000000008003, 0x8000000000008003, 0x8000000000008003 + .quad 0x8000000000008002, 0x8000000000008002, 0x8000000000008002, 0x8000000000008002 + .quad 0x8000000000000080, 0x8000000000000080, 0x8000000000000080, 0x8000000000000080 + .quad 0x000000000000800a, 0x000000000000800a, 0x000000000000800a, 0x000000000000800a + .quad 0x800000008000000a, 0x800000008000000a, 0x800000008000000a, 0x800000008000000a + .quad 0x8000000080008081, 0x8000000080008081, 0x8000000080008081, 0x8000000080008081 + .quad 0x8000000000008080, 0x8000000000008080, 0x8000000000008080, 0x8000000000008080 + .quad 0x0000000080000001, 0x0000000080000001, 0x0000000080000001, 0x0000000080000001 + .quad 0x8000000080008008, 0x8000000080008008, 0x8000000080008008, 0x8000000080008008 + +.asciz "Keccak-1600 absorb and squeeze for AVX512VL, CRYPTOGAMS by " +___ + +print $code; +close STDOUT; diff --git a/crypto/sha/asm/keccak1600-c64x.pl b/crypto/sha/asm/keccak1600-c64x.pl new file mode 100755 index 00000000..585f64b7 --- /dev/null +++ b/crypto/sha/asm/keccak1600-c64x.pl @@ -0,0 +1,882 @@ +#!/usr/bin/env perl +# 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# [ABI- and endian-neutral] Keccak-1600 for C64x. +# +# June 2017. +# +# This is straightforward KECCAK_1X_ALT variant (see sha/keccak1600.c) +# with bit interleaving. 64-bit values are simply split between A- and +# B-files, with A-file holding least significant halves. This works +# out perfectly, because all operations including cross-communications +# [in rotate operations] are always complementary. Performance is +# [incredible for a 32-bit processor] 10.9 cycles per processed byte +# for r=1088, which corresponds to SHA3-256. This is >15x faster than +# compiler-generated KECCAK_1X_ALT code, and >10x than other variants. +# On average processor ends up issuing ~4.5 instructions per cycle... + +my @A = map([ $_, ($_+1), ($_+2), ($_+3), ($_+4) ], (5,10,16,21,26)); + $A[1][4] = 31; # B14 is reserved, A14 is used as iota[] + ($A[3][0],$A[4][1]) = ($A[4][1],$A[3][0]); +my @C = (0..4,$A[3][0],$A[4][0]); +my $iotas = "A14"; + +my @rhotates = ([ 0, 1, 62, 28, 27 ], + [ 36, 44, 6, 55, 20 ], + [ 3, 10, 43, 25, 39 ], + [ 41, 45, 15, 21, 8 ], + [ 18, 2, 61, 56, 14 ]); + +sub ROL64 { + my ($src,$rot,$dst,$p) = @_; + + if ($rot&1) { +$code.=<<___; +$p ROTL B$src,$rot/2+1,A$dst +|| ROTL A$src,$rot/2, B$dst +___ + } else { +$code.=<<___; +$p ROTL A$src,$rot/2,A$dst +|| ROTL B$src,$rot/2,B$dst +___ + } +} + +######################################################################## +# Stack frame layout +# +# SP--->+------+------+ +# | | | +# +1--->+------+------+<- -9 below 4 slots are used by KeccakF1600_int +# | | | +# +2--->+------+------+<- -8 +# | | | +# +3--->+------+------+<- -7 +# | A2 | A3 | A3:A2 are preserved by KeccakF1600_int +# +4--->+------+------+<- -6 +# | B2 | B3 | B3:B2 are preserved by KeccakF1600_int +# +5--->+------+------+<- -5 below is ABI-compliant layout +# | A10 | A11 | +# +6--->+------+------+<- -4 +# | A12 | A13 | +# +7--->+------+------+<- -3 +# | A14 | B3 | +# +8--->+------+------+<- -2 +# | B10 | B11 | +# +9--->+------+------+<- -1 +# | B12 | B13 | +# +------+------+<---FP +# | A15 | +# +------+-- + +$code.=<<___; + .text + + .if .ASSEMBLER_VERSION<7000000 + .asg 0,__TI_EABI__ + .endif + .if __TI_EABI__ + .nocmp + .asg KeccakF1600,_KeccakF1600 + .asg SHA3_absorb,_SHA3_absorb + .asg SHA3_squeeze,_SHA3_squeeze + .endif + + .asg B3,RA + .asg A15,FP + .asg B15,SP + + .align 32 +_KeccakF1600_int: + .asmfunc + STDW A3:A2,*FP[-7] +|| STDW B3:B2,*SP[4] +_KeccakF1600_cheat: + .if __TI_EABI__ + ADDKPC _KeccakF1600_int,B0 +|| MVKL \$PCR_OFFSET(iotas,_KeccakF1600_int),$iotas + MVKH \$PCR_OFFSET(iotas,_KeccakF1600_int),$iotas + .else + ADDKPC _KeccakF1600_int,B0 +|| MVKL (iotas-_KeccakF1600_int),$iotas + MVKH (iotas-_KeccakF1600_int),$iotas + .endif + ADD B0,$iotas,$iotas +loop?: + XOR A$A[0][2],A$A[1][2],A$C[2] ; Theta +|| XOR B$A[0][2],B$A[1][2],B$C[2] +|| XOR A$A[0][3],A$A[1][3],A$C[3] +|| XOR B$A[0][3],B$A[1][3],B$C[3] +|| XOR A$A[0][0],A$A[1][0],A$C[0] +|| XOR B$A[0][0],B$A[1][0],B$C[0] + XOR A$A[2][2],A$C[2],A$C[2] +|| XOR B$A[2][2],B$C[2],B$C[2] +|| XOR A$A[2][3],A$C[3],A$C[3] +|| XOR B$A[2][3],B$C[3],B$C[3] +|| XOR A$A[2][0],A$C[0],A$C[0] +|| XOR B$A[2][0],B$C[0],B$C[0] + XOR A$A[3][2],A$C[2],A$C[2] +|| XOR B$A[3][2],B$C[2],B$C[2] +|| XOR A$A[3][3],A$C[3],A$C[3] +|| XOR B$A[3][3],B$C[3],B$C[3] +|| XOR A$A[3][0],A$C[0],A$C[0] +|| XOR B$A[3][0],B$C[0],B$C[0] + XOR A$A[4][2],A$C[2],A$C[2] +|| XOR B$A[4][2],B$C[2],B$C[2] +|| XOR A$A[4][3],A$C[3],A$C[3] +|| XOR B$A[4][3],B$C[3],B$C[3] +|| XOR A$A[4][0],A$C[0],A$C[0] +|| XOR B$A[4][0],B$C[0],B$C[0] + XOR A$A[0][4],A$A[1][4],A$C[4] +|| XOR B$A[0][4],B$A[1][4],B$C[4] +|| XOR A$A[0][1],A$A[1][1],A$C[1] +|| XOR B$A[0][1],B$A[1][1],B$C[1] +|| STDW A$A[3][0]:A$A[4][0],*SP[1] ; offload some data + STDW B$A[3][0]:B$A[4][0],*SP[2] +|| XOR A$A[2][4],A$C[4],A$C[4] +|| XOR B$A[2][4],B$C[4],B$C[4] +|| XOR A$A[2][1],A$C[1],A$C[1] +|| XOR B$A[2][1],B$C[1],B$C[1] +|| ROTL B$C[2],1,A$C[5] ; ROL64(C[2],1) +|| ROTL A$C[2],0,B$C[5] + XOR A$A[3][4],A$C[4],A$C[4] +|| XOR B$A[3][4],B$C[4],B$C[4] +|| XOR A$A[3][1],A$C[1],A$C[1] +|| XOR B$A[3][1],B$C[1],B$C[1] +|| ROTL B$C[3],1,A$C[6] ; ROL64(C[3],1) +|| ROTL A$C[3],0,B$C[6] + XOR A$A[4][4],A$C[4],A$C[4] +|| XOR B$A[4][4],B$C[4],B$C[4] +|| XOR A$A[4][1],A$C[1],A$C[1] +|| XOR B$A[4][1],B$C[1],B$C[1] +|| XOR A$C[0],A$C[5],A$C[5] ; C[0] ^ ROL64(C[2],1) +|| XOR B$C[0],B$C[5],B$C[5] + XOR A$C[5],A$A[0][1],A$A[0][1] +|| XOR B$C[5],B$A[0][1],B$A[0][1] +|| XOR A$C[5],A$A[1][1],A$A[1][1] +|| XOR B$C[5],B$A[1][1],B$A[1][1] +|| XOR A$C[5],A$A[2][1],A$A[2][1] +|| XOR B$C[5],B$A[2][1],B$A[2][1] + XOR A$C[5],A$A[3][1],A$A[3][1] +|| XOR B$C[5],B$A[3][1],B$A[3][1] +|| XOR A$C[5],A$A[4][1],A$A[4][1] +|| XOR B$C[5],B$A[4][1],B$A[4][1] +|| ROTL B$C[4],1,A$C[5] ; ROL64(C[4],1) +|| ROTL A$C[4],0,B$C[5] +|| XOR A$C[1],A$C[6],A$C[6] ; C[1] ^ ROL64(C[3],1) +|| XOR B$C[1],B$C[6],B$C[6] + XOR A$C[6],A$A[0][2],A$A[0][2] +|| XOR B$C[6],B$A[0][2],B$A[0][2] +|| XOR A$C[6],A$A[1][2],A$A[1][2] +|| XOR B$C[6],B$A[1][2],B$A[1][2] +|| XOR A$C[6],A$A[2][2],A$A[2][2] +|| XOR B$C[6],B$A[2][2],B$A[2][2] +|| ROTL B$C[1],1,A$C[1] ; ROL64(C[1],1) +|| ROTL A$C[1],0,B$C[1] + XOR A$C[6],A$A[3][2],A$A[3][2] +|| XOR B$C[6],B$A[3][2],B$A[3][2] +|| XOR A$C[6],A$A[4][2],A$A[4][2] +|| XOR B$C[6],B$A[4][2],B$A[4][2] +|| ROTL B$C[0],1,A$C[6] ; ROL64(C[0],1) +|| ROTL A$C[0],0,B$C[6] +|| XOR A$C[5],A$C[2],A$C[2] ; C[2] ^= ROL64(C[4],1) +|| XOR B$C[5],B$C[2],B$C[2] + XOR A$C[2],A$A[0][3],A$A[0][3] +|| XOR B$C[2],B$A[0][3],B$A[0][3] +|| XOR A$C[2],A$A[1][3],A$A[1][3] +|| XOR B$C[2],B$A[1][3],B$A[1][3] +|| XOR A$C[2],A$A[2][3],A$A[2][3] +|| XOR B$C[2],B$A[2][3],B$A[2][3] + XOR A$C[6],A$C[3],A$C[3] ; C[3] ^= ROL64(C[0],1) +|| XOR B$C[6],B$C[3],B$C[3] +|| LDDW *FP[-9],A$A[3][0]:A$A[4][0] ; restore offloaded data +|| LDDW *SP[2],B$A[3][0]:B$A[4][0] +|| XOR A$C[2],A$A[3][3],A$A[3][3] +|| XOR B$C[2],B$A[3][3],B$A[3][3] + XOR A$C[2],A$A[4][3],A$A[4][3] +|| XOR B$C[2],B$A[4][3],B$A[4][3] +|| XOR A$C[3],A$A[0][4],A$A[0][4] +|| XOR B$C[3],B$A[0][4],B$A[0][4] +|| XOR A$C[3],A$A[1][4],A$A[1][4] +|| XOR B$C[3],B$A[1][4],B$A[1][4] + XOR A$C[3],A$A[2][4],A$A[2][4] +|| XOR B$C[3],B$A[2][4],B$A[2][4] +|| XOR A$C[3],A$A[3][4],A$A[3][4] +|| XOR B$C[3],B$A[3][4],B$A[3][4] +|| XOR A$C[3],A$A[4][4],A$A[4][4] +|| XOR B$C[3],B$A[4][4],B$A[4][4] + XOR A$C[1],A$C[4],A$C[4] ; C[4] ^= ROL64(C[1],1) +|| XOR B$C[1],B$C[4],B$C[4] +|| MV A$A[0][1],A$C[1] ; Rho+Pi, "early start" +|| MV B$A[0][1],B$C[1] +___ + &ROL64 ($A[1][1],$rhotates[1][1],$A[0][1],"||"); +$code.=<<___; + XOR A$C[4],A$A[0][0],A$A[0][0] +|| XOR B$C[4],B$A[0][0],B$A[0][0] +|| XOR A$C[4],A$A[1][0],A$A[1][0] +|| XOR B$C[4],B$A[1][0],B$A[1][0] +|| MV A$A[0][3],A$C[3] +|| MV B$A[0][3],B$C[3] +___ + &ROL64 ($A[3][3],$rhotates[3][3],$A[0][3],"||"); +$code.=<<___; + XOR A$C[4],A$A[2][0],A$A[2][0] +|| XOR B$C[4],B$A[2][0],B$A[2][0] +|| XOR A$C[4],A$A[3][0],A$A[3][0] +|| XOR B$C[4],B$A[3][0],B$A[3][0] +|| MV A$A[0][2],A$C[2] +|| MV B$A[0][2],B$C[2] +___ + &ROL64 ($A[2][2],$rhotates[2][2],$A[0][2],"||"); +$code.=<<___; + XOR A$C[4],A$A[4][0],A$A[4][0] +|| XOR B$C[4],B$A[4][0],B$A[4][0] +|| MV A$A[0][4],A$C[4] +|| MV B$A[0][4],B$C[4] +___ + &ROL64 ($A[4][4],$rhotates[4][4],$A[0][4],"||"); + + &ROL64 ($A[1][4],$rhotates[1][4],$A[1][1]); +$code.=<<___; +|| LDW *${iotas}++[2],A$C[0] +___ + &ROL64 ($A[2][3],$rhotates[2][3],$A[2][2]); +$code.=<<___; +|| LDW *${iotas}[-1],B$C[0] +___ + &ROL64 ($A[3][2],$rhotates[3][2],$A[3][3]); + &ROL64 ($A[4][1],$rhotates[4][1],$A[4][4]); + + &ROL64 ($A[4][2],$rhotates[4][2],$A[1][4]); + &ROL64 ($A[3][4],$rhotates[3][4],$A[2][3]); + &ROL64 ($A[2][1],$rhotates[2][1],$A[3][2]); + &ROL64 ($A[1][3],$rhotates[1][3],$A[4][1]); + + &ROL64 ($A[2][4],$rhotates[2][4],$A[4][2]); + &ROL64 ($A[4][3],$rhotates[4][3],$A[3][4]); + &ROL64 ($A[1][2],$rhotates[1][2],$A[2][1]); + &ROL64 ($A[3][1],$rhotates[3][1],$A[1][3]); + + &ROL64 ($A[4][0],$rhotates[4][0],$A[2][4]); + &ROL64 ($A[3][0],$rhotates[3][0],$A[4][3]); + &ROL64 ($A[2][0],$rhotates[2][0],$A[1][2]); + &ROL64 ($A[1][0],$rhotates[1][0],$A[3][1]); + + #&ROL64 ($C[3], $rhotates[0][3],$A[1][0]); # moved below + &ROL64 ($C[1], $rhotates[0][1],$A[2][0]); + &ROL64 ($C[4], $rhotates[0][4],$A[3][0]); + &ROL64 ($C[2], $rhotates[0][2],$A[4][0]); +$code.=<<___; +|| ANDN A$A[0][2],A$A[0][1],A$C[4] ; Chi+Iota +|| ANDN B$A[0][2],B$A[0][1],B$C[4] +|| ANDN A$A[0][3],A$A[0][2],A$C[1] +|| ANDN B$A[0][3],B$A[0][2],B$C[1] +|| ANDN A$A[0][4],A$A[0][3],A$C[2] +|| ANDN B$A[0][4],B$A[0][3],B$C[2] +___ + &ROL64 ($C[3], $rhotates[0][3],$A[1][0]); +$code.=<<___; +|| ANDN A$A[0][0],A$A[0][4],A$C[3] +|| ANDN B$A[0][0],B$A[0][4],B$C[3] +|| XOR A$C[4],A$A[0][0],A$A[0][0] +|| XOR B$C[4],B$A[0][0],B$A[0][0] +|| ANDN A$A[0][1],A$A[0][0],A$C[4] +|| ANDN B$A[0][1],B$A[0][0],B$C[4] + XOR A$C[1],A$A[0][1],A$A[0][1] +|| XOR B$C[1],B$A[0][1],B$A[0][1] +|| XOR A$C[2],A$A[0][2],A$A[0][2] +|| XOR B$C[2],B$A[0][2],B$A[0][2] +|| XOR A$C[3],A$A[0][3],A$A[0][3] +|| XOR B$C[3],B$A[0][3],B$A[0][3] + XOR A$C[4],A$A[0][4],A$A[0][4] +|| XOR B$C[4],B$A[0][4],B$A[0][4] +|| XOR A$C[0],A$A[0][0],A$A[0][0] ; A[0][0] ^= iotas[i++]; +|| XOR B$C[0],B$A[0][0],B$A[0][0] +|| EXTU $iotas,24,24,A0 ; A0 is A$C[0], as we done? + + ANDN A$A[1][2],A$A[1][1],A$C[4] +|| ANDN B$A[1][2],B$A[1][1],B$C[4] +|| ANDN A$A[1][3],A$A[1][2],A$C[1] +|| ANDN B$A[1][3],B$A[1][2],B$C[1] +|| ANDN A$A[1][4],A$A[1][3],A$C[2] +|| ANDN B$A[1][4],B$A[1][3],B$C[2] + ANDN A$A[1][0],A$A[1][4],A$C[3] +|| ANDN B$A[1][0],B$A[1][4],B$C[3] +|| XOR A$C[4],A$A[1][0],A$A[1][0] +|| XOR B$C[4],B$A[1][0],B$A[1][0] +|| ANDN A$A[1][1],A$A[1][0],A$C[4] +|| ANDN B$A[1][1],B$A[1][0],B$C[4] + XOR A$C[1],A$A[1][1],A$A[1][1] +|| XOR B$C[1],B$A[1][1],B$A[1][1] +|| XOR A$C[2],A$A[1][2],A$A[1][2] +|| XOR B$C[2],B$A[1][2],B$A[1][2] +|| XOR A$C[3],A$A[1][3],A$A[1][3] +|| XOR B$C[3],B$A[1][3],B$A[1][3] + XOR A$C[4],A$A[1][4],A$A[1][4] +|| XOR B$C[4],B$A[1][4],B$A[1][4] + +|| ANDN A$A[2][2],A$A[2][1],A$C[4] +|| ANDN B$A[2][2],B$A[2][1],B$C[4] +|| ANDN A$A[2][3],A$A[2][2],A$C[1] +|| ANDN B$A[2][3],B$A[2][2],B$C[1] + ANDN A$A[2][4],A$A[2][3],A$C[2] +|| ANDN B$A[2][4],B$A[2][3],B$C[2] +|| ANDN A$A[2][0],A$A[2][4],A$C[3] +|| ANDN B$A[2][0],B$A[2][4],B$C[3] +|| XOR A$C[4],A$A[2][0],A$A[2][0] +|| XOR B$C[4],B$A[2][0],B$A[2][0] + ANDN A$A[2][1],A$A[2][0],A$C[4] +|| ANDN B$A[2][1],B$A[2][0],B$C[4] +|| XOR A$C[1],A$A[2][1],A$A[2][1] +|| XOR B$C[1],B$A[2][1],B$A[2][1] +|| XOR A$C[2],A$A[2][2],A$A[2][2] +|| XOR B$C[2],B$A[2][2],B$A[2][2] + XOR A$C[3],A$A[2][3],A$A[2][3] +|| XOR B$C[3],B$A[2][3],B$A[2][3] +|| XOR A$C[4],A$A[2][4],A$A[2][4] +|| XOR B$C[4],B$A[2][4],B$A[2][4] + + ANDN A$A[3][2],A$A[3][1],A$C[4] +|| ANDN B$A[3][2],B$A[3][1],B$C[4] +|| ANDN A$A[3][3],A$A[3][2],A$C[1] +|| ANDN B$A[3][3],B$A[3][2],B$C[1] +|| ANDN A$A[3][4],A$A[3][3],A$C[2] +|| ANDN B$A[3][4],B$A[3][3],B$C[2] + ANDN A$A[3][0],A$A[3][4],A$C[3] +|| ANDN B$A[3][0],B$A[3][4],B$C[3] +|| XOR A$C[4],A$A[3][0],A$A[3][0] +|| XOR B$C[4],B$A[3][0],B$A[3][0] +|| ANDN A$A[3][1],A$A[3][0],A$C[4] +|| ANDN B$A[3][1],B$A[3][0],B$C[4] + XOR A$C[1],A$A[3][1],A$A[3][1] +|| XOR B$C[1],B$A[3][1],B$A[3][1] +|| XOR A$C[2],A$A[3][2],A$A[3][2] +|| XOR B$C[2],B$A[3][2],B$A[3][2] +|| XOR A$C[3],A$A[3][3],A$A[3][3] +||[A0] BNOP loop? + XOR B$C[3],B$A[3][3],B$A[3][3] +|| XOR A$C[4],A$A[3][4],A$A[3][4] +|| XOR B$C[4],B$A[3][4],B$A[3][4] +||[!A0] LDDW *FP[-7],A3:A2 +||[!A0] LDDW *SP[4], RA:B2 + + ANDN A$A[4][2],A$A[4][1],A$C[4] +|| ANDN B$A[4][2],B$A[4][1],B$C[4] +|| ANDN A$A[4][3],A$A[4][2],A$C[1] +|| ANDN B$A[4][3],B$A[4][2],B$C[1] +|| ANDN A$A[4][4],A$A[4][3],A$C[2] +|| ANDN B$A[4][4],B$A[4][3],B$C[2] + ANDN A$A[4][0],A$A[4][4],A$C[3] +|| ANDN B$A[4][0],B$A[4][4],B$C[3] +|| XOR A$C[4],A$A[4][0],A$A[4][0] +|| XOR B$C[4],B$A[4][0],B$A[4][0] +|| ANDN A$A[4][1],A$A[4][0],A$C[4] +|| ANDN B$A[4][1],B$A[4][0],B$C[4] + XOR A$C[1],A$A[4][1],A$A[4][1] +|| XOR B$C[1],B$A[4][1],B$A[4][1] +|| XOR A$C[2],A$A[4][2],A$A[4][2] +|| XOR B$C[2],B$A[4][2],B$A[4][2] +|| XOR A$C[3],A$A[4][3],A$A[4][3] +|| XOR B$C[3],B$A[4][3],B$A[4][3] + XOR A$C[4],A$A[4][4],A$A[4][4] +|| XOR B$C[4],B$A[4][4],B$A[4][4] +;;===== branch to loop? is taken here + + BNOP RA,5 + .endasmfunc + + .newblock + .global _KeccakF1600 + .align 32 +_KeccakF1600: + .asmfunc stack_usage(80) + STW FP,*SP--(80) ; save frame pointer +|| MV SP,FP + STDW B13:B12,*SP[9] +|| STDW A13:A12,*FP[-4] + STDW B11:B10,*SP[8] +|| STDW A11:A10,*FP[-5] + STW RA, *SP[15] +|| STW A14,*FP[-6] +|| MV A4,A2 +|| ADD 4,A4,B2 + + LDW *A2++[2],A$A[0][0] ; load A[5][5] +|| LDW *B2++[2],B$A[0][0] + LDW *A2++[2],A$A[0][1] +|| LDW *B2++[2],B$A[0][1] + LDW *A2++[2],A$A[0][2] +|| LDW *B2++[2],B$A[0][2] + LDW *A2++[2],A$A[0][3] +|| LDW *B2++[2],B$A[0][3] + LDW *A2++[2],A$A[0][4] +|| LDW *B2++[2],B$A[0][4] + + LDW *A2++[2],A$A[1][0] +|| LDW *B2++[2],B$A[1][0] + LDW *A2++[2],A$A[1][1] +|| LDW *B2++[2],B$A[1][1] + LDW *A2++[2],A$A[1][2] +|| LDW *B2++[2],B$A[1][2] + LDW *A2++[2],A$A[1][3] +|| LDW *B2++[2],B$A[1][3] + LDW *A2++[2],A$A[1][4] +|| LDW *B2++[2],B$A[1][4] + + LDW *A2++[2],A$A[2][0] +|| LDW *B2++[2],B$A[2][0] + LDW *A2++[2],A$A[2][1] +|| LDW *B2++[2],B$A[2][1] + LDW *A2++[2],A$A[2][2] +|| LDW *B2++[2],B$A[2][2] + LDW *A2++[2],A$A[2][3] +|| LDW *B2++[2],B$A[2][3] + LDW *A2++[2],A$A[2][4] +|| LDW *B2++[2],B$A[2][4] + + LDW *A2++[2],A$A[3][0] +|| LDW *B2++[2],B$A[3][0] + LDW *A2++[2],A$A[3][1] +|| LDW *B2++[2],B$A[3][1] + LDW *A2++[2],A$A[3][2] +|| LDW *B2++[2],B$A[3][2] + LDW *A2++[2],A$A[3][3] +|| LDW *B2++[2],B$A[3][3] + LDW *A2++[2],A$A[3][4] +|| LDW *B2++[2],B$A[3][4] +|| BNOP _KeccakF1600_int + + ADDKPC ret?,RA +|| LDW *A2++[2],A$A[4][0] +|| LDW *B2++[2],B$A[4][0] + LDW *A2++[2],A$A[4][1] +|| LDW *B2++[2],B$A[4][1] + LDW *A2++[2],A$A[4][2] +|| LDW *B2++[2],B$A[4][2] + LDW *A2++[2],A$A[4][3] +|| LDW *B2++[2],B$A[4][3] + LDW *A2,A$A[4][4] +|| LDW *B2,B$A[4][4] +|| ADDK -192,A2 ; rewind +|| ADDK -192,B2 + + .align 16 +ret?: + STW A$A[0][0],*A2++[2] ; store A[5][5] +|| STW B$A[0][0],*B2++[2] + STW A$A[0][1],*A2++[2] +|| STW B$A[0][1],*B2++[2] + STW A$A[0][2],*A2++[2] +|| STW B$A[0][2],*B2++[2] + STW A$A[0][3],*A2++[2] +|| STW B$A[0][3],*B2++[2] + STW A$A[0][4],*A2++[2] +|| STW B$A[0][4],*B2++[2] + + STW A$A[1][0],*A2++[2] +|| STW B$A[1][0],*B2++[2] + STW A$A[1][1],*A2++[2] +|| STW B$A[1][1],*B2++[2] + STW A$A[1][2],*A2++[2] +|| STW B$A[1][2],*B2++[2] + STW A$A[1][3],*A2++[2] +|| STW B$A[1][3],*B2++[2] + STW A$A[1][4],*A2++[2] +|| STW B$A[1][4],*B2++[2] + + STW A$A[2][0],*A2++[2] +|| STW B$A[2][0],*B2++[2] + STW A$A[2][1],*A2++[2] +|| STW B$A[2][1],*B2++[2] + STW A$A[2][2],*A2++[2] +|| STW B$A[2][2],*B2++[2] + STW A$A[2][3],*A2++[2] +|| STW B$A[2][3],*B2++[2] + STW A$A[2][4],*A2++[2] +|| STW B$A[2][4],*B2++[2] + + STW A$A[3][0],*A2++[2] +|| STW B$A[3][0],*B2++[2] + STW A$A[3][1],*A2++[2] +|| STW B$A[3][1],*B2++[2] + STW A$A[3][2],*A2++[2] +|| STW B$A[3][2],*B2++[2] + STW A$A[3][3],*A2++[2] +|| STW B$A[3][3],*B2++[2] + STW A$A[3][4],*A2++[2] +|| STW B$A[3][4],*B2++[2] + + LDW *SP[15],RA +|| LDW *FP[-6],A14 + + STW A$A[4][0],*A2++[2] +|| STW B$A[4][0],*B2++[2] + STW A$A[4][1],*A2++[2] +|| STW B$A[4][1],*B2++[2] + STW A$A[4][2],*A2++[2] +|| STW B$A[4][2],*B2++[2] + STW A$A[4][3],*A2++[2] +|| STW B$A[4][3],*B2++[2] + STW A$A[4][4],*A2 +|| STW B$A[4][4],*B2 +|| ADDK -192,A2 ; rewind + + MV A2,A4 ; return original A4 +|| LDDW *SP[8], B11:B10 +|| LDDW *FP[-5],A11:A10 + LDDW *SP[9], B13:B12 +|| LDDW *FP[-4],A13:A12 +|| BNOP RA + LDW *++SP(80),FP ; restore frame pointer + NOP 4 ; wait till FP is committed + .endasmfunc + + .newblock + .asg B2,BSZ + .asg A2,INP + .asg A3,LEN + .global _SHA3_absorb + .align 32 +_SHA3_absorb: + .asmfunc stack_usage(80) + STW FP,*SP--(80) ; save frame pointer +|| MV SP,FP + STDW B13:B12,*SP[9] +|| STDW A13:A12,*FP[-4] + STDW B11:B10,*SP[8] +|| STDW A11:A10,*FP[-5] + STW RA, *SP[15] +|| STW A14,*FP[-6] + + STW A4,*SP[1] ; save A[][] +|| MV B4,INP ; reassign arguments +|| MV A6,LEN +|| MV B6,BSZ +|| ADD 4,A4,B4 + + LDW *A4++[2],A$A[0][0] ; load A[5][5] +|| LDW *B4++[2],B$A[0][0] + LDW *A4++[2],A$A[0][1] +|| LDW *B4++[2],B$A[0][1] + LDW *A4++[2],A$A[0][2] +|| LDW *B4++[2],B$A[0][2] + LDW *A4++[2],A$A[0][3] +|| LDW *B4++[2],B$A[0][3] + LDW *A4++[2],A$A[0][4] +|| LDW *B4++[2],B$A[0][4] + + LDW *A4++[2],A$A[1][0] +|| LDW *B4++[2],B$A[1][0] + LDW *A4++[2],A$A[1][1] +|| LDW *B4++[2],B$A[1][1] + LDW *A4++[2],A$A[1][2] +|| LDW *B4++[2],B$A[1][2] + LDW *A4++[2],A$A[1][3] +|| LDW *B4++[2],B$A[1][3] + LDW *A4++[2],A$A[1][4] +|| LDW *B4++[2],B$A[1][4] + + LDW *A4++[2],A$A[2][0] +|| LDW *B4++[2],B$A[2][0] + LDW *A4++[2],A$A[2][1] +|| LDW *B4++[2],B$A[2][1] + LDW *A4++[2],A$A[2][2] +|| LDW *B4++[2],B$A[2][2] + LDW *A4++[2],A$A[2][3] +|| LDW *B4++[2],B$A[2][3] + LDW *A4++[2],A$A[2][4] +|| LDW *B4++[2],B$A[2][4] + + LDW *A4++[2],A$A[3][0] +|| LDW *B4++[2],B$A[3][0] + LDW *A4++[2],A$A[3][1] +|| LDW *B4++[2],B$A[3][1] + LDW *A4++[2],A$A[3][2] +|| LDW *B4++[2],B$A[3][2] + LDW *A4++[2],A$A[3][3] +|| LDW *B4++[2],B$A[3][3] + LDW *A4++[2],A$A[3][4] +|| LDW *B4++[2],B$A[3][4] + + LDW *A4++[2],A$A[4][0] +|| LDW *B4++[2],B$A[4][0] + LDW *A4++[2],A$A[4][1] +|| LDW *B4++[2],B$A[4][1] + LDW *A4++[2],A$A[4][2] +|| LDW *B4++[2],B$A[4][2] + LDW *A4++[2],A$A[4][3] +|| LDW *B4++[2],B$A[4][3] + LDW *A4,A$A[4][4] +|| LDW *B4,B$A[4][4] +|| ADDKPC loop?,RA + STDW RA:BSZ,*SP[4] + +loop?: + CMPLTU LEN,BSZ,A0 ; len < bsz? +|| SHRU BSZ,3,BSZ + [A0] BNOP ret? +||[A0] ZERO BSZ +||[A0] LDW *SP[1],A2 ; pull A[][] + [BSZ] LDNDW *INP++,A1:A0 +||[BSZ] SUB LEN,8,LEN +||[BSZ] SUB BSZ,1,BSZ + NOP 4 +___ +for ($y = 0; $y < 5; $y++) { + for ($x = 0; $x < ($y<4 ? 5 : 4); $x++) { +$code.=<<___; + .if .BIG_ENDIAN + SWAP2 A0,A1 +|| SWAP2 A1,A0 + SWAP4 A0,A0 + SWAP4 A1,A1 +||[!BSZ]BNOP _KeccakF1600_cheat +||[!BSZ]STDW LEN:INP,*SP[3] +|| DEAL A0,A0 + .else + [!BSZ]BNOP _KeccakF1600_cheat +||[!BSZ]STDW LEN:INP,*SP[3] +|| DEAL A0,A0 + .endif + [BSZ] LDNDW *INP++,A1:A0 +|| DEAL A1,A1 + [BSZ] SUB LEN,8,LEN +||[BSZ] SUB BSZ,1,BSZ + PACK2 A1,A0,A0 +|| PACKH2 A1,A0,A1 + XOR A0,A$A[$y][$x],A$A[$y][$x] + XOR A1,B$A[$y][$x],B$A[$y][$x] +___ + } +} +$code.=<<___; + .if .BIG_ENDIAN + SWAP2 A0,A1 +|| SWAP2 A1,A0 + SWAP4 A0,A0 + SWAP4 A1,A1 + .endif + BNOP _KeccakF1600_cheat +|| STDW LEN:INP,*SP[3] +|| DEAL A0,A0 + DEAL A1,A1 + NOP + PACK2 A1,A0,A0 +|| PACKH2 A1,A0,A1 + XOR A0,A$A[4][4],A$A[4][4] + XOR A1,B$A[4][4],B$A[4][4] + + .align 16 +ret?: + MV LEN,A4 ; return value +|| ADD 4,A2,B2 + + STW A$A[0][0],*A2++[2] ; store A[5][5] +|| STW B$A[0][0],*B2++[2] + STW A$A[0][1],*A2++[2] +|| STW B$A[0][1],*B2++[2] + STW A$A[0][2],*A2++[2] +|| STW B$A[0][2],*B2++[2] + STW A$A[0][3],*A2++[2] +|| STW B$A[0][3],*B2++[2] + STW A$A[0][4],*A2++[2] +|| STW B$A[0][4],*B2++[2] + + STW A$A[1][0],*A2++[2] +|| STW B$A[1][0],*B2++[2] + STW A$A[1][1],*A2++[2] +|| STW B$A[1][1],*B2++[2] + STW A$A[1][2],*A2++[2] +|| STW B$A[1][2],*B2++[2] + STW A$A[1][3],*A2++[2] +|| STW B$A[1][3],*B2++[2] + STW A$A[1][4],*A2++[2] +|| STW B$A[1][4],*B2++[2] + + STW A$A[2][0],*A2++[2] +|| STW B$A[2][0],*B2++[2] + STW A$A[2][1],*A2++[2] +|| STW B$A[2][1],*B2++[2] + STW A$A[2][2],*A2++[2] +|| STW B$A[2][2],*B2++[2] + STW A$A[2][3],*A2++[2] +|| STW B$A[2][3],*B2++[2] + STW A$A[2][4],*A2++[2] +|| STW B$A[2][4],*B2++[2] + + LDW *SP[15],RA +|| LDW *FP[-6],A14 + + STW A$A[3][0],*A2++[2] +|| STW B$A[3][0],*B2++[2] + STW A$A[3][1],*A2++[2] +|| STW B$A[3][1],*B2++[2] + STW A$A[3][2],*A2++[2] +|| STW B$A[3][2],*B2++[2] + STW A$A[3][3],*A2++[2] +|| STW B$A[3][3],*B2++[2] + STW A$A[3][4],*A2++[2] +|| STW B$A[3][4],*B2++[2] + + LDDW *SP[8], B11:B10 +|| LDDW *FP[-5],A11:A10 + LDDW *SP[9], B13:B12 +|| LDDW *FP[-4],A13:A12 + BNOP RA +|| LDW *++SP(80),FP ; restore frame pointer + + STW A$A[4][0],*A2++[2] +|| STW B$A[4][0],*B2++[2] + STW A$A[4][1],*A2++[2] +|| STW B$A[4][1],*B2++[2] + STW A$A[4][2],*A2++[2] +|| STW B$A[4][2],*B2++[2] + STW A$A[4][3],*A2++[2] +|| STW B$A[4][3],*B2++[2] + STW A$A[4][4],*A2++[2] +|| STW B$A[4][4],*B2++[2] + .endasmfunc + + .newblock + .global _SHA3_squeeze + .asg A12,OUT + .asg A13,LEN + .asg A14,BSZ + .align 32 +_SHA3_squeeze: + .asmfunc stack_usage(24) + STW FP,*SP--(24) ; save frame pointer +|| MV SP,FP + STW RA, *SP[5] +|| STW A14,*FP[-2] + STDW A13:A12,*FP[-2] +|| MV B4,OUT ; reassign arguments + MV A6,LEN +|| MV B6,BSZ + +loop?: + LDW *SP[5],RA ; reload RA +|| SHRU BSZ,3,A1 +|| MV A4,A8 +|| ADD 4,A4,B8 +block?: + CMPLTU LEN,8,A0 ; len < 8? + [A0] BNOP tail? + LDW *A8++[2],A9 +|| LDW *B8++[2],B9 +|| SUB LEN,8,LEN ; len -= 8 + MV LEN,A0 +|| SUB A1,1,A1 ; bsz-- +|| NOP 4 + .if .BIG_ENDIAN + SWAP4 A9,A9 +|| SWAP4 B9,B9 + SWAP2 A9,A9 +|| SWAP2 B9,B9 + .endif + [!A0] BNOP ret? +||[!A0] ZERO A1 + PACK2 B9,A9,B7 +||[A1] BNOP block? + PACKH2 B9,A9,B9 +|| SHFL B7,B7 + SHFL B9,B9 + STNW B7,*OUT++ + STNW B9,*OUT++ + NOP + + BNOP _KeccakF1600,4 + ADDKPC loop?,RA + + .align 16 +tail?: + .if .BIG_ENDIAN + SWAP4 A9,A9 +|| SWAP4 B9,B9 + SWAP2 A9,A9 +|| SWAP2 B9,B9 + .endif + PACK2 B9,A9,B7 + PACKH2 B9,A9,B9 +|| SHFL B7,B7 + SHFL B9,B9 + + STB B7,*OUT++ +|| SHRU B7,8,B7 +|| ADD LEN,7,A0 + [A0] STB B7,*OUT++ +||[A0] SHRU B7,8,B7 +||[A0] SUB A0,1,A0 + [A0] STB B7,*OUT++ +||[A0] SHRU B7,8,B7 +||[A0] SUB A0,1,A0 + [A0] STB B7,*OUT++ +||[A0] SUB A0,1,A0 + [A0] STB B9,*OUT++ +||[A0] SHRU B9,8,B9 +||[A0] SUB A0,1,A0 + [A0] STB B9,*OUT++ +||[A0] SHRU B9,8,B9 +||[A0] SUB A0,1,A0 + [A0] STB B9,*OUT++ + +ret?: + LDDW *FP[-2],A13:A12 + BNOP RA +|| LDW *FP[-2],A14 + LDW *++SP(24),FP ; restore frame pointer + NOP 4 ; wait till FP is committed + .endasmfunc + + .if __TI_EABI__ + .sect ".text:sha_asm.const" + .else + .sect ".const:sha_asm" + .endif + .align 256 + .uword 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 +iotas: + .uword 0x00000001, 0x00000000 + .uword 0x00000000, 0x00000089 + .uword 0x00000000, 0x8000008b + .uword 0x00000000, 0x80008080 + .uword 0x00000001, 0x0000008b + .uword 0x00000001, 0x00008000 + .uword 0x00000001, 0x80008088 + .uword 0x00000001, 0x80000082 + .uword 0x00000000, 0x0000000b + .uword 0x00000000, 0x0000000a + .uword 0x00000001, 0x00008082 + .uword 0x00000000, 0x00008003 + .uword 0x00000001, 0x0000808b + .uword 0x00000001, 0x8000000b + .uword 0x00000001, 0x8000008a + .uword 0x00000001, 0x80000081 + .uword 0x00000000, 0x80000081 + .uword 0x00000000, 0x80000008 + .uword 0x00000000, 0x00000083 + .uword 0x00000000, 0x80008003 + .uword 0x00000001, 0x80008088 + .uword 0x00000000, 0x80000088 + .uword 0x00000001, 0x00008000 + .uword 0x00000000, 0x80008082 + + .cstring "Keccak-1600 absorb and squeeze for C64x, CRYPTOGAMS by " + .align 4 +___ + +print $code; diff --git a/crypto/sha/asm/keccak1600-mmx.pl b/crypto/sha/asm/keccak1600-mmx.pl new file mode 100755 index 00000000..c7685add --- /dev/null +++ b/crypto/sha/asm/keccak1600-mmx.pl @@ -0,0 +1,440 @@ +#!/usr/bin/env perl +# 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# Keccak-1600 for x86 MMX. +# +# June 2017. +# +# Below code is KECCAK_2X implementation (see sha/keccak1600.c) with +# C[5] held in register bank and D[5] offloaded to memory. Though +# instead of actually unrolling the loop pair-wise I simply flip +# pointers to T[][] and A[][] and the end of round. Since number of +# rounds is even, last round writes to A[][] and everything works out. +# It's argued that MMX is the only code path meaningful to implement +# for x86. This is because non-MMX-capable processors is an extinct +# breed, and they as well can lurk executing compiler-generated code. +# For reference gcc-5.x-generated KECCAK_2X code takes 89 cycles per +# processed byte on Pentium. Which is fair result. But older compilers +# produce worse code. On the other hand one can wonder why not 128-bit +# SSE2? Well, SSE2 won't provide double improvement, rather far from +# that, if any at all on some processors, because it will take extra +# permutations and inter-bank data trasfers. Besides, contemporary +# CPUs are better off executing 64-bit code, and it makes lesser sense +# to invest into fancy 32-bit code. And the decision doesn't seem to +# be inadequate, if one compares below results to "64-bit platforms in +# 32-bit mode" SIMD data points available at +# http://keccak.noekeon.org/sw_performance.html. +# +######################################################################## +# Numbers are cycles per processed byte out of large message. +# +# r=1088(i) +# +# PIII 30/+150% +# Pentium M 27/+150% +# P4 40/+85% +# Core 2 19/+170% +# Sandy Bridge(ii) 18/+140% +# Atom 33/+180% +# Silvermont(ii) 30/+180% +# VIA Nano(ii) 43/+60% +# Sledgehammer(ii)(iii) 24/+130% +# +# (i) Corresponds to SHA3-256. Numbers after slash are improvement +# coefficients over KECCAK_2X [with bit interleave and lane +# complementing] position-independent *scalar* code generated +# by gcc-5.x. It's not exactly fair comparison, but it's a +# datapoint... +# (ii) 64-bit processor executing 32-bit code. +# (iii) Result is considered to be representative even for older AMD +# processors. + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +push(@INC,"${dir}","${dir}../../perlasm"); +require "x86asm.pl"; + +$output=pop; +open STDOUT,">$output"; + +&asm_init($ARGV[0],$ARGV[$#ARGV] eq "386"); + +my @C = map("mm$_",(0..4)); +my @T = map("mm$_",(5..7)); +my @A = map([ 8*$_-100, 8*($_+1)-100, 8*($_+2)-100, + 8*($_+3)-100, 8*($_+4)-100 ], (0,5,10,15,20)); +my @D = map(8*$_+4, (0..4)); +my @rhotates = ([ 0, 1, 62, 28, 27 ], + [ 36, 44, 6, 55, 20 ], + [ 3, 10, 43, 25, 39 ], + [ 41, 45, 15, 21, 8 ], + [ 18, 2, 61, 56, 14 ]); + +&static_label("iotas"); + +&function_begin_B("_KeccakF1600"); + &movq (@C[0],&QWP($A[4][0],"esi")); + &movq (@C[1],&QWP($A[4][1],"esi")); + &movq (@C[2],&QWP($A[4][2],"esi")); + &movq (@C[3],&QWP($A[4][3],"esi")); + &movq (@C[4],&QWP($A[4][4],"esi")); + + &mov ("ecx",24); # loop counter + &jmp (&label("loop")); + + &set_label("loop",16); + ######################################### Theta + &pxor (@C[0],&QWP($A[0][0],"esi")); + &pxor (@C[1],&QWP($A[0][1],"esi")); + &pxor (@C[2],&QWP($A[0][2],"esi")); + &pxor (@C[3],&QWP($A[0][3],"esi")); + &pxor (@C[4],&QWP($A[0][4],"esi")); + + &pxor (@C[0],&QWP($A[1][0],"esi")); + &pxor (@C[1],&QWP($A[1][1],"esi")); + &pxor (@C[2],&QWP($A[1][2],"esi")); + &pxor (@C[3],&QWP($A[1][3],"esi")); + &pxor (@C[4],&QWP($A[1][4],"esi")); + + &pxor (@C[0],&QWP($A[2][0],"esi")); + &pxor (@C[1],&QWP($A[2][1],"esi")); + &pxor (@C[2],&QWP($A[2][2],"esi")); + &pxor (@C[3],&QWP($A[2][3],"esi")); + &pxor (@C[4],&QWP($A[2][4],"esi")); + + &pxor (@C[2],&QWP($A[3][2],"esi")); + &pxor (@C[0],&QWP($A[3][0],"esi")); + &pxor (@C[1],&QWP($A[3][1],"esi")); + &pxor (@C[3],&QWP($A[3][3],"esi")); + &movq (@T[0],@C[2]); + &pxor (@C[4],&QWP($A[3][4],"esi")); + + &movq (@T[2],@C[2]); + &psrlq (@T[0],63); + &movq (@T[1],@C[0]); + &psllq (@T[2],1); + &pxor (@T[0],@C[0]); + &psrlq (@C[0],63); + &pxor (@T[0],@T[2]); + &psllq (@T[1],1); + &movq (@T[2],@C[1]); + &movq (&QWP(@D[1],"esp"),@T[0]); # D[1] = E[0] = ROL64(C[2], 1) ^ C[0]; + + &pxor (@T[1],@C[0]); + &psrlq (@T[2],63); + &pxor (@T[1],@C[3]); + &movq (@C[0],@C[1]); + &movq (&QWP(@D[4],"esp"),@T[1]); # D[4] = E[1] = ROL64(C[0], 1) ^ C[3]; + + &psllq (@C[0],1); + &pxor (@T[2],@C[4]); + &pxor (@C[0],@T[2]); + + &movq (@T[2],@C[3]); + &psrlq (@C[3],63); + &movq (&QWP(@D[0],"esp"),@C[0]); # D[0] = C[0] = ROL64(C[1], 1) ^ C[4]; + &psllq (@T[2],1); + &movq (@T[0],@C[4]); + &psrlq (@C[4],63); + &pxor (@C[1],@C[3]); + &psllq (@T[0],1); + &pxor (@C[1],@T[2]); + &pxor (@C[2],@C[4]); + &movq (&QWP(@D[2],"esp"),@C[1]); # D[2] = C[1] = ROL64(C[3], 1) ^ C[1]; + &pxor (@C[2],@T[0]); + + ######################################### first Rho(0) is special + &movq (@C[3],&QWP($A[3][3],"esi")); + &movq (&QWP(@D[3],"esp"),@C[2]); # D[3] = C[2] = ROL64(C[4], 1) ^ C[2]; + &pxor (@C[3],@C[2]); + &movq (@C[4],&QWP($A[4][4],"esi")); + &movq (@T[2],@C[3]); + &psrlq (@C[3],64-$rhotates[3][3]); + &pxor (@C[4],@T[1]); + &psllq (@T[2],$rhotates[3][3]); + &movq (@T[1],@C[4]); + &psrlq (@C[4],64-$rhotates[4][4]); + &por (@C[3],@T[2]); # C[3] = ROL64(A[3][3] ^ C[2], rhotates[3][3]); /* D[3] */ + &psllq (@T[1],$rhotates[4][4]); + + &movq (@C[2],&QWP($A[2][2],"esi")); + &por (@C[4],@T[1]); # C[4] = ROL64(A[4][4] ^ E[1], rhotates[4][4]); /* D[4] */ + &pxor (@C[2],@C[1]); + &movq (@C[1],&QWP($A[1][1],"esi")); + &movq (@T[1],@C[2]); + &psrlq (@C[2],64-$rhotates[2][2]); + &pxor (@C[1],&QWP(@D[1],"esp")); + &psllq (@T[1],$rhotates[2][2]); + + &movq (@T[2],@C[1]); + &psrlq (@C[1],64-$rhotates[1][1]); + &por (@C[2],@T[1]); # C[2] = ROL64(A[2][2] ^ C[1], rhotates[2][2]); /* D[2] */ + &psllq (@T[2],$rhotates[1][1]); + &pxor (@C[0],&QWP($A[0][0],"esi")); # /* rotate by 0 */ /* D[0] */ + &por (@C[1],@T[2]); # C[1] = ROL64(A[1][1] ^ D[1], rhotates[1][1]); + +sub Chi() { ######### regular Chi step + my ($y,$xrho) = @_; + + &movq (@T[0],@C[1]); + &movq (@T[1],@C[2]); + &pandn (@T[0],@C[2]); + &pandn (@C[2],@C[3]); + &pxor (@T[0],@C[0]); + &pxor (@C[2],@C[1]); + &pxor (@T[0],&QWP(0,"ebx")) if ($y == 0); + &lea ("ebx",&DWP(8,"ebx")) if ($y == 0); + + &movq (@T[2],@C[3]); + &movq (&QWP($A[$y][0],"edi"),@T[0]); # R[0][0] = C[0] ^ (~C[1] & C[2]) ^ iotas[i]; + &movq (@T[0],@C[4]); + &pandn (@C[3],@C[4]); + &pandn (@C[4],@C[0]); + &pxor (@C[3],@T[1]); + &movq (&QWP($A[$y][1],"edi"),@C[2]); # R[0][1] = C[1] ^ (~C[2] & C[3]); + &pxor (@C[4],@T[2]); + &movq (@T[2],&QWP($A[0][$xrho],"esi")) if (defined($xrho)); + + &movq (&QWP($A[$y][2],"edi"),@C[3]); # R[0][2] = C[2] ^ (~C[3] & C[4]); + &pandn (@C[0],@C[1]); + &movq (&QWP($A[$y][3],"edi"),@C[4]); # R[0][3] = C[3] ^ (~C[4] & C[0]); + &pxor (@C[0],@T[0]); + &pxor (@T[2],&QWP(@D[$xrho],"esp")) if (defined($xrho)); + &movq (&QWP($A[$y][4],"edi"),@C[0]); # R[0][4] = C[4] ^ (~C[0] & C[1]); +} + &Chi (0, 3); + +sub Rho() { ######### regular Rho step + my $x = shift; + + #&movq (@T[2],&QWP($A[0][$x],"esi")); # moved to Chi + #&pxor (@T[2],&QWP(@D[$x],"esp")); # moved to Chi + &movq (@C[0],@T[2]); + &psrlq (@T[2],64-$rhotates[0][$x]); + &movq (@C[1],&QWP($A[1][($x+1)%5],"esi")); + &psllq (@C[0],$rhotates[0][$x]); + &pxor (@C[1],&QWP(@D[($x+1)%5],"esp")); + &por (@C[0],@T[2]); # C[0] = ROL64(A[0][3] ^ D[3], rhotates[0][3]); + + &movq (@T[1],@C[1]); + &psrlq (@C[1],64-$rhotates[1][($x+1)%5]); + &movq (@C[2],&QWP($A[2][($x+2)%5],"esi")); + &psllq (@T[1],$rhotates[1][($x+1)%5]); + &pxor (@C[2],&QWP(@D[($x+2)%5],"esp")); + &por (@C[1],@T[1]); # C[1] = ROL64(A[1][4] ^ D[4], rhotates[1][4]); + + &movq (@T[2],@C[2]); + &psrlq (@C[2],64-$rhotates[2][($x+2)%5]); + &movq (@C[3],&QWP($A[3][($x+3)%5],"esi")); + &psllq (@T[2],$rhotates[2][($x+2)%5]); + &pxor (@C[3],&QWP(@D[($x+3)%5],"esp")); + &por (@C[2],@T[2]); # C[2] = ROL64(A[2][0] ^ D[0], rhotates[2][0]); + + &movq (@T[0],@C[3]); + &psrlq (@C[3],64-$rhotates[3][($x+3)%5]); + &movq (@C[4],&QWP($A[4][($x+4)%5],"esi")); + &psllq (@T[0],$rhotates[3][($x+3)%5]); + &pxor (@C[4],&QWP(@D[($x+4)%5],"esp")); + &por (@C[3],@T[0]); # C[3] = ROL64(A[3][1] ^ D[1], rhotates[3][1]); + + &movq (@T[1],@C[4]); + &psrlq (@C[4],64-$rhotates[4][($x+4)%5]); + &psllq (@T[1],$rhotates[4][($x+4)%5]); + &por (@C[4],@T[1]); # C[4] = ROL64(A[4][2] ^ D[2], rhotates[4][2]); +} + &Rho (3); &Chi (1, 1); + &Rho (1); &Chi (2, 4); + &Rho (4); &Chi (3, 2); + &Rho (2); ###&Chi (4); + + &movq (@T[0],@C[0]); ######### last Chi(4) is special + &xor ("edi","esi"); # &xchg ("esi","edi"); + &movq (&QWP(@D[1],"esp"),@C[1]); + &xor ("esi","edi"); + &xor ("edi","esi"); + + &movq (@T[1],@C[1]); + &movq (@T[2],@C[2]); + &pandn (@T[1],@C[2]); + &pandn (@T[2],@C[3]); + &pxor (@C[0],@T[1]); + &pxor (@C[1],@T[2]); + + &movq (@T[1],@C[3]); + &movq (&QWP($A[4][0],"esi"),@C[0]); # R[4][0] = C[0] ^= (~C[1] & C[2]); + &pandn (@T[1],@C[4]); + &movq (&QWP($A[4][1],"esi"),@C[1]); # R[4][1] = C[1] ^= (~C[2] & C[3]); + &pxor (@C[2],@T[1]); + &movq (@T[2],@C[4]); + &movq (&QWP($A[4][2],"esi"),@C[2]); # R[4][2] = C[2] ^= (~C[3] & C[4]); + + &pandn (@T[2],@T[0]); + &pandn (@T[0],&QWP(@D[1],"esp")); + &pxor (@C[3],@T[2]); + &pxor (@C[4],@T[0]); + &movq (&QWP($A[4][3],"esi"),@C[3]); # R[4][3] = C[3] ^= (~C[4] & D[0]); + &sub ("ecx",1); + &movq (&QWP($A[4][4],"esi"),@C[4]); # R[4][4] = C[4] ^= (~D[0] & D[1]); + &jnz (&label("loop")); + + &lea ("ebx",&DWP(-192,"ebx")); # rewind iotas + &ret (); +&function_end_B("_KeccakF1600"); + +&function_begin("KeccakF1600"); + &mov ("esi",&wparam(0)); + &mov ("ebp","esp"); + &sub ("esp",240); + &call (&label("pic_point")); + &set_label("pic_point"); + &blindpop("ebx"); + &lea ("ebx",&DWP(&label("iotas")."-".&label("pic_point"),"ebx")); + &and ("esp",-8); + &lea ("esi",&DWP(100,"esi")); # size optimization + &lea ("edi",&DWP(8*5+100,"esp")); # size optimization + + &call ("_KeccakF1600"); + + &mov ("esp","ebp"); + &emms (); +&function_end("KeccakF1600"); + +&function_begin("SHA3_absorb"); + &mov ("esi",&wparam(0)); # A[][] + &mov ("eax",&wparam(1)); # inp + &mov ("ecx",&wparam(2)); # len + &mov ("edx",&wparam(3)); # bsz + &mov ("ebp","esp"); + &sub ("esp",240+8); + &call (&label("pic_point")); + &set_label("pic_point"); + &blindpop("ebx"); + &lea ("ebx",&DWP(&label("iotas")."-".&label("pic_point"),"ebx")); + &and ("esp",-8); + + &mov ("edi","esi"); + &lea ("esi",&DWP(100,"esi")); # size optimization + &mov (&DWP(-4,"ebp"),"edx"); # save bsz + &jmp (&label("loop")); + +&set_label("loop",16); + &cmp ("ecx","edx"); # len < bsz? + &jc (&label("absorbed")); + + &shr ("edx",3); # bsz /= 8 +&set_label("block"); + &movq ("mm0",&QWP(0,"eax")); + &lea ("eax",&DWP(8,"eax")); + &pxor ("mm0",&QWP(0,"edi")); + &lea ("edi",&DWP(8,"edi")); + &sub ("ecx",8); # len -= 8 + &movq (&QWP(-8,"edi"),"mm0"); + &dec ("edx"); # bsz-- + &jnz (&label("block")); + + &lea ("edi",&DWP(8*5+100,"esp")); # size optimization + &mov (&DWP(-8,"ebp"),"ecx"); # save len + &call ("_KeccakF1600"); + &mov ("ecx",&DWP(-8,"ebp")); # pull len + &mov ("edx",&DWP(-4,"ebp")); # pull bsz + &lea ("edi",&DWP(-100,"esi")); + &jmp (&label("loop")); + +&set_label("absorbed",16); + &mov ("eax","ecx"); # return value + &mov ("esp","ebp"); + &emms (); +&function_end("SHA3_absorb"); + +&function_begin("SHA3_squeeze"); + &mov ("esi",&wparam(0)); # A[][] + &mov ("eax",&wparam(1)); # out + &mov ("ecx",&wparam(2)); # len + &mov ("edx",&wparam(3)); # bsz + &mov ("ebp","esp"); + &sub ("esp",240+8); + &call (&label("pic_point")); + &set_label("pic_point"); + &blindpop("ebx"); + &lea ("ebx",&DWP(&label("iotas")."-".&label("pic_point"),"ebx")); + &and ("esp",-8); + + &shr ("edx",3); # bsz /= 8 + &mov ("edi","esi"); + &lea ("esi",&DWP(100,"esi")); # size optimization + &mov (&DWP(-4,"ebp"),"edx"); # save bsz + &jmp (&label("loop")); + +&set_label("loop",16); + &cmp ("ecx",8); # len < 8? + &jc (&label("tail")); + + &movq ("mm0",&QWP(0,"edi")); + &lea ("edi",&DWP(8,"edi")); + &movq (&QWP(0,"eax"),"mm0"); + &lea ("eax",&DWP(8,"eax")); + &sub ("ecx",8); # len -= 8 + &jz (&label("done")); + + &dec ("edx"); # bsz-- + &jnz (&label("loop")); + + &lea ("edi",&DWP(8*5+100,"esp")); # size optimization + &mov (&DWP(-8,"ebp"),"ecx"); # save len + &call ("_KeccakF1600"); + &mov ("ecx",&DWP(-8,"ebp")); # pull len + &mov ("edx",&DWP(-4,"ebp")); # pull bsz + &lea ("edi",&DWP(-100,"esi")); + &jmp (&label("loop")); + +&set_label("tail",16); + &mov ("esi","edi"); + &mov ("edi","eax"); + &data_word("0xA4F39066"); # rep movsb + +&set_label("done"); + &mov ("esp","ebp"); + &emms (); +&function_end("SHA3_squeeze"); + +&set_label("iotas",32); + &data_word(0x00000001,0x00000000); + &data_word(0x00008082,0x00000000); + &data_word(0x0000808a,0x80000000); + &data_word(0x80008000,0x80000000); + &data_word(0x0000808b,0x00000000); + &data_word(0x80000001,0x00000000); + &data_word(0x80008081,0x80000000); + &data_word(0x00008009,0x80000000); + &data_word(0x0000008a,0x00000000); + &data_word(0x00000088,0x00000000); + &data_word(0x80008009,0x00000000); + &data_word(0x8000000a,0x00000000); + &data_word(0x8000808b,0x00000000); + &data_word(0x0000008b,0x80000000); + &data_word(0x00008089,0x80000000); + &data_word(0x00008003,0x80000000); + &data_word(0x00008002,0x80000000); + &data_word(0x00000080,0x80000000); + &data_word(0x0000800a,0x00000000); + &data_word(0x8000000a,0x80000000); + &data_word(0x80008081,0x80000000); + &data_word(0x00008080,0x80000000); + &data_word(0x80000001,0x00000000); + &data_word(0x80008008,0x80000000); +&asciz("Keccak-1600 absorb and squeeze for MMX, CRYPTOGAMS by "); + +&asm_finish(); + +close STDOUT; diff --git a/crypto/sha/asm/keccak1600-ppc64.pl b/crypto/sha/asm/keccak1600-ppc64.pl new file mode 100755 index 00000000..f89f71c8 --- /dev/null +++ b/crypto/sha/asm/keccak1600-ppc64.pl @@ -0,0 +1,757 @@ +#!/usr/bin/env perl +# 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# Keccak-1600 for PPC64. +# +# June 2017. +# +# This is straightforward KECCAK_1X_ALT implementation that works on +# *any* PPC64. Then PowerISA 2.07 adds 2x64-bit vector rotate, and +# it's possible to achieve performance better than below, but that is +# naturally option only for POWER8 and successors... +# +###################################################################### +# Numbers are cycles per processed byte. +# +# r=1088(*) +# +# PPC970/G5 14.6/+120% +# POWER7 10.3/+100% +# POWER8 11.5/+85% +# +# (*) Corresponds to SHA3-256. Percentage after slash is improvement +# over gcc-4.x-generated KECCAK_1X_ALT code. Newer compilers do +# much better (but watch out for them generating code specific +# to processor they execute on). + +$flavour = shift; + +if ($flavour =~ /64/) { + $SIZE_T =8; + $LRSAVE =2*$SIZE_T; + $UCMP ="cmpld"; + $STU ="stdu"; + $POP ="ld"; + $PUSH ="std"; +} else { die "nonsense $flavour"; } + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +( $xlate="${dir}ppc-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../perlasm/ppc-xlate.pl" and -f $xlate) or +die "can't locate ppc-xlate.pl"; + +open STDOUT,"| $^X $xlate $flavour ".shift || die "can't call $xlate: $!"; + +$FRAME=24*$SIZE_T+6*$SIZE_T+32; +$LOCALS=6*$SIZE_T; +$TEMP=$LOCALS+6*$SIZE_T; + +my $sp ="r1"; + +my @A = map([ "r$_", "r".($_+1), "r".($_+2), "r".($_+3), "r".($_+4) ], + (7, 12, 17, 22, 27)); + $A[1][1] = "r6"; # r13 is reserved + +my @C = map("r$_", (0,3,4,5)); + +my @rhotates = ([ 0, 1, 62, 28, 27 ], + [ 36, 44, 6, 55, 20 ], + [ 3, 10, 43, 25, 39 ], + [ 41, 45, 15, 21, 8 ], + [ 18, 2, 61, 56, 14 ]); + +$code.=<<___; +.text + +.type KeccakF1600_int,\@function +.align 5 +KeccakF1600_int: + li r0,24 + mtctr r0 + b .Loop +.align 4 +.Loop: + xor $C[0],$A[0][0],$A[1][0] ; Theta + std $A[0][4],`$TEMP+0`($sp) + xor $C[1],$A[0][1],$A[1][1] + std $A[1][4],`$TEMP+8`($sp) + xor $C[2],$A[0][2],$A[1][2] + std $A[2][4],`$TEMP+16`($sp) + xor $C[3],$A[0][3],$A[1][3] + std $A[3][4],`$TEMP+24`($sp) +___ + $C[4]=$A[0][4]; + $C[5]=$A[1][4]; + $C[6]=$A[2][4]; + $C[7]=$A[3][4]; +$code.=<<___; + xor $C[4],$A[0][4],$A[1][4] + xor $C[0],$C[0],$A[2][0] + xor $C[1],$C[1],$A[2][1] + xor $C[2],$C[2],$A[2][2] + xor $C[3],$C[3],$A[2][3] + xor $C[4],$C[4],$A[2][4] + xor $C[0],$C[0],$A[3][0] + xor $C[1],$C[1],$A[3][1] + xor $C[2],$C[2],$A[3][2] + xor $C[3],$C[3],$A[3][3] + xor $C[4],$C[4],$A[3][4] + xor $C[0],$C[0],$A[4][0] + xor $C[2],$C[2],$A[4][2] + xor $C[1],$C[1],$A[4][1] + xor $C[3],$C[3],$A[4][3] + rotldi $C[5],$C[2],1 + xor $C[4],$C[4],$A[4][4] + rotldi $C[6],$C[3],1 + xor $C[5],$C[5],$C[0] + rotldi $C[7],$C[4],1 + + xor $A[0][1],$A[0][1],$C[5] + xor $A[1][1],$A[1][1],$C[5] + xor $A[2][1],$A[2][1],$C[5] + xor $A[3][1],$A[3][1],$C[5] + xor $A[4][1],$A[4][1],$C[5] + + rotldi $C[5],$C[0],1 + xor $C[6],$C[6],$C[1] + xor $C[2],$C[2],$C[7] + rotldi $C[7],$C[1],1 + xor $C[3],$C[3],$C[5] + xor $C[4],$C[4],$C[7] + + xor $C[1], $A[0][2],$C[6] ;mr $C[1],$A[0][2] + xor $A[1][2],$A[1][2],$C[6] + xor $A[2][2],$A[2][2],$C[6] + xor $A[3][2],$A[3][2],$C[6] + xor $A[4][2],$A[4][2],$C[6] + + xor $A[0][0],$A[0][0],$C[4] + xor $A[1][0],$A[1][0],$C[4] + xor $A[2][0],$A[2][0],$C[4] + xor $A[3][0],$A[3][0],$C[4] + xor $A[4][0],$A[4][0],$C[4] +___ + $C[4]=undef; + $C[5]=undef; + $C[6]=undef; + $C[7]=undef; +$code.=<<___; + ld $A[0][4],`$TEMP+0`($sp) + xor $C[0], $A[0][3],$C[2] ;mr $C[0],$A[0][3] + ld $A[1][4],`$TEMP+8`($sp) + xor $A[1][3],$A[1][3],$C[2] + ld $A[2][4],`$TEMP+16`($sp) + xor $A[2][3],$A[2][3],$C[2] + ld $A[3][4],`$TEMP+24`($sp) + xor $A[3][3],$A[3][3],$C[2] + xor $A[4][3],$A[4][3],$C[2] + + xor $C[2], $A[0][4],$C[3] ;mr $C[2],$A[0][4] + xor $A[1][4],$A[1][4],$C[3] + xor $A[2][4],$A[2][4],$C[3] + xor $A[3][4],$A[3][4],$C[3] + xor $A[4][4],$A[4][4],$C[3] + + mr $C[3],$A[0][1] ; Rho+Pi + rotldi $A[0][1],$A[1][1],$rhotates[1][1] + ;mr $C[1],$A[0][2] + rotldi $A[0][2],$A[2][2],$rhotates[2][2] + ;mr $C[0],$A[0][3] + rotldi $A[0][3],$A[3][3],$rhotates[3][3] + ;mr $C[2],$A[0][4] + rotldi $A[0][4],$A[4][4],$rhotates[4][4] + + rotldi $A[1][1],$A[1][4],$rhotates[1][4] + rotldi $A[2][2],$A[2][3],$rhotates[2][3] + rotldi $A[3][3],$A[3][2],$rhotates[3][2] + rotldi $A[4][4],$A[4][1],$rhotates[4][1] + + rotldi $A[1][4],$A[4][2],$rhotates[4][2] + rotldi $A[2][3],$A[3][4],$rhotates[3][4] + rotldi $A[3][2],$A[2][1],$rhotates[2][1] + rotldi $A[4][1],$A[1][3],$rhotates[1][3] + + rotldi $A[4][2],$A[2][4],$rhotates[2][4] + rotldi $A[3][4],$A[4][3],$rhotates[4][3] + rotldi $A[2][1],$A[1][2],$rhotates[1][2] + rotldi $A[1][3],$A[3][1],$rhotates[3][1] + + rotldi $A[2][4],$A[4][0],$rhotates[4][0] + rotldi $A[4][3],$A[3][0],$rhotates[3][0] + rotldi $A[1][2],$A[2][0],$rhotates[2][0] + rotldi $A[3][1],$A[1][0],$rhotates[1][0] + + rotldi $A[1][0],$C[0],$rhotates[0][3] + rotldi $A[2][0],$C[3],$rhotates[0][1] + rotldi $A[3][0],$C[2],$rhotates[0][4] + rotldi $A[4][0],$C[1],$rhotates[0][2] + + andc $C[0],$A[0][2],$A[0][1] ; Chi+Iota + andc $C[1],$A[0][3],$A[0][2] + andc $C[2],$A[0][0],$A[0][4] + andc $C[3],$A[0][1],$A[0][0] + xor $A[0][0],$A[0][0],$C[0] + andc $C[0],$A[0][4],$A[0][3] + xor $A[0][1],$A[0][1],$C[1] + ld $C[1],`$LOCALS+4*$SIZE_T`($sp) + xor $A[0][3],$A[0][3],$C[2] + xor $A[0][4],$A[0][4],$C[3] + xor $A[0][2],$A[0][2],$C[0] + ldu $C[3],8($C[1]) ; Iota[i++] + + andc $C[0],$A[1][2],$A[1][1] + std $C[1],`$LOCALS+4*$SIZE_T`($sp) + andc $C[1],$A[1][3],$A[1][2] + andc $C[2],$A[1][0],$A[1][4] + xor $A[0][0],$A[0][0],$C[3] ; A[0][0] ^= Iota + andc $C[3],$A[1][1],$A[1][0] + xor $A[1][0],$A[1][0],$C[0] + andc $C[0],$A[1][4],$A[1][3] + xor $A[1][1],$A[1][1],$C[1] + xor $A[1][3],$A[1][3],$C[2] + xor $A[1][4],$A[1][4],$C[3] + xor $A[1][2],$A[1][2],$C[0] + + andc $C[0],$A[2][2],$A[2][1] + andc $C[1],$A[2][3],$A[2][2] + andc $C[2],$A[2][0],$A[2][4] + andc $C[3],$A[2][1],$A[2][0] + xor $A[2][0],$A[2][0],$C[0] + andc $C[0],$A[2][4],$A[2][3] + xor $A[2][1],$A[2][1],$C[1] + xor $A[2][3],$A[2][3],$C[2] + xor $A[2][4],$A[2][4],$C[3] + xor $A[2][2],$A[2][2],$C[0] + + andc $C[0],$A[3][2],$A[3][1] + andc $C[1],$A[3][3],$A[3][2] + andc $C[2],$A[3][0],$A[3][4] + andc $C[3],$A[3][1],$A[3][0] + xor $A[3][0],$A[3][0],$C[0] + andc $C[0],$A[3][4],$A[3][3] + xor $A[3][1],$A[3][1],$C[1] + xor $A[3][3],$A[3][3],$C[2] + xor $A[3][4],$A[3][4],$C[3] + xor $A[3][2],$A[3][2],$C[0] + + andc $C[0],$A[4][2],$A[4][1] + andc $C[1],$A[4][3],$A[4][2] + andc $C[2],$A[4][0],$A[4][4] + andc $C[3],$A[4][1],$A[4][0] + xor $A[4][0],$A[4][0],$C[0] + andc $C[0],$A[4][4],$A[4][3] + xor $A[4][1],$A[4][1],$C[1] + xor $A[4][3],$A[4][3],$C[2] + xor $A[4][4],$A[4][4],$C[3] + xor $A[4][2],$A[4][2],$C[0] + + bdnz .Loop + + blr + .long 0 + .byte 0,12,0x14,0,0,0,0,0 +.size KeccakF1600_int,.-KeccakF1600_int + +.type KeccakF1600,\@function +.align 5 +KeccakF1600: + $STU $sp,-$FRAME($sp) + mflr r0 + $PUSH r14,`$FRAME-$SIZE_T*18`($sp) + $PUSH r15,`$FRAME-$SIZE_T*17`($sp) + $PUSH r16,`$FRAME-$SIZE_T*16`($sp) + $PUSH r17,`$FRAME-$SIZE_T*15`($sp) + $PUSH r18,`$FRAME-$SIZE_T*14`($sp) + $PUSH r19,`$FRAME-$SIZE_T*13`($sp) + $PUSH r20,`$FRAME-$SIZE_T*12`($sp) + $PUSH r21,`$FRAME-$SIZE_T*11`($sp) + $PUSH r22,`$FRAME-$SIZE_T*10`($sp) + $PUSH r23,`$FRAME-$SIZE_T*9`($sp) + $PUSH r24,`$FRAME-$SIZE_T*8`($sp) + $PUSH r25,`$FRAME-$SIZE_T*7`($sp) + $PUSH r26,`$FRAME-$SIZE_T*6`($sp) + $PUSH r27,`$FRAME-$SIZE_T*5`($sp) + $PUSH r28,`$FRAME-$SIZE_T*4`($sp) + $PUSH r29,`$FRAME-$SIZE_T*3`($sp) + $PUSH r30,`$FRAME-$SIZE_T*2`($sp) + $PUSH r31,`$FRAME-$SIZE_T*1`($sp) + $PUSH r0,`$FRAME+$LRSAVE`($sp) + + bl PICmeup + subi r12,r12,8 ; prepare for ldu + + $PUSH r3,`$LOCALS+0*$SIZE_T`($sp) + ;$PUSH r4,`$LOCALS+1*$SIZE_T`($sp) + ;$PUSH r5,`$LOCALS+2*$SIZE_T`($sp) + ;$PUSH r6,`$LOCALS+3*$SIZE_T`($sp) + $PUSH r12,`$LOCALS+4*$SIZE_T`($sp) + + ld $A[0][0],`8*0`(r3) ; load A[5][5] + ld $A[0][1],`8*1`(r3) + ld $A[0][2],`8*2`(r3) + ld $A[0][3],`8*3`(r3) + ld $A[0][4],`8*4`(r3) + ld $A[1][0],`8*5`(r3) + ld $A[1][1],`8*6`(r3) + ld $A[1][2],`8*7`(r3) + ld $A[1][3],`8*8`(r3) + ld $A[1][4],`8*9`(r3) + ld $A[2][0],`8*10`(r3) + ld $A[2][1],`8*11`(r3) + ld $A[2][2],`8*12`(r3) + ld $A[2][3],`8*13`(r3) + ld $A[2][4],`8*14`(r3) + ld $A[3][0],`8*15`(r3) + ld $A[3][1],`8*16`(r3) + ld $A[3][2],`8*17`(r3) + ld $A[3][3],`8*18`(r3) + ld $A[3][4],`8*19`(r3) + ld $A[4][0],`8*20`(r3) + ld $A[4][1],`8*21`(r3) + ld $A[4][2],`8*22`(r3) + ld $A[4][3],`8*23`(r3) + ld $A[4][4],`8*24`(r3) + + bl KeccakF1600_int + + $POP r3,`$LOCALS+0*$SIZE_T`($sp) + std $A[0][0],`8*0`(r3) ; return A[5][5] + std $A[0][1],`8*1`(r3) + std $A[0][2],`8*2`(r3) + std $A[0][3],`8*3`(r3) + std $A[0][4],`8*4`(r3) + std $A[1][0],`8*5`(r3) + std $A[1][1],`8*6`(r3) + std $A[1][2],`8*7`(r3) + std $A[1][3],`8*8`(r3) + std $A[1][4],`8*9`(r3) + std $A[2][0],`8*10`(r3) + std $A[2][1],`8*11`(r3) + std $A[2][2],`8*12`(r3) + std $A[2][3],`8*13`(r3) + std $A[2][4],`8*14`(r3) + std $A[3][0],`8*15`(r3) + std $A[3][1],`8*16`(r3) + std $A[3][2],`8*17`(r3) + std $A[3][3],`8*18`(r3) + std $A[3][4],`8*19`(r3) + std $A[4][0],`8*20`(r3) + std $A[4][1],`8*21`(r3) + std $A[4][2],`8*22`(r3) + std $A[4][3],`8*23`(r3) + std $A[4][4],`8*24`(r3) + + $POP r0,`$FRAME+$LRSAVE`($sp) + $POP r14,`$FRAME-$SIZE_T*18`($sp) + $POP r15,`$FRAME-$SIZE_T*17`($sp) + $POP r16,`$FRAME-$SIZE_T*16`($sp) + $POP r17,`$FRAME-$SIZE_T*15`($sp) + $POP r18,`$FRAME-$SIZE_T*14`($sp) + $POP r19,`$FRAME-$SIZE_T*13`($sp) + $POP r20,`$FRAME-$SIZE_T*12`($sp) + $POP r21,`$FRAME-$SIZE_T*11`($sp) + $POP r22,`$FRAME-$SIZE_T*10`($sp) + $POP r23,`$FRAME-$SIZE_T*9`($sp) + $POP r24,`$FRAME-$SIZE_T*8`($sp) + $POP r25,`$FRAME-$SIZE_T*7`($sp) + $POP r26,`$FRAME-$SIZE_T*6`($sp) + $POP r27,`$FRAME-$SIZE_T*5`($sp) + $POP r28,`$FRAME-$SIZE_T*4`($sp) + $POP r29,`$FRAME-$SIZE_T*3`($sp) + $POP r30,`$FRAME-$SIZE_T*2`($sp) + $POP r31,`$FRAME-$SIZE_T*1`($sp) + mtlr r0 + addi $sp,$sp,$FRAME + blr + .long 0 + .byte 0,12,4,1,0x80,18,1,0 + .long 0 +.size KeccakF1600,.-KeccakF1600 + +.type dword_le_load,\@function +.align 5 +dword_le_load: + lbzu r0,1(r3) + lbzu r4,1(r3) + lbzu r5,1(r3) + insrdi r0,r4,8,48 + lbzu r4,1(r3) + insrdi r0,r5,8,40 + lbzu r5,1(r3) + insrdi r0,r4,8,32 + lbzu r4,1(r3) + insrdi r0,r5,8,24 + lbzu r5,1(r3) + insrdi r0,r4,8,16 + lbzu r4,1(r3) + insrdi r0,r5,8,8 + insrdi r0,r4,8,0 + blr + .long 0 + .byte 0,12,0x14,0,0,0,1,0 + .long 0 +.size dword_le_load,.-dword_le_load + +.globl SHA3_absorb +.type SHA3_absorb,\@function +.align 5 +SHA3_absorb: + $STU $sp,-$FRAME($sp) + mflr r0 + $PUSH r14,`$FRAME-$SIZE_T*18`($sp) + $PUSH r15,`$FRAME-$SIZE_T*17`($sp) + $PUSH r16,`$FRAME-$SIZE_T*16`($sp) + $PUSH r17,`$FRAME-$SIZE_T*15`($sp) + $PUSH r18,`$FRAME-$SIZE_T*14`($sp) + $PUSH r19,`$FRAME-$SIZE_T*13`($sp) + $PUSH r20,`$FRAME-$SIZE_T*12`($sp) + $PUSH r21,`$FRAME-$SIZE_T*11`($sp) + $PUSH r22,`$FRAME-$SIZE_T*10`($sp) + $PUSH r23,`$FRAME-$SIZE_T*9`($sp) + $PUSH r24,`$FRAME-$SIZE_T*8`($sp) + $PUSH r25,`$FRAME-$SIZE_T*7`($sp) + $PUSH r26,`$FRAME-$SIZE_T*6`($sp) + $PUSH r27,`$FRAME-$SIZE_T*5`($sp) + $PUSH r28,`$FRAME-$SIZE_T*4`($sp) + $PUSH r29,`$FRAME-$SIZE_T*3`($sp) + $PUSH r30,`$FRAME-$SIZE_T*2`($sp) + $PUSH r31,`$FRAME-$SIZE_T*1`($sp) + $PUSH r0,`$FRAME+$LRSAVE`($sp) + + bl PICmeup + subi r4,r4,1 ; prepare for lbzu + subi r12,r12,8 ; prepare for ldu + + $PUSH r3,`$LOCALS+0*$SIZE_T`($sp) ; save A[][] + $PUSH r4,`$LOCALS+1*$SIZE_T`($sp) ; save inp + $PUSH r5,`$LOCALS+2*$SIZE_T`($sp) ; save len + $PUSH r6,`$LOCALS+3*$SIZE_T`($sp) ; save bsz + mr r0,r6 + $PUSH r12,`$LOCALS+4*$SIZE_T`($sp) + + ld $A[0][0],`8*0`(r3) ; load A[5][5] + ld $A[0][1],`8*1`(r3) + ld $A[0][2],`8*2`(r3) + ld $A[0][3],`8*3`(r3) + ld $A[0][4],`8*4`(r3) + ld $A[1][0],`8*5`(r3) + ld $A[1][1],`8*6`(r3) + ld $A[1][2],`8*7`(r3) + ld $A[1][3],`8*8`(r3) + ld $A[1][4],`8*9`(r3) + ld $A[2][0],`8*10`(r3) + ld $A[2][1],`8*11`(r3) + ld $A[2][2],`8*12`(r3) + ld $A[2][3],`8*13`(r3) + ld $A[2][4],`8*14`(r3) + ld $A[3][0],`8*15`(r3) + ld $A[3][1],`8*16`(r3) + ld $A[3][2],`8*17`(r3) + ld $A[3][3],`8*18`(r3) + ld $A[3][4],`8*19`(r3) + ld $A[4][0],`8*20`(r3) + ld $A[4][1],`8*21`(r3) + ld $A[4][2],`8*22`(r3) + ld $A[4][3],`8*23`(r3) + ld $A[4][4],`8*24`(r3) + + mr r3,r4 + mr r4,r5 + mr r5,r0 + + b .Loop_absorb + +.align 4 +.Loop_absorb: + $UCMP r4,r5 ; len < bsz? + blt .Labsorbed + + sub r4,r4,r5 ; len -= bsz + srwi r5,r5,3 + $PUSH r4,`$LOCALS+2*$SIZE_T`($sp) ; save len + mtctr r5 + bl dword_le_load ; *inp++ + xor $A[0][0],$A[0][0],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[0][1],$A[0][1],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[0][2],$A[0][2],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[0][3],$A[0][3],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[0][4],$A[0][4],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[1][0],$A[1][0],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[1][1],$A[1][1],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[1][2],$A[1][2],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[1][3],$A[1][3],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[1][4],$A[1][4],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[2][0],$A[2][0],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[2][1],$A[2][1],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[2][2],$A[2][2],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[2][3],$A[2][3],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[2][4],$A[2][4],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[3][0],$A[3][0],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[3][1],$A[3][1],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[3][2],$A[3][2],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[3][3],$A[3][3],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[3][4],$A[3][4],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[4][0],$A[4][0],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[4][1],$A[4][1],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[4][2],$A[4][2],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[4][3],$A[4][3],r0 + bdz .Lprocess_block + bl dword_le_load ; *inp++ + xor $A[4][4],$A[4][4],r0 + +.Lprocess_block: + $PUSH r3,`$LOCALS+1*$SIZE_T`($sp) ; save inp + + bl KeccakF1600_int + + $POP r0,`$LOCALS+4*$SIZE_T`($sp) ; pull iotas[24] + $POP r5,`$LOCALS+3*$SIZE_T`($sp) ; restore bsz + $POP r4,`$LOCALS+2*$SIZE_T`($sp) ; restore len + $POP r3,`$LOCALS+1*$SIZE_T`($sp) ; restore inp + addic r0,r0,`-8*24` ; rewind iotas + $PUSH r0,`$LOCALS+4*$SIZE_T`($sp) + + b .Loop_absorb + +.align 4 +.Labsorbed: + $POP r3,`$LOCALS+0*$SIZE_T`($sp) + std $A[0][0],`8*0`(r3) ; return A[5][5] + std $A[0][1],`8*1`(r3) + std $A[0][2],`8*2`(r3) + std $A[0][3],`8*3`(r3) + std $A[0][4],`8*4`(r3) + std $A[1][0],`8*5`(r3) + std $A[1][1],`8*6`(r3) + std $A[1][2],`8*7`(r3) + std $A[1][3],`8*8`(r3) + std $A[1][4],`8*9`(r3) + std $A[2][0],`8*10`(r3) + std $A[2][1],`8*11`(r3) + std $A[2][2],`8*12`(r3) + std $A[2][3],`8*13`(r3) + std $A[2][4],`8*14`(r3) + std $A[3][0],`8*15`(r3) + std $A[3][1],`8*16`(r3) + std $A[3][2],`8*17`(r3) + std $A[3][3],`8*18`(r3) + std $A[3][4],`8*19`(r3) + std $A[4][0],`8*20`(r3) + std $A[4][1],`8*21`(r3) + std $A[4][2],`8*22`(r3) + std $A[4][3],`8*23`(r3) + std $A[4][4],`8*24`(r3) + + mr r3,r4 ; return value + $POP r0,`$FRAME+$LRSAVE`($sp) + $POP r14,`$FRAME-$SIZE_T*18`($sp) + $POP r15,`$FRAME-$SIZE_T*17`($sp) + $POP r16,`$FRAME-$SIZE_T*16`($sp) + $POP r17,`$FRAME-$SIZE_T*15`($sp) + $POP r18,`$FRAME-$SIZE_T*14`($sp) + $POP r19,`$FRAME-$SIZE_T*13`($sp) + $POP r20,`$FRAME-$SIZE_T*12`($sp) + $POP r21,`$FRAME-$SIZE_T*11`($sp) + $POP r22,`$FRAME-$SIZE_T*10`($sp) + $POP r23,`$FRAME-$SIZE_T*9`($sp) + $POP r24,`$FRAME-$SIZE_T*8`($sp) + $POP r25,`$FRAME-$SIZE_T*7`($sp) + $POP r26,`$FRAME-$SIZE_T*6`($sp) + $POP r27,`$FRAME-$SIZE_T*5`($sp) + $POP r28,`$FRAME-$SIZE_T*4`($sp) + $POP r29,`$FRAME-$SIZE_T*3`($sp) + $POP r30,`$FRAME-$SIZE_T*2`($sp) + $POP r31,`$FRAME-$SIZE_T*1`($sp) + mtlr r0 + addi $sp,$sp,$FRAME + blr + .long 0 + .byte 0,12,4,1,0x80,18,4,0 + .long 0 +.size SHA3_absorb,.-SHA3_absorb +___ +{ +my ($A_flat,$out,$len,$bsz) = map("r$_",(28..31)); +$code.=<<___; +.globl SHA3_squeeze +.type SHA3_squeeze,\@function +.align 5 +SHA3_squeeze: + $STU $sp,`-10*$SIZE_T`($sp) + mflr r0 + $PUSH r28,`6*$SIZE_T`($sp) + $PUSH r29,`7*$SIZE_T`($sp) + $PUSH r30,`8*$SIZE_T`($sp) + $PUSH r31,`9*$SIZE_T`($sp) + $PUSH r0,`10*$SIZE_T+$LRSAVE`($sp) + + mr $A_flat,r3 + subi r3,r3,8 ; prepare for ldu + subi $out,r4,1 ; prepare for stbu + mr $len,r5 + mr $bsz,r6 + b .Loop_squeeze + +.align 4 +.Loop_squeeze: + ldu r0,8(r3) + ${UCMP}i $len,8 + blt .Lsqueeze_tail + + stbu r0,1($out) + srdi r0,r0,8 + stbu r0,1($out) + srdi r0,r0,8 + stbu r0,1($out) + srdi r0,r0,8 + stbu r0,1($out) + srdi r0,r0,8 + stbu r0,1($out) + srdi r0,r0,8 + stbu r0,1($out) + srdi r0,r0,8 + stbu r0,1($out) + srdi r0,r0,8 + stbu r0,1($out) + + subic. $len,$len,8 + beq .Lsqueeze_done + + subic. r6,r6,8 + bgt .Loop_squeeze + + mr r3,$A_flat + bl KeccakF1600 + subi r3,$A_flat,8 ; prepare for ldu + mr r6,$bsz + b .Loop_squeeze + +.align 4 +.Lsqueeze_tail: + mtctr $len +.Loop_tail: + stbu r0,1($out) + srdi r0,r0,8 + bdnz .Loop_tail + +.Lsqueeze_done: + $POP r0,`10*$SIZE_T+$LRSAVE`($sp) + $POP r28,`6*$SIZE_T`($sp) + $POP r29,`7*$SIZE_T`($sp) + $POP r30,`8*$SIZE_T`($sp) + $POP r31,`9*$SIZE_T`($sp) + mtlr r0 + addi $sp,$sp,`10*$SIZE_T` + blr + .long 0 + .byte 0,12,4,1,0x80,4,4,0 + .long 0 +.size SHA3_squeeze,.-SHA3_squeeze +___ +} + +# Ugly hack here, because PPC assembler syntax seem to vary too +# much from platforms to platform... +$code.=<<___; +.align 6 +PICmeup: + mflr r0 + bcl 20,31,\$+4 + mflr r12 ; vvvvvv "distance" between . and 1st data entry + addi r12,r12,`64-8` + mtlr r0 + blr + .long 0 + .byte 0,12,0x14,0,0,0,0,0 + .space `64-9*4` +.type iotas,\@object +iotas: + .quad 0x0000000000000001 + .quad 0x0000000000008082 + .quad 0x800000000000808a + .quad 0x8000000080008000 + .quad 0x000000000000808b + .quad 0x0000000080000001 + .quad 0x8000000080008081 + .quad 0x8000000000008009 + .quad 0x000000000000008a + .quad 0x0000000000000088 + .quad 0x0000000080008009 + .quad 0x000000008000000a + .quad 0x000000008000808b + .quad 0x800000000000008b + .quad 0x8000000000008089 + .quad 0x8000000000008003 + .quad 0x8000000000008002 + .quad 0x8000000000000080 + .quad 0x000000000000800a + .quad 0x800000008000000a + .quad 0x8000000080008081 + .quad 0x8000000000008080 + .quad 0x0000000080000001 + .quad 0x8000000080008008 +.size iotas,.-iotas +.asciz "Keccak-1600 absorb and squeeze for PPC64, CRYPTOGAMS by " +___ + +$code =~ s/\`([^\`]*)\`/eval $1/gem; +print $code; +close STDOUT; diff --git a/crypto/sha/asm/keccak1600-s390x.pl b/crypto/sha/asm/keccak1600-s390x.pl new file mode 100755 index 00000000..4bd3619f --- /dev/null +++ b/crypto/sha/asm/keccak1600-s390x.pl @@ -0,0 +1,561 @@ +#!/usr/bin/env perl +# 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# Keccak-1600 for s390x. +# +# June 2017. +# +# Below code is [lane complementing] KECCAK_2X implementation (see +# sha/keccak1600.c) with C[5] and D[5] held in register bank. Though +# instead of actually unrolling the loop pair-wise I simply flip +# pointers to T[][] and A[][] at the end of round. Since number of +# rounds is even, last round writes to A[][] and everything works out. +# In the nutshell it's transliteration of x86_64 module, because both +# architectures have similar capabilities/limitations. Performance +# measurement is problematic as I don't have access to an idle system. +# It looks like z13 processes one byte [out of long message] in ~14 +# cycles. At least the result is consistent with estimate based on +# amount of instruction and assumed instruction issue rate. It's ~2.5x +# faster than compiler-generated code. + +$flavour = shift; + +if ($flavour =~ /3[12]/) { + $SIZE_T=4; + $g=""; +} else { + $SIZE_T=8; + $g="g"; +} + +while (($output=shift) && ($output!~/\w[\w\-]*\.\w+$/)) {} +open STDOUT,">$output"; + +my @A = map([ 8*$_, 8*($_+1), 8*($_+2), 8*($_+3), 8*($_+4) ], (0,5,10,15,20)); + +my @C = map("%r$_",(0,1,5..7)); +my @D = map("%r$_",(8..12)); +my @T = map("%r$_",(13..14)); +my ($src,$dst,$iotas) = map("%r$_",(2..4)); +my $sp = "%r15"; + +$stdframe=16*$SIZE_T+4*8; +$frame=$stdframe+25*8; + +my @rhotates = ([ 0, 1, 62, 28, 27 ], + [ 36, 44, 6, 55, 20 ], + [ 3, 10, 43, 25, 39 ], + [ 41, 45, 15, 21, 8 ], + [ 18, 2, 61, 56, 14 ]); + +{ my @C = @C; # copy, because we mess them up... + my @D = @D; + +$code.=<<___; +.text + +.type __KeccakF1600,\@function +.align 32 +__KeccakF1600: + st${g} %r14,$SIZE_T*14($sp) + lg @C[0],$A[4][0]($src) + lg @C[1],$A[4][1]($src) + lg @C[2],$A[4][2]($src) + lg @C[3],$A[4][3]($src) + lg @C[4],$A[4][4]($src) + larl $iotas,iotas + j .Loop + +.align 16 +.Loop: + lg @D[0],$A[0][0]($src) + lg @D[1],$A[1][1]($src) + lg @D[2],$A[2][2]($src) + lg @D[3],$A[3][3]($src) + + xgr @C[0],@D[0] + xg @C[1],$A[0][1]($src) + xg @C[2],$A[0][2]($src) + xg @C[3],$A[0][3]($src) + lgr @D[4],@C[4] + xg @C[4],$A[0][4]($src) + + xg @C[0],$A[1][0]($src) + xgr @C[1],@D[1] + xg @C[2],$A[1][2]($src) + xg @C[3],$A[1][3]($src) + xg @C[4],$A[1][4]($src) + + xg @C[0],$A[2][0]($src) + xg @C[1],$A[2][1]($src) + xgr @C[2],@D[2] + xg @C[3],$A[2][3]($src) + xg @C[4],$A[2][4]($src) + + xg @C[0],$A[3][0]($src) + xg @C[1],$A[3][1]($src) + xg @C[2],$A[3][2]($src) + xgr @C[3],@D[3] + xg @C[4],$A[3][4]($src) + + lgr @T[0],@C[2] + rllg @C[2],@C[2],1 + xgr @C[2],@C[0] # D[1] = ROL64(C[2], 1) ^ C[0] + + rllg @C[0],@C[0],1 + xgr @C[0],@C[3] # D[4] = ROL64(C[0], 1) ^ C[3] + + rllg @C[3],@C[3],1 + xgr @C[3],@C[1] # D[2] = ROL64(C[3], 1) ^ C[1] + + rllg @C[1],@C[1],1 + xgr @C[1],@C[4] # D[0] = ROL64(C[1], 1) ^ C[4] + + rllg @C[4],@C[4],1 + xgr @C[4],@T[0] # D[3] = ROL64(C[4], 1) ^ C[2] +___ + (@D[0..4], @C) = (@C[1..4,0], @D); +$code.=<<___; + xgr @C[1],@D[1] + xgr @C[2],@D[2] + xgr @C[3],@D[3] + rllg @C[1],@C[1],$rhotates[1][1] + xgr @C[4],@D[4] + rllg @C[2],@C[2],$rhotates[2][2] + xgr @C[0],@D[0] + + lgr @T[0],@C[1] + ogr @C[1],@C[2] + rllg @C[3],@C[3],$rhotates[3][3] + xgr @C[1],@C[0] # C[0] ^ ( C[1] | C[2]) + rllg @C[4],@C[4],$rhotates[4][4] + xg @C[1],0($iotas) + la $iotas,8($iotas) + stg @C[1],$A[0][0]($dst) # R[0][0] = C[0] ^ ( C[1] | C[2]) ^ iotas[i] + + lgr @T[1],@C[4] + ngr @C[4],@C[3] + lghi @C[1],-1 # no 'not' instruction :-( + xgr @C[4],@C[2] # C[2] ^ ( C[4] & C[3]) + xgr @C[2],@C[1] # not @C[2] + stg @C[4],$A[0][2]($dst) # R[0][2] = C[2] ^ ( C[4] & C[3]) + ogr @C[2],@C[3] + xgr @C[2],@T[0] # C[1] ^ (~C[2] | C[3]) + + ngr @T[0],@C[0] + stg @C[2],$A[0][1]($dst) # R[0][1] = C[1] ^ (~C[2] | C[3]) + xgr @T[0],@T[1] # C[4] ^ ( C[1] & C[0]) + ogr @T[1],@C[0] + stg @T[0],$A[0][4]($dst) # R[0][4] = C[4] ^ ( C[1] & C[0]) + xgr @T[1],@C[3] # C[3] ^ ( C[4] | C[0]) + stg @T[1],$A[0][3]($dst) # R[0][3] = C[3] ^ ( C[4] | C[0]) + + + lg @C[0],$A[0][3]($src) + lg @C[4],$A[4][2]($src) + lg @C[3],$A[3][1]($src) + lg @C[1],$A[1][4]($src) + lg @C[2],$A[2][0]($src) + + xgr @C[0],@D[3] + xgr @C[4],@D[2] + rllg @C[0],@C[0],$rhotates[0][3] + xgr @C[3],@D[1] + rllg @C[4],@C[4],$rhotates[4][2] + xgr @C[1],@D[4] + rllg @C[3],@C[3],$rhotates[3][1] + xgr @C[2],@D[0] + + lgr @T[0],@C[0] + ogr @C[0],@C[4] + rllg @C[1],@C[1],$rhotates[1][4] + xgr @C[0],@C[3] # C[3] ^ (C[0] | C[4]) + rllg @C[2],@C[2],$rhotates[2][0] + stg @C[0],$A[1][3]($dst) # R[1][3] = C[3] ^ (C[0] | C[4]) + + lgr @T[1],@C[1] + ngr @C[1],@T[0] + lghi @C[0],-1 # no 'not' instruction :-( + xgr @C[1],@C[4] # C[4] ^ (C[1] & C[0]) + xgr @C[4],@C[0] # not @C[4] + stg @C[1],$A[1][4]($dst) # R[1][4] = C[4] ^ (C[1] & C[0]) + + ogr @C[4],@C[3] + xgr @C[4],@C[2] # C[2] ^ (~C[4] | C[3]) + + ngr @C[3],@C[2] + stg @C[4],$A[1][2]($dst) # R[1][2] = C[2] ^ (~C[4] | C[3]) + xgr @C[3],@T[1] # C[1] ^ (C[3] & C[2]) + ogr @T[1],@C[2] + stg @C[3],$A[1][1]($dst) # R[1][1] = C[1] ^ (C[3] & C[2]) + xgr @T[1],@T[0] # C[0] ^ (C[1] | C[2]) + stg @T[1],$A[1][0]($dst) # R[1][0] = C[0] ^ (C[1] | C[2]) + + + lg @C[2],$A[2][3]($src) + lg @C[3],$A[3][4]($src) + lg @C[1],$A[1][2]($src) + lg @C[4],$A[4][0]($src) + lg @C[0],$A[0][1]($src) + + xgr @C[2],@D[3] + xgr @C[3],@D[4] + rllg @C[2],@C[2],$rhotates[2][3] + xgr @C[1],@D[2] + rllg @C[3],@C[3],$rhotates[3][4] + xgr @C[4],@D[0] + rllg @C[1],@C[1],$rhotates[1][2] + xgr @C[0],@D[1] + + lgr @T[0],@C[2] + ngr @C[2],@C[3] + rllg @C[4],@C[4],$rhotates[4][0] + xgr @C[2],@C[1] # C[1] ^ ( C[2] & C[3]) + lghi @T[1],-1 # no 'not' instruction :-( + stg @C[2],$A[2][1]($dst) # R[2][1] = C[1] ^ ( C[2] & C[3]) + + xgr @C[3],@T[1] # not @C[3] + lgr @T[1],@C[4] + ngr @C[4],@C[3] + rllg @C[0],@C[0],$rhotates[0][1] + xgr @C[4],@T[0] # C[2] ^ ( C[4] & ~C[3]) + ogr @T[0],@C[1] + stg @C[4],$A[2][2]($dst) # R[2][2] = C[2] ^ ( C[4] & ~C[3]) + xgr @T[0],@C[0] # C[0] ^ ( C[2] | C[1]) + + ngr @C[1],@C[0] + stg @T[0],$A[2][0]($dst) # R[2][0] = C[0] ^ ( C[2] | C[1]) + xgr @C[1],@T[1] # C[4] ^ ( C[1] & C[0]) + ogr @C[0],@T[1] + stg @C[1],$A[2][4]($dst) # R[2][4] = C[4] ^ ( C[1] & C[0]) + xgr @C[0],@C[3] # ~C[3] ^ ( C[0] | C[4]) + stg @C[0],$A[2][3]($dst) # R[2][3] = ~C[3] ^ ( C[0] | C[4]) + + + lg @C[2],$A[2][1]($src) + lg @C[3],$A[3][2]($src) + lg @C[1],$A[1][0]($src) + lg @C[4],$A[4][3]($src) + lg @C[0],$A[0][4]($src) + + xgr @C[2],@D[1] + xgr @C[3],@D[2] + rllg @C[2],@C[2],$rhotates[2][1] + xgr @C[1],@D[0] + rllg @C[3],@C[3],$rhotates[3][2] + xgr @C[4],@D[3] + rllg @C[1],@C[1],$rhotates[1][0] + xgr @C[0],@D[4] + rllg @C[4],@C[4],$rhotates[4][3] + + lgr @T[0],@C[2] + ogr @C[2],@C[3] + lghi @T[1],-1 # no 'not' instruction :-( + xgr @C[2],@C[1] # C[1] ^ ( C[2] | C[3]) + xgr @C[3],@T[1] # not @C[3] + stg @C[2],$A[3][1]($dst) # R[3][1] = C[1] ^ ( C[2] | C[3]) + + lgr @T[1],@C[4] + ogr @C[4],@C[3] + rllg @C[0],@C[0],$rhotates[0][4] + xgr @C[4],@T[0] # C[2] ^ ( C[4] | ~C[3]) + ngr @T[0],@C[1] + stg @C[4],$A[3][2]($dst) # R[3][2] = C[2] ^ ( C[4] | ~C[3]) + xgr @T[0],@C[0] # C[0] ^ ( C[2] & C[1]) + + ogr @C[1],@C[0] + stg @T[0],$A[3][0]($dst) # R[3][0] = C[0] ^ ( C[2] & C[1]) + xgr @C[1],@T[1] # C[4] ^ ( C[1] | C[0]) + ngr @C[0],@T[1] + stg @C[1],$A[3][4]($dst) # R[3][4] = C[4] ^ ( C[1] | C[0]) + xgr @C[0],@C[3] # ~C[3] ^ ( C[0] & C[4]) + stg @C[0],$A[3][3]($dst) # R[3][3] = ~C[3] ^ ( C[0] & C[4]) + + + xg @D[2],$A[0][2]($src) + xg @D[3],$A[1][3]($src) + xg @D[1],$A[4][1]($src) + xg @D[4],$A[2][4]($src) + xgr $dst,$src # xchg $dst,$src + rllg @D[2],@D[2],$rhotates[0][2] + xg @D[0],$A[3][0]($src) + rllg @D[3],@D[3],$rhotates[1][3] + xgr $src,$dst + rllg @D[1],@D[1],$rhotates[4][1] + xgr $dst,$src + rllg @D[4],@D[4],$rhotates[2][4] +___ + @C = @D[2..4,0,1]; +$code.=<<___; + lgr @T[0],@C[0] + ngr @C[0],@C[1] + lghi @T[1],-1 # no 'not' instruction :-( + xgr @C[0],@C[4] # C[4] ^ ( C[0] & C[1]) + xgr @C[1],@T[1] # not @C[1] + stg @C[0],$A[4][4]($src) # R[4][4] = C[4] ^ ( C[0] & C[1]) + + lgr @T[1],@C[2] + ngr @C[2],@C[1] + rllg @D[0],@D[0],$rhotates[3][0] + xgr @C[2],@T[0] # C[0] ^ ( C[2] & ~C[1]) + ogr @T[0],@C[4] + stg @C[2],$A[4][0]($src) # R[4][0] = C[0] ^ ( C[2] & ~C[1]) + xgr @T[0],@C[3] # C[3] ^ ( C[0] | C[4]) + + ngr @C[4],@C[3] + stg @T[0],$A[4][3]($src) # R[4][3] = C[3] ^ ( C[0] | C[4]) + xgr @C[4],@T[1] # C[2] ^ ( C[4] & C[3]) + ogr @C[3],@T[1] + stg @C[4],$A[4][2]($src) # R[4][2] = C[2] ^ ( C[4] & C[3]) + xgr @C[3],@C[1] # ~C[1] ^ ( C[2] | C[3]) + + lgr @C[1],@C[0] # harmonize with the loop top + lgr @C[0],@T[0] + stg @C[3],$A[4][1]($src) # R[4][1] = ~C[1] ^ ( C[2] | C[3]) + + tmll $iotas,255 + jnz .Loop + + l${g} %r14,$SIZE_T*14($sp) + br %r14 +.size __KeccakF1600,.-__KeccakF1600 +___ +} +{ +$code.=<<___; +.globl KeccakF1600 +.type KeccakF1600,\@function +.align 32 +KeccakF1600: +.LKeccakF1600: + lghi %r1,-$frame + stm${g} %r6,%r15,$SIZE_T*6($sp) + lgr %r0,$sp + la $sp,0(%r1,$sp) + st${g} %r0,0($sp) + + lghi @D[0],-1 # no 'not' instruction :-( + lghi @D[1],-1 + lghi @D[2],-1 + lghi @D[3],-1 + lghi @D[4],-1 + lghi @T[0],-1 + xg @D[0],$A[0][1]($src) + xg @D[1],$A[0][2]($src) + xg @D[2],$A[1][3]($src) + xg @D[3],$A[2][2]($src) + xg @D[4],$A[3][2]($src) + xg @T[0],$A[4][0]($src) + stmg @D[0],@D[1],$A[0][1]($src) + stg @D[2],$A[1][3]($src) + stg @D[3],$A[2][2]($src) + stg @D[4],$A[3][2]($src) + stg @T[0],$A[4][0]($src) + + la $dst,$stdframe($sp) + + bras %r14,__KeccakF1600 + + lghi @D[0],-1 # no 'not' instruction :-( + lghi @D[1],-1 + lghi @D[2],-1 + lghi @D[3],-1 + lghi @D[4],-1 + lghi @T[0],-1 + xg @D[0],$A[0][1]($src) + xg @D[1],$A[0][2]($src) + xg @D[2],$A[1][3]($src) + xg @D[3],$A[2][2]($src) + xg @D[4],$A[3][2]($src) + xg @T[0],$A[4][0]($src) + stmg @D[0],@D[1],$A[0][1]($src) + stg @D[2],$A[1][3]($src) + stg @D[3],$A[2][2]($src) + stg @D[4],$A[3][2]($src) + stg @T[0],$A[4][0]($src) + + lm${g} %r6,%r15,$frame+6*$SIZE_T($sp) + br %r14 +.size KeccakF1600,.-KeccakF1600 +___ +} +{ my ($A_flat,$inp,$len,$bsz) = map("%r$_",(2..5)); + +$code.=<<___; +.globl SHA3_absorb +.type SHA3_absorb,\@function +.align 32 +SHA3_absorb: + lghi %r1,-$frame + stm${g} %r5,%r15,$SIZE_T*5($sp) + lgr %r0,$sp + la $sp,0(%r1,$sp) + st${g} %r0,0($sp) + + lghi @D[0],-1 # no 'not' instruction :-( + lghi @D[1],-1 + lghi @D[2],-1 + lghi @D[3],-1 + lghi @D[4],-1 + lghi @T[0],-1 + xg @D[0],$A[0][1]($src) + xg @D[1],$A[0][2]($src) + xg @D[2],$A[1][3]($src) + xg @D[3],$A[2][2]($src) + xg @D[4],$A[3][2]($src) + xg @T[0],$A[4][0]($src) + stmg @D[0],@D[1],$A[0][1]($src) + stg @D[2],$A[1][3]($src) + stg @D[3],$A[2][2]($src) + stg @D[4],$A[3][2]($src) + stg @T[0],$A[4][0]($src) + +.Loop_absorb: + cl${g}r $len,$bsz + jl .Ldone_absorb + + srl${g} $bsz,3 + la %r1,0($A_flat) + +.Lblock_absorb: + lrvg %r0,0($inp) + la $inp,8($inp) + xg %r0,0(%r1) + la %r1,8(%r1) + a${g}hi $len,-8 + stg %r0,-8(%r1) + brct $bsz,.Lblock_absorb + + stm${g} $inp,$len,$frame+3*$SIZE_T($sp) + la $dst,$stdframe($sp) + bras %r14,__KeccakF1600 + lm${g} $inp,$bsz,$frame+3*$SIZE_T($sp) + j .Loop_absorb + +.align 16 +.Ldone_absorb: + lghi @D[0],-1 # no 'not' instruction :-( + lghi @D[1],-1 + lghi @D[2],-1 + lghi @D[3],-1 + lghi @D[4],-1 + lghi @T[0],-1 + xg @D[0],$A[0][1]($src) + xg @D[1],$A[0][2]($src) + xg @D[2],$A[1][3]($src) + xg @D[3],$A[2][2]($src) + xg @D[4],$A[3][2]($src) + xg @T[0],$A[4][0]($src) + stmg @D[0],@D[1],$A[0][1]($src) + stg @D[2],$A[1][3]($src) + stg @D[3],$A[2][2]($src) + stg @D[4],$A[3][2]($src) + stg @T[0],$A[4][0]($src) + + lgr %r2,$len # return value + + lm${g} %r6,%r15,$frame+6*$SIZE_T($sp) + br %r14 +.size SHA3_absorb,.-SHA3_absorb +___ +} +{ my ($A_flat,$out,$len,$bsz) = map("%r$_",(2..5)); + +$code.=<<___; +.globl SHA3_squeeze +.type SHA3_squeeze,\@function +.align 32 +SHA3_squeeze: + srl${g} $bsz,3 + st${g} %r14,2*$SIZE_T($sp) + lghi %r14,8 + st${g} $bsz,5*$SIZE_T($sp) + la %r1,0($A_flat) + + j .Loop_squeeze + +.align 16 +.Loop_squeeze: + cl${g}r $len,%r14 + jl .Ltail_squeeze + + lrvg %r0,0(%r1) + la %r1,8(%r1) + stg %r0,0($out) + la $out,8($out) + a${g}hi $len,-8 # len -= 8 + jz .Ldone_squeeze + + brct $bsz,.Loop_squeeze # bsz-- + + stm${g} $out,$len,3*$SIZE_T($sp) + bras %r14,.LKeccakF1600 + lm${g} $out,$bsz,3*$SIZE_T($sp) + lghi %r14,8 + la %r1,0($A_flat) + j .Loop_squeeze + +.Ltail_squeeze: + lg %r0,0(%r1) +.Loop_tail_squeeze: + stc %r0,0($out) + la $out,1($out) + srlg %r0,8 + brct $len,.Loop_tail_squeeze + +.Ldone_squeeze: + l${g} %r14,2*$SIZE_T($sp) + br %r14 +.size SHA3_squeeze,.-SHA3_squeeze +___ +} +$code.=<<___; +.align 256 + .quad 0,0,0,0,0,0,0,0 +.type iotas,\@object +iotas: + .quad 0x0000000000000001 + .quad 0x0000000000008082 + .quad 0x800000000000808a + .quad 0x8000000080008000 + .quad 0x000000000000808b + .quad 0x0000000080000001 + .quad 0x8000000080008081 + .quad 0x8000000000008009 + .quad 0x000000000000008a + .quad 0x0000000000000088 + .quad 0x0000000080008009 + .quad 0x000000008000000a + .quad 0x000000008000808b + .quad 0x800000000000008b + .quad 0x8000000000008089 + .quad 0x8000000000008003 + .quad 0x8000000000008002 + .quad 0x8000000000000080 + .quad 0x000000000000800a + .quad 0x800000008000000a + .quad 0x8000000080008081 + .quad 0x8000000000008080 + .quad 0x0000000080000001 + .quad 0x8000000080008008 +.size iotas,.-iotas +.asciz "Keccak-1600 absorb and squeeze for s390x, CRYPTOGAMS by " +___ + +# unlike 32-bit shift 64-bit one takes three arguments +$code =~ s/(srlg\s+)(%r[0-9]+),/$1$2,$2,/gm; + +print $code; +close STDOUT; diff --git a/crypto/sha/asm/keccak1600-x86_64.pl b/crypto/sha/asm/keccak1600-x86_64.pl new file mode 100755 index 00000000..94c9c10f --- /dev/null +++ b/crypto/sha/asm/keccak1600-x86_64.pl @@ -0,0 +1,608 @@ +#!/usr/bin/env perl +# 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# Keccak-1600 for x86_64. +# +# June 2017. +# +# Below code is [lane complementing] KECCAK_2X implementation (see +# sha/keccak1600.c) with C[5] and D[5] held in register bank. Though +# instead of actually unrolling the loop pair-wise I simply flip +# pointers to T[][] and A[][] at the end of round. Since number of +# rounds is even, last round writes to A[][] and everything works out. +# How does it compare to x86_64 assembly module in Keccak Code Package? +# Depending on processor it's either as fast or faster by up to 15%... +# +######################################################################## +# Numbers are cycles per processed byte out of large message. +# +# r=1088(*) +# +# P4 25.8 +# Core 2 12.9 +# Westmere 13.7 +# Sandy Bridge 12.9(**) +# Haswell 9.6 +# Skylake 9.4 +# Silvermont 22.8 +# Goldmont 15.8 +# VIA Nano 17.3 +# Sledgehammer 13.3 +# Bulldozer 16.5 +# Ryzen 8.8 +# +# (*) Corresponds to SHA3-256. Improvement over compiler-generate +# varies a lot, most commont coefficient is 15% in comparison to +# gcc-5.x, 50% for gcc-4.x, 90% for gcc-3.x. +# (**) Sandy Bridge has broken rotate instruction. Performance can be +# improved by 14% by replacing rotates with double-precision +# shift with same register as source and destination. + +$flavour = shift; +$output = shift; +if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } + +$win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or +die "can't locate x86_64-xlate.pl"; + +open OUT,"| \"$^X\" \"$xlate\" $flavour \"$output\""; +*STDOUT=*OUT; + +my @A = map([ 8*$_-100, 8*($_+1)-100, 8*($_+2)-100, + 8*($_+3)-100, 8*($_+4)-100 ], (0,5,10,15,20)); + +my @C = ("%rax","%rbx","%rcx","%rdx","%rbp"); +my @D = map("%r$_",(8..12)); +my @T = map("%r$_",(13..14)); +my $iotas = "%r15"; + +my @rhotates = ([ 0, 1, 62, 28, 27 ], + [ 36, 44, 6, 55, 20 ], + [ 3, 10, 43, 25, 39 ], + [ 41, 45, 15, 21, 8 ], + [ 18, 2, 61, 56, 14 ]); + +$code.=<<___; +.text + +.type __KeccakF1600,\@function +.align 32 +__KeccakF1600: + mov $A[4][0](%rdi),@C[0] + mov $A[4][1](%rdi),@C[1] + mov $A[4][2](%rdi),@C[2] + mov $A[4][3](%rdi),@C[3] + mov $A[4][4](%rdi),@C[4] + jmp .Loop + +.align 32 +.Loop: + mov $A[0][0](%rdi),@D[0] + mov $A[1][1](%rdi),@D[1] + mov $A[2][2](%rdi),@D[2] + mov $A[3][3](%rdi),@D[3] + + xor $A[0][2](%rdi),@C[2] + xor $A[0][3](%rdi),@C[3] + xor @D[0], @C[0] + xor $A[0][1](%rdi),@C[1] + xor $A[1][2](%rdi),@C[2] + xor $A[1][0](%rdi),@C[0] + mov @C[4],@D[4] + xor $A[0][4](%rdi),@C[4] + + xor @D[2], @C[2] + xor $A[2][0](%rdi),@C[0] + xor $A[1][3](%rdi),@C[3] + xor @D[1], @C[1] + xor $A[1][4](%rdi),@C[4] + + xor $A[3][2](%rdi),@C[2] + xor $A[3][0](%rdi),@C[0] + xor $A[2][3](%rdi),@C[3] + xor $A[2][1](%rdi),@C[1] + xor $A[2][4](%rdi),@C[4] + + mov @C[2],@T[0] + rol \$1,@C[2] + xor @C[0],@C[2] # D[1] = ROL64(C[2], 1) ^ C[0] + xor @D[3], @C[3] + + rol \$1,@C[0] + xor @C[3],@C[0] # D[4] = ROL64(C[0], 1) ^ C[3] + xor $A[3][1](%rdi),@C[1] + + rol \$1,@C[3] + xor @C[1],@C[3] # D[2] = ROL64(C[3], 1) ^ C[1] + xor $A[3][4](%rdi),@C[4] + + rol \$1,@C[1] + xor @C[4],@C[1] # D[0] = ROL64(C[1], 1) ^ C[4] + + rol \$1,@C[4] + xor @T[0],@C[4] # D[3] = ROL64(C[4], 1) ^ C[2] +___ + (@D[0..4], @C) = (@C[1..4,0], @D); +$code.=<<___; + xor @D[1],@C[1] + xor @D[2],@C[2] + rol \$$rhotates[1][1],@C[1] + xor @D[3],@C[3] + xor @D[4],@C[4] + rol \$$rhotates[2][2],@C[2] + xor @D[0],@C[0] + mov @C[1],@T[0] + rol \$$rhotates[3][3],@C[3] + or @C[2],@C[1] + xor @C[0],@C[1] # C[0] ^ ( C[1] | C[2]) + rol \$$rhotates[4][4],@C[4] + + xor ($iotas),@C[1] + lea 8($iotas),$iotas + + mov @C[4],@T[1] + and @C[3],@C[4] + mov @C[1],$A[0][0](%rsi) # R[0][0] = C[0] ^ ( C[1] | C[2]) ^ iotas[i] + xor @C[2],@C[4] # C[2] ^ ( C[4] & C[3]) + not @C[2] + mov @C[4],$A[0][2](%rsi) # R[0][2] = C[2] ^ ( C[4] & C[3]) + + or @C[3],@C[2] + mov $A[4][2](%rdi),@C[4] + xor @T[0],@C[2] # C[1] ^ (~C[2] | C[3]) + mov @C[2],$A[0][1](%rsi) # R[0][1] = C[1] ^ (~C[2] | C[3]) + + and @C[0],@T[0] + mov $A[1][4](%rdi),@C[1] + xor @T[1],@T[0] # C[4] ^ ( C[1] & C[0]) + mov $A[2][0](%rdi),@C[2] + mov @T[0],$A[0][4](%rsi) # R[0][4] = C[4] ^ ( C[1] & C[0]) + + or @C[0],@T[1] + mov $A[0][3](%rdi),@C[0] + xor @C[3],@T[1] # C[3] ^ ( C[4] | C[0]) + mov $A[3][1](%rdi),@C[3] + mov @T[1],$A[0][3](%rsi) # R[0][3] = C[3] ^ ( C[4] | C[0]) + + + xor @D[3],@C[0] + xor @D[2],@C[4] + rol \$$rhotates[0][3],@C[0] + xor @D[1],@C[3] + xor @D[4],@C[1] + rol \$$rhotates[4][2],@C[4] + rol \$$rhotates[3][1],@C[3] + xor @D[0],@C[2] + rol \$$rhotates[1][4],@C[1] + mov @C[0],@T[0] + or @C[4],@C[0] + rol \$$rhotates[2][0],@C[2] + + xor @C[3],@C[0] # C[3] ^ (C[0] | C[4]) + mov @C[0],$A[1][3](%rsi) # R[1][3] = C[3] ^ (C[0] | C[4]) + + mov @C[1],@T[1] + and @T[0],@C[1] + mov $A[0][1](%rdi),@C[0] + xor @C[4],@C[1] # C[4] ^ (C[1] & C[0]) + not @C[4] + mov @C[1],$A[1][4](%rsi) # R[1][4] = C[4] ^ (C[1] & C[0]) + + or @C[3],@C[4] + mov $A[1][2](%rdi),@C[1] + xor @C[2],@C[4] # C[2] ^ (~C[4] | C[3]) + mov @C[4],$A[1][2](%rsi) # R[1][2] = C[2] ^ (~C[4] | C[3]) + + and @C[2],@C[3] + mov $A[4][0](%rdi),@C[4] + xor @T[1],@C[3] # C[1] ^ (C[3] & C[2]) + mov @C[3],$A[1][1](%rsi) # R[1][1] = C[1] ^ (C[3] & C[2]) + + or @C[2],@T[1] + mov $A[2][3](%rdi),@C[2] + xor @T[0],@T[1] # C[0] ^ (C[1] | C[2]) + mov $A[3][4](%rdi),@C[3] + mov @T[1],$A[1][0](%rsi) # R[1][0] = C[0] ^ (C[1] | C[2]) + + + xor @D[3],@C[2] + xor @D[4],@C[3] + rol \$$rhotates[2][3],@C[2] + xor @D[2],@C[1] + rol \$$rhotates[3][4],@C[3] + xor @D[0],@C[4] + rol \$$rhotates[1][2],@C[1] + xor @D[1],@C[0] + rol \$$rhotates[4][0],@C[4] + mov @C[2],@T[0] + and @C[3],@C[2] + rol \$$rhotates[0][1],@C[0] + + not @C[3] + xor @C[1],@C[2] # C[1] ^ ( C[2] & C[3]) + mov @C[2],$A[2][1](%rsi) # R[2][1] = C[1] ^ ( C[2] & C[3]) + + mov @C[4],@T[1] + and @C[3],@C[4] + mov $A[2][1](%rdi),@C[2] + xor @T[0],@C[4] # C[2] ^ ( C[4] & ~C[3]) + mov @C[4],$A[2][2](%rsi) # R[2][2] = C[2] ^ ( C[4] & ~C[3]) + + or @C[1],@T[0] + mov $A[4][3](%rdi),@C[4] + xor @C[0],@T[0] # C[0] ^ ( C[2] | C[1]) + mov @T[0],$A[2][0](%rsi) # R[2][0] = C[0] ^ ( C[2] | C[1]) + + and @C[0],@C[1] + xor @T[1],@C[1] # C[4] ^ ( C[1] & C[0]) + mov @C[1],$A[2][4](%rsi) # R[2][4] = C[4] ^ ( C[1] & C[0]) + + or @C[0],@T[1] + mov $A[1][0](%rdi),@C[1] + xor @C[3],@T[1] # ~C[3] ^ ( C[0] | C[4]) + mov $A[3][2](%rdi),@C[3] + mov @T[1],$A[2][3](%rsi) # R[2][3] = ~C[3] ^ ( C[0] | C[4]) + + + mov $A[0][4](%rdi),@C[0] + + xor @D[1],@C[2] + xor @D[2],@C[3] + rol \$$rhotates[2][1],@C[2] + xor @D[0],@C[1] + rol \$$rhotates[3][2],@C[3] + xor @D[3],@C[4] + rol \$$rhotates[1][0],@C[1] + xor @D[4],@C[0] + rol \$$rhotates[4][3],@C[4] + mov @C[2],@T[0] + or @C[3],@C[2] + rol \$$rhotates[0][4],@C[0] + + not @C[3] + xor @C[1],@C[2] # C[1] ^ ( C[2] | C[3]) + mov @C[2],$A[3][1](%rsi) # R[3][1] = C[1] ^ ( C[2] | C[3]) + + mov @C[4],@T[1] + or @C[3],@C[4] + xor @T[0],@C[4] # C[2] ^ ( C[4] | ~C[3]) + mov @C[4],$A[3][2](%rsi) # R[3][2] = C[2] ^ ( C[4] | ~C[3]) + + and @C[1],@T[0] + xor @C[0],@T[0] # C[0] ^ ( C[2] & C[1]) + mov @T[0],$A[3][0](%rsi) # R[3][0] = C[0] ^ ( C[2] & C[1]) + + or @C[0],@C[1] + xor @T[1],@C[1] # C[4] ^ ( C[1] | C[0]) + mov @C[1],$A[3][4](%rsi) # R[3][4] = C[4] ^ ( C[1] | C[0]) + + and @T[1],@C[0] + xor @C[3],@C[0] # ~C[3] ^ ( C[0] & C[4]) + mov @C[0],$A[3][3](%rsi) # R[3][3] = ~C[3] ^ ( C[0] & C[4]) + + + xor $A[0][2](%rdi),@D[2] + xor $A[1][3](%rdi),@D[3] + rol \$$rhotates[0][2],@D[2] + xor $A[4][1](%rdi),@D[1] + rol \$$rhotates[1][3],@D[3] + xor $A[2][4](%rdi),@D[4] + rol \$$rhotates[4][1],@D[1] + xor $A[3][0](%rdi),@D[0] + xchg %rsi,%rdi + rol \$$rhotates[2][4],@D[4] + rol \$$rhotates[3][0],@D[0] +___ + @C = @D[2..4,0,1]; +$code.=<<___; + mov @C[0],@T[0] + and @C[1],@C[0] + not @C[1] + xor @C[4],@C[0] # C[4] ^ ( C[0] & C[1]) + mov @C[0],$A[4][4](%rdi) # R[4][4] = C[4] ^ ( C[0] & C[1]) + + mov @C[2],@T[1] + and @C[1],@C[2] + xor @T[0],@C[2] # C[0] ^ ( C[2] & ~C[1]) + mov @C[2],$A[4][0](%rdi) # R[4][0] = C[0] ^ ( C[2] & ~C[1]) + + or @C[4],@T[0] + xor @C[3],@T[0] # C[3] ^ ( C[0] | C[4]) + mov @T[0],$A[4][3](%rdi) # R[4][3] = C[3] ^ ( C[0] | C[4]) + + and @C[3],@C[4] + xor @T[1],@C[4] # C[2] ^ ( C[4] & C[3]) + mov @C[4],$A[4][2](%rdi) # R[4][2] = C[2] ^ ( C[4] & C[3]) + + or @T[1],@C[3] + xor @C[1],@C[3] # ~C[1] ^ ( C[2] | C[3]) + mov @C[3],$A[4][1](%rdi) # R[4][1] = ~C[1] ^ ( C[2] | C[3]) + + mov @C[0],@C[1] # harmonize with the loop top + mov @T[0],@C[0] + + test \$255,$iotas + jnz .Loop + + lea -192($iotas),$iotas # rewind iotas + ret +.size __KeccakF1600,.-__KeccakF1600 + +.globl KeccakF1600 +.type KeccakF1600,\@function +.align 32 +KeccakF1600: +.cfi_startproc + push %rbx +.cfi_push %rbx + push %rbp +.cfi_push %rbp + push %r12 +.cfi_push %r12 + push %r13 +.cfi_push %r13 + push %r14 +.cfi_push %r14 + push %r15 +.cfi_push %r15 + + lea 100(%rdi),%rdi # size optimization + sub \$200,%rsp +.cfi_adjust_cfa_offset 200 + + notq $A[0][1](%rdi) + notq $A[0][2](%rdi) + notq $A[1][3](%rdi) + notq $A[2][2](%rdi) + notq $A[3][2](%rdi) + notq $A[4][0](%rdi) + + lea iotas(%rip),$iotas + lea 100(%rsp),%rsi # size optimization + + call __KeccakF1600 + + notq $A[0][1](%rdi) + notq $A[0][2](%rdi) + notq $A[1][3](%rdi) + notq $A[2][2](%rdi) + notq $A[3][2](%rdi) + notq $A[4][0](%rdi) + lea -100(%rdi),%rdi # preserve A[][] + + add \$200,%rsp +.cfi_adjust_cfa_offset -200 + + pop %r15 +.cfi_pop %r15 + pop %r14 +.cfi_pop %r14 + pop %r13 +.cfi_pop %r13 + pop %r12 +.cfi_pop %r12 + pop %rbp +.cfi_pop %rbp + pop %rbx +.cfi_pop %rbx + ret +.cfi_endproc +.size KeccakF1600,.-KeccakF1600 +___ + +{ my ($A_flat,$inp,$len,$bsz) = ("%rdi","%rsi","%rdx","%rcx"); + ($A_flat,$inp) = ("%r8","%r9"); +$code.=<<___; +.globl SHA3_absorb +.type SHA3_absorb,\@function +.align 32 +SHA3_absorb: +.cfi_startproc + push %rbx +.cfi_push %rbx + push %rbp +.cfi_push %rbp + push %r12 +.cfi_push %r12 + push %r13 +.cfi_push %r13 + push %r14 +.cfi_push %r14 + push %r15 +.cfi_push %r15 + + lea 100(%rdi),%rdi # size optimization + sub \$232,%rsp +.cfi_adjust_cfa_offset 232 + + mov %rsi,$inp + lea 100(%rsp),%rsi # size optimization + + notq $A[0][1](%rdi) + notq $A[0][2](%rdi) + notq $A[1][3](%rdi) + notq $A[2][2](%rdi) + notq $A[3][2](%rdi) + notq $A[4][0](%rdi) + lea iotas(%rip),$iotas + + mov $bsz,216-100(%rsi) # save bsz + +.Loop_absorb: + cmp $bsz,$len + jc .Ldone_absorb + + shr \$3,$bsz + lea -100(%rdi),$A_flat + +.Lblock_absorb: + mov ($inp),%rax + lea 8($inp),$inp + xor ($A_flat),%rax + lea 8($A_flat),$A_flat + sub \$8,$len + mov %rax,-8($A_flat) + sub \$1,$bsz + jnz .Lblock_absorb + + mov $inp,200-100(%rsi) # save inp + mov $len,208-100(%rsi) # save len + call __KeccakF1600 + mov 200-100(%rsi),$inp # pull inp + mov 208-100(%rsi),$len # pull len + mov 216-100(%rsi),$bsz # pull bsz + jmp .Loop_absorb + +.align 32 +.Ldone_absorb: + mov $len,%rax # return value + + notq $A[0][1](%rdi) + notq $A[0][2](%rdi) + notq $A[1][3](%rdi) + notq $A[2][2](%rdi) + notq $A[3][2](%rdi) + notq $A[4][0](%rdi) + + add \$232,%rsp +.cfi_adjust_cfa_offset -232 + + pop %r15 +.cfi_pop %r15 + pop %r14 +.cfi_pop %r14 + pop %r13 +.cfi_pop %r13 + pop %r12 +.cfi_pop %r12 + pop %rbp +.cfi_pop %rbp + pop %rbx +.cfi_pop %rbx + ret +.cfi_endproc +.size SHA3_absorb,.-SHA3_absorb +___ +} +{ my ($A_flat,$out,$len,$bsz) = ("%rdi","%rsi","%rdx","%rcx"); + ($out,$len,$bsz) = ("%r12","%r13","%r14"); + +$code.=<<___; +.globl SHA3_squeeze +.type SHA3_squeeze,\@function +.align 32 +SHA3_squeeze: +.cfi_startproc + push %r12 +.cfi_push %r12 + push %r13 +.cfi_push %r13 + push %r14 +.cfi_push %r14 + + shr \$3,%rcx + mov $A_flat,%r8 + mov %rsi,$out + mov %rdx,$len + mov %rcx,$bsz + jmp .Loop_squeeze + +.align 32 +.Loop_squeeze: + cmp \$8,$len + jb .Ltail_squeeze + + mov (%r8),%rax + lea 8(%r8),%r8 + mov %rax,($out) + lea 8($out),$out + sub \$8,$len # len -= 8 + jz .Ldone_squeeze + + sub \$1,%rcx # bsz-- + jnz .Loop_squeeze + + call KeccakF1600 + mov $A_flat,%r8 + mov $bsz,%rcx + jmp .Loop_squeeze + +.Ltail_squeeze: + mov %r8, %rsi + mov $out,%rdi + mov $len,%rcx + .byte 0xf3,0xa4 # rep movsb + +.Ldone_squeeze: + pop %r14 +.cfi_pop %r14 + pop %r13 +.cfi_pop %r13 + pop %r12 +.cfi_pop %r13 + ret +.cfi_endproc +.size SHA3_squeeze,.-SHA3_squeeze +___ +} +$code.=<<___; +.align 256 + .quad 0,0,0,0,0,0,0,0 +.type iotas,\@object +iotas: + .quad 0x0000000000000001 + .quad 0x0000000000008082 + .quad 0x800000000000808a + .quad 0x8000000080008000 + .quad 0x000000000000808b + .quad 0x0000000080000001 + .quad 0x8000000080008081 + .quad 0x8000000000008009 + .quad 0x000000000000008a + .quad 0x0000000000000088 + .quad 0x0000000080008009 + .quad 0x000000008000000a + .quad 0x000000008000808b + .quad 0x800000000000008b + .quad 0x8000000000008089 + .quad 0x8000000000008003 + .quad 0x8000000000008002 + .quad 0x8000000000000080 + .quad 0x000000000000800a + .quad 0x800000008000000a + .quad 0x8000000080008081 + .quad 0x8000000000008080 + .quad 0x0000000080000001 + .quad 0x8000000080008008 +.size iotas,.-iotas +.asciz "Keccak-1600 absorb and squeeze for x86_64, CRYPTOGAMS by " +___ + +foreach (split("\n",$code)) { + # Below replacement results in 11.2 on Sandy Bridge, 9.4 on + # Haswell, but it hurts other processors by up to 2-3-4x... + #s/rol\s+(\$[0-9]+),(%[a-z][a-z0-9]+)/shld\t$1,$2,$2/; + # Below replacement results in 9.3 on Haswell [as well as + # on Ryzen, i.e. it *hurts* Ryzen]... + #s/rol\s+\$([0-9]+),(%[a-z][a-z0-9]+)/rorx\t\$64-$1,$2,$2/; + + print $_, "\n"; +} + +close STDOUT; diff --git a/crypto/sha/asm/keccak1600p8-ppc.pl b/crypto/sha/asm/keccak1600p8-ppc.pl new file mode 100755 index 00000000..feec6883 --- /dev/null +++ b/crypto/sha/asm/keccak1600p8-ppc.pl @@ -0,0 +1,850 @@ +#!/usr/bin/env perl +# 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 +# +# ==================================================================== +# Written by Andy Polyakov for the OpenSSL +# project. The module is, however, dual licensed under OpenSSL and +# CRYPTOGAMS licenses depending on where you obtain it. For further +# details see http://www.openssl.org/~appro/cryptogams/. +# ==================================================================== +# +# Keccak-1600 for PowerISA 2.07. +# +# June 2017. +# +# This is straightforward KECCAK_1X_ALT SIMD implementation, but with +# disjoint Rho and Pi. The module is ABI-bitness- and endian-neutral. +# POWER8 processor spends 9.8 cycles to process byte out of large +# buffer for r=1088, which matches SHA3-256. This is 17% better than +# scalar PPC64 code. It probably should be noted that if POWER8's +# successor can achieve higher scalar instruction issue rate, then +# this module will loose... + +$flavour = shift; + +if ($flavour =~ /64/) { + $SIZE_T =8; + $LRSAVE =2*$SIZE_T; + $UCMP ="cmpld"; + $STU ="stdu"; + $POP ="ld"; + $PUSH ="std"; +} elsif ($flavour =~ /32/) { + $SIZE_T =4; + $LRSAVE =$SIZE_T; + $STU ="stwu"; + $POP ="lwz"; + $PUSH ="stw"; + $UCMP ="cmplw"; +} else { die "nonsense $flavour"; } + +$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; +( $xlate="${dir}ppc-xlate.pl" and -f $xlate ) or +( $xlate="${dir}../../perlasm/ppc-xlate.pl" and -f $xlate) or +die "can't locate ppc-xlate.pl"; + +open STDOUT,"| $^X $xlate $flavour ".shift || die "can't call $xlate: $!"; + +$FRAME=6*$SIZE_T+13*16; # 13*16 is for v20-v31 offload + +my $sp ="r1"; + +my $iotas = "r12"; + +######################################################################## +# Register layout: +# +# v0 A[0][0] A[1][0] +# v1 A[0][1] A[1][1] +# v2 A[0][2] A[1][2] +# v3 A[0][3] A[1][3] +# v4 A[0][4] A[1][4] +# +# v5 A[2][0] A[3][0] +# v6 A[2][1] A[3][1] +# v7 A[2][2] A[3][2] +# v8 A[2][3] A[3][3] +# v9 A[2][4] A[3][4] +# +# v10 A[4][0] A[4][1] +# v11 A[4][2] A[4][3] +# v12 A[4][4] A[4][4] +# +# v13..25 rhotates[][] +# v26..31 volatile +# +$code.=<<___; +.machine "any" +.text + +.type KeccakF1600_int,\@function +.align 5 +KeccakF1600_int: + li r0,24 + mtctr r0 + li r0,0 + b .Loop + +.align 4 +.Loop: + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Theta + vxor v26,v0, v5 ; A[0..1][0]^A[2..3][0] + vxor v27,v1, v6 ; A[0..1][1]^A[2..3][1] + vxor v28,v2, v7 ; A[0..1][2]^A[2..3][2] + vxor v29,v3, v8 ; A[0..1][3]^A[2..3][3] + vxor v30,v4, v9 ; A[0..1][4]^A[2..3][4] + vpermdi v31,v26,v27,0b00 ; A[0][0..1]^A[2][0..1] + vpermdi v26,v26,v27,0b11 ; A[1][0..1]^A[3][0..1] + vpermdi v27,v28,v29,0b00 ; A[0][2..3]^A[2][2..3] + vpermdi v28,v28,v29,0b11 ; A[1][2..3]^A[3][2..3] + vpermdi v29,v30,v30,0b10 ; A[1..0][4]^A[3..2][4] + vxor v26,v26,v31 ; C[0..1] + vxor v27,v27,v28 ; C[2..3] + vxor v28,v29,v30 ; C[4..4] + vspltisb v31,1 + vxor v26,v26,v10 ; C[0..1] ^= A[4][0..1] + vxor v27,v27,v11 ; C[2..3] ^= A[4][2..3] + vxor v28,v28,v12 ; C[4..4] ^= A[4][4..4], low! + + vrld v29,v26,v31 ; ROL64(C[0..1],1) + vrld v30,v27,v31 ; ROL64(C[2..3],1) + vrld v31,v28,v31 ; ROL64(C[4..4],1) + vpermdi v31,v31,v29,0b10 + vxor v26,v26,v30 ; C[0..1] ^= ROL64(C[2..3],1) + vxor v27,v27,v31 ; C[2..3] ^= ROL64(C[4..0],1) + vxor v28,v28,v29 ; C[4..4] ^= ROL64(C[0..1],1), low! + + vpermdi v29,v26,v26,0b00 ; C[0..0] + vpermdi v30,v28,v26,0b10 ; C[4..0] + vpermdi v31,v28,v28,0b11 ; C[4..4] + vxor v1, v1, v29 ; A[0..1][1] ^= C[0..0] + vxor v6, v6, v29 ; A[2..3][1] ^= C[0..0] + vxor v10,v10,v30 ; A[4][0..1] ^= C[4..0] + vxor v0, v0, v31 ; A[0..1][0] ^= C[4..4] + vxor v5, v5, v31 ; A[2..3][0] ^= C[4..4] + + vpermdi v29,v27,v27,0b00 ; C[2..2] + vpermdi v30,v26,v26,0b11 ; C[1..1] + vpermdi v31,v26,v27,0b10 ; C[1..2] + vxor v3, v3, v29 ; A[0..1][3] ^= C[2..2] + vxor v8, v8, v29 ; A[2..3][3] ^= C[2..2] + vxor v2, v2, v30 ; A[0..1][2] ^= C[1..1] + vxor v7, v7, v30 ; A[2..3][2] ^= C[1..1] + vxor v11,v11,v31 ; A[4][2..3] ^= C[1..2] + + vpermdi v29,v27,v27,0b11 ; C[3..3] + vxor v4, v4, v29 ; A[0..1][4] ^= C[3..3] + vxor v9, v9, v29 ; A[2..3][4] ^= C[3..3] + vxor v12,v12,v29 ; A[4..4][4] ^= C[3..3] + + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Rho + vrld v26,v0, v13 ; v0 + vrld v1, v1, v14 + vrld v27,v2, v15 ; v2 + vrld v28,v3, v16 ; v3 + vrld v4, v4, v17 + vrld v5, v5, v18 + vrld v6, v6, v19 + vrld v29,v7, v20 ; v7 + vrld v8, v8, v21 + vrld v9, v9, v22 + vrld v10,v10,v23 + vrld v30,v11,v24 ; v11 + vrld v12,v12,v25 + + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Pi + vpermdi v0, v26,v28,0b00 ; [0][0] [1][0] < [0][0] [0][3] + vpermdi v2, v29,v5, 0b00 ; [0][2] [1][2] < [2][2] [2][0] + vpermdi v11,v9, v5, 0b01 ; [4][2] [4][3] < [2][4] [3][0] + vpermdi v5, v1, v4, 0b00 ; [2][0] [3][0] < [0][1] [0][4] + vpermdi v1, v1, v4, 0b11 ; [0][1] [1][1] < [1][1] [1][4] + vpermdi v3, v8, v6, 0b11 ; [0][3] [1][3] < [3][3] [3][1] + vpermdi v4, v12,v30,0b10 ; [0][4] [1][4] < [4][4] [4][2] + vpermdi v7, v8, v6, 0b00 ; [2][2] [3][2] < [2][3] [2][1] + vpermdi v6, v27,v26,0b11 ; [2][1] [3][1] < [1][2] [1][0] + vpermdi v8, v9, v29,0b11 ; [2][3] [3][3] < [3][4] [3][2] + vpermdi v12,v10,v10,0b11 ; [4][4] [4][4] < [4][1] [4][1] + vpermdi v9, v10,v30,0b01 ; [2][4] [3][4] < [4][0] [4][3] + vpermdi v10,v27,v28,0b01 ; [4][0] [4][1] < [0][2] [1][3] + + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Chi + Iota + lvx_u v31,$iotas,r0 ; iotas[index] + addic r0,r0,16 ; index++ + + vandc v26,v2, v1 ; (~A[0..1][1] & A[0..1][2]) + vandc v27,v3, v2 ; (~A[0..1][2] & A[0..1][3]) + vandc v28,v4, v3 ; (~A[0..1][3] & A[0..1][4]) + vandc v29,v0, v4 ; (~A[0..1][4] & A[0..1][0]) + vandc v30,v1, v0 ; (~A[0..1][0] & A[0..1][1]) + vxor v0, v0, v26 ; A[0..1][0] ^= (~A[0..1][1] & A[0..1][2]) + vxor v1, v1, v27 ; A[0..1][1] ^= (~A[0..1][2] & A[0..1][3]) + vxor v2, v2, v28 ; A[0..1][2] ^= (~A[0..1][3] & A[0..1][4]) + vxor v3, v3, v29 ; A[0..1][3] ^= (~A[0..1][4] & A[0..1][0]) + vxor v4, v4, v30 ; A[0..1][4] ^= (~A[0..1][0] & A[0..1][1]) + + vandc v26,v7, v6 ; (~A[2..3][1] & A[2..3][2]) + vandc v27,v8, v7 ; (~A[2..3][2] & A[2..3][3]) + vandc v28,v9, v8 ; (~A[2..3][3] & A[2..3][4]) + vandc v29,v5, v9 ; (~A[2..3][4] & A[2..3][0]) + vandc v30,v6, v5 ; (~A[2..3][0] & A[2..3][1]) + vxor v5, v5, v26 ; A[2..3][0] ^= (~A[2..3][1] & A[2..3][2]) + vxor v6, v6, v27 ; A[2..3][1] ^= (~A[2..3][2] & A[2..3][3]) + vxor v7, v7, v28 ; A[2..3][2] ^= (~A[2..3][3] & A[2..3][4]) + vxor v8, v8, v29 ; A[2..3][3] ^= (~A[2..3][4] & A[2..3][0]) + vxor v9, v9, v30 ; A[2..3][4] ^= (~A[2..3][0] & A[2..3][1]) + + vxor v0, v0, v31 ; A[0][0] ^= iotas[index++] + + vpermdi v26,v10,v11,0b10 ; A[4][1..2] + vpermdi v27,v12,v10,0b00 ; A[4][4..0] + vpermdi v28,v11,v12,0b10 ; A[4][3..4] + vpermdi v29,v10,v10,0b10 ; A[4][1..0] + vandc v26,v11,v26 ; (~A[4][1..2] & A[4][2..3]) + vandc v27,v27,v28 ; (~A[4][3..4] & A[4][4..0]) + vandc v28,v10,v29 ; (~A[4][1..0] & A[4][0..1]) + vxor v10,v10,v26 ; A[4][0..1] ^= (~A[4][1..2] & A[4][2..3]) + vxor v11,v11,v27 ; A[4][2..3] ^= (~A[4][3..4] & A[4][4..0]) + vxor v12,v12,v28 ; A[4][4..4] ^= (~A[4][0..1] & A[4][1..0]) + + bdnz .Loop + + vpermdi v12,v12,v12,0b11 ; broadcast A[4][4] + blr + .long 0 + .byte 0,12,0x14,0,0,0,0,0 +.size KeccakF1600_int,.-KeccakF1600_int + +.type KeccakF1600,\@function +.align 5 +KeccakF1600: + $STU $sp,-$FRAME($sp) + li r10,`15+6*$SIZE_T` + li r11,`31+6*$SIZE_T` + mflr r8 + mfspr r7, 256 ; save vrsave + stvx v20,r10,$sp + addi r10,r10,32 + stvx v21,r11,$sp + addi r11,r11,32 + stvx v22,r10,$sp + addi r10,r10,32 + stvx v23,r11,$sp + addi r11,r11,32 + stvx v24,r10,$sp + addi r10,r10,32 + stvx v25,r11,$sp + addi r11,r11,32 + stvx v26,r10,$sp + addi r10,r10,32 + stvx v27,r11,$sp + addi r11,r11,32 + stvx v28,r10,$sp + addi r10,r10,32 + stvx v29,r11,$sp + addi r11,r11,32 + stvx v30,r10,$sp + stvx v31,r11,$sp + stw r7,`$FRAME-4`($sp) ; save vrsave + li r0, -1 + $PUSH r8,`$FRAME+$LRSAVE`($sp) + mtspr 256, r0 ; preserve all AltiVec registers + + li r11,16 + lvx_4w v0,0,r3 ; load A[5][5] + li r10,32 + lvx_4w v1,r11,r3 + addi r11,r11,32 + lvx_4w v2,r10,r3 + addi r10,r10,32 + lvx_4w v3,r11,r3 + addi r11,r11,32 + lvx_4w v4,r10,r3 + addi r10,r10,32 + lvx_4w v5,r11,r3 + addi r11,r11,32 + lvx_4w v6,r10,r3 + addi r10,r10,32 + lvx_4w v7,r11,r3 + addi r11,r11,32 + lvx_4w v8,r10,r3 + addi r10,r10,32 + lvx_4w v9,r11,r3 + addi r11,r11,32 + lvx_4w v10,r10,r3 + addi r10,r10,32 + lvx_4w v11,r11,r3 + lvx_splt v12,r10,r3 + + bl PICmeup + + li r11,16 + lvx_u v13,0,r12 ; load rhotates + li r10,32 + lvx_u v14,r11,r12 + addi r11,r11,32 + lvx_u v15,r10,r12 + addi r10,r10,32 + lvx_u v16,r11,r12 + addi r11,r11,32 + lvx_u v17,r10,r12 + addi r10,r10,32 + lvx_u v18,r11,r12 + addi r11,r11,32 + lvx_u v19,r10,r12 + addi r10,r10,32 + lvx_u v20,r11,r12 + addi r11,r11,32 + lvx_u v21,r10,r12 + addi r10,r10,32 + lvx_u v22,r11,r12 + addi r11,r11,32 + lvx_u v23,r10,r12 + addi r10,r10,32 + lvx_u v24,r11,r12 + lvx_u v25,r10,r12 + addi r12,r12,`16*16` ; points at iotas + + bl KeccakF1600_int + + li r11,16 + stvx_4w v0,0,r3 ; return A[5][5] + li r10,32 + stvx_4w v1,r11,r3 + addi r11,r11,32 + stvx_4w v2,r10,r3 + addi r10,r10,32 + stvx_4w v3,r11,r3 + addi r11,r11,32 + stvx_4w v4,r10,r3 + addi r10,r10,32 + stvx_4w v5,r11,r3 + addi r11,r11,32 + stvx_4w v6,r10,r3 + addi r10,r10,32 + stvx_4w v7,r11,r3 + addi r11,r11,32 + stvx_4w v8,r10,r3 + addi r10,r10,32 + stvx_4w v9,r11,r3 + addi r11,r11,32 + stvx_4w v10,r10,r3 + addi r10,r10,32 + stvx_4w v11,r11,r3 + stvdx_u v12,r10,r3 + + li r10,`15+6*$SIZE_T` + li r11,`31+6*$SIZE_T` + mtlr r8 + mtspr 256, r7 ; restore vrsave + lvx v20,r10,$sp + addi r10,r10,32 + lvx v21,r11,$sp + addi r11,r11,32 + lvx v22,r10,$sp + addi r10,r10,32 + lvx v23,r11,$sp + addi r11,r11,32 + lvx v24,r10,$sp + addi r10,r10,32 + lvx v25,r11,$sp + addi r11,r11,32 + lvx v26,r10,$sp + addi r10,r10,32 + lvx v27,r11,$sp + addi r11,r11,32 + lvx v28,r10,$sp + addi r10,r10,32 + lvx v29,r11,$sp + addi r11,r11,32 + lvx v30,r10,$sp + lvx v31,r11,$sp + addi $sp,$sp,$FRAME + blr + .long 0 + .byte 0,12,0x04,1,0x80,0,1,0 + .long 0 +.size KeccakF1600,.-KeccakF1600 +___ +{ +my ($A_jagged,$inp,$len,$bsz) = map("r$_",(3..6)); + +$code.=<<___; +.globl SHA3_absorb +.type SHA3_absorb,\@function +.align 5 +SHA3_absorb: + $STU $sp,-$FRAME($sp) + li r10,`15+6*$SIZE_T` + li r11,`31+6*$SIZE_T` + mflr r8 + mfspr r7, 256 ; save vrsave + stvx v20,r10,$sp + addi r10,r10,32 + stvx v21,r11,$sp + addi r11,r11,32 + stvx v22,r10,$sp + addi r10,r10,32 + stvx v23,r11,$sp + addi r11,r11,32 + stvx v24,r10,$sp + addi r10,r10,32 + stvx v25,r11,$sp + addi r11,r11,32 + stvx v26,r10,$sp + addi r10,r10,32 + stvx v27,r11,$sp + addi r11,r11,32 + stvx v28,r10,$sp + addi r10,r10,32 + stvx v29,r11,$sp + addi r11,r11,32 + stvx v30,r10,$sp + stvx v31,r11,$sp + stw r7,`$FRAME-4`($sp) ; save vrsave + li r0, -1 + $PUSH r8,`$FRAME+$LRSAVE`($sp) + mtspr 256, r0 ; preserve all AltiVec registers + + li r11,16 + lvx_4w v0,0,$A_jagged ; load A[5][5] + li r10,32 + lvx_4w v1,r11,$A_jagged + addi r11,r11,32 + lvx_4w v2,r10,$A_jagged + addi r10,r10,32 + lvx_4w v3,r11,$A_jagged + addi r11,r11,32 + lvx_4w v4,r10,$A_jagged + addi r10,r10,32 + lvx_4w v5,r11,$A_jagged + addi r11,r11,32 + lvx_4w v6,r10,$A_jagged + addi r10,r10,32 + lvx_4w v7,r11,$A_jagged + addi r11,r11,32 + lvx_4w v8,r10,$A_jagged + addi r10,r10,32 + lvx_4w v9,r11,$A_jagged + addi r11,r11,32 + lvx_4w v10,r10,$A_jagged + addi r10,r10,32 + lvx_4w v11,r11,$A_jagged + lvx_splt v12,r10,$A_jagged + + bl PICmeup + + li r11,16 + lvx_u v13,0,r12 ; load rhotates + li r10,32 + lvx_u v14,r11,r12 + addi r11,r11,32 + lvx_u v15,r10,r12 + addi r10,r10,32 + lvx_u v16,r11,r12 + addi r11,r11,32 + lvx_u v17,r10,r12 + addi r10,r10,32 + lvx_u v18,r11,r12 + addi r11,r11,32 + lvx_u v19,r10,r12 + addi r10,r10,32 + lvx_u v20,r11,r12 + addi r11,r11,32 + lvx_u v21,r10,r12 + addi r10,r10,32 + lvx_u v22,r11,r12 + addi r11,r11,32 + lvx_u v23,r10,r12 + addi r10,r10,32 + lvx_u v24,r11,r12 + lvx_u v25,r10,r12 + li r10,-32 + li r11,-16 + addi r12,r12,`16*16` ; points at iotas + b .Loop_absorb + +.align 4 +.Loop_absorb: + $UCMP $len,$bsz ; len < bsz? + blt .Labsorbed + + sub $len,$len,$bsz ; len -= bsz + srwi r0,$bsz,3 + mtctr r0 + + lvx_u v30,r10,r12 ; permutation masks + lvx_u v31,r11,r12 + ?vspltisb v27,7 ; prepare masks for byte swap + ?vxor v30,v30,v27 ; on big-endian + ?vxor v31,v31,v27 + + vxor v27,v27,v27 ; zero + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v0, v0, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v1, v1, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v2, v2, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v3, v3, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v4, v4, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v0, v0, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v1, v1, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v2, v2, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v3, v3, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v4, v4, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v5, v5, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v6, v6, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v7, v7, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v8, v8, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v9, v9, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v5, v5, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v6, v6, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v7, v7, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v8, v8, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v9, v9, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v10, v10, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v10, v10, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v30 + vxor v11, v11, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v11, v11, v26 + bdz .Lprocess_block + lvdx_u v26,0,$inp + addi $inp,$inp,8 + vperm v26,v26,v27,v31 + vxor v12, v12, v26 + +.Lprocess_block: + bl KeccakF1600_int + + b .Loop_absorb + +.align 4 +.Labsorbed: + li r11,16 + stvx_4w v0,0,$A_jagged ; return A[5][5] + li r10,32 + stvx_4w v1,r11,$A_jagged + addi r11,r11,32 + stvx_4w v2,r10,$A_jagged + addi r10,r10,32 + stvx_4w v3,r11,$A_jagged + addi r11,r11,32 + stvx_4w v4,r10,$A_jagged + addi r10,r10,32 + stvx_4w v5,r11,$A_jagged + addi r11,r11,32 + stvx_4w v6,r10,$A_jagged + addi r10,r10,32 + stvx_4w v7,r11,$A_jagged + addi r11,r11,32 + stvx_4w v8,r10,$A_jagged + addi r10,r10,32 + stvx_4w v9,r11,$A_jagged + addi r11,r11,32 + stvx_4w v10,r10,$A_jagged + addi r10,r10,32 + stvx_4w v11,r11,$A_jagged + stvdx_u v12,r10,$A_jagged + + mr r3,$len ; return value + li r10,`15+6*$SIZE_T` + li r11,`31+6*$SIZE_T` + mtlr r8 + mtspr 256, r7 ; restore vrsave + lvx v20,r10,$sp + addi r10,r10,32 + lvx v21,r11,$sp + addi r11,r11,32 + lvx v22,r10,$sp + addi r10,r10,32 + lvx v23,r11,$sp + addi r11,r11,32 + lvx v24,r10,$sp + addi r10,r10,32 + lvx v25,r11,$sp + addi r11,r11,32 + lvx v26,r10,$sp + addi r10,r10,32 + lvx v27,r11,$sp + addi r11,r11,32 + lvx v28,r10,$sp + addi r10,r10,32 + lvx v29,r11,$sp + addi r11,r11,32 + lvx v30,r10,$sp + lvx v31,r11,$sp + addi $sp,$sp,$FRAME + blr + .long 0 + .byte 0,12,0x04,1,0x80,0,4,0 + .long 0 +.size SHA3_absorb,.-SHA3_absorb +___ +} +{ +my ($A_jagged,$out,$len,$bsz) = map("r$_",(3..6)); + +$code.=<<___; +.globl SHA3_squeeze +.type SHA3_squeeze,\@function +.align 5 +SHA3_squeeze: + mflr r9 ; r9 is not touched by KeccakF1600 + subi $out,$out,1 ; prepare for stbu + addi r8,$A_jagged,4 ; prepare volatiles + mr r10,$bsz + li r11,0 + b .Loop_squeeze +.align 4 +.Loop_squeeze: + lwzx r7,r11,r8 ; lo + lwzx r0,r11,$A_jagged ; hi + ${UCMP}i $len,8 + blt .Lsqueeze_tail + + stbu r7,1($out) ; write lo + srwi r7,r7,8 + stbu r7,1($out) + srwi r7,r7,8 + stbu r7,1($out) + srwi r7,r7,8 + stbu r7,1($out) + stbu r0,1($out) ; write hi + srwi r0,r0,8 + stbu r0,1($out) + srwi r0,r0,8 + stbu r0,1($out) + srwi r0,r0,8 + stbu r0,1($out) + + subic. $len,$len,8 + beqlr ; return if done + + subic. r10,r10,8 + ble .Loutput_expand + + addi r11,r11,16 ; calculate jagged index + cmplwi r11,`16*5` + blt .Loop_squeeze + subi r11,r11,72 + beq .Loop_squeeze + addi r11,r11,72 + cmplwi r11,`16*5+8` + subi r11,r11,8 + beq .Loop_squeeze + addi r11,r11,8 + cmplwi r11,`16*10` + subi r11,r11,72 + beq .Loop_squeeze + addi r11,r11,72 + blt .Loop_squeeze + subi r11,r11,8 + b .Loop_squeeze + +.align 4 +.Loutput_expand: + bl KeccakF1600 + mtlr r9 + + addi r8,$A_jagged,4 ; restore volatiles + mr r10,$bsz + li r11,0 + b .Loop_squeeze + +.align 4 +.Lsqueeze_tail: + mtctr $len + subic. $len,$len,4 + ble .Loop_tail_lo + li r8,4 + mtctr r8 +.Loop_tail_lo: + stbu r7,1($out) + srdi r7,r7,8 + bdnz .Loop_tail_lo + ble .Lsqueeze_done + mtctr $len +.Loop_tail_hi: + stbu r0,1($out) + srdi r0,r0,8 + bdnz .Loop_tail_hi + +.Lsqueeze_done: + blr + .long 0 + .byte 0,12,0x14,0,0,0,4,0 + .long 0 +.size SHA3_squeeze,.-SHA3_squeeze +___ +} +$code.=<<___; +.align 6 +PICmeup: + mflr r0 + bcl 20,31,\$+4 + mflr r12 ; vvvvvv "distance" between . and 1st data entry + addi r12,r12,`64-8` + mtlr r0 + blr + .long 0 + .byte 0,12,0x14,0,0,0,0,0 + .space `64-9*4` +.type rhotates,\@object +.align 6 +rhotates: + .quad 0, 36 + .quad 1, 44 + .quad 62, 6 + .quad 28, 55 + .quad 27, 20 + .quad 3, 41 + .quad 10, 45 + .quad 43, 15 + .quad 25, 21 + .quad 39, 8 + .quad 18, 2 + .quad 61, 56 + .quad 14, 14 +.size rhotates,.-rhotates + .quad 0,0 + .quad 0x0001020304050607,0x1011121314151617 + .quad 0x1011121314151617,0x0001020304050607 +.type iotas,\@object +iotas: + .quad 0x0000000000000001,0 + .quad 0x0000000000008082,0 + .quad 0x800000000000808a,0 + .quad 0x8000000080008000,0 + .quad 0x000000000000808b,0 + .quad 0x0000000080000001,0 + .quad 0x8000000080008081,0 + .quad 0x8000000000008009,0 + .quad 0x000000000000008a,0 + .quad 0x0000000000000088,0 + .quad 0x0000000080008009,0 + .quad 0x000000008000000a,0 + .quad 0x000000008000808b,0 + .quad 0x800000000000008b,0 + .quad 0x8000000000008089,0 + .quad 0x8000000000008003,0 + .quad 0x8000000000008002,0 + .quad 0x8000000000000080,0 + .quad 0x000000000000800a,0 + .quad 0x800000008000000a,0 + .quad 0x8000000080008081,0 + .quad 0x8000000000008080,0 + .quad 0x0000000080000001,0 + .quad 0x8000000080008008,0 +.size iotas,.-iotas +.asciz "Keccak-1600 absorb and squeeze for PowerISA 2.07, CRYPTOGAMS by " +___ + +foreach (split("\n",$code)) { + s/\`([^\`]*)\`/eval $1/ge; + + if ($flavour =~ /le$/) { # little-endian + s/\?([a-z]+)/;$1/; + } else { # big-endian + s/\?([a-z]+)/$1/; + } + + print $_,"\n"; +} + +close STDOUT; diff --git a/crypto/sha/asm/sha1-586.pl b/crypto/sha/asm/sha1-586.pl index 5adca234..ca376399 100644 --- a/crypto/sha/asm/sha1-586.pl +++ b/crypto/sha/asm/sha1-586.pl @@ -35,10 +35,9 @@ # P4 +85%(!) +45% # # As you can see Pentium came out as looser:-( Yet I reckoned that -# improvement on P4 outweights the loss and incorporate this +# improvement on P4 outweighs the loss and incorporate this # re-tuned code to 0.9.7 and later. # ---------------------------------------------------------------- -# # August 2009. # @@ -104,10 +103,12 @@ # Sandy Bridge 8.8 6.2/+40% 5.1(**)/+73% # Ivy Bridge 7.2 4.8/+51% 4.7(**)/+53% # Haswell 6.5 4.3/+51% 4.1(**)/+58% +# Skylake 6.4 4.1/+55% 4.1(**)/+55% # Bulldozer 11.6 6.0/+92% # VIA Nano 10.6 7.5/+41% # Atom 12.5 9.3(*)/+35% # Silvermont 14.5 9.9(*)/+46% +# Goldmont 8.8 6.7/+30% 1.7(***)/+415% # # (*) Loop is 1056 instructions long and expected result is ~8.25. # The discrepancy is because of front-end limitations, so @@ -115,6 +116,8 @@ # limited parallelism. # # (**) As per above comment, the result is for AVX *plus* sh[rl]d. +# +# (***) SHAEXT result $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; push(@INC,"${dir}","${dir}../../perlasm"); @@ -123,7 +126,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"sha1-586.pl",$ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$ARGV[$#ARGV] eq "386"); $xmm=$ymm=0; for (@ARGV) { $xmm=1 if (/-DOPENSSL_IA32_SSE2/); } @@ -133,7 +136,7 @@ $ymm=1 if ($xmm && =~ /GNU assembler version ([2-9]\.[0-9]+)/ && $1>=2.19); # first version supporting AVX -$ymm=1 if ($xmm && !$ymm && $ARGV[0] eq "win32n" && +$ymm=1 if ($xmm && !$ymm && $ARGV[0] eq "win32n" && `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)/ && $1>=2.03); # first version supporting AVX @@ -546,7 +549,7 @@ for($i=0;$i<20-4;$i+=2) { # being implemented in SSSE3). Once 8 quadruples or 32 elements are # collected, it switches to routine proposed by Max Locktyukhin. # -# Calculations inevitably require temporary reqisters, and there are +# Calculations inevitably require temporary registers, and there are # no %xmm registers left to spare. For this reason part of the ring # buffer, X[2..4] to be specific, is offloaded to 3 quadriples ring # buffer on the stack. Keep in mind that X[2] is alias X[-6], X[3] - diff --git a/crypto/sha/asm/sha1-alpha.pl b/crypto/sha/asm/sha1-alpha.pl index 4124958f..c1a0b0c6 100644 --- a/crypto/sha/asm/sha1-alpha.pl +++ b/crypto/sha/asm/sha1-alpha.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. diff --git a/crypto/sha/asm/sha1-armv8.pl b/crypto/sha/asm/sha1-armv8.pl index 84a00bf2..3ba871fe 100644 --- a/crypto/sha/asm/sha1-armv8.pl +++ b/crypto/sha/asm/sha1-armv8.pl @@ -26,6 +26,7 @@ # Denver 2.13 3.97 (+0%)(**) # X-Gene 8.80 (+200%) # Mongoose 2.05 6.50 (+160%) +# Kryo 1.88 8.00 (+90%) # # (*) Software results are presented mostly for reference purposes. # (**) Keep in mind that Denver relies on binary translation, which diff --git a/crypto/sha/asm/sha1-ia64.pl b/crypto/sha/asm/sha1-ia64.pl index dec21f92..bf1d2ebe 100644 --- a/crypto/sha/asm/sha1-ia64.pl +++ b/crypto/sha/asm/sha1-ia64.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. diff --git a/crypto/sha/asm/sha1-mb-x86_64.pl b/crypto/sha/asm/sha1-mb-x86_64.pl index 51c73c05..443b6498 100644 --- a/crypto/sha/asm/sha1-mb-x86_64.pl +++ b/crypto/sha/asm/sha1-mb-x86_64.pl @@ -95,7 +95,7 @@ $K="%xmm15"; if (1) { # Atom-specific optimization aiming to eliminate pshufb with high - # registers [and thus get rid of 48 cycles accumulated penalty] + # registers [and thus get rid of 48 cycles accumulated penalty] @Xi=map("%xmm$_",(0..4)); ($tx,$t0,$t1,$t2,$t3)=map("%xmm$_",(5..9)); @V=($A,$B,$C,$D,$E)=map("%xmm$_",(10..14)); @@ -126,7 +126,7 @@ my $k=$i+2; # ... # $i==13: 14,15,15,15, # $i==14: 15 -# +# # Then at $i==15 Xupdate is applied one iteration in advance... $code.=<<___ if ($i==0); movd (@ptr[0]),@Xi[0] @@ -363,6 +363,7 @@ $code.=<<___; .type sha1_multi_block,\@function,3 .align 32 sha1_multi_block: +.cfi_startproc mov OPENSSL_ia32cap_P+4(%rip),%rcx bt \$61,%rcx # check SHA bit jc _shaext_shortcut @@ -373,8 +374,11 @@ $code.=<<___ if ($avx); ___ $code.=<<___; mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbx ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -393,6 +397,7 @@ $code.=<<___; sub \$`$REG_SZ*18`,%rsp and \$-256,%rsp mov %rax,`$REG_SZ*17`(%rsp) # original %rsp +.cfi_cfa_expression %rsp+`$REG_SZ*17`,deref,+8 .Lbody: lea K_XX_XX(%rip),$Tbl lea `$REG_SZ*16`(%rsp),%rbx @@ -439,7 +444,7 @@ for(;$i<80;$i++) { &BODY_20_39($i,@V); unshift(@V,pop(@V)); } $code.=<<___; movdqa (%rbx),@Xi[0] # pull counters mov \$1,%ecx - cmp 4*0(%rbx),%ecx # examinte counters + cmp 4*0(%rbx),%ecx # examine counters pxor $t2,$t2 cmovge $Tbl,@ptr[0] # cancel input cmp 4*1(%rbx),%ecx @@ -487,6 +492,7 @@ $code.=<<___; .Ldone: mov `$REG_SZ*17`(%rsp),%rax # original %rsp +.cfi_def_cfa %rax,8 ___ $code.=<<___ if ($win64); movaps -0xb8(%rax),%xmm6 @@ -502,10 +508,14 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Lepilogue: ret +.cfi_endproc .size sha1_multi_block,.-sha1_multi_block ___ {{{ @@ -517,10 +527,14 @@ $code.=<<___; .type sha1_multi_block_shaext,\@function,3 .align 32 sha1_multi_block_shaext: +.cfi_startproc _shaext_shortcut: mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -756,10 +770,14 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_shaext: ret +.cfi_endproc .size sha1_multi_block_shaext,.-sha1_multi_block_shaext ___ }}} @@ -1002,6 +1020,7 @@ $code.=<<___; .type sha1_multi_block_avx,\@function,3 .align 32 sha1_multi_block_avx: +.cfi_startproc _avx_shortcut: ___ $code.=<<___ if ($avx>1); @@ -1016,8 +1035,11 @@ $code.=<<___ if ($avx>1); ___ $code.=<<___; mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -1036,6 +1058,7 @@ $code.=<<___; sub \$`$REG_SZ*18`, %rsp and \$-256,%rsp mov %rax,`$REG_SZ*17`(%rsp) # original %rsp +.cfi_cfa_expression %rsp+`$REG_SZ*17`,deref,+8 .Lbody_avx: lea K_XX_XX(%rip),$Tbl lea `$REG_SZ*16`(%rsp),%rbx @@ -1125,6 +1148,7 @@ $code.=<<___; .Ldone_avx: mov `$REG_SZ*17`(%rsp),%rax # original %rsp +.cfi_def_cfa %rax,8 vzeroupper ___ $code.=<<___ if ($win64); @@ -1141,10 +1165,14 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_avx: ret +.cfi_endproc .size sha1_multi_block_avx,.-sha1_multi_block_avx ___ @@ -1164,14 +1192,22 @@ $code.=<<___; .type sha1_multi_block_avx2,\@function,3 .align 32 sha1_multi_block_avx2: +.cfi_startproc _avx2_shortcut: mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -1190,6 +1226,7 @@ $code.=<<___; sub \$`$REG_SZ*18`, %rsp and \$-256,%rsp mov %rax,`$REG_SZ*17`(%rsp) # original %rsp +.cfi_cfa_expression %rsp+`$REG_SZ*17`,deref,+8 .Lbody_avx2: lea K_XX_XX(%rip),$Tbl shr \$1,$num @@ -1280,6 +1317,7 @@ $code.=<<___; .Ldone_avx2: mov `$REG_SZ*17`(%rsp),%rax # original %rsp +.cfi_def_cfa %rax,8 vzeroupper ___ $code.=<<___ if ($win64); @@ -1296,14 +1334,22 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -48(%rax),%r15 +.cfi_restore %r15 mov -40(%rax),%r14 +.cfi_restore %r14 mov -32(%rax),%r13 +.cfi_restore %r13 mov -24(%rax),%r12 +.cfi_restore %r12 mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_avx2: ret +.cfi_endproc .size sha1_multi_block_avx2,.-sha1_multi_block_avx2 ___ } }}} @@ -1462,10 +1508,10 @@ avx2_handler: mov -48(%rax),%r15 mov %rbx,144($context) # restore context->Rbx mov %rbp,160($context) # restore context->Rbp - mov %r12,216($context) # restore cotnext->R12 - mov %r13,224($context) # restore cotnext->R13 - mov %r14,232($context) # restore cotnext->R14 - mov %r15,240($context) # restore cotnext->R15 + mov %r12,216($context) # restore context->R12 + mov %r13,224($context) # restore context->R13 + mov %r14,232($context) # restore context->R14 + mov %r15,240($context) # restore context->R15 lea -56-10*16(%rax),%rsi lea 512($context),%rdi # &context.Xmm6 diff --git a/crypto/sha/asm/sha1-mips.pl b/crypto/sha/asm/sha1-mips.pl index 882f9731..71dc7225 100644 --- a/crypto/sha/asm/sha1-mips.pl +++ b/crypto/sha/asm/sha1-mips.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -56,15 +56,15 @@ $flavour = shift || "o32"; # supported flavours are o32,n32,64,nubi32,nubi64 if ($flavour =~ /64|n32/i) { - $PTR_ADD="dadd"; # incidentally works even on n32 - $PTR_SUB="dsub"; # incidentally works even on n32 + $PTR_ADD="daddu"; # incidentally works even on n32 + $PTR_SUB="dsubu"; # incidentally works even on n32 $REG_S="sd"; $REG_L="ld"; $PTR_SLL="dsll"; # incidentally works even on n32 $SZREG=8; } else { - $PTR_ADD="add"; - $PTR_SUB="sub"; + $PTR_ADD="addu"; + $PTR_SUB="subu"; $REG_S="sw"; $REG_L="lw"; $PTR_SLL="sll"; @@ -126,10 +126,14 @@ $code.=<<___; addu $e,$K # $i xor $t0,$c,$d rotr $t1,$a,27 - lwl @X[$j],$j*4+$MSB($inp) and $t0,$b addu $e,$t1 +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + lw @X[$j],$j*4($inp) +#else + lwl @X[$j],$j*4+$MSB($inp) lwr @X[$j],$j*4+$LSB($inp) +#endif xor $t0,$d addu $e,@X[$i] rotr $b,$b,2 @@ -336,13 +340,7 @@ $FRAMESIZE=16; # large enough to accommodate NUBI saved registers $SAVED_REGS_MASK = ($flavour =~ /nubi/i) ? "0xc0fff008" : "0xc0ff0000"; $code=<<___; -#ifdef OPENSSL_FIPSCANISTER -# include -#endif - -#if defined(__mips_smartmips) && !defined(_MIPS_ARCH_MIPS32R2) -#define _MIPS_ARCH_MIPS32R2 -#endif +#include "mips_arch.h" .text @@ -387,10 +385,16 @@ $code.=<<___; .align 4 .Loop: .set reorder +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + lui $K,0x5a82 + lw @X[0],($inp) + ori $K,0x7999 # K_00_19 +#else lwl @X[0],$MSB($inp) lui $K,0x5a82 lwr @X[0],$LSB($inp) ori $K,0x7999 # K_00_19 +#endif ___ for ($i=0;$i<15;$i++) { &BODY_00_14($i,@V); unshift(@V,pop(@V)); } for (;$i<20;$i++) { &BODY_15_19($i,@V); unshift(@V,pop(@V)); } diff --git a/crypto/sha/asm/sha1-parisc.pl b/crypto/sha/asm/sha1-parisc.pl index a85d126f..822288e6 100644 --- a/crypto/sha/asm/sha1-parisc.pl +++ b/crypto/sha/asm/sha1-parisc.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. diff --git a/crypto/sha/asm/sha1-ppc.pl b/crypto/sha/asm/sha1-ppc.pl index add5a9ea..0cda0a3e 100755 --- a/crypto/sha/asm/sha1-ppc.pl +++ b/crypto/sha/asm/sha1-ppc.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. diff --git a/crypto/sha/asm/sha1-s390x.pl b/crypto/sha/asm/sha1-s390x.pl index 79df1ffd..5729c308 100644 --- a/crypto/sha/asm/sha1-s390x.pl +++ b/crypto/sha/asm/sha1-s390x.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -160,6 +160,8 @@ ___ } $code.=<<___; +#include "s390x_arch.h" + .text .align 64 .type Ktable,\@object @@ -172,7 +174,7 @@ sha1_block_data_order: ___ $code.=<<___ if ($kimdfunc); larl %r1,OPENSSL_s390xcap_P - lg %r0,16(%r1) # check kimd capabilities + lg %r0,S390X_KIMD(%r1) # check kimd capabilities tmhh %r0,`0x8000>>$kimdfunc` jz .Lsoftware lghi %r0,$kimdfunc diff --git a/crypto/sha/asm/sha1-sparcv9.pl b/crypto/sha/asm/sha1-sparcv9.pl index 7437ff4f..3e612e3d 100644 --- a/crypto/sha/asm/sha1-sparcv9.pl +++ b/crypto/sha/asm/sha1-sparcv9.pl @@ -8,12 +8,12 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. # -# Hardware SPARC T4 support by David S. Miller . +# Hardware SPARC T4 support by David S. Miller # ==================================================================== # Performance improvement is not really impressive on pre-T1 CPU: +8% @@ -227,7 +227,7 @@ sha1_block_data_order: ldd [%o1 + 0x20], %f16 ldd [%o1 + 0x28], %f18 ldd [%o1 + 0x30], %f20 - subcc %o2, 1, %o2 ! done yet? + subcc %o2, 1, %o2 ! done yet? ldd [%o1 + 0x38], %f22 add %o1, 0x40, %o1 prefetch [%o1 + 63], 20 diff --git a/crypto/sha/asm/sha1-sparcv9a.pl b/crypto/sha/asm/sha1-sparcv9a.pl index f9ed5630..50d3e136 100644 --- a/crypto/sha/asm/sha1-sparcv9a.pl +++ b/crypto/sha/asm/sha1-sparcv9a.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -519,7 +519,7 @@ $code.=<<___; mov $Cctx,$C mov $Dctx,$D mov $Ectx,$E - alignaddr %g0,$tmp0,%g0 + alignaddr %g0,$tmp0,%g0 dec 1,$len ba .Loop mov $nXfer,$Xfer diff --git a/crypto/sha/asm/sha1-thumb.pl b/crypto/sha/asm/sha1-thumb.pl index 661fd9f9..ac74a25d 100644 --- a/crypto/sha/asm/sha1-thumb.pl +++ b/crypto/sha/asm/sha1-thumb.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -21,7 +21,7 @@ # The code does not present direct interest to OpenSSL, because of low # performance. Its purpose is to establish _size_ benchmark. Pretty # useless one I must say, because 30% or 88 bytes larger ARMv4 code -# [avialable on demand] is almost _twice_ as fast. It should also be +# [available on demand] is almost _twice_ as fast. It should also be # noted that in-lining of .Lcommon and .Lrotate improves performance # by over 40%, while code increases by only 10% or 32 bytes. But once # again, the goal was to establish _size_ benchmark, not performance. diff --git a/crypto/sha/asm/sha1-x86_64.pl b/crypto/sha/asm/sha1-x86_64.pl index 6a3378ba..60819f61 100755 --- a/crypto/sha/asm/sha1-x86_64.pl +++ b/crypto/sha/asm/sha1-x86_64.pl @@ -82,9 +82,11 @@ # Haswell 5.45 4.15/+31% 3.57/+53% # Skylake 5.18 4.06/+28% 3.54/+46% # Bulldozer 9.11 5.95/+53% +# Ryzen 4.75 3.80/+24% 1.93/+150%(**) # VIA Nano 9.32 7.15/+30% # Atom 10.3 9.17/+12% # Silvermont 13.1(*) 9.37/+40% +# Knights L 13.2(*) 9.68/+36% 8.30/+59% # Goldmont 8.13 6.42/+27% 1.70/+380%(**) # # (*) obviously suboptimal result, nothing was done about it, @@ -257,6 +259,7 @@ $code.=<<___; .type sha1_block_data_order,\@function,3 .align 16 sha1_block_data_order: +.cfi_startproc mov OPENSSL_ia32cap_P+0(%rip),%r9d mov OPENSSL_ia32cap_P+4(%rip),%r8d mov OPENSSL_ia32cap_P+8(%rip),%r10d @@ -264,7 +267,7 @@ sha1_block_data_order: jz .Lialu ___ $code.=<<___ if ($shaext); - test \$`1<<29`,%r10d # check SHA bit + test \$`1<<29`,%r10d # check SHA bit jnz _shaext_shortcut ___ $code.=<<___ if ($avx>1); @@ -285,17 +288,24 @@ $code.=<<___; .align 16 .Lialu: mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 mov %rdi,$ctx # reassigned argument sub \$`8+16*4`,%rsp mov %rsi,$inp # reassigned argument and \$-64,%rsp mov %rdx,$num # reassigned argument mov %rax,`16*4`(%rsp) +.cfi_cfa_expression %rsp+64,deref,+8 .Lprologue: mov 0($ctx),$A @@ -329,14 +339,22 @@ $code.=<<___; jnz .Lloop mov `16*4`(%rsp),%rsi +.cfi_def_cfa %rsi,8 mov -40(%rsi),%r14 +.cfi_restore %r14 mov -32(%rsi),%r13 +.cfi_restore %r13 mov -24(%rsi),%r12 +.cfi_restore %r12 mov -16(%rsi),%rbp +.cfi_restore %rbp mov -8(%rsi),%rbx +.cfi_restore %rbx lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lepilogue: ret +.cfi_endproc .size sha1_block_data_order,.-sha1_block_data_order ___ if ($shaext) {{{ @@ -352,6 +370,7 @@ $code.=<<___; .align 32 sha1_block_data_order_shaext: _shaext_shortcut: +.cfi_startproc ___ $code.=<<___ if ($win64); lea `-8-4*16`(%rsp),%rsp @@ -449,6 +468,7 @@ $code.=<<___ if ($win64); .Lepilogue_shaext: ___ $code.=<<___; +.cfi_endproc ret .size sha1_block_data_order_shaext,.-sha1_block_data_order_shaext ___ @@ -462,7 +482,8 @@ my @V=($A,$B,$C,$D,$E)=("%eax","%ebx","%ecx","%edx","%ebp"); # size optimization my @T=("%esi","%edi"); my $j=0; my $rx=0; -my $K_XX_XX="%r11"; +my $K_XX_XX="%r14"; +my $fp="%r11"; my $_rol=sub { &rol(@_) }; my $_ror=sub { &ror(@_) }; @@ -483,25 +504,31 @@ $code.=<<___; .align 16 sha1_block_data_order_ssse3: _ssse3_shortcut: - mov %rsp,%rax +.cfi_startproc + mov %rsp,$fp # frame pointer +.cfi_def_cfa_register $fp push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 # redundant, done to share Win64 SE handler +.cfi_push %r13 push %r14 +.cfi_push %r14 lea `-64-($win64?6*16:0)`(%rsp),%rsp ___ $code.=<<___ if ($win64); - movaps %xmm6,-40-6*16(%rax) - movaps %xmm7,-40-5*16(%rax) - movaps %xmm8,-40-4*16(%rax) - movaps %xmm9,-40-3*16(%rax) - movaps %xmm10,-40-2*16(%rax) - movaps %xmm11,-40-1*16(%rax) + movaps %xmm6,-40-6*16($fp) + movaps %xmm7,-40-5*16($fp) + movaps %xmm8,-40-4*16($fp) + movaps %xmm9,-40-3*16($fp) + movaps %xmm10,-40-2*16($fp) + movaps %xmm11,-40-1*16($fp) .Lprologue_ssse3: ___ $code.=<<___; - mov %rax,%r14 # original %rsp and \$-64,%rsp mov %rdi,$ctx # reassigned argument mov %rsi,$inp # reassigned argument @@ -908,23 +935,29 @@ $code.=<<___; mov $E,16($ctx) ___ $code.=<<___ if ($win64); - movaps -40-6*16(%r14),%xmm6 - movaps -40-5*16(%r14),%xmm7 - movaps -40-4*16(%r14),%xmm8 - movaps -40-3*16(%r14),%xmm9 - movaps -40-2*16(%r14),%xmm10 - movaps -40-1*16(%r14),%xmm11 + movaps -40-6*16($fp),%xmm6 + movaps -40-5*16($fp),%xmm7 + movaps -40-4*16($fp),%xmm8 + movaps -40-3*16($fp),%xmm9 + movaps -40-2*16($fp),%xmm10 + movaps -40-1*16($fp),%xmm11 ___ $code.=<<___; - lea (%r14),%rsi - mov -40(%rsi),%r14 - mov -32(%rsi),%r13 - mov -24(%rsi),%r12 - mov -16(%rsi),%rbp - mov -8(%rsi),%rbx - lea (%rsi),%rsp + mov -40($fp),%r14 +.cfi_restore %r14 + mov -32($fp),%r13 +.cfi_restore %r13 + mov -24($fp),%r12 +.cfi_restore %r12 + mov -16($fp),%rbp +.cfi_restore %rbp + mov -8($fp),%rbx +.cfi_restore %rbx + lea ($fp),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_ssse3: ret +.cfi_endproc .size sha1_block_data_order_ssse3,.-sha1_block_data_order_ssse3 ___ @@ -945,26 +978,32 @@ $code.=<<___; .align 16 sha1_block_data_order_avx: _avx_shortcut: - mov %rsp,%rax +.cfi_startproc + mov %rsp,$fp +.cfi_def_cfa_register $fp push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 # redundant, done to share Win64 SE handler +.cfi_push %r13 push %r14 +.cfi_push %r14 lea `-64-($win64?6*16:0)`(%rsp),%rsp vzeroupper ___ $code.=<<___ if ($win64); - vmovaps %xmm6,-40-6*16(%rax) - vmovaps %xmm7,-40-5*16(%rax) - vmovaps %xmm8,-40-4*16(%rax) - vmovaps %xmm9,-40-3*16(%rax) - vmovaps %xmm10,-40-2*16(%rax) - vmovaps %xmm11,-40-1*16(%rax) + vmovaps %xmm6,-40-6*16($fp) + vmovaps %xmm7,-40-5*16($fp) + vmovaps %xmm8,-40-4*16($fp) + vmovaps %xmm9,-40-3*16($fp) + vmovaps %xmm10,-40-2*16($fp) + vmovaps %xmm11,-40-1*16($fp) .Lprologue_avx: ___ $code.=<<___; - mov %rax,%r14 # original %rsp and \$-64,%rsp mov %rdi,$ctx # reassigned argument mov %rsi,$inp # reassigned argument @@ -1272,23 +1311,29 @@ $code.=<<___; mov $E,16($ctx) ___ $code.=<<___ if ($win64); - movaps -40-6*16(%r14),%xmm6 - movaps -40-5*16(%r14),%xmm7 - movaps -40-4*16(%r14),%xmm8 - movaps -40-3*16(%r14),%xmm9 - movaps -40-2*16(%r14),%xmm10 - movaps -40-1*16(%r14),%xmm11 + movaps -40-6*16($fp),%xmm6 + movaps -40-5*16($fp),%xmm7 + movaps -40-4*16($fp),%xmm8 + movaps -40-3*16($fp),%xmm9 + movaps -40-2*16($fp),%xmm10 + movaps -40-1*16($fp),%xmm11 ___ $code.=<<___; - lea (%r14),%rsi - mov -40(%rsi),%r14 - mov -32(%rsi),%r13 - mov -24(%rsi),%r12 - mov -16(%rsi),%rbp - mov -8(%rsi),%rbx - lea (%rsi),%rsp + mov -40($fp),%r14 +.cfi_restore %r14 + mov -32($fp),%r13 +.cfi_restore %r13 + mov -24($fp),%r12 +.cfi_restore %r12 + mov -16($fp),%rbp +.cfi_restore %rbp + mov -8($fp),%rbx +.cfi_restore %rbx + lea ($fp),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_avx: ret +.cfi_endproc .size sha1_block_data_order_avx,.-sha1_block_data_order_avx ___ @@ -1312,26 +1357,32 @@ $code.=<<___; .align 16 sha1_block_data_order_avx2: _avx2_shortcut: - mov %rsp,%rax +.cfi_startproc + mov %rsp,$fp +.cfi_def_cfa_register $fp push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 vzeroupper ___ $code.=<<___ if ($win64); lea -6*16(%rsp),%rsp - vmovaps %xmm6,-40-6*16(%rax) - vmovaps %xmm7,-40-5*16(%rax) - vmovaps %xmm8,-40-4*16(%rax) - vmovaps %xmm9,-40-3*16(%rax) - vmovaps %xmm10,-40-2*16(%rax) - vmovaps %xmm11,-40-1*16(%rax) + vmovaps %xmm6,-40-6*16($fp) + vmovaps %xmm7,-40-5*16($fp) + vmovaps %xmm8,-40-4*16($fp) + vmovaps %xmm9,-40-3*16($fp) + vmovaps %xmm10,-40-2*16($fp) + vmovaps %xmm11,-40-1*16($fp) .Lprologue_avx2: ___ $code.=<<___; - mov %rax,%r14 # original %rsp mov %rdi,$ctx # reassigned argument mov %rsi,$inp # reassigned argument mov %rdx,$num # reassigned argument @@ -1751,23 +1802,29 @@ $code.=<<___; vzeroupper ___ $code.=<<___ if ($win64); - movaps -40-6*16(%r14),%xmm6 - movaps -40-5*16(%r14),%xmm7 - movaps -40-4*16(%r14),%xmm8 - movaps -40-3*16(%r14),%xmm9 - movaps -40-2*16(%r14),%xmm10 - movaps -40-1*16(%r14),%xmm11 + movaps -40-6*16($fp),%xmm6 + movaps -40-5*16($fp),%xmm7 + movaps -40-4*16($fp),%xmm8 + movaps -40-3*16($fp),%xmm9 + movaps -40-2*16($fp),%xmm10 + movaps -40-1*16($fp),%xmm11 ___ $code.=<<___; - lea (%r14),%rsi - mov -40(%rsi),%r14 - mov -32(%rsi),%r13 - mov -24(%rsi),%r12 - mov -16(%rsi),%rbp - mov -8(%rsi),%rbx - lea (%rsi),%rsp + mov -40($fp),%r14 +.cfi_restore %r14 + mov -32($fp),%r13 +.cfi_restore %r13 + mov -24($fp),%r12 +.cfi_restore %r12 + mov -16($fp),%rbp +.cfi_restore %rbp + mov -8($fp),%rbx +.cfi_restore %rbx + lea ($fp),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_avx2: ret +.cfi_endproc .size sha1_block_data_order_avx2,.-sha1_block_data_order_avx2 ___ } @@ -1908,15 +1965,13 @@ ssse3_handler: cmp %r10,%rbx # context->RipRsp + mov 208($context),%rax # pull context->R11 mov 4(%r11),%r10d # HandlerData[1] lea (%rsi,%r10),%r10 # epilogue label cmp %r10,%rbx # context->Rip>=epilogue label jae .Lcommon_seh_tail - mov 232($context),%rax # pull context->R14 - lea -40-6*16(%rax),%rsi lea 512($context),%rdi # &context.Xmm6 mov \$12,%ecx @@ -1929,9 +1984,9 @@ ssse3_handler: mov -40(%rax),%r14 mov %rbx,144($context) # restore context->Rbx mov %rbp,160($context) # restore context->Rbp - mov %r12,216($context) # restore cotnext->R12 - mov %r13,224($context) # restore cotnext->R13 - mov %r14,232($context) # restore cotnext->R14 + mov %r12,216($context) # restore context->R12 + mov %r13,224($context) # restore context->R13 + mov %r14,232($context) # restore context->R14 .Lcommon_seh_tail: mov 8(%rax),%rdi diff --git a/crypto/sha/asm/sha256-586.pl b/crypto/sha/asm/sha256-586.pl index 6af1d84b..48830728 100644 --- a/crypto/sha/asm/sha256-586.pl +++ b/crypto/sha/asm/sha256-586.pl @@ -18,7 +18,7 @@ # # Performance improvement over compiler generated code varies from # 10% to 40% [see below]. Not very impressive on some µ-archs, but -# it's 5 times smaller and optimizies amount of writes. +# it's 5 times smaller and optimizes amount of writes. # # May 2012. # @@ -47,7 +47,7 @@ # # Performance in clock cycles per processed byte (less is better): # -# gcc icc x86 asm(*) SIMD x86_64 asm(**) +# gcc icc x86 asm(*) SIMD x86_64 asm(**) # Pentium 46 57 40/38 - - # PIII 36 33 27/24 - - # P4 41 38 28 - 17.3 @@ -57,14 +57,17 @@ # Sandy Bridge 25 - 15.9 12.4 11.6 # Ivy Bridge 24 - 15.0 11.4 10.3 # Haswell 22 - 13.9 9.46 7.80 +# Skylake 20 - 14.9 9.50 7.70 # Bulldozer 36 - 27/22 17.0 13.6 # VIA Nano 36 - 25/22 16.8 16.5 # Atom 50 - 30/25 21.9 18.9 # Silvermont 40 - 34/31 22.9 20.6 +# Goldmont 29 - 20 16.3(***) # # (*) numbers after slash are for unrolled loop, where applicable; # (**) x86_64 assembly performance is presented for reference # purposes, results are best-available; +# (***) SHAEXT result is 4.1, strangely enough better than 64-bit one; $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; push(@INC,"${dir}","${dir}../../perlasm"); @@ -73,7 +76,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"sha512-586.pl",$ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$ARGV[$#ARGV] eq "386"); $xmm=$avx=0; for (@ARGV) { $xmm=1 if (/-DOPENSSL_IA32_SSE2/); } @@ -276,7 +279,7 @@ my $suffix=shift; &mov ($Coff,"ecx"); &mov ($Doff,"edi"); &mov (&DWP(0,"esp"),"ebx"); # magic - &mov ($E,&DWP(16,"esi")); + &mov ($E,&DWP(16,"esi")); &mov ("ebx",&DWP(20,"esi")); &mov ("ecx",&DWP(24,"esi")); &mov ("edi",&DWP(28,"esi")); @@ -385,7 +388,7 @@ my @AH=($A,$K256); &xor ($AH[1],"ecx"); # magic &mov (&DWP(8,"esp"),"ecx"); &mov (&DWP(12,"esp"),"ebx"); - &mov ($E,&DWP(16,"esi")); + &mov ($E,&DWP(16,"esi")); &mov ("ebx",&DWP(20,"esi")); &mov ("ecx",&DWP(24,"esi")); &mov ("esi",&DWP(28,"esi")); diff --git a/crypto/sha/asm/sha256-mb-x86_64.pl b/crypto/sha/asm/sha256-mb-x86_64.pl index fbcd29f2..73978dbd 100644 --- a/crypto/sha/asm/sha256-mb-x86_64.pl +++ b/crypto/sha/asm/sha256-mb-x86_64.pl @@ -36,7 +36,7 @@ # (iii) "this" is for n=8, when we gather twice as much data, result # for n=4 is 20.3+4.44=24.7; # (iv) presented improvement coefficients are asymptotic limits and -# in real-life application are somewhat lower, e.g. for 2KB +# in real-life application are somewhat lower, e.g. for 2KB # fragments they range from 75% to 130% (on Haswell); $flavour = shift; @@ -244,6 +244,7 @@ $code.=<<___; .type sha256_multi_block,\@function,3 .align 32 sha256_multi_block: +.cfi_startproc mov OPENSSL_ia32cap_P+4(%rip),%rcx bt \$61,%rcx # check SHA bit jc _shaext_shortcut @@ -254,8 +255,11 @@ $code.=<<___ if ($avx); ___ $code.=<<___; mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -274,6 +278,7 @@ $code.=<<___; sub \$`$REG_SZ*18`, %rsp and \$-256,%rsp mov %rax,`$REG_SZ*17`(%rsp) # original %rsp +.cfi_cfa_expression %rsp+`$REG_SZ*17`,deref,+8 .Lbody: lea K256+128(%rip),$Tbl lea `$REG_SZ*16`(%rsp),%rbx @@ -391,6 +396,7 @@ $code.=<<___; .Ldone: mov `$REG_SZ*17`(%rsp),%rax # original %rsp +.cfi_def_cfa %rax,8 ___ $code.=<<___ if ($win64); movaps -0xb8(%rax),%xmm6 @@ -406,10 +412,14 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Lepilogue: ret +.cfi_endproc .size sha256_multi_block,.-sha256_multi_block ___ {{{ @@ -421,10 +431,14 @@ $code.=<<___; .type sha256_multi_block_shaext,\@function,3 .align 32 sha256_multi_block_shaext: +.cfi_startproc _shaext_shortcut: mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -758,10 +772,14 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_shaext: ret +.cfi_endproc .size sha256_multi_block_shaext,.-sha256_multi_block_shaext ___ }}} @@ -921,6 +939,7 @@ $code.=<<___; .type sha256_multi_block_avx,\@function,3 .align 32 sha256_multi_block_avx: +.cfi_startproc _avx_shortcut: ___ $code.=<<___ if ($avx>1); @@ -935,8 +954,11 @@ $code.=<<___ if ($avx>1); ___ $code.=<<___; mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -955,6 +977,7 @@ $code.=<<___; sub \$`$REG_SZ*18`, %rsp and \$-256,%rsp mov %rax,`$REG_SZ*17`(%rsp) # original %rsp +.cfi_cfa_expression %rsp+`$REG_SZ*17`,deref,+8 .Lbody_avx: lea K256+128(%rip),$Tbl lea `$REG_SZ*16`(%rsp),%rbx @@ -1070,6 +1093,7 @@ $code.=<<___; .Ldone_avx: mov `$REG_SZ*17`(%rsp),%rax # original %rsp +.cfi_def_cfa %rax,8 vzeroupper ___ $code.=<<___ if ($win64); @@ -1086,10 +1110,14 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_avx: ret +.cfi_endproc .size sha256_multi_block_avx,.-sha256_multi_block_avx ___ if ($avx>1) { @@ -1105,14 +1133,22 @@ $code.=<<___; .type sha256_multi_block_avx2,\@function,3 .align 32 sha256_multi_block_avx2: +.cfi_startproc _avx2_shortcut: mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 ___ $code.=<<___ if ($win64); lea -0xa8(%rsp),%rsp @@ -1131,6 +1167,7 @@ $code.=<<___; sub \$`$REG_SZ*18`, %rsp and \$-256,%rsp mov %rax,`$REG_SZ*17`(%rsp) # original %rsp +.cfi_cfa_expression %rsp+`$REG_SZ*17`,deref,+8 .Lbody_avx2: lea K256+128(%rip),$Tbl lea 0x80($ctx),$ctx # size optimization @@ -1246,6 +1283,7 @@ $code.=<<___; .Ldone_avx2: mov `$REG_SZ*17`(%rsp),%rax # original %rsp +.cfi_def_cfa %rax,8 vzeroupper ___ $code.=<<___ if ($win64); @@ -1262,14 +1300,22 @@ $code.=<<___ if ($win64); ___ $code.=<<___; mov -48(%rax),%r15 +.cfi_restore %r15 mov -40(%rax),%r14 +.cfi_restore %r14 mov -32(%rax),%r13 +.cfi_restore %r13 mov -24(%rax),%r12 +.cfi_restore %r12 mov -16(%rax),%rbp +.cfi_restore %rbp mov -8(%rax),%rbx +.cfi_restore %rbx lea (%rax),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_avx2: ret +.cfi_endproc .size sha256_multi_block_avx2,.-sha256_multi_block_avx2 ___ } }}} @@ -1462,10 +1508,10 @@ avx2_handler: mov -48(%rax),%r15 mov %rbx,144($context) # restore context->Rbx mov %rbp,160($context) # restore context->Rbp - mov %r12,216($context) # restore cotnext->R12 - mov %r13,224($context) # restore cotnext->R13 - mov %r14,232($context) # restore cotnext->R14 - mov %r15,240($context) # restore cotnext->R15 + mov %r12,216($context) # restore context->R12 + mov %r13,224($context) # restore context->R13 + mov %r14,232($context) # restore context->R14 + mov %r15,240($context) # restore context->R15 lea -56-10*16(%rax),%rsi lea 512($context),%rdi # &context.Xmm6 diff --git a/crypto/sha/asm/sha512-586.pl b/crypto/sha/asm/sha512-586.pl index 3873934b..867ce30b 100644 --- a/crypto/sha/asm/sha512-586.pl +++ b/crypto/sha/asm/sha512-586.pl @@ -32,6 +32,7 @@ # Sandy Bridge 58 - 35 11.9 11.2 # Ivy Bridge 50 - 33 11.5 8.17 # Haswell 46 - 29 11.3 7.66 +# Skylake 40 - 26 13.3 7.25 # Bulldozer 121 - 50 14.0 13.5 # VIA Nano 91 - 52 33 14.7 # Atom 126 - 68 48(***) 14.7 @@ -41,7 +42,7 @@ # (*) whichever best applicable. # (**) x86_64 assembler performance is presented for reference # purposes, the results are for integer-only code. -# (***) paddq is increadibly slow on Atom. +# (***) paddq is incredibly slow on Atom. # # IALU code-path is optimized for elder Pentiums. On vanilla Pentium # performance improvement over compiler generated code reaches ~60%, @@ -61,7 +62,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"sha512-586.pl",$ARGV[$#ARGV] eq "386"); +&asm_init($ARGV[0],$ARGV[$#ARGV] eq "386"); $sse2=0; for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } @@ -384,7 +385,7 @@ if ($sse2) { &set_label("16_79_sse2",16); for ($j=0;$j<2;$j++) { # 2x unroll - #&movq ("mm7",&QWP(8*(9+16-1),"esp")); # prefetched in BODY_00_15 + #&movq ("mm7",&QWP(8*(9+16-1),"esp")); # prefetched in BODY_00_15 &movq ("mm5",&QWP(8*(9+16-14),"esp")); &movq ("mm1","mm7"); &psrlq ("mm7",1); diff --git a/crypto/sha/asm/sha512-armv8.pl b/crypto/sha/asm/sha512-armv8.pl index c1aaf778..ac84ebb5 100644 --- a/crypto/sha/asm/sha512-armv8.pl +++ b/crypto/sha/asm/sha512-armv8.pl @@ -1,17 +1,18 @@ #! /usr/bin/env perl -# Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2014-2018 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 -# # ==================================================================== # Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. +# +# Permission to use under GPLv2 terms is granted. # ==================================================================== # # SHA256/512 for ARMv8. @@ -26,7 +27,8 @@ # Denver 2.01 10.5 (+26%) 6.70 (+8%) # X-Gene 20.0 (+100%) 12.8 (+300%(***)) # Mongoose 2.36 13.0 (+50%) 8.36 (+33%) -# +# Kryo 1.92 17.4 (+30%) 11.2 (+8%) +# # (*) Software SHA256 results are of lesser relevance, presented # mostly for informational purposes. # (**) The result is a trade-off: it's possible to improve it by @@ -34,19 +36,37 @@ # on Cortex-A53 (or by 4 cycles per round). # (***) Super-impressive coefficients over gcc-generated code are # indication of some compiler "pathology", most notably code -# generated with -mgeneral-regs-only is significanty faster +# generated with -mgeneral-regs-only is significantly faster # and the gap is only 40-90%. +# +# October 2016. +# +# Originally it was reckoned that it makes no sense to implement NEON +# version of SHA256 for 64-bit processors. This is because performance +# improvement on most wide-spread Cortex-A5x processors was observed +# to be marginal, same on Cortex-A53 and ~10% on A57. But then it was +# observed that 32-bit NEON SHA256 performs significantly better than +# 64-bit scalar version on *some* of the more recent processors. As +# result 64-bit NEON version of SHA256 was added to provide best +# all-round performance. For example it executes ~30% faster on X-Gene +# and Mongoose. [For reference, NEON version of SHA512 is bound to +# deliver much less improvement, likely *negative* on Cortex-A5x. +# Which is why NEON support is limited to SHA256.] -$flavour=shift; -$output=shift; +$output=pop; +$flavour=pop; -$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; -( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or -( $xlate="${dir}../../perlasm/arm-xlate.pl" and -f $xlate) or -die "can't locate arm-xlate.pl"; +if ($flavour && $flavour ne "void") { + $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; + ( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or + ( $xlate="${dir}../../perlasm/arm-xlate.pl" and -f $xlate) or + die "can't locate arm-xlate.pl"; -open OUT,"| \"$^X\" $xlate $flavour $output"; -*STDOUT=*OUT; + open OUT,"| \"$^X\" $xlate $flavour $output"; + *STDOUT=*OUT; +} else { + open STDOUT,">$output"; +} if ($output =~ /512/) { $BITS=512; @@ -83,7 +103,7 @@ my ($T0,$T1,$T2)=(@X[($i-8)&15],@X[($i-9)&15],@X[($i-10)&15]); $T0=@X[$i+3] if ($i<11); $code.=<<___ if ($i<16); -#ifndef __ARMEB__ +#ifndef __AARCH64EB__ rev @X[$i],@X[$i] // $i #endif ___ @@ -166,7 +186,9 @@ ___ } $code.=<<___; -#include "arm_arch.h" +#ifndef __KERNEL__ +# include "arm_arch.h" +#endif .text @@ -175,20 +197,28 @@ $code.=<<___; .type $func,%function .align 6 $func: -___ -$code.=<<___ if ($SZ==4); -#ifdef __ILP32__ +#ifndef __KERNEL__ +# ifdef __ILP32__ ldrsw x16,.LOPENSSL_armcap_P -#else +# else ldr x16,.LOPENSSL_armcap_P -#endif +# endif adr x17,.LOPENSSL_armcap_P add x16,x16,x17 ldr w16,[x16] +___ +$code.=<<___ if ($SZ==4); tst w16,#ARMV8_SHA256 b.ne .Lv8_entry + tst w16,#ARMV7_NEON + b.ne .Lneon_entry +___ +$code.=<<___ if ($SZ==8); + tst w16,#ARMV8_SHA512 + b.ne .Lv8_entry ___ $code.=<<___; +#endif stp x29,x30,[sp,#-128]! add x29,sp,#0 @@ -321,12 +351,14 @@ $code.=<<___ if ($SZ==4); ___ $code.=<<___; .size .LK$BITS,.-.LK$BITS +#ifndef __KERNEL__ .align 3 .LOPENSSL_armcap_P: -#ifdef __ILP32__ +# ifdef __ILP32__ .long OPENSSL_armcap_P-. -#else +# else .quad OPENSSL_armcap_P-. +# endif #endif .asciz "SHA$BITS block transform for ARMv8, CRYPTOGAMS by " .align 2 @@ -341,6 +373,7 @@ my ($W0,$W1)=("v16.4s","v17.4s"); my ($ABCD_SAVE,$EFGH_SAVE)=("v18.16b","v19.16b"); $code.=<<___; +#ifndef __KERNEL__ .type sha256_block_armv8,%function .align 6 sha256_block_armv8: @@ -409,11 +442,406 @@ $code.=<<___; ldr x29,[sp],#16 ret .size sha256_block_armv8,.-sha256_block_armv8 +#endif +___ +} + +if ($SZ==4) { ######################################### NEON stuff # +# You'll surely note a lot of similarities with sha256-armv4 module, +# and of course it's not a coincidence. sha256-armv4 was used as +# initial template, but was adapted for ARMv8 instruction set and +# extensively re-tuned for all-round performance. + +my @V = ($A,$B,$C,$D,$E,$F,$G,$H) = map("w$_",(3..10)); +my ($t0,$t1,$t2,$t3,$t4) = map("w$_",(11..15)); +my $Ktbl="x16"; +my $Xfer="x17"; +my @X = map("q$_",(0..3)); +my ($T0,$T1,$T2,$T3,$T4,$T5,$T6,$T7) = map("q$_",(4..7,16..19)); +my $j=0; + +sub AUTOLOAD() # thunk [simplified] x86-style perlasm +{ my $opcode = $AUTOLOAD; $opcode =~ s/.*:://; $opcode =~ s/_/\./; + my $arg = pop; + $arg = "#$arg" if ($arg*1 eq $arg); + $code .= "\t$opcode\t".join(',',@_,$arg)."\n"; +} + +sub Dscalar { shift =~ m|[qv]([0-9]+)|?"d$1":""; } +sub Dlo { shift =~ m|[qv]([0-9]+)|?"v$1.d[0]":""; } +sub Dhi { shift =~ m|[qv]([0-9]+)|?"v$1.d[1]":""; } + +sub Xupdate() +{ use integer; + my $body = shift; + my @insns = (&$body,&$body,&$body,&$body); + my ($a,$b,$c,$d,$e,$f,$g,$h); + + &ext_8 ($T0,@X[0],@X[1],4); # X[1..4] + eval(shift(@insns)); + eval(shift(@insns)); + eval(shift(@insns)); + &ext_8 ($T3,@X[2],@X[3],4); # X[9..12] + eval(shift(@insns)); + eval(shift(@insns)); + &mov (&Dscalar($T7),&Dhi(@X[3])); # X[14..15] + eval(shift(@insns)); + eval(shift(@insns)); + &ushr_32 ($T2,$T0,$sigma0[0]); + eval(shift(@insns)); + &ushr_32 ($T1,$T0,$sigma0[2]); + eval(shift(@insns)); + &add_32 (@X[0],@X[0],$T3); # X[0..3] += X[9..12] + eval(shift(@insns)); + &sli_32 ($T2,$T0,32-$sigma0[0]); + eval(shift(@insns)); + eval(shift(@insns)); + &ushr_32 ($T3,$T0,$sigma0[1]); + eval(shift(@insns)); + eval(shift(@insns)); + &eor_8 ($T1,$T1,$T2); + eval(shift(@insns)); + eval(shift(@insns)); + &sli_32 ($T3,$T0,32-$sigma0[1]); + eval(shift(@insns)); + eval(shift(@insns)); + &ushr_32 ($T4,$T7,$sigma1[0]); + eval(shift(@insns)); + eval(shift(@insns)); + &eor_8 ($T1,$T1,$T3); # sigma0(X[1..4]) + eval(shift(@insns)); + eval(shift(@insns)); + &sli_32 ($T4,$T7,32-$sigma1[0]); + eval(shift(@insns)); + eval(shift(@insns)); + &ushr_32 ($T5,$T7,$sigma1[2]); + eval(shift(@insns)); + eval(shift(@insns)); + &ushr_32 ($T3,$T7,$sigma1[1]); + eval(shift(@insns)); + eval(shift(@insns)); + &add_32 (@X[0],@X[0],$T1); # X[0..3] += sigma0(X[1..4]) + eval(shift(@insns)); + eval(shift(@insns)); + &sli_u32 ($T3,$T7,32-$sigma1[1]); + eval(shift(@insns)); + eval(shift(@insns)); + &eor_8 ($T5,$T5,$T4); + eval(shift(@insns)); + eval(shift(@insns)); + eval(shift(@insns)); + &eor_8 ($T5,$T5,$T3); # sigma1(X[14..15]) + eval(shift(@insns)); + eval(shift(@insns)); + eval(shift(@insns)); + &add_32 (@X[0],@X[0],$T5); # X[0..1] += sigma1(X[14..15]) + eval(shift(@insns)); + eval(shift(@insns)); + eval(shift(@insns)); + &ushr_32 ($T6,@X[0],$sigma1[0]); + eval(shift(@insns)); + &ushr_32 ($T7,@X[0],$sigma1[2]); + eval(shift(@insns)); + eval(shift(@insns)); + &sli_32 ($T6,@X[0],32-$sigma1[0]); + eval(shift(@insns)); + &ushr_32 ($T5,@X[0],$sigma1[1]); + eval(shift(@insns)); + eval(shift(@insns)); + &eor_8 ($T7,$T7,$T6); + eval(shift(@insns)); + eval(shift(@insns)); + &sli_32 ($T5,@X[0],32-$sigma1[1]); + eval(shift(@insns)); + eval(shift(@insns)); + &ld1_32 ("{$T0}","[$Ktbl], #16"); + eval(shift(@insns)); + &eor_8 ($T7,$T7,$T5); # sigma1(X[16..17]) + eval(shift(@insns)); + eval(shift(@insns)); + &eor_8 ($T5,$T5,$T5); + eval(shift(@insns)); + eval(shift(@insns)); + &mov (&Dhi($T5), &Dlo($T7)); + eval(shift(@insns)); + eval(shift(@insns)); + eval(shift(@insns)); + &add_32 (@X[0],@X[0],$T5); # X[2..3] += sigma1(X[16..17]) + eval(shift(@insns)); + eval(shift(@insns)); + eval(shift(@insns)); + &add_32 ($T0,$T0,@X[0]); + while($#insns>=1) { eval(shift(@insns)); } + &st1_32 ("{$T0}","[$Xfer], #16"); + eval(shift(@insns)); + + push(@X,shift(@X)); # "rotate" X[] +} + +sub Xpreload() +{ use integer; + my $body = shift; + my @insns = (&$body,&$body,&$body,&$body); + my ($a,$b,$c,$d,$e,$f,$g,$h); + + eval(shift(@insns)); + eval(shift(@insns)); + &ld1_8 ("{@X[0]}","[$inp],#16"); + eval(shift(@insns)); + eval(shift(@insns)); + &ld1_32 ("{$T0}","[$Ktbl],#16"); + eval(shift(@insns)); + eval(shift(@insns)); + eval(shift(@insns)); + eval(shift(@insns)); + &rev32 (@X[0],@X[0]); + eval(shift(@insns)); + eval(shift(@insns)); + eval(shift(@insns)); + eval(shift(@insns)); + &add_32 ($T0,$T0,@X[0]); + foreach (@insns) { eval; } # remaining instructions + &st1_32 ("{$T0}","[$Xfer], #16"); + + push(@X,shift(@X)); # "rotate" X[] +} + +sub body_00_15 () { + ( + '($a,$b,$c,$d,$e,$f,$g,$h)=@V;'. + '&add ($h,$h,$t1)', # h+=X[i]+K[i] + '&add ($a,$a,$t4);'. # h+=Sigma0(a) from the past + '&and ($t1,$f,$e)', + '&bic ($t4,$g,$e)', + '&eor ($t0,$e,$e,"ror#".($Sigma1[1]-$Sigma1[0]))', + '&add ($a,$a,$t2)', # h+=Maj(a,b,c) from the past + '&orr ($t1,$t1,$t4)', # Ch(e,f,g) + '&eor ($t0,$t0,$e,"ror#".($Sigma1[2]-$Sigma1[0]))', # Sigma1(e) + '&eor ($t4,$a,$a,"ror#".($Sigma0[1]-$Sigma0[0]))', + '&add ($h,$h,$t1)', # h+=Ch(e,f,g) + '&ror ($t0,$t0,"#$Sigma1[0]")', + '&eor ($t2,$a,$b)', # a^b, b^c in next round + '&eor ($t4,$t4,$a,"ror#".($Sigma0[2]-$Sigma0[0]))', # Sigma0(a) + '&add ($h,$h,$t0)', # h+=Sigma1(e) + '&ldr ($t1,sprintf "[sp,#%d]",4*(($j+1)&15)) if (($j&15)!=15);'. + '&ldr ($t1,"[$Ktbl]") if ($j==15);'. + '&and ($t3,$t3,$t2)', # (b^c)&=(a^b) + '&ror ($t4,$t4,"#$Sigma0[0]")', + '&add ($d,$d,$h)', # d+=h + '&eor ($t3,$t3,$b)', # Maj(a,b,c) + '$j++; unshift(@V,pop(@V)); ($t2,$t3)=($t3,$t2);' + ) +} + +$code.=<<___; +#ifdef __KERNEL__ +.globl sha256_block_neon +#endif +.type sha256_block_neon,%function +.align 4 +sha256_block_neon: +.Lneon_entry: + stp x29, x30, [sp, #-16]! + mov x29, sp + sub sp,sp,#16*4 + + adr $Ktbl,.LK256 + add $num,$inp,$num,lsl#6 // len to point at the end of inp + + ld1.8 {@X[0]},[$inp], #16 + ld1.8 {@X[1]},[$inp], #16 + ld1.8 {@X[2]},[$inp], #16 + ld1.8 {@X[3]},[$inp], #16 + ld1.32 {$T0},[$Ktbl], #16 + ld1.32 {$T1},[$Ktbl], #16 + ld1.32 {$T2},[$Ktbl], #16 + ld1.32 {$T3},[$Ktbl], #16 + rev32 @X[0],@X[0] // yes, even on + rev32 @X[1],@X[1] // big-endian + rev32 @X[2],@X[2] + rev32 @X[3],@X[3] + mov $Xfer,sp + add.32 $T0,$T0,@X[0] + add.32 $T1,$T1,@X[1] + add.32 $T2,$T2,@X[2] + st1.32 {$T0-$T1},[$Xfer], #32 + add.32 $T3,$T3,@X[3] + st1.32 {$T2-$T3},[$Xfer] + sub $Xfer,$Xfer,#32 + + ldp $A,$B,[$ctx] + ldp $C,$D,[$ctx,#8] + ldp $E,$F,[$ctx,#16] + ldp $G,$H,[$ctx,#24] + ldr $t1,[sp,#0] + mov $t2,wzr + eor $t3,$B,$C + mov $t4,wzr + b .L_00_48 + +.align 4 +.L_00_48: +___ + &Xupdate(\&body_00_15); + &Xupdate(\&body_00_15); + &Xupdate(\&body_00_15); + &Xupdate(\&body_00_15); +$code.=<<___; + cmp $t1,#0 // check for K256 terminator + ldr $t1,[sp,#0] + sub $Xfer,$Xfer,#64 + bne .L_00_48 + + sub $Ktbl,$Ktbl,#256 // rewind $Ktbl + cmp $inp,$num + mov $Xfer, #64 + csel $Xfer, $Xfer, xzr, eq + sub $inp,$inp,$Xfer // avoid SEGV + mov $Xfer,sp +___ + &Xpreload(\&body_00_15); + &Xpreload(\&body_00_15); + &Xpreload(\&body_00_15); + &Xpreload(\&body_00_15); +$code.=<<___; + add $A,$A,$t4 // h+=Sigma0(a) from the past + ldp $t0,$t1,[$ctx,#0] + add $A,$A,$t2 // h+=Maj(a,b,c) from the past + ldp $t2,$t3,[$ctx,#8] + add $A,$A,$t0 // accumulate + add $B,$B,$t1 + ldp $t0,$t1,[$ctx,#16] + add $C,$C,$t2 + add $D,$D,$t3 + ldp $t2,$t3,[$ctx,#24] + add $E,$E,$t0 + add $F,$F,$t1 + ldr $t1,[sp,#0] + stp $A,$B,[$ctx,#0] + add $G,$G,$t2 + mov $t2,wzr + stp $C,$D,[$ctx,#8] + add $H,$H,$t3 + stp $E,$F,[$ctx,#16] + eor $t3,$B,$C + stp $G,$H,[$ctx,#24] + mov $t4,wzr + mov $Xfer,sp + b.ne .L_00_48 + + ldr x29,[x29] + add sp,sp,#16*4+16 + ret +.size sha256_block_neon,.-sha256_block_neon +___ +} + +if ($SZ==8) { +my $Ktbl="x3"; + +my @H = map("v$_.16b",(0..4)); +my ($fg,$de,$m9_10)=map("v$_.16b",(5..7)); +my @MSG=map("v$_.16b",(16..23)); +my ($W0,$W1)=("v24.2d","v25.2d"); +my ($AB,$CD,$EF,$GH)=map("v$_.16b",(26..29)); + +$code.=<<___; +#ifndef __KERNEL__ +.type sha512_block_armv8,%function +.align 6 +sha512_block_armv8: +.Lv8_entry: + stp x29,x30,[sp,#-16]! + add x29,sp,#0 + + ld1 {@MSG[0]-@MSG[3]},[$inp],#64 // load input + ld1 {@MSG[4]-@MSG[7]},[$inp],#64 + + ld1.64 {@H[0]-@H[3]},[$ctx] // load context + adr $Ktbl,.LK512 + + rev64 @MSG[0],@MSG[0] + rev64 @MSG[1],@MSG[1] + rev64 @MSG[2],@MSG[2] + rev64 @MSG[3],@MSG[3] + rev64 @MSG[4],@MSG[4] + rev64 @MSG[5],@MSG[5] + rev64 @MSG[6],@MSG[6] + rev64 @MSG[7],@MSG[7] + b .Loop_hw + +.align 4 +.Loop_hw: + ld1.64 {$W0},[$Ktbl],#16 + subs $num,$num,#1 + sub x4,$inp,#128 + orr $AB,@H[0],@H[0] // offload + orr $CD,@H[1],@H[1] + orr $EF,@H[2],@H[2] + orr $GH,@H[3],@H[3] + csel $inp,$inp,x4,ne // conditional rewind +___ +for($i=0;$i<32;$i++) { +$code.=<<___; + add.i64 $W0,$W0,@MSG[0] + ld1.64 {$W1},[$Ktbl],#16 + ext $W0,$W0,$W0,#8 + ext $fg,@H[2],@H[3],#8 + ext $de,@H[1],@H[2],#8 + add.i64 @H[3],@H[3],$W0 // "T1 + H + K512[i]" + sha512su0 @MSG[0],@MSG[1] + ext $m9_10,@MSG[4],@MSG[5],#8 + sha512h @H[3],$fg,$de + sha512su1 @MSG[0],@MSG[7],$m9_10 + add.i64 @H[4],@H[1],@H[3] // "D + T1" + sha512h2 @H[3],$H[1],@H[0] +___ + ($W0,$W1)=($W1,$W0); push(@MSG,shift(@MSG)); + @H = (@H[3],@H[0],@H[4],@H[2],@H[1]); +} +for(;$i<40;$i++) { +$code.=<<___ if ($i<39); + ld1.64 {$W1},[$Ktbl],#16 +___ +$code.=<<___ if ($i==39); + sub $Ktbl,$Ktbl,#$rounds*$SZ // rewind +___ +$code.=<<___; + add.i64 $W0,$W0,@MSG[0] + ld1 {@MSG[0]},[$inp],#16 // load next input + ext $W0,$W0,$W0,#8 + ext $fg,@H[2],@H[3],#8 + ext $de,@H[1],@H[2],#8 + add.i64 @H[3],@H[3],$W0 // "T1 + H + K512[i]" + sha512h @H[3],$fg,$de + rev64 @MSG[0],@MSG[0] + add.i64 @H[4],@H[1],@H[3] // "D + T1" + sha512h2 @H[3],$H[1],@H[0] +___ + ($W0,$W1)=($W1,$W0); push(@MSG,shift(@MSG)); + @H = (@H[3],@H[0],@H[4],@H[2],@H[1]); +} +$code.=<<___; + add.i64 @H[0],@H[0],$AB // accumulate + add.i64 @H[1],@H[1],$CD + add.i64 @H[2],@H[2],$EF + add.i64 @H[3],@H[3],$GH + + cbnz $num,.Loop_hw + + st1.64 {@H[0]-@H[3]},[$ctx] // store context + + ldr x29,[sp],#16 + ret +.size sha512_block_armv8,.-sha512_block_armv8 +#endif ___ } $code.=<<___; +#ifndef __KERNEL__ .comm OPENSSL_armcap_P,4,4 +#endif ___ { my %opcode = ( @@ -431,14 +859,43 @@ ___ } } +{ my %opcode = ( + "sha512h" => 0xce608000, "sha512h2" => 0xce608400, + "sha512su0" => 0xcec08000, "sha512su1" => 0xce608800 ); + + sub unsha512 { + my ($mnemonic,$arg)=@_; + + $arg =~ m/[qv]([0-9]+)[^,]*,\s*[qv]([0-9]+)[^,]*(?:,\s*[qv]([0-9]+))?/o + && + sprintf ".inst\t0x%08x\t//%s %s", + $opcode{$mnemonic}|$1|($2<<5)|($3<<16), + $mnemonic,$arg; + } +} + +open SELF,$0; +while() { + next if (/^#!/); + last if (!s/^#/\/\// and !/^$/); + print; +} +close SELF; + foreach(split("\n",$code)) { - s/\`([^\`]*)\`/eval($1)/geo; + s/\`([^\`]*)\`/eval($1)/ge; - s/\b(sha256\w+)\s+([qv].*)/unsha256($1,$2)/geo; + s/\b(sha512\w+)\s+([qv].*)/unsha512($1,$2)/ge or + s/\b(sha256\w+)\s+([qv].*)/unsha256($1,$2)/ge; - s/\.\w?32\b//o and s/\.16b/\.4s/go; - m/(ld|st)1[^\[]+\[0\]/o and s/\.4s/\.s/go; + s/\bq([0-9]+)\b/v$1.16b/g; # old->new registers + + s/\.[ui]?8(\s)/$1/; + s/\.\w?64\b// and s/\.16b/\.2d/g or + s/\.\w?32\b// and s/\.16b/\.4s/g; + m/\bext\b/ and s/\.2d/\.16b/g or + m/(ld|st)1[^\[]+\[0\]/ and s/\.4s/\.s/g; print $_,"\n"; } diff --git a/crypto/sha/asm/sha512-mips.pl b/crypto/sha/asm/sha512-mips.pl index 5c2d23fa..e6fd2687 100644 --- a/crypto/sha/asm/sha512-mips.pl +++ b/crypto/sha/asm/sha512-mips.pl @@ -60,16 +60,16 @@ $flavour = shift || "o32"; # supported flavours are o32,n32,64,nubi32,nubi64 if ($flavour =~ /64|n32/i) { $PTR_LA="dla"; - $PTR_ADD="dadd"; # incidentally works even on n32 - $PTR_SUB="dsub"; # incidentally works even on n32 + $PTR_ADD="daddu"; # incidentally works even on n32 + $PTR_SUB="dsubu"; # incidentally works even on n32 $REG_S="sd"; $REG_L="ld"; $PTR_SLL="dsll"; # incidentally works even on n32 $SZREG=8; } else { $PTR_LA="la"; - $PTR_ADD="add"; - $PTR_SUB="sub"; + $PTR_ADD="addu"; + $PTR_SUB="subu"; $REG_S="sw"; $REG_L="lw"; $PTR_SLL="sll"; @@ -135,8 +135,12 @@ my ($i,$a,$b,$c,$d,$e,$f,$g,$h)=@_; my ($T1,$tmp0,$tmp1,$tmp2)=(@X[4],@X[5],@X[6],@X[7]); $code.=<<___ if ($i<15); +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + ${LD} @X[1],`($i+1)*$SZ`($inp) +#else ${LD}l @X[1],`($i+1)*$SZ+$MSB`($inp) ${LD}r @X[1],`($i+1)*$SZ+$LSB`($inp) +#endif ___ $code.=<<___ if (!$big_endian && $i<16 && $SZ==4); #if defined(_MIPS_ARCH_MIPS32R2) || defined(_MIPS_ARCH_MIPS64R2) @@ -298,13 +302,7 @@ $FRAMESIZE=16*$SZ+16*$SZREG; $SAVED_REGS_MASK = ($flavour =~ /nubi/i) ? "0xc0fff008" : "0xc0ff0000"; $code.=<<___; -#ifdef OPENSSL_FIPSCANISTER -# include -#endif - -#if defined(__mips_smartmips) && !defined(_MIPS_ARCH_MIPS32R2) -#define _MIPS_ARCH_MIPS32R2 -#endif +#include "mips_arch.h" .text .set noat @@ -369,8 +367,12 @@ $code.=<<___; .align 5 .Loop: +#if defined(_MIPS_ARCH_MIPS32R6) || defined(_MIPS_ARCH_MIPS64R6) + ${LD} @X[0],($inp) +#else ${LD}l @X[0],$MSB($inp) ${LD}r @X[0],$LSB($inp) +#endif ___ for ($i=0;$i<16;$i++) { &BODY_00_15($i,@V); unshift(@V,pop(@V)); push(@X,shift(@X)); } diff --git a/crypto/sha/asm/sha512-parisc.pl b/crypto/sha/asm/sha512-parisc.pl index fcb61579..5a082ba6 100755 --- a/crypto/sha/asm/sha512-parisc.pl +++ b/crypto/sha/asm/sha512-parisc.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -368,7 +368,7 @@ L\$parisc1 ___ @V=( $Ahi, $Alo, $Bhi, $Blo, $Chi, $Clo, $Dhi, $Dlo, - $Ehi, $Elo, $Fhi, $Flo, $Ghi, $Glo, $Hhi, $Hlo) = + $Ehi, $Elo, $Fhi, $Flo, $Ghi, $Glo, $Hhi, $Hlo) = ( "%r1", "%r2", "%r3", "%r4", "%r5", "%r6", "%r7", "%r8", "%r9","%r10","%r11","%r12","%r13","%r14","%r15","%r16"); $a0 ="%r17"; @@ -419,7 +419,7 @@ $code.=<<___; add $t0,$hlo,$hlo shd $ahi,$alo,$Sigma0[0],$t0 addc $t1,$hhi,$hhi ; h += Sigma1(e) - shd $alo,$ahi,$Sigma0[0],$t1 + shd $alo,$ahi,$Sigma0[0],$t1 add $a0,$hlo,$hlo shd $ahi,$alo,$Sigma0[1],$t2 addc $a1,$hhi,$hhi ; h += Ch(e,f,g) @@ -773,7 +773,7 @@ foreach (split("\n",$code)) { s/shd\s+(%r[0-9]+),(%r[0-9]+),([0-9]+)/ $3>31 ? sprintf("shd\t%$2,%$1,%d",$3-32) # rotation for >=32 : sprintf("shd\t%$1,%$2,%d",$3)/e or - # translate made up instructons: _ror, _shr, _align, _shl + # translate made up instructions: _ror, _shr, _align, _shl s/_ror(\s+)(%r[0-9]+),/ ($SZ==4 ? "shd" : "shrpd")."$1$2,$2,"/e or diff --git a/crypto/sha/asm/sha512-ppc.pl b/crypto/sha/asm/sha512-ppc.pl index fe95b015..71699f66 100755 --- a/crypto/sha/asm/sha512-ppc.pl +++ b/crypto/sha/asm/sha512-ppc.pl @@ -26,7 +26,7 @@ # # (*) 64-bit code in 32-bit application context, which actually is # on TODO list. It should be noted that for safe deployment in -# 32-bit *mutli-threaded* context asyncronous signals should be +# 32-bit *multi-threaded* context asynchronous signals should be # blocked upon entry to SHA512 block routine. This is because # 32-bit signaling procedure invalidates upper halves of GPRs. # Context switch procedure preserves them, but not signaling:-( diff --git a/crypto/sha/asm/sha512-s390x.pl b/crypto/sha/asm/sha512-s390x.pl index 427d6f82..4c0f4e79 100644 --- a/crypto/sha/asm/sha512-s390x.pl +++ b/crypto/sha/asm/sha512-s390x.pl @@ -8,7 +8,7 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. @@ -170,6 +170,8 @@ ___ } $code.=<<___; +#include "s390x_arch.h" + .text .align 64 .type $Table,\@object @@ -244,7 +246,7 @@ $Func: ___ $code.=<<___ if ($kimdfunc); larl %r1,OPENSSL_s390xcap_P - lg %r0,16(%r1) # check kimd capabilities + lg %r0,S390X_KIMD(%r1) # check kimd capabilities tmhh %r0,`0x8000>>$kimdfunc` jz .Lsoftware lghi %r0,$kimdfunc @@ -308,7 +310,7 @@ $code.=<<___; cl${g} $inp,`$frame+4*$SIZE_T`($sp) jne .Lloop - lm${g} %r6,%r15,`$frame+6*$SIZE_T`($sp) + lm${g} %r6,%r15,`$frame+6*$SIZE_T`($sp) br %r14 .size $Func,.-$Func .string "SHA${label} block transform for s390x, CRYPTOGAMS by " diff --git a/crypto/sha/asm/sha512-sparcv9.pl b/crypto/sha/asm/sha512-sparcv9.pl index 4a1ce5fe..4432bda6 100644 --- a/crypto/sha/asm/sha512-sparcv9.pl +++ b/crypto/sha/asm/sha512-sparcv9.pl @@ -8,12 +8,12 @@ # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. # -# Hardware SPARC T4 support by David S. Miller . +# Hardware SPARC T4 support by David S. Miller # ==================================================================== # SHA256 performance improvement over compiler generated code varies @@ -102,7 +102,7 @@ if ($output =~ /512/) { $locals=0; # X[16] is register resident @X=("%o0","%o1","%o2","%o3","%o4","%o5","%g1","%o7"); - + $A="%l0"; $B="%l1"; $C="%l2"; @@ -254,7 +254,7 @@ $code.=<<___; $SLL $a,`$SZ*8-@Sigma0[1]`,$tmp1 xor $tmp0,$h,$h $SRL $a,@Sigma0[2],$tmp0 - xor $tmp1,$h,$h + xor $tmp1,$h,$h $SLL $a,`$SZ*8-@Sigma0[0]`,$tmp1 xor $tmp0,$h,$h xor $tmp1,$h,$h ! Sigma0(a) diff --git a/crypto/sha/asm/sha512-x86_64.pl b/crypto/sha/asm/sha512-x86_64.pl index c9b7b281..f2ebdfdb 100755 --- a/crypto/sha/asm/sha512-x86_64.pl +++ b/crypto/sha/asm/sha512-x86_64.pl @@ -95,9 +95,11 @@ # Haswell 12.2 9.28(+31%) 7.80(+56%) 7.66 5.40(+42%) # Skylake 11.4 9.03(+26%) 7.70(+48%) 7.25 5.20(+40%) # Bulldozer 21.1 13.6(+54%) 13.6(+54%(***)) 13.5 8.58(+57%) +# Ryzen 11.0 9.02(+22%) 2.05(+440%) 7.05 5.67(+20%) # VIA Nano 23.0 16.5(+39%) - 14.7 - # Atom 23.0 18.9(+22%) - 14.7 - # Silvermont 27.4 20.6(+33%) - 17.5 - +# Knights L 27.4 21.0(+30%) 19.6(+40%) 17.5 12.8(+37%) # Goldmont 18.9 14.3(+32%) 4.16(+350%) 12.0 - # # (*) whichever best applicable, including SHAEXT; @@ -176,7 +178,7 @@ $Tbl="%rbp"; $_ctx="16*$SZ+0*8(%rsp)"; $_inp="16*$SZ+1*8(%rsp)"; $_end="16*$SZ+2*8(%rsp)"; -$_rsp="16*$SZ+3*8(%rsp)"; +$_rsp="`16*$SZ+3*8`(%rsp)"; $framesz="16*$SZ+4*8"; @@ -269,6 +271,7 @@ $code=<<___; .type $func,\@function,3 .align 16 $func: +.cfi_startproc ___ $code.=<<___ if ($SZ==4 || $avx); lea OPENSSL_ia32cap_P(%rip),%r11 @@ -301,13 +304,20 @@ $code.=<<___ if ($SZ==4); jnz .Lssse3_shortcut ___ $code.=<<___; + mov %rsp,%rax # copy %rsp +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 - mov %rsp,%r11 # copy %rsp +.cfi_push %r15 shl \$4,%rdx # num*16 sub \$$framesz,%rsp lea ($inp,%rdx,$SZ),%rdx # inp+num*16*$SZ @@ -315,7 +325,8 @@ $code.=<<___; mov $ctx,$_ctx # save ctx, 1st arg mov $inp,$_inp # save inp, 2nd arh mov %rdx,$_end # save end pointer, "3rd" arg - mov %r11,$_rsp # save copy of %rsp + mov %rax,$_rsp # save copy of %rsp +.cfi_cfa_expression $_rsp,deref,+8 .Lprologue: mov $SZ*0($ctx),$A @@ -382,15 +393,24 @@ $code.=<<___; jb .Lloop mov $_rsp,%rsi - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp +.cfi_def_cfa %rsi,8 + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lepilogue: ret +.cfi_endproc .size $func,.-$func ___ @@ -760,14 +780,22 @@ $code.=<<___; .type ${func}_ssse3,\@function,3 .align 64 ${func}_ssse3: +.cfi_startproc .Lssse3_shortcut: + mov %rsp,%rax # copy %rsp +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 - mov %rsp,%r11 # copy %rsp +.cfi_push %r15 shl \$4,%rdx # num*16 sub \$`$framesz+$win64*16*4`,%rsp lea ($inp,%rdx,$SZ),%rdx # inp+num*16*$SZ @@ -775,7 +803,8 @@ ${func}_ssse3: mov $ctx,$_ctx # save ctx, 1st arg mov $inp,$_inp # save inp, 2nd arh mov %rdx,$_end # save end pointer, "3rd" arg - mov %r11,$_rsp # save copy of %rsp + mov %rax,$_rsp # save copy of %rsp +.cfi_cfa_expression $_rsp,deref,+8 ___ $code.=<<___ if ($win64); movaps %xmm6,16*$SZ+32(%rsp) @@ -1074,6 +1103,7 @@ $code.=<<___; jb .Lloop_ssse3 mov $_rsp,%rsi +.cfi_def_cfa %rsi,8 ___ $code.=<<___ if ($win64); movaps 16*$SZ+32(%rsp),%xmm6 @@ -1082,15 +1112,23 @@ $code.=<<___ if ($win64); movaps 16*$SZ+80(%rsp),%xmm9 ___ $code.=<<___; - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_ssse3: ret +.cfi_endproc .size ${func}_ssse3,.-${func}_ssse3 ___ } @@ -1104,14 +1142,22 @@ $code.=<<___; .type ${func}_xop,\@function,3 .align 64 ${func}_xop: +.cfi_startproc .Lxop_shortcut: + mov %rsp,%rax # copy %rsp +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 - mov %rsp,%r11 # copy %rsp +.cfi_push %r15 shl \$4,%rdx # num*16 sub \$`$framesz+$win64*16*($SZ==4?4:6)`,%rsp lea ($inp,%rdx,$SZ),%rdx # inp+num*16*$SZ @@ -1119,7 +1165,8 @@ ${func}_xop: mov $ctx,$_ctx # save ctx, 1st arg mov $inp,$_inp # save inp, 2nd arh mov %rdx,$_end # save end pointer, "3rd" arg - mov %r11,$_rsp # save copy of %rsp + mov %rax,$_rsp # save copy of %rsp +.cfi_cfa_expression $_rsp,deref,+8 ___ $code.=<<___ if ($win64); movaps %xmm6,16*$SZ+32(%rsp) @@ -1446,6 +1493,7 @@ $code.=<<___; jb .Lloop_xop mov $_rsp,%rsi +.cfi_def_cfa %rsi,8 vzeroupper ___ $code.=<<___ if ($win64); @@ -1459,15 +1507,23 @@ $code.=<<___ if ($win64 && $SZ>4); movaps 16*$SZ+112(%rsp),%xmm11 ___ $code.=<<___; - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_xop: ret +.cfi_endproc .size ${func}_xop,.-${func}_xop ___ } @@ -1480,14 +1536,22 @@ $code.=<<___; .type ${func}_avx,\@function,3 .align 64 ${func}_avx: +.cfi_startproc .Lavx_shortcut: + mov %rsp,%rax # copy %rsp +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 - mov %rsp,%r11 # copy %rsp +.cfi_push %r15 shl \$4,%rdx # num*16 sub \$`$framesz+$win64*16*($SZ==4?4:6)`,%rsp lea ($inp,%rdx,$SZ),%rdx # inp+num*16*$SZ @@ -1495,7 +1559,8 @@ ${func}_avx: mov $ctx,$_ctx # save ctx, 1st arg mov $inp,$_inp # save inp, 2nd arh mov %rdx,$_end # save end pointer, "3rd" arg - mov %r11,$_rsp # save copy of %rsp + mov %rax,$_rsp # save copy of %rsp +.cfi_cfa_expression $_rsp,deref,+8 ___ $code.=<<___ if ($win64); movaps %xmm6,16*$SZ+32(%rsp) @@ -1754,6 +1819,7 @@ $code.=<<___; jb .Lloop_avx mov $_rsp,%rsi +.cfi_def_cfa %rsi,8 vzeroupper ___ $code.=<<___ if ($win64); @@ -1767,15 +1833,23 @@ $code.=<<___ if ($win64 && $SZ>4); movaps 16*$SZ+112(%rsp),%xmm11 ___ $code.=<<___; - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_avx: ret +.cfi_endproc .size ${func}_avx,.-${func}_avx ___ @@ -1783,7 +1857,7 @@ if ($avx>1) {{ ###################################################################### # AVX2+BMI code path # -my $a5=$SZ==4?"%esi":"%rsi"; # zap $inp +my $a5=$SZ==4?"%esi":"%rsi"; # zap $inp my $PUSH8=8*2*$SZ; use integer; @@ -1831,14 +1905,22 @@ $code.=<<___; .type ${func}_avx2,\@function,3 .align 64 ${func}_avx2: +.cfi_startproc .Lavx2_shortcut: + mov %rsp,%rax # copy %rsp +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 - mov %rsp,%r11 # copy %rsp +.cfi_push %r15 sub \$`2*$SZ*$rounds+4*8+$win64*16*($SZ==4?4:6)`,%rsp shl \$4,%rdx # num*16 and \$-256*$SZ,%rsp # align stack frame @@ -1847,7 +1929,8 @@ ${func}_avx2: mov $ctx,$_ctx # save ctx, 1st arg mov $inp,$_inp # save inp, 2nd arh mov %rdx,$_end # save end pointer, "3rd" arg - mov %r11,$_rsp # save copy of %rsp + mov %rax,$_rsp # save copy of %rsp +.cfi_cfa_expression $_rsp,deref,+8 ___ $code.=<<___ if ($win64); movaps %xmm6,16*$SZ+32(%rsp) @@ -2128,6 +2211,7 @@ $code.=<<___; .Ldone_avx2: lea ($Tbl),%rsp mov $_rsp,%rsi +.cfi_def_cfa %rsi,8 vzeroupper ___ $code.=<<___ if ($win64); @@ -2141,15 +2225,23 @@ $code.=<<___ if ($win64 && $SZ>4); movaps 16*$SZ+112(%rsp),%xmm11 ___ $code.=<<___; - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lepilogue_avx2: ret +.cfi_endproc .size ${func}_avx2,.-${func}_avx2 ___ }} @@ -2209,7 +2301,6 @@ ___ $code.=<<___; mov %rax,%rsi # put aside Rsp mov 16*$SZ+3*8(%rax),%rax # pull $_rsp - lea 48(%rax),%rax mov -8(%rax),%rbx mov -16(%rax),%rbp diff --git a/crypto/sha/asm/sha512p8-ppc.pl b/crypto/sha/asm/sha512p8-ppc.pl index 4d3d3b2f..93dfef20 100755 --- a/crypto/sha/asm/sha512p8-ppc.pl +++ b/crypto/sha/asm/sha512p8-ppc.pl @@ -25,11 +25,20 @@ # sha1-ppc.pl and 1.6x slower than aes-128-cbc. Another interesting # result is degree of computational resources' utilization. POWER8 is # "massively multi-threaded chip" and difference between single- and -# maximum multi-process benchmark results tells that utlization is +# maximum multi-process benchmark results tells that utilization is # whooping 94%. For sha512-ppc.pl we get [not unimpressive] 84% and # for sha1-ppc.pl - 73%. 100% means that multi-process result equals # to single-process one, given that all threads end up on the same # physical core. +# +###################################################################### +# Believed-to-be-accurate results in cycles per processed byte [on +# little-endian system]. Numbers in square brackets are for 64-bit +# build of sha512-ppc.pl, presented for reference. +# +# POWER8 +# SHA256 9.9 [15.8] +# SHA512 6.3 [10.3] $flavour=shift; $output =shift; diff --git a/crypto/sha/build.info b/crypto/sha/build.info index 5843e508..9dffec3f 100644 --- a/crypto/sha/build.info +++ b/crypto/sha/build.info @@ -1,17 +1,21 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ - sha1dgst.c sha1_one.c sha256.c sha512.c {- $target{sha1_asm_src} -} + sha1dgst.c sha1_one.c sha256.c sha512.c {- $target{sha1_asm_src} -} \ + keccak1600.c -GENERATE[sha1-586.s]=asm/sha1-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[sha1-586.s]=asm/sha1-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[sha1-586.s]=../perlasm/x86asm.pl -GENERATE[sha256-586.s]=asm/sha256-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[sha256-586.s]=asm/sha256-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[sha256-586.s]=../perlasm/x86asm.pl -GENERATE[sha512-586.s]=asm/sha512-586.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[sha512-586.s]=asm/sha512-586.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[sha512-586.s]=../perlasm/x86asm.pl -GENERATE[sha1-ia64.s]=asm/sha1-ia64.pl $(CFLAGS) $(LIB_CFLAGS) -GENERATE[sha256-ia64.s]=asm/sha512-ia64.pl $(CFLAGS) $(LIB_CFLAGS) -GENERATE[sha512-ia64.s]=asm/sha512-ia64.pl $(CFLAGS) $(LIB_CFLAGS) +GENERATE[sha1-ia64.s]=asm/sha1-ia64.pl $(LIB_CFLAGS) $(LIB_CPPFLAGS) +GENERATE[sha256-ia64.s]=asm/sha512-ia64.pl $(LIB_CFLAGS) $(LIB_CPPFLAGS) +GENERATE[sha512-ia64.s]=asm/sha512-ia64.pl $(LIB_CFLAGS) $(LIB_CPPFLAGS) GENERATE[sha1-alpha.S]=asm/sha1-alpha.pl $(PERLASM_SCHEME) @@ -39,8 +43,11 @@ GENERATE[sha256-parisc.s]=asm/sha512-parisc.pl $(PERLASM_SCHEME) GENERATE[sha512-parisc.s]=asm/sha512-parisc.pl $(PERLASM_SCHEME) GENERATE[sha1-mips.S]=asm/sha1-mips.pl $(PERLASM_SCHEME) +INCLUDE[sha1-mips.o]=.. GENERATE[sha256-mips.S]=asm/sha512-mips.pl $(PERLASM_SCHEME) +INCLUDE[sha256-mips.o]=.. GENERATE[sha512-mips.S]=asm/sha512-mips.pl $(PERLASM_SCHEME) +INCLUDE[sha512-mips.o]=.. GENERATE[sha1-armv4-large.S]=asm/sha1-armv4-large.pl $(PERLASM_SCHEME) INCLUDE[sha1-armv4-large.o]=.. @@ -56,6 +63,13 @@ INCLUDE[sha256-armv8.o]=.. GENERATE[sha512-armv8.S]=asm/sha512-armv8.pl $(PERLASM_SCHEME) INCLUDE[sha512-armv8.o]=.. +GENERATE[sha1-s390x.S]=asm/sha1-s390x.pl $(PERLASM_SCHEME) +INCLUDE[sha1-s390x.o]=.. +GENERATE[sha256-s390x.S]=asm/sha512-s390x.pl $(PERLASM_SCHEME) +INCLUDE[sha256-s390x.o]=.. +GENERATE[sha512-s390x.S]=asm/sha512-s390x.pl $(PERLASM_SCHEME) +INCLUDE[sha512-s390x.o]=.. + BEGINRAW[Makefile(unix)] ##### SHA assembler implementations diff --git a/crypto/sha/keccak1600.c b/crypto/sha/keccak1600.c new file mode 100644 index 00000000..e7223486 --- /dev/null +++ b/crypto/sha/keccak1600.c @@ -0,0 +1,1246 @@ +/* + * 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 + */ + +#include +#include +#include + +size_t SHA3_absorb(uint64_t A[5][5], const unsigned char *inp, size_t len, + size_t r); +void SHA3_squeeze(uint64_t A[5][5], unsigned char *out, size_t len, size_t r); + +#if !defined(KECCAK1600_ASM) || !defined(SELFTEST) + +/* + * Choose some sensible defaults + */ +#if !defined(KECCAK_REF) && !defined(KECCAK_1X) && !defined(KECCAK_1X_ALT) && \ + !defined(KECCAK_2X) && !defined(KECCAK_INPLACE) +# define KECCAK_2X /* default to KECCAK_2X variant */ +#endif + +#if defined(__i386) || defined(__i386__) || defined(_M_IX86) +# define KECCAK_COMPLEMENTING_TRANSFORM +#endif + +#if defined(__x86_64__) || defined(__aarch64__) || \ + defined(__mips64) || defined(__ia64) || \ + (defined(__VMS) && !defined(__vax)) +/* + * These are available even in ILP32 flavours, but even then they are + * capable of performing 64-bit operations as efficiently as in *P64. + * Since it's not given that we can use sizeof(void *), just shunt it. + */ +# define BIT_INTERLEAVE (0) +#else +# define BIT_INTERLEAVE (sizeof(void *) < 8) +#endif + +#define ROL32(a, offset) (((a) << (offset)) | ((a) >> ((32 - (offset)) & 31))) + +static uint64_t ROL64(uint64_t val, int offset) +{ + if (offset == 0) { + return val; + } else if (!BIT_INTERLEAVE) { + return (val << offset) | (val >> (64-offset)); + } else { + uint32_t hi = (uint32_t)(val >> 32), lo = (uint32_t)val; + + if (offset & 1) { + uint32_t tmp = hi; + + offset >>= 1; + hi = ROL32(lo, offset); + lo = ROL32(tmp, offset + 1); + } else { + offset >>= 1; + lo = ROL32(lo, offset); + hi = ROL32(hi, offset); + } + + return ((uint64_t)hi << 32) | lo; + } +} + +static const unsigned char rhotates[5][5] = { + { 0, 1, 62, 28, 27 }, + { 36, 44, 6, 55, 20 }, + { 3, 10, 43, 25, 39 }, + { 41, 45, 15, 21, 8 }, + { 18, 2, 61, 56, 14 } +}; + +static const uint64_t iotas[] = { + BIT_INTERLEAVE ? 0x0000000000000001U : 0x0000000000000001U, + BIT_INTERLEAVE ? 0x0000008900000000U : 0x0000000000008082U, + BIT_INTERLEAVE ? 0x8000008b00000000U : 0x800000000000808aU, + BIT_INTERLEAVE ? 0x8000808000000000U : 0x8000000080008000U, + BIT_INTERLEAVE ? 0x0000008b00000001U : 0x000000000000808bU, + BIT_INTERLEAVE ? 0x0000800000000001U : 0x0000000080000001U, + BIT_INTERLEAVE ? 0x8000808800000001U : 0x8000000080008081U, + BIT_INTERLEAVE ? 0x8000008200000001U : 0x8000000000008009U, + BIT_INTERLEAVE ? 0x0000000b00000000U : 0x000000000000008aU, + BIT_INTERLEAVE ? 0x0000000a00000000U : 0x0000000000000088U, + BIT_INTERLEAVE ? 0x0000808200000001U : 0x0000000080008009U, + BIT_INTERLEAVE ? 0x0000800300000000U : 0x000000008000000aU, + BIT_INTERLEAVE ? 0x0000808b00000001U : 0x000000008000808bU, + BIT_INTERLEAVE ? 0x8000000b00000001U : 0x800000000000008bU, + BIT_INTERLEAVE ? 0x8000008a00000001U : 0x8000000000008089U, + BIT_INTERLEAVE ? 0x8000008100000001U : 0x8000000000008003U, + BIT_INTERLEAVE ? 0x8000008100000000U : 0x8000000000008002U, + BIT_INTERLEAVE ? 0x8000000800000000U : 0x8000000000000080U, + BIT_INTERLEAVE ? 0x0000008300000000U : 0x000000000000800aU, + BIT_INTERLEAVE ? 0x8000800300000000U : 0x800000008000000aU, + BIT_INTERLEAVE ? 0x8000808800000001U : 0x8000000080008081U, + BIT_INTERLEAVE ? 0x8000008800000000U : 0x8000000000008080U, + BIT_INTERLEAVE ? 0x0000800000000001U : 0x0000000080000001U, + BIT_INTERLEAVE ? 0x8000808200000000U : 0x8000000080008008U +}; + +#if defined(KECCAK_REF) +/* + * This is straightforward or "maximum clarity" implementation aiming + * to resemble section 3.2 of the FIPS PUB 202 "SHA-3 Standard: + * Permutation-Based Hash and Extendible-Output Functions" as much as + * possible. With one caveat. Because of the way C stores matrices, + * references to A[x,y] in the specification are presented as A[y][x]. + * Implementation unrolls inner x-loops so that modulo 5 operations are + * explicitly pre-computed. + */ +static void Theta(uint64_t A[5][5]) +{ + uint64_t C[5], D[5]; + size_t y; + + C[0] = A[0][0]; + C[1] = A[0][1]; + C[2] = A[0][2]; + C[3] = A[0][3]; + C[4] = A[0][4]; + + for (y = 1; y < 5; y++) { + C[0] ^= A[y][0]; + C[1] ^= A[y][1]; + C[2] ^= A[y][2]; + C[3] ^= A[y][3]; + C[4] ^= A[y][4]; + } + + D[0] = ROL64(C[1], 1) ^ C[4]; + D[1] = ROL64(C[2], 1) ^ C[0]; + D[2] = ROL64(C[3], 1) ^ C[1]; + D[3] = ROL64(C[4], 1) ^ C[2]; + D[4] = ROL64(C[0], 1) ^ C[3]; + + for (y = 0; y < 5; y++) { + A[y][0] ^= D[0]; + A[y][1] ^= D[1]; + A[y][2] ^= D[2]; + A[y][3] ^= D[3]; + A[y][4] ^= D[4]; + } +} + +static void Rho(uint64_t A[5][5]) +{ + size_t y; + + for (y = 0; y < 5; y++) { + A[y][0] = ROL64(A[y][0], rhotates[y][0]); + A[y][1] = ROL64(A[y][1], rhotates[y][1]); + A[y][2] = ROL64(A[y][2], rhotates[y][2]); + A[y][3] = ROL64(A[y][3], rhotates[y][3]); + A[y][4] = ROL64(A[y][4], rhotates[y][4]); + } +} + +static void Pi(uint64_t A[5][5]) +{ + uint64_t T[5][5]; + + /* + * T = A + * A[y][x] = T[x][(3*y+x)%5] + */ + memcpy(T, A, sizeof(T)); + + A[0][0] = T[0][0]; + A[0][1] = T[1][1]; + A[0][2] = T[2][2]; + A[0][3] = T[3][3]; + A[0][4] = T[4][4]; + + A[1][0] = T[0][3]; + A[1][1] = T[1][4]; + A[1][2] = T[2][0]; + A[1][3] = T[3][1]; + A[1][4] = T[4][2]; + + A[2][0] = T[0][1]; + A[2][1] = T[1][2]; + A[2][2] = T[2][3]; + A[2][3] = T[3][4]; + A[2][4] = T[4][0]; + + A[3][0] = T[0][4]; + A[3][1] = T[1][0]; + A[3][2] = T[2][1]; + A[3][3] = T[3][2]; + A[3][4] = T[4][3]; + + A[4][0] = T[0][2]; + A[4][1] = T[1][3]; + A[4][2] = T[2][4]; + A[4][3] = T[3][0]; + A[4][4] = T[4][1]; +} + +static void Chi(uint64_t A[5][5]) +{ + uint64_t C[5]; + size_t y; + + for (y = 0; y < 5; y++) { + C[0] = A[y][0] ^ (~A[y][1] & A[y][2]); + C[1] = A[y][1] ^ (~A[y][2] & A[y][3]); + C[2] = A[y][2] ^ (~A[y][3] & A[y][4]); + C[3] = A[y][3] ^ (~A[y][4] & A[y][0]); + C[4] = A[y][4] ^ (~A[y][0] & A[y][1]); + + A[y][0] = C[0]; + A[y][1] = C[1]; + A[y][2] = C[2]; + A[y][3] = C[3]; + A[y][4] = C[4]; + } +} + +static void Iota(uint64_t A[5][5], size_t i) +{ + assert(i < (sizeof(iotas) / sizeof(iotas[0]))); + A[0][0] ^= iotas[i]; +} + +static void KeccakF1600(uint64_t A[5][5]) +{ + size_t i; + + for (i = 0; i < 24; i++) { + Theta(A); + Rho(A); + Pi(A); + Chi(A); + Iota(A, i); + } +} + +#elif defined(KECCAK_1X) +/* + * This implementation is optimization of above code featuring unroll + * of even y-loops, their fusion and code motion. It also minimizes + * temporary storage. Compiler would normally do all these things for + * you, purpose of manual optimization is to provide "unobscured" + * reference for assembly implementation [in case this approach is + * chosen for implementation on some platform]. In the nutshell it's + * equivalent of "plane-per-plane processing" approach discussed in + * section 2.4 of "Keccak implementation overview". + */ +static void Round(uint64_t A[5][5], size_t i) +{ + uint64_t C[5], E[2]; /* registers */ + uint64_t D[5], T[2][5]; /* memory */ + + assert(i < (sizeof(iotas) / sizeof(iotas[0]))); + + C[0] = A[0][0] ^ A[1][0] ^ A[2][0] ^ A[3][0] ^ A[4][0]; + C[1] = A[0][1] ^ A[1][1] ^ A[2][1] ^ A[3][1] ^ A[4][1]; + C[2] = A[0][2] ^ A[1][2] ^ A[2][2] ^ A[3][2] ^ A[4][2]; + C[3] = A[0][3] ^ A[1][3] ^ A[2][3] ^ A[3][3] ^ A[4][3]; + C[4] = A[0][4] ^ A[1][4] ^ A[2][4] ^ A[3][4] ^ A[4][4]; + +#if defined(__arm__) + D[1] = E[0] = ROL64(C[2], 1) ^ C[0]; + D[4] = E[1] = ROL64(C[0], 1) ^ C[3]; + D[0] = C[0] = ROL64(C[1], 1) ^ C[4]; + D[2] = C[1] = ROL64(C[3], 1) ^ C[1]; + D[3] = C[2] = ROL64(C[4], 1) ^ C[2]; + + T[0][0] = A[3][0] ^ C[0]; /* borrow T[0][0] */ + T[0][1] = A[0][1] ^ E[0]; /* D[1] */ + T[0][2] = A[0][2] ^ C[1]; /* D[2] */ + T[0][3] = A[0][3] ^ C[2]; /* D[3] */ + T[0][4] = A[0][4] ^ E[1]; /* D[4] */ + + C[3] = ROL64(A[3][3] ^ C[2], rhotates[3][3]); /* D[3] */ + C[4] = ROL64(A[4][4] ^ E[1], rhotates[4][4]); /* D[4] */ + C[0] = A[0][0] ^ C[0]; /* rotate by 0 */ /* D[0] */ + C[2] = ROL64(A[2][2] ^ C[1], rhotates[2][2]); /* D[2] */ + C[1] = ROL64(A[1][1] ^ E[0], rhotates[1][1]); /* D[1] */ +#else + D[0] = ROL64(C[1], 1) ^ C[4]; + D[1] = ROL64(C[2], 1) ^ C[0]; + D[2] = ROL64(C[3], 1) ^ C[1]; + D[3] = ROL64(C[4], 1) ^ C[2]; + D[4] = ROL64(C[0], 1) ^ C[3]; + + T[0][0] = A[3][0] ^ D[0]; /* borrow T[0][0] */ + T[0][1] = A[0][1] ^ D[1]; + T[0][2] = A[0][2] ^ D[2]; + T[0][3] = A[0][3] ^ D[3]; + T[0][4] = A[0][4] ^ D[4]; + + C[0] = A[0][0] ^ D[0]; /* rotate by 0 */ + C[1] = ROL64(A[1][1] ^ D[1], rhotates[1][1]); + C[2] = ROL64(A[2][2] ^ D[2], rhotates[2][2]); + C[3] = ROL64(A[3][3] ^ D[3], rhotates[3][3]); + C[4] = ROL64(A[4][4] ^ D[4], rhotates[4][4]); +#endif + A[0][0] = C[0] ^ (~C[1] & C[2]) ^ iotas[i]; + A[0][1] = C[1] ^ (~C[2] & C[3]); + A[0][2] = C[2] ^ (~C[3] & C[4]); + A[0][3] = C[3] ^ (~C[4] & C[0]); + A[0][4] = C[4] ^ (~C[0] & C[1]); + + T[1][0] = A[1][0] ^ (C[3] = D[0]); + T[1][1] = A[2][1] ^ (C[4] = D[1]); /* borrow T[1][1] */ + T[1][2] = A[1][2] ^ (E[0] = D[2]); + T[1][3] = A[1][3] ^ (E[1] = D[3]); + T[1][4] = A[2][4] ^ (C[2] = D[4]); /* borrow T[1][4] */ + + C[0] = ROL64(T[0][3], rhotates[0][3]); + C[1] = ROL64(A[1][4] ^ C[2], rhotates[1][4]); /* D[4] */ + C[2] = ROL64(A[2][0] ^ C[3], rhotates[2][0]); /* D[0] */ + C[3] = ROL64(A[3][1] ^ C[4], rhotates[3][1]); /* D[1] */ + C[4] = ROL64(A[4][2] ^ E[0], rhotates[4][2]); /* D[2] */ + + A[1][0] = C[0] ^ (~C[1] & C[2]); + A[1][1] = C[1] ^ (~C[2] & C[3]); + A[1][2] = C[2] ^ (~C[3] & C[4]); + A[1][3] = C[3] ^ (~C[4] & C[0]); + A[1][4] = C[4] ^ (~C[0] & C[1]); + + C[0] = ROL64(T[0][1], rhotates[0][1]); + C[1] = ROL64(T[1][2], rhotates[1][2]); + C[2] = ROL64(A[2][3] ^ D[3], rhotates[2][3]); + C[3] = ROL64(A[3][4] ^ D[4], rhotates[3][4]); + C[4] = ROL64(A[4][0] ^ D[0], rhotates[4][0]); + + A[2][0] = C[0] ^ (~C[1] & C[2]); + A[2][1] = C[1] ^ (~C[2] & C[3]); + A[2][2] = C[2] ^ (~C[3] & C[4]); + A[2][3] = C[3] ^ (~C[4] & C[0]); + A[2][4] = C[4] ^ (~C[0] & C[1]); + + C[0] = ROL64(T[0][4], rhotates[0][4]); + C[1] = ROL64(T[1][0], rhotates[1][0]); + C[2] = ROL64(T[1][1], rhotates[2][1]); /* originally A[2][1] */ + C[3] = ROL64(A[3][2] ^ D[2], rhotates[3][2]); + C[4] = ROL64(A[4][3] ^ D[3], rhotates[4][3]); + + A[3][0] = C[0] ^ (~C[1] & C[2]); + A[3][1] = C[1] ^ (~C[2] & C[3]); + A[3][2] = C[2] ^ (~C[3] & C[4]); + A[3][3] = C[3] ^ (~C[4] & C[0]); + A[3][4] = C[4] ^ (~C[0] & C[1]); + + C[0] = ROL64(T[0][2], rhotates[0][2]); + C[1] = ROL64(T[1][3], rhotates[1][3]); + C[2] = ROL64(T[1][4], rhotates[2][4]); /* originally A[2][4] */ + C[3] = ROL64(T[0][0], rhotates[3][0]); /* originally A[3][0] */ + C[4] = ROL64(A[4][1] ^ D[1], rhotates[4][1]); + + A[4][0] = C[0] ^ (~C[1] & C[2]); + A[4][1] = C[1] ^ (~C[2] & C[3]); + A[4][2] = C[2] ^ (~C[3] & C[4]); + A[4][3] = C[3] ^ (~C[4] & C[0]); + A[4][4] = C[4] ^ (~C[0] & C[1]); +} + +static void KeccakF1600(uint64_t A[5][5]) +{ + size_t i; + + for (i = 0; i < 24; i++) { + Round(A, i); + } +} + +#elif defined(KECCAK_1X_ALT) +/* + * This is variant of above KECCAK_1X that reduces requirement for + * temporary storage even further, but at cost of more updates to A[][]. + * It's less suitable if A[][] is memory bound, but better if it's + * register bound. + */ + +static void Round(uint64_t A[5][5], size_t i) +{ + uint64_t C[5], D[5]; + + assert(i < (sizeof(iotas) / sizeof(iotas[0]))); + + C[0] = A[0][0] ^ A[1][0] ^ A[2][0] ^ A[3][0] ^ A[4][0]; + C[1] = A[0][1] ^ A[1][1] ^ A[2][1] ^ A[3][1] ^ A[4][1]; + C[2] = A[0][2] ^ A[1][2] ^ A[2][2] ^ A[3][2] ^ A[4][2]; + C[3] = A[0][3] ^ A[1][3] ^ A[2][3] ^ A[3][3] ^ A[4][3]; + C[4] = A[0][4] ^ A[1][4] ^ A[2][4] ^ A[3][4] ^ A[4][4]; + + D[1] = C[0] ^ ROL64(C[2], 1); + D[2] = C[1] ^ ROL64(C[3], 1); + D[3] = C[2] ^= ROL64(C[4], 1); + D[4] = C[3] ^= ROL64(C[0], 1); + D[0] = C[4] ^= ROL64(C[1], 1); + + A[0][1] ^= D[1]; + A[1][1] ^= D[1]; + A[2][1] ^= D[1]; + A[3][1] ^= D[1]; + A[4][1] ^= D[1]; + + A[0][2] ^= D[2]; + A[1][2] ^= D[2]; + A[2][2] ^= D[2]; + A[3][2] ^= D[2]; + A[4][2] ^= D[2]; + + A[0][3] ^= C[2]; + A[1][3] ^= C[2]; + A[2][3] ^= C[2]; + A[3][3] ^= C[2]; + A[4][3] ^= C[2]; + + A[0][4] ^= C[3]; + A[1][4] ^= C[3]; + A[2][4] ^= C[3]; + A[3][4] ^= C[3]; + A[4][4] ^= C[3]; + + A[0][0] ^= C[4]; + A[1][0] ^= C[4]; + A[2][0] ^= C[4]; + A[3][0] ^= C[4]; + A[4][0] ^= C[4]; + + C[1] = A[0][1]; + C[2] = A[0][2]; + C[3] = A[0][3]; + C[4] = A[0][4]; + + A[0][1] = ROL64(A[1][1], rhotates[1][1]); + A[0][2] = ROL64(A[2][2], rhotates[2][2]); + A[0][3] = ROL64(A[3][3], rhotates[3][3]); + A[0][4] = ROL64(A[4][4], rhotates[4][4]); + + A[1][1] = ROL64(A[1][4], rhotates[1][4]); + A[2][2] = ROL64(A[2][3], rhotates[2][3]); + A[3][3] = ROL64(A[3][2], rhotates[3][2]); + A[4][4] = ROL64(A[4][1], rhotates[4][1]); + + A[1][4] = ROL64(A[4][2], rhotates[4][2]); + A[2][3] = ROL64(A[3][4], rhotates[3][4]); + A[3][2] = ROL64(A[2][1], rhotates[2][1]); + A[4][1] = ROL64(A[1][3], rhotates[1][3]); + + A[4][2] = ROL64(A[2][4], rhotates[2][4]); + A[3][4] = ROL64(A[4][3], rhotates[4][3]); + A[2][1] = ROL64(A[1][2], rhotates[1][2]); + A[1][3] = ROL64(A[3][1], rhotates[3][1]); + + A[2][4] = ROL64(A[4][0], rhotates[4][0]); + A[4][3] = ROL64(A[3][0], rhotates[3][0]); + A[1][2] = ROL64(A[2][0], rhotates[2][0]); + A[3][1] = ROL64(A[1][0], rhotates[1][0]); + + A[1][0] = ROL64(C[3], rhotates[0][3]); + A[2][0] = ROL64(C[1], rhotates[0][1]); + A[3][0] = ROL64(C[4], rhotates[0][4]); + A[4][0] = ROL64(C[2], rhotates[0][2]); + + C[0] = A[0][0]; + C[1] = A[1][0]; + D[0] = A[0][1]; + D[1] = A[1][1]; + + A[0][0] ^= (~A[0][1] & A[0][2]); + A[1][0] ^= (~A[1][1] & A[1][2]); + A[0][1] ^= (~A[0][2] & A[0][3]); + A[1][1] ^= (~A[1][2] & A[1][3]); + A[0][2] ^= (~A[0][3] & A[0][4]); + A[1][2] ^= (~A[1][3] & A[1][4]); + A[0][3] ^= (~A[0][4] & C[0]); + A[1][3] ^= (~A[1][4] & C[1]); + A[0][4] ^= (~C[0] & D[0]); + A[1][4] ^= (~C[1] & D[1]); + + C[2] = A[2][0]; + C[3] = A[3][0]; + D[2] = A[2][1]; + D[3] = A[3][1]; + + A[2][0] ^= (~A[2][1] & A[2][2]); + A[3][0] ^= (~A[3][1] & A[3][2]); + A[2][1] ^= (~A[2][2] & A[2][3]); + A[3][1] ^= (~A[3][2] & A[3][3]); + A[2][2] ^= (~A[2][3] & A[2][4]); + A[3][2] ^= (~A[3][3] & A[3][4]); + A[2][3] ^= (~A[2][4] & C[2]); + A[3][3] ^= (~A[3][4] & C[3]); + A[2][4] ^= (~C[2] & D[2]); + A[3][4] ^= (~C[3] & D[3]); + + C[4] = A[4][0]; + D[4] = A[4][1]; + + A[4][0] ^= (~A[4][1] & A[4][2]); + A[4][1] ^= (~A[4][2] & A[4][3]); + A[4][2] ^= (~A[4][3] & A[4][4]); + A[4][3] ^= (~A[4][4] & C[4]); + A[4][4] ^= (~C[4] & D[4]); + A[0][0] ^= iotas[i]; +} + +static void KeccakF1600(uint64_t A[5][5]) +{ + size_t i; + + for (i = 0; i < 24; i++) { + Round(A, i); + } +} + +#elif defined(KECCAK_2X) +/* + * This implementation is variant of KECCAK_1X above with outer-most + * round loop unrolled twice. This allows to take temporary storage + * out of round procedure and simplify references to it by alternating + * it with actual data (see round loop below). Originally it was meant + * rather as reference for an assembly implementation, but it seems to + * play best with compilers [as well as provide best instruction per + * processed byte ratio at minimal round unroll factor]... + */ +static void Round(uint64_t R[5][5], uint64_t A[5][5], size_t i) +{ + uint64_t C[5], D[5]; + + assert(i < (sizeof(iotas) / sizeof(iotas[0]))); + + C[0] = A[0][0] ^ A[1][0] ^ A[2][0] ^ A[3][0] ^ A[4][0]; + C[1] = A[0][1] ^ A[1][1] ^ A[2][1] ^ A[3][1] ^ A[4][1]; + C[2] = A[0][2] ^ A[1][2] ^ A[2][2] ^ A[3][2] ^ A[4][2]; + C[3] = A[0][3] ^ A[1][3] ^ A[2][3] ^ A[3][3] ^ A[4][3]; + C[4] = A[0][4] ^ A[1][4] ^ A[2][4] ^ A[3][4] ^ A[4][4]; + + D[0] = ROL64(C[1], 1) ^ C[4]; + D[1] = ROL64(C[2], 1) ^ C[0]; + D[2] = ROL64(C[3], 1) ^ C[1]; + D[3] = ROL64(C[4], 1) ^ C[2]; + D[4] = ROL64(C[0], 1) ^ C[3]; + + C[0] = A[0][0] ^ D[0]; /* rotate by 0 */ + C[1] = ROL64(A[1][1] ^ D[1], rhotates[1][1]); + C[2] = ROL64(A[2][2] ^ D[2], rhotates[2][2]); + C[3] = ROL64(A[3][3] ^ D[3], rhotates[3][3]); + C[4] = ROL64(A[4][4] ^ D[4], rhotates[4][4]); + +#ifdef KECCAK_COMPLEMENTING_TRANSFORM + R[0][0] = C[0] ^ ( C[1] | C[2]) ^ iotas[i]; + R[0][1] = C[1] ^ (~C[2] | C[3]); + R[0][2] = C[2] ^ ( C[3] & C[4]); + R[0][3] = C[3] ^ ( C[4] | C[0]); + R[0][4] = C[4] ^ ( C[0] & C[1]); +#else + R[0][0] = C[0] ^ (~C[1] & C[2]) ^ iotas[i]; + R[0][1] = C[1] ^ (~C[2] & C[3]); + R[0][2] = C[2] ^ (~C[3] & C[4]); + R[0][3] = C[3] ^ (~C[4] & C[0]); + R[0][4] = C[4] ^ (~C[0] & C[1]); +#endif + + C[0] = ROL64(A[0][3] ^ D[3], rhotates[0][3]); + C[1] = ROL64(A[1][4] ^ D[4], rhotates[1][4]); + C[2] = ROL64(A[2][0] ^ D[0], rhotates[2][0]); + C[3] = ROL64(A[3][1] ^ D[1], rhotates[3][1]); + C[4] = ROL64(A[4][2] ^ D[2], rhotates[4][2]); + +#ifdef KECCAK_COMPLEMENTING_TRANSFORM + R[1][0] = C[0] ^ (C[1] | C[2]); + R[1][1] = C[1] ^ (C[2] & C[3]); + R[1][2] = C[2] ^ (C[3] | ~C[4]); + R[1][3] = C[3] ^ (C[4] | C[0]); + R[1][4] = C[4] ^ (C[0] & C[1]); +#else + R[1][0] = C[0] ^ (~C[1] & C[2]); + R[1][1] = C[1] ^ (~C[2] & C[3]); + R[1][2] = C[2] ^ (~C[3] & C[4]); + R[1][3] = C[3] ^ (~C[4] & C[0]); + R[1][4] = C[4] ^ (~C[0] & C[1]); +#endif + + C[0] = ROL64(A[0][1] ^ D[1], rhotates[0][1]); + C[1] = ROL64(A[1][2] ^ D[2], rhotates[1][2]); + C[2] = ROL64(A[2][3] ^ D[3], rhotates[2][3]); + C[3] = ROL64(A[3][4] ^ D[4], rhotates[3][4]); + C[4] = ROL64(A[4][0] ^ D[0], rhotates[4][0]); + +#ifdef KECCAK_COMPLEMENTING_TRANSFORM + R[2][0] = C[0] ^ ( C[1] | C[2]); + R[2][1] = C[1] ^ ( C[2] & C[3]); + R[2][2] = C[2] ^ (~C[3] & C[4]); + R[2][3] = ~C[3] ^ ( C[4] | C[0]); + R[2][4] = C[4] ^ ( C[0] & C[1]); +#else + R[2][0] = C[0] ^ (~C[1] & C[2]); + R[2][1] = C[1] ^ (~C[2] & C[3]); + R[2][2] = C[2] ^ (~C[3] & C[4]); + R[2][3] = C[3] ^ (~C[4] & C[0]); + R[2][4] = C[4] ^ (~C[0] & C[1]); +#endif + + C[0] = ROL64(A[0][4] ^ D[4], rhotates[0][4]); + C[1] = ROL64(A[1][0] ^ D[0], rhotates[1][0]); + C[2] = ROL64(A[2][1] ^ D[1], rhotates[2][1]); + C[3] = ROL64(A[3][2] ^ D[2], rhotates[3][2]); + C[4] = ROL64(A[4][3] ^ D[3], rhotates[4][3]); + +#ifdef KECCAK_COMPLEMENTING_TRANSFORM + R[3][0] = C[0] ^ ( C[1] & C[2]); + R[3][1] = C[1] ^ ( C[2] | C[3]); + R[3][2] = C[2] ^ (~C[3] | C[4]); + R[3][3] = ~C[3] ^ ( C[4] & C[0]); + R[3][4] = C[4] ^ ( C[0] | C[1]); +#else + R[3][0] = C[0] ^ (~C[1] & C[2]); + R[3][1] = C[1] ^ (~C[2] & C[3]); + R[3][2] = C[2] ^ (~C[3] & C[4]); + R[3][3] = C[3] ^ (~C[4] & C[0]); + R[3][4] = C[4] ^ (~C[0] & C[1]); +#endif + + C[0] = ROL64(A[0][2] ^ D[2], rhotates[0][2]); + C[1] = ROL64(A[1][3] ^ D[3], rhotates[1][3]); + C[2] = ROL64(A[2][4] ^ D[4], rhotates[2][4]); + C[3] = ROL64(A[3][0] ^ D[0], rhotates[3][0]); + C[4] = ROL64(A[4][1] ^ D[1], rhotates[4][1]); + +#ifdef KECCAK_COMPLEMENTING_TRANSFORM + R[4][0] = C[0] ^ (~C[1] & C[2]); + R[4][1] = ~C[1] ^ ( C[2] | C[3]); + R[4][2] = C[2] ^ ( C[3] & C[4]); + R[4][3] = C[3] ^ ( C[4] | C[0]); + R[4][4] = C[4] ^ ( C[0] & C[1]); +#else + R[4][0] = C[0] ^ (~C[1] & C[2]); + R[4][1] = C[1] ^ (~C[2] & C[3]); + R[4][2] = C[2] ^ (~C[3] & C[4]); + R[4][3] = C[3] ^ (~C[4] & C[0]); + R[4][4] = C[4] ^ (~C[0] & C[1]); +#endif +} + +static void KeccakF1600(uint64_t A[5][5]) +{ + uint64_t T[5][5]; + size_t i; + +#ifdef KECCAK_COMPLEMENTING_TRANSFORM + A[0][1] = ~A[0][1]; + A[0][2] = ~A[0][2]; + A[1][3] = ~A[1][3]; + A[2][2] = ~A[2][2]; + A[3][2] = ~A[3][2]; + A[4][0] = ~A[4][0]; +#endif + + for (i = 0; i < 24; i += 2) { + Round(T, A, i); + Round(A, T, i + 1); + } + +#ifdef KECCAK_COMPLEMENTING_TRANSFORM + A[0][1] = ~A[0][1]; + A[0][2] = ~A[0][2]; + A[1][3] = ~A[1][3]; + A[2][2] = ~A[2][2]; + A[3][2] = ~A[3][2]; + A[4][0] = ~A[4][0]; +#endif +} + +#else /* define KECCAK_INPLACE to compile this code path */ +/* + * This implementation is KECCAK_1X from above combined 4 times with + * a twist that allows to omit temporary storage and perform in-place + * processing. It's discussed in section 2.5 of "Keccak implementation + * overview". It's likely to be best suited for processors with large + * register bank... On the other hand processor with large register + * bank can as well use KECCAK_1X_ALT, it would be as fast but much + * more compact... + */ +static void FourRounds(uint64_t A[5][5], size_t i) +{ + uint64_t B[5], C[5], D[5]; + + assert(i <= (sizeof(iotas) / sizeof(iotas[0]) - 4)); + + /* Round 4*n */ + C[0] = A[0][0] ^ A[1][0] ^ A[2][0] ^ A[3][0] ^ A[4][0]; + C[1] = A[0][1] ^ A[1][1] ^ A[2][1] ^ A[3][1] ^ A[4][1]; + C[2] = A[0][2] ^ A[1][2] ^ A[2][2] ^ A[3][2] ^ A[4][2]; + C[3] = A[0][3] ^ A[1][3] ^ A[2][3] ^ A[3][3] ^ A[4][3]; + C[4] = A[0][4] ^ A[1][4] ^ A[2][4] ^ A[3][4] ^ A[4][4]; + + D[0] = ROL64(C[1], 1) ^ C[4]; + D[1] = ROL64(C[2], 1) ^ C[0]; + D[2] = ROL64(C[3], 1) ^ C[1]; + D[3] = ROL64(C[4], 1) ^ C[2]; + D[4] = ROL64(C[0], 1) ^ C[3]; + + B[0] = A[0][0] ^ D[0]; /* rotate by 0 */ + B[1] = ROL64(A[1][1] ^ D[1], rhotates[1][1]); + B[2] = ROL64(A[2][2] ^ D[2], rhotates[2][2]); + B[3] = ROL64(A[3][3] ^ D[3], rhotates[3][3]); + B[4] = ROL64(A[4][4] ^ D[4], rhotates[4][4]); + + C[0] = A[0][0] = B[0] ^ (~B[1] & B[2]) ^ iotas[i]; + C[1] = A[1][1] = B[1] ^ (~B[2] & B[3]); + C[2] = A[2][2] = B[2] ^ (~B[3] & B[4]); + C[3] = A[3][3] = B[3] ^ (~B[4] & B[0]); + C[4] = A[4][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[0][3] ^ D[3], rhotates[0][3]); + B[1] = ROL64(A[1][4] ^ D[4], rhotates[1][4]); + B[2] = ROL64(A[2][0] ^ D[0], rhotates[2][0]); + B[3] = ROL64(A[3][1] ^ D[1], rhotates[3][1]); + B[4] = ROL64(A[4][2] ^ D[2], rhotates[4][2]); + + C[0] ^= A[2][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[3][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[4][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[0][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[1][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[0][1] ^ D[1], rhotates[0][1]); + B[1] = ROL64(A[1][2] ^ D[2], rhotates[1][2]); + B[2] = ROL64(A[2][3] ^ D[3], rhotates[2][3]); + B[3] = ROL64(A[3][4] ^ D[4], rhotates[3][4]); + B[4] = ROL64(A[4][0] ^ D[0], rhotates[4][0]); + + C[0] ^= A[4][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[0][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[1][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[2][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[3][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[0][4] ^ D[4], rhotates[0][4]); + B[1] = ROL64(A[1][0] ^ D[0], rhotates[1][0]); + B[2] = ROL64(A[2][1] ^ D[1], rhotates[2][1]); + B[3] = ROL64(A[3][2] ^ D[2], rhotates[3][2]); + B[4] = ROL64(A[4][3] ^ D[3], rhotates[4][3]); + + C[0] ^= A[1][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[2][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[3][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[4][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[0][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[0][2] ^ D[2], rhotates[0][2]); + B[1] = ROL64(A[1][3] ^ D[3], rhotates[1][3]); + B[2] = ROL64(A[2][4] ^ D[4], rhotates[2][4]); + B[3] = ROL64(A[3][0] ^ D[0], rhotates[3][0]); + B[4] = ROL64(A[4][1] ^ D[1], rhotates[4][1]); + + C[0] ^= A[3][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[4][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[0][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[1][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[2][4] = B[4] ^ (~B[0] & B[1]); + + /* Round 4*n+1 */ + D[0] = ROL64(C[1], 1) ^ C[4]; + D[1] = ROL64(C[2], 1) ^ C[0]; + D[2] = ROL64(C[3], 1) ^ C[1]; + D[3] = ROL64(C[4], 1) ^ C[2]; + D[4] = ROL64(C[0], 1) ^ C[3]; + + B[0] = A[0][0] ^ D[0]; /* rotate by 0 */ + B[1] = ROL64(A[3][1] ^ D[1], rhotates[1][1]); + B[2] = ROL64(A[1][2] ^ D[2], rhotates[2][2]); + B[3] = ROL64(A[4][3] ^ D[3], rhotates[3][3]); + B[4] = ROL64(A[2][4] ^ D[4], rhotates[4][4]); + + C[0] = A[0][0] = B[0] ^ (~B[1] & B[2]) ^ iotas[i + 1]; + C[1] = A[3][1] = B[1] ^ (~B[2] & B[3]); + C[2] = A[1][2] = B[2] ^ (~B[3] & B[4]); + C[3] = A[4][3] = B[3] ^ (~B[4] & B[0]); + C[4] = A[2][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[3][3] ^ D[3], rhotates[0][3]); + B[1] = ROL64(A[1][4] ^ D[4], rhotates[1][4]); + B[2] = ROL64(A[4][0] ^ D[0], rhotates[2][0]); + B[3] = ROL64(A[2][1] ^ D[1], rhotates[3][1]); + B[4] = ROL64(A[0][2] ^ D[2], rhotates[4][2]); + + C[0] ^= A[4][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[2][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[0][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[3][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[1][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[1][1] ^ D[1], rhotates[0][1]); + B[1] = ROL64(A[4][2] ^ D[2], rhotates[1][2]); + B[2] = ROL64(A[2][3] ^ D[3], rhotates[2][3]); + B[3] = ROL64(A[0][4] ^ D[4], rhotates[3][4]); + B[4] = ROL64(A[3][0] ^ D[0], rhotates[4][0]); + + C[0] ^= A[3][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[1][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[4][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[2][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[0][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[4][4] ^ D[4], rhotates[0][4]); + B[1] = ROL64(A[2][0] ^ D[0], rhotates[1][0]); + B[2] = ROL64(A[0][1] ^ D[1], rhotates[2][1]); + B[3] = ROL64(A[3][2] ^ D[2], rhotates[3][2]); + B[4] = ROL64(A[1][3] ^ D[3], rhotates[4][3]); + + C[0] ^= A[2][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[0][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[3][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[1][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[4][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[2][2] ^ D[2], rhotates[0][2]); + B[1] = ROL64(A[0][3] ^ D[3], rhotates[1][3]); + B[2] = ROL64(A[3][4] ^ D[4], rhotates[2][4]); + B[3] = ROL64(A[1][0] ^ D[0], rhotates[3][0]); + B[4] = ROL64(A[4][1] ^ D[1], rhotates[4][1]); + + C[0] ^= A[1][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[4][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[2][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[0][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[3][4] = B[4] ^ (~B[0] & B[1]); + + /* Round 4*n+2 */ + D[0] = ROL64(C[1], 1) ^ C[4]; + D[1] = ROL64(C[2], 1) ^ C[0]; + D[2] = ROL64(C[3], 1) ^ C[1]; + D[3] = ROL64(C[4], 1) ^ C[2]; + D[4] = ROL64(C[0], 1) ^ C[3]; + + B[0] = A[0][0] ^ D[0]; /* rotate by 0 */ + B[1] = ROL64(A[2][1] ^ D[1], rhotates[1][1]); + B[2] = ROL64(A[4][2] ^ D[2], rhotates[2][2]); + B[3] = ROL64(A[1][3] ^ D[3], rhotates[3][3]); + B[4] = ROL64(A[3][4] ^ D[4], rhotates[4][4]); + + C[0] = A[0][0] = B[0] ^ (~B[1] & B[2]) ^ iotas[i + 2]; + C[1] = A[2][1] = B[1] ^ (~B[2] & B[3]); + C[2] = A[4][2] = B[2] ^ (~B[3] & B[4]); + C[3] = A[1][3] = B[3] ^ (~B[4] & B[0]); + C[4] = A[3][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[4][3] ^ D[3], rhotates[0][3]); + B[1] = ROL64(A[1][4] ^ D[4], rhotates[1][4]); + B[2] = ROL64(A[3][0] ^ D[0], rhotates[2][0]); + B[3] = ROL64(A[0][1] ^ D[1], rhotates[3][1]); + B[4] = ROL64(A[2][2] ^ D[2], rhotates[4][2]); + + C[0] ^= A[3][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[0][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[2][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[4][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[1][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[3][1] ^ D[1], rhotates[0][1]); + B[1] = ROL64(A[0][2] ^ D[2], rhotates[1][2]); + B[2] = ROL64(A[2][3] ^ D[3], rhotates[2][3]); + B[3] = ROL64(A[4][4] ^ D[4], rhotates[3][4]); + B[4] = ROL64(A[1][0] ^ D[0], rhotates[4][0]); + + C[0] ^= A[1][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[3][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[0][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[2][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[4][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[2][4] ^ D[4], rhotates[0][4]); + B[1] = ROL64(A[4][0] ^ D[0], rhotates[1][0]); + B[2] = ROL64(A[1][1] ^ D[1], rhotates[2][1]); + B[3] = ROL64(A[3][2] ^ D[2], rhotates[3][2]); + B[4] = ROL64(A[0][3] ^ D[3], rhotates[4][3]); + + C[0] ^= A[4][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[1][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[3][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[0][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[2][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[1][2] ^ D[2], rhotates[0][2]); + B[1] = ROL64(A[3][3] ^ D[3], rhotates[1][3]); + B[2] = ROL64(A[0][4] ^ D[4], rhotates[2][4]); + B[3] = ROL64(A[2][0] ^ D[0], rhotates[3][0]); + B[4] = ROL64(A[4][1] ^ D[1], rhotates[4][1]); + + C[0] ^= A[2][0] = B[0] ^ (~B[1] & B[2]); + C[1] ^= A[4][1] = B[1] ^ (~B[2] & B[3]); + C[2] ^= A[1][2] = B[2] ^ (~B[3] & B[4]); + C[3] ^= A[3][3] = B[3] ^ (~B[4] & B[0]); + C[4] ^= A[0][4] = B[4] ^ (~B[0] & B[1]); + + /* Round 4*n+3 */ + D[0] = ROL64(C[1], 1) ^ C[4]; + D[1] = ROL64(C[2], 1) ^ C[0]; + D[2] = ROL64(C[3], 1) ^ C[1]; + D[3] = ROL64(C[4], 1) ^ C[2]; + D[4] = ROL64(C[0], 1) ^ C[3]; + + B[0] = A[0][0] ^ D[0]; /* rotate by 0 */ + B[1] = ROL64(A[0][1] ^ D[1], rhotates[1][1]); + B[2] = ROL64(A[0][2] ^ D[2], rhotates[2][2]); + B[3] = ROL64(A[0][3] ^ D[3], rhotates[3][3]); + B[4] = ROL64(A[0][4] ^ D[4], rhotates[4][4]); + + /* C[0] = */ A[0][0] = B[0] ^ (~B[1] & B[2]) ^ iotas[i + 3]; + /* C[1] = */ A[0][1] = B[1] ^ (~B[2] & B[3]); + /* C[2] = */ A[0][2] = B[2] ^ (~B[3] & B[4]); + /* C[3] = */ A[0][3] = B[3] ^ (~B[4] & B[0]); + /* C[4] = */ A[0][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[1][3] ^ D[3], rhotates[0][3]); + B[1] = ROL64(A[1][4] ^ D[4], rhotates[1][4]); + B[2] = ROL64(A[1][0] ^ D[0], rhotates[2][0]); + B[3] = ROL64(A[1][1] ^ D[1], rhotates[3][1]); + B[4] = ROL64(A[1][2] ^ D[2], rhotates[4][2]); + + /* C[0] ^= */ A[1][0] = B[0] ^ (~B[1] & B[2]); + /* C[1] ^= */ A[1][1] = B[1] ^ (~B[2] & B[3]); + /* C[2] ^= */ A[1][2] = B[2] ^ (~B[3] & B[4]); + /* C[3] ^= */ A[1][3] = B[3] ^ (~B[4] & B[0]); + /* C[4] ^= */ A[1][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[2][1] ^ D[1], rhotates[0][1]); + B[1] = ROL64(A[2][2] ^ D[2], rhotates[1][2]); + B[2] = ROL64(A[2][3] ^ D[3], rhotates[2][3]); + B[3] = ROL64(A[2][4] ^ D[4], rhotates[3][4]); + B[4] = ROL64(A[2][0] ^ D[0], rhotates[4][0]); + + /* C[0] ^= */ A[2][0] = B[0] ^ (~B[1] & B[2]); + /* C[1] ^= */ A[2][1] = B[1] ^ (~B[2] & B[3]); + /* C[2] ^= */ A[2][2] = B[2] ^ (~B[3] & B[4]); + /* C[3] ^= */ A[2][3] = B[3] ^ (~B[4] & B[0]); + /* C[4] ^= */ A[2][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[3][4] ^ D[4], rhotates[0][4]); + B[1] = ROL64(A[3][0] ^ D[0], rhotates[1][0]); + B[2] = ROL64(A[3][1] ^ D[1], rhotates[2][1]); + B[3] = ROL64(A[3][2] ^ D[2], rhotates[3][2]); + B[4] = ROL64(A[3][3] ^ D[3], rhotates[4][3]); + + /* C[0] ^= */ A[3][0] = B[0] ^ (~B[1] & B[2]); + /* C[1] ^= */ A[3][1] = B[1] ^ (~B[2] & B[3]); + /* C[2] ^= */ A[3][2] = B[2] ^ (~B[3] & B[4]); + /* C[3] ^= */ A[3][3] = B[3] ^ (~B[4] & B[0]); + /* C[4] ^= */ A[3][4] = B[4] ^ (~B[0] & B[1]); + + B[0] = ROL64(A[4][2] ^ D[2], rhotates[0][2]); + B[1] = ROL64(A[4][3] ^ D[3], rhotates[1][3]); + B[2] = ROL64(A[4][4] ^ D[4], rhotates[2][4]); + B[3] = ROL64(A[4][0] ^ D[0], rhotates[3][0]); + B[4] = ROL64(A[4][1] ^ D[1], rhotates[4][1]); + + /* C[0] ^= */ A[4][0] = B[0] ^ (~B[1] & B[2]); + /* C[1] ^= */ A[4][1] = B[1] ^ (~B[2] & B[3]); + /* C[2] ^= */ A[4][2] = B[2] ^ (~B[3] & B[4]); + /* C[3] ^= */ A[4][3] = B[3] ^ (~B[4] & B[0]); + /* C[4] ^= */ A[4][4] = B[4] ^ (~B[0] & B[1]); +} + +static void KeccakF1600(uint64_t A[5][5]) +{ + size_t i; + + for (i = 0; i < 24; i += 4) { + FourRounds(A, i); + } +} + +#endif + +static uint64_t BitInterleave(uint64_t Ai) +{ + if (BIT_INTERLEAVE) { + uint32_t hi = (uint32_t)(Ai >> 32), lo = (uint32_t)Ai; + uint32_t t0, t1; + + t0 = lo & 0x55555555; + t0 |= t0 >> 1; t0 &= 0x33333333; + t0 |= t0 >> 2; t0 &= 0x0f0f0f0f; + t0 |= t0 >> 4; t0 &= 0x00ff00ff; + t0 |= t0 >> 8; t0 &= 0x0000ffff; + + t1 = hi & 0x55555555; + t1 |= t1 >> 1; t1 &= 0x33333333; + t1 |= t1 >> 2; t1 &= 0x0f0f0f0f; + t1 |= t1 >> 4; t1 &= 0x00ff00ff; + t1 |= t1 >> 8; t1 <<= 16; + + lo &= 0xaaaaaaaa; + lo |= lo << 1; lo &= 0xcccccccc; + lo |= lo << 2; lo &= 0xf0f0f0f0; + lo |= lo << 4; lo &= 0xff00ff00; + lo |= lo << 8; lo >>= 16; + + hi &= 0xaaaaaaaa; + hi |= hi << 1; hi &= 0xcccccccc; + hi |= hi << 2; hi &= 0xf0f0f0f0; + hi |= hi << 4; hi &= 0xff00ff00; + hi |= hi << 8; hi &= 0xffff0000; + + Ai = ((uint64_t)(hi | lo) << 32) | (t1 | t0); + } + + return Ai; +} + +static uint64_t BitDeinterleave(uint64_t Ai) +{ + if (BIT_INTERLEAVE) { + uint32_t hi = (uint32_t)(Ai >> 32), lo = (uint32_t)Ai; + uint32_t t0, t1; + + t0 = lo & 0x0000ffff; + t0 |= t0 << 8; t0 &= 0x00ff00ff; + t0 |= t0 << 4; t0 &= 0x0f0f0f0f; + t0 |= t0 << 2; t0 &= 0x33333333; + t0 |= t0 << 1; t0 &= 0x55555555; + + t1 = hi << 16; + t1 |= t1 >> 8; t1 &= 0xff00ff00; + t1 |= t1 >> 4; t1 &= 0xf0f0f0f0; + t1 |= t1 >> 2; t1 &= 0xcccccccc; + t1 |= t1 >> 1; t1 &= 0xaaaaaaaa; + + lo >>= 16; + lo |= lo << 8; lo &= 0x00ff00ff; + lo |= lo << 4; lo &= 0x0f0f0f0f; + lo |= lo << 2; lo &= 0x33333333; + lo |= lo << 1; lo &= 0x55555555; + + hi &= 0xffff0000; + hi |= hi >> 8; hi &= 0xff00ff00; + hi |= hi >> 4; hi &= 0xf0f0f0f0; + hi |= hi >> 2; hi &= 0xcccccccc; + hi |= hi >> 1; hi &= 0xaaaaaaaa; + + Ai = ((uint64_t)(hi | lo) << 32) | (t1 | t0); + } + + return Ai; +} + +/* + * SHA3_absorb can be called multiple times, but at each invocation + * largest multiple of |r| out of |len| bytes are processed. Then + * remaining amount of bytes is returned. This is done to spare caller + * trouble of calculating the largest multiple of |r|. |r| can be viewed + * as blocksize. It is commonly (1600 - 256*n)/8, e.g. 168, 136, 104, + * 72, but can also be (1600 - 448)/8 = 144. All this means that message + * padding and intermediate sub-block buffering, byte- or bitwise, is + * caller's responsibility. + */ +size_t SHA3_absorb(uint64_t A[5][5], const unsigned char *inp, size_t len, + size_t r) +{ + uint64_t *A_flat = (uint64_t *)A; + size_t i, w = r / 8; + + assert(r < (25 * sizeof(A[0][0])) && (r % 8) == 0); + + while (len >= r) { + for (i = 0; i < w; i++) { + uint64_t Ai = (uint64_t)inp[0] | (uint64_t)inp[1] << 8 | + (uint64_t)inp[2] << 16 | (uint64_t)inp[3] << 24 | + (uint64_t)inp[4] << 32 | (uint64_t)inp[5] << 40 | + (uint64_t)inp[6] << 48 | (uint64_t)inp[7] << 56; + inp += 8; + + A_flat[i] ^= BitInterleave(Ai); + } + KeccakF1600(A); + len -= r; + } + + return len; +} + +/* + * SHA3_squeeze is called once at the end to generate |out| hash value + * of |len| bytes. + */ +void SHA3_squeeze(uint64_t A[5][5], unsigned char *out, size_t len, size_t r) +{ + uint64_t *A_flat = (uint64_t *)A; + size_t i, w = r / 8; + + assert(r < (25 * sizeof(A[0][0])) && (r % 8) == 0); + + while (len != 0) { + for (i = 0; i < w && len != 0; i++) { + uint64_t Ai = BitDeinterleave(A_flat[i]); + + if (len < 8) { + for (i = 0; i < len; i++) { + *out++ = (unsigned char)Ai; + Ai >>= 8; + } + return; + } + + out[0] = (unsigned char)(Ai); + out[1] = (unsigned char)(Ai >> 8); + out[2] = (unsigned char)(Ai >> 16); + out[3] = (unsigned char)(Ai >> 24); + out[4] = (unsigned char)(Ai >> 32); + out[5] = (unsigned char)(Ai >> 40); + out[6] = (unsigned char)(Ai >> 48); + out[7] = (unsigned char)(Ai >> 56); + out += 8; + len -= 8; + } + if (len) + KeccakF1600(A); + } +} +#endif + +#ifdef SELFTEST +/* + * Post-padding one-shot implementations would look as following: + * + * SHA3_224 SHA3_sponge(inp, len, out, 224/8, (1600-448)/8); + * SHA3_256 SHA3_sponge(inp, len, out, 256/8, (1600-512)/8); + * SHA3_384 SHA3_sponge(inp, len, out, 384/8, (1600-768)/8); + * SHA3_512 SHA3_sponge(inp, len, out, 512/8, (1600-1024)/8); + * SHAKE_128 SHA3_sponge(inp, len, out, d, (1600-256)/8); + * SHAKE_256 SHA3_sponge(inp, len, out, d, (1600-512)/8); + */ + +void SHA3_sponge(const unsigned char *inp, size_t len, + unsigned char *out, size_t d, size_t r) +{ + uint64_t A[5][5]; + + memset(A, 0, sizeof(A)); + SHA3_absorb(A, inp, len, r); + SHA3_squeeze(A, out, d, r); +} + +# include + +int main() +{ + /* + * This is 5-bit SHAKE128 test from http://csrc.nist.gov/groups/ST/toolkit/examples.html#aHashing + */ + unsigned char test[168] = { '\xf3', '\x3' }; + unsigned char out[512]; + size_t i; + static const unsigned char result[512] = { + 0x2E, 0x0A, 0xBF, 0xBA, 0x83, 0xE6, 0x72, 0x0B, + 0xFB, 0xC2, 0x25, 0xFF, 0x6B, 0x7A, 0xB9, 0xFF, + 0xCE, 0x58, 0xBA, 0x02, 0x7E, 0xE3, 0xD8, 0x98, + 0x76, 0x4F, 0xEF, 0x28, 0x7D, 0xDE, 0xCC, 0xCA, + 0x3E, 0x6E, 0x59, 0x98, 0x41, 0x1E, 0x7D, 0xDB, + 0x32, 0xF6, 0x75, 0x38, 0xF5, 0x00, 0xB1, 0x8C, + 0x8C, 0x97, 0xC4, 0x52, 0xC3, 0x70, 0xEA, 0x2C, + 0xF0, 0xAF, 0xCA, 0x3E, 0x05, 0xDE, 0x7E, 0x4D, + 0xE2, 0x7F, 0xA4, 0x41, 0xA9, 0xCB, 0x34, 0xFD, + 0x17, 0xC9, 0x78, 0xB4, 0x2D, 0x5B, 0x7E, 0x7F, + 0x9A, 0xB1, 0x8F, 0xFE, 0xFF, 0xC3, 0xC5, 0xAC, + 0x2F, 0x3A, 0x45, 0x5E, 0xEB, 0xFD, 0xC7, 0x6C, + 0xEA, 0xEB, 0x0A, 0x2C, 0xCA, 0x22, 0xEE, 0xF6, + 0xE6, 0x37, 0xF4, 0xCA, 0xBE, 0x5C, 0x51, 0xDE, + 0xD2, 0xE3, 0xFA, 0xD8, 0xB9, 0x52, 0x70, 0xA3, + 0x21, 0x84, 0x56, 0x64, 0xF1, 0x07, 0xD1, 0x64, + 0x96, 0xBB, 0x7A, 0xBF, 0xBE, 0x75, 0x04, 0xB6, + 0xED, 0xE2, 0xE8, 0x9E, 0x4B, 0x99, 0x6F, 0xB5, + 0x8E, 0xFD, 0xC4, 0x18, 0x1F, 0x91, 0x63, 0x38, + 0x1C, 0xBE, 0x7B, 0xC0, 0x06, 0xA7, 0xA2, 0x05, + 0x98, 0x9C, 0x52, 0x6C, 0xD1, 0xBD, 0x68, 0x98, + 0x36, 0x93, 0xB4, 0xBD, 0xC5, 0x37, 0x28, 0xB2, + 0x41, 0xC1, 0xCF, 0xF4, 0x2B, 0xB6, 0x11, 0x50, + 0x2C, 0x35, 0x20, 0x5C, 0xAB, 0xB2, 0x88, 0x75, + 0x56, 0x55, 0xD6, 0x20, 0xC6, 0x79, 0x94, 0xF0, + 0x64, 0x51, 0x18, 0x7F, 0x6F, 0xD1, 0x7E, 0x04, + 0x66, 0x82, 0xBA, 0x12, 0x86, 0x06, 0x3F, 0xF8, + 0x8F, 0xE2, 0x50, 0x8D, 0x1F, 0xCA, 0xF9, 0x03, + 0x5A, 0x12, 0x31, 0xAD, 0x41, 0x50, 0xA9, 0xC9, + 0xB2, 0x4C, 0x9B, 0x2D, 0x66, 0xB2, 0xAD, 0x1B, + 0xDE, 0x0B, 0xD0, 0xBB, 0xCB, 0x8B, 0xE0, 0x5B, + 0x83, 0x52, 0x29, 0xEF, 0x79, 0x19, 0x73, 0x73, + 0x23, 0x42, 0x44, 0x01, 0xE1, 0xD8, 0x37, 0xB6, + 0x6E, 0xB4, 0xE6, 0x30, 0xFF, 0x1D, 0xE7, 0x0C, + 0xB3, 0x17, 0xC2, 0xBA, 0xCB, 0x08, 0x00, 0x1D, + 0x34, 0x77, 0xB7, 0xA7, 0x0A, 0x57, 0x6D, 0x20, + 0x86, 0x90, 0x33, 0x58, 0x9D, 0x85, 0xA0, 0x1D, + 0xDB, 0x2B, 0x66, 0x46, 0xC0, 0x43, 0xB5, 0x9F, + 0xC0, 0x11, 0x31, 0x1D, 0xA6, 0x66, 0xFA, 0x5A, + 0xD1, 0xD6, 0x38, 0x7F, 0xA9, 0xBC, 0x40, 0x15, + 0xA3, 0x8A, 0x51, 0xD1, 0xDA, 0x1E, 0xA6, 0x1D, + 0x64, 0x8D, 0xC8, 0xE3, 0x9A, 0x88, 0xB9, 0xD6, + 0x22, 0xBD, 0xE2, 0x07, 0xFD, 0xAB, 0xC6, 0xF2, + 0x82, 0x7A, 0x88, 0x0C, 0x33, 0x0B, 0xBF, 0x6D, + 0xF7, 0x33, 0x77, 0x4B, 0x65, 0x3E, 0x57, 0x30, + 0x5D, 0x78, 0xDC, 0xE1, 0x12, 0xF1, 0x0A, 0x2C, + 0x71, 0xF4, 0xCD, 0xAD, 0x92, 0xED, 0x11, 0x3E, + 0x1C, 0xEA, 0x63, 0xB9, 0x19, 0x25, 0xED, 0x28, + 0x19, 0x1E, 0x6D, 0xBB, 0xB5, 0xAA, 0x5A, 0x2A, + 0xFD, 0xA5, 0x1F, 0xC0, 0x5A, 0x3A, 0xF5, 0x25, + 0x8B, 0x87, 0x66, 0x52, 0x43, 0x55, 0x0F, 0x28, + 0x94, 0x8A, 0xE2, 0xB8, 0xBE, 0xB6, 0xBC, 0x9C, + 0x77, 0x0B, 0x35, 0xF0, 0x67, 0xEA, 0xA6, 0x41, + 0xEF, 0xE6, 0x5B, 0x1A, 0x44, 0x90, 0x9D, 0x1B, + 0x14, 0x9F, 0x97, 0xEE, 0xA6, 0x01, 0x39, 0x1C, + 0x60, 0x9E, 0xC8, 0x1D, 0x19, 0x30, 0xF5, 0x7C, + 0x18, 0xA4, 0xE0, 0xFA, 0xB4, 0x91, 0xD1, 0xCA, + 0xDF, 0xD5, 0x04, 0x83, 0x44, 0x9E, 0xDC, 0x0F, + 0x07, 0xFF, 0xB2, 0x4D, 0x2C, 0x6F, 0x9A, 0x9A, + 0x3B, 0xFF, 0x39, 0xAE, 0x3D, 0x57, 0xF5, 0x60, + 0x65, 0x4D, 0x7D, 0x75, 0xC9, 0x08, 0xAB, 0xE6, + 0x25, 0x64, 0x75, 0x3E, 0xAC, 0x39, 0xD7, 0x50, + 0x3D, 0xA6, 0xD3, 0x7C, 0x2E, 0x32, 0xE1, 0xAF, + 0x3B, 0x8A, 0xEC, 0x8A, 0xE3, 0x06, 0x9C, 0xD9 + }; + + test[167] = '\x80'; + SHA3_sponge(test, sizeof(test), out, sizeof(out), sizeof(test)); + + /* + * Rationale behind keeping output [formatted as below] is that + * one should be able to redirect it to a file, then copy-n-paste + * final "output val" from official example to another file, and + * compare the two with diff(1). + */ + for (i = 0; i < sizeof(out);) { + printf("%02X", out[i]); + printf(++i % 16 && i != sizeof(out) ? " " : "\n"); + } + + if (memcmp(out,result,sizeof(out))) { + fprintf(stderr,"failure\n"); + return 1; + } else { + fprintf(stderr,"success\n"); + return 0; + } +} +#endif diff --git a/crypto/sha/sha1_one.c b/crypto/sha/sha1_one.c index 273ab08d..e5b38211 100644 --- a/crypto/sha/sha1_one.c +++ b/crypto/sha/sha1_one.c @@ -24,5 +24,5 @@ unsigned char *SHA1(const unsigned char *d, size_t n, unsigned char *md) SHA1_Update(&c, d, n); SHA1_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); - return (md); + return md; } diff --git a/crypto/sha/sha256.c b/crypto/sha/sha256.c index 5e7ba439..bf78f075 100644 --- a/crypto/sha/sha256.c +++ b/crypto/sha/sha256.c @@ -57,7 +57,7 @@ unsigned char *SHA224(const unsigned char *d, size_t n, unsigned char *md) SHA256_Update(&c, d, n); SHA256_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); - return (md); + return md; } unsigned char *SHA256(const unsigned char *d, size_t n, unsigned char *md) @@ -71,7 +71,7 @@ unsigned char *SHA256(const unsigned char *d, size_t n, unsigned char *md) SHA256_Update(&c, d, n); SHA256_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); - return (md); + return md; } int SHA224_Update(SHA256_CTX *c, const void *data, size_t len) diff --git a/crypto/sha/sha512.c b/crypto/sha/sha512.c index e94de437..50b65ee8 100644 --- a/crypto/sha/sha512.c +++ b/crypto/sha/sha512.c @@ -1,5 +1,5 @@ /* - * Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2004-2018 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 @@ -41,7 +41,6 @@ * As this implementation relies on 64-bit integer type, it's totally * inappropriate for platforms which don't support it, most notably * 16-bit platforms. - * */ #include #include @@ -51,6 +50,7 @@ #include #include "internal/cryptlib.h" +#include "internal/sha.h" #if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(_M_AMD64) || defined(_M_X64) || \ @@ -60,6 +60,42 @@ # define SHA512_BLOCK_CAN_MANAGE_UNALIGNED_DATA #endif +int sha512_224_init(SHA512_CTX *c) +{ + c->h[0] = U64(0x8c3d37c819544da2); + c->h[1] = U64(0x73e1996689dcd4d6); + c->h[2] = U64(0x1dfab7ae32ff9c82); + c->h[3] = U64(0x679dd514582f9fcf); + c->h[4] = U64(0x0f6d2b697bd44da8); + c->h[5] = U64(0x77e36f7304c48942); + c->h[6] = U64(0x3f9d85a86a1d36c8); + c->h[7] = U64(0x1112e6ad91d692a1); + + c->Nl = 0; + c->Nh = 0; + c->num = 0; + c->md_len = SHA224_DIGEST_LENGTH; + return 1; +} + +int sha512_256_init(SHA512_CTX *c) +{ + c->h[0] = U64(0x22312194fc2bf72c); + c->h[1] = U64(0x9f555fa3c84c64c2); + c->h[2] = U64(0x2393b86b6f53b151); + c->h[3] = U64(0x963877195940eabd); + c->h[4] = U64(0x96283ee2a88effe3); + c->h[5] = U64(0xbe5e1e2553863992); + c->h[6] = U64(0x2b0199fc2c85b8aa); + c->h[7] = U64(0x0eb72ddc81c52ca2); + + c->Nl = 0; + c->Nh = 0; + c->num = 0; + c->md_len = SHA256_DIGEST_LENGTH; + return 1; +} + int SHA384_Init(SHA512_CTX *c) { c->h[0] = U64(0xcbbb9d5dc1059ed8); @@ -144,6 +180,46 @@ int SHA512_Final(unsigned char *md, SHA512_CTX *c) switch (c->md_len) { /* Let compiler decide if it's appropriate to unroll... */ + case SHA224_DIGEST_LENGTH: + for (n = 0; n < SHA224_DIGEST_LENGTH / 8; n++) { + SHA_LONG64 t = c->h[n]; + + *(md++) = (unsigned char)(t >> 56); + *(md++) = (unsigned char)(t >> 48); + *(md++) = (unsigned char)(t >> 40); + *(md++) = (unsigned char)(t >> 32); + *(md++) = (unsigned char)(t >> 24); + *(md++) = (unsigned char)(t >> 16); + *(md++) = (unsigned char)(t >> 8); + *(md++) = (unsigned char)(t); + } + /* + * For 224 bits, there are four bytes left over that have to be + * processed separately. + */ + { + SHA_LONG64 t = c->h[SHA224_DIGEST_LENGTH / 8]; + + *(md++) = (unsigned char)(t >> 56); + *(md++) = (unsigned char)(t >> 48); + *(md++) = (unsigned char)(t >> 40); + *(md++) = (unsigned char)(t >> 32); + } + break; + case SHA256_DIGEST_LENGTH: + for (n = 0; n < SHA256_DIGEST_LENGTH / 8; n++) { + SHA_LONG64 t = c->h[n]; + + *(md++) = (unsigned char)(t >> 56); + *(md++) = (unsigned char)(t >> 48); + *(md++) = (unsigned char)(t >> 40); + *(md++) = (unsigned char)(t >> 32); + *(md++) = (unsigned char)(t >> 24); + *(md++) = (unsigned char)(t >> 16); + *(md++) = (unsigned char)(t >> 8); + *(md++) = (unsigned char)(t); + } + break; case SHA384_DIGEST_LENGTH: for (n = 0; n < SHA384_DIGEST_LENGTH / 8; n++) { SHA_LONG64 t = c->h[n]; @@ -258,7 +334,7 @@ unsigned char *SHA384(const unsigned char *d, size_t n, unsigned char *md) SHA512_Update(&c, d, n); SHA512_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); - return (md); + return md; } unsigned char *SHA512(const unsigned char *d, size_t n, unsigned char *md) @@ -272,7 +348,7 @@ unsigned char *SHA512(const unsigned char *d, size_t n, unsigned char *md) SHA512_Update(&c, d, n); SHA512_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); - return (md); + return md; } #ifndef SHA512_ASM @@ -399,9 +475,6 @@ static SHA_LONG64 __fastcall __pull64be(const void *x) } # endif # define PULL64(x) __pull64be(&(x)) -# if _MSC_VER<=1200 -# pragma inline_depth(0) -# endif # endif # endif # endif diff --git a/crypto/sha/sha_locl.h b/crypto/sha/sha_locl.h index 918278a8..4e5a0903 100644 --- a/crypto/sha/sha_locl.h +++ b/crypto/sha/sha_locl.h @@ -67,11 +67,12 @@ int HASH_INIT(SHA_CTX *c) #define K_60_79 0xca62c1d6UL /* - * As pointed out by Wei Dai , F() below can be simplified - * to the code in F_00_19. Wei attributes these optimisations to Peter - * Gutmann's SHS code, and he attributes it to Rich Schroeppel. #define - * F(x,y,z) (((x) & (y)) | ((~(x)) & (z))) I've just become aware of another - * tweak to be made, again from Wei Dai, in F_40_59, (x&a)|(y&a) -> (x|y)&a + * As pointed out by Wei Dai, F() below can be simplified to the code in + * F_00_19. Wei attributes these optimizations to Peter Gutmann's SHS code, + * and he attributes it to Rich Schroeppel. + * #define F(x,y,z) (((x) & (y)) | ((~(x)) & (z))) + * I've just become aware of another tweak to be made, again from Wei Dai, + * in F_40_59, (x&a)|(y&a) -> (x|y)&a */ #define F_00_19(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) #define F_20_39(b,c,d) ((b) ^ (c) ^ (d)) @@ -120,7 +121,6 @@ int HASH_INIT(SHA_CTX *c) * "find" this expectation reasonable:-( On order to make such * compilers generate better code I replace X[] with a bunch of * X0, X1, etc. See the function body below... - * */ # define X(i) XX##i # else diff --git a/crypto/siphash/build.info b/crypto/siphash/build.info new file mode 100644 index 00000000..4166344a --- /dev/null +++ b/crypto/siphash/build.info @@ -0,0 +1,5 @@ +LIBS=../../libcrypto +SOURCE[../../libcrypto]=\ + siphash.c \ + siphash_pmeth.c \ + siphash_ameth.c diff --git a/crypto/siphash/siphash.c b/crypto/siphash/siphash.c new file mode 100644 index 00000000..72fd5198 --- /dev/null +++ b/crypto/siphash/siphash.c @@ -0,0 +1,234 @@ +/* + * 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 + */ + +/* Based on https://131002.net/siphash C reference implementation */ +/* + SipHash reference C implementation + + Copyright (c) 2012-2016 Jean-Philippe Aumasson + Copyright (c) 2012-2014 Daniel J. Bernstein + + To the extent possible under law, the author(s) have dedicated all copyright + and related and neighboring rights to this software to the public domain + worldwide. This software is distributed without any warranty. + + You should have received a copy of the CC0 Public Domain Dedication along + with this software. If not, see + . + */ + +#include +#include +#include + +#include "internal/siphash.h" +#include "siphash_local.h" + +/* default: SipHash-2-4 */ +#define SIPHASH_C_ROUNDS 2 +#define SIPHASH_D_ROUNDS 4 + +#define ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b)))) + +#define U32TO8_LE(p, v) \ + (p)[0] = (uint8_t)((v)); \ + (p)[1] = (uint8_t)((v) >> 8); \ + (p)[2] = (uint8_t)((v) >> 16); \ + (p)[3] = (uint8_t)((v) >> 24); + +#define U64TO8_LE(p, v) \ + U32TO8_LE((p), (uint32_t)((v))); \ + U32TO8_LE((p) + 4, (uint32_t)((v) >> 32)); + +#define U8TO64_LE(p) \ + (((uint64_t)((p)[0])) | ((uint64_t)((p)[1]) << 8) | \ + ((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) | \ + ((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) | \ + ((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56)) + +#define SIPROUND \ + do { \ + v0 += v1; \ + v1 = ROTL(v1, 13); \ + v1 ^= v0; \ + v0 = ROTL(v0, 32); \ + v2 += v3; \ + v3 = ROTL(v3, 16); \ + v3 ^= v2; \ + v0 += v3; \ + v3 = ROTL(v3, 21); \ + v3 ^= v0; \ + v2 += v1; \ + v1 = ROTL(v1, 17); \ + v1 ^= v2; \ + v2 = ROTL(v2, 32); \ + } while (0) + +size_t SipHash_ctx_size(void) +{ + return sizeof(SIPHASH); +} + +size_t SipHash_hash_size(SIPHASH *ctx) +{ + return ctx->hash_size; +} + +/* hash_size = crounds = drounds = 0 means SipHash24 with 16-byte output */ +int SipHash_Init(SIPHASH *ctx, const unsigned char *k, int hash_size, int crounds, int drounds) +{ + uint64_t k0 = U8TO64_LE(k); + uint64_t k1 = U8TO64_LE(k + 8); + + if (hash_size == 0) + hash_size = SIPHASH_MAX_DIGEST_SIZE; + else if (hash_size != SIPHASH_MIN_DIGEST_SIZE && + hash_size != SIPHASH_MAX_DIGEST_SIZE) + return 0; + + if (drounds == 0) + drounds = SIPHASH_D_ROUNDS; + if (crounds == 0) + crounds = SIPHASH_C_ROUNDS; + + ctx->crounds = crounds; + ctx->drounds = drounds; + ctx->hash_size = hash_size; + + ctx->len = 0; + ctx->total_inlen = 0; + + ctx->v0 = 0x736f6d6570736575ULL ^ k0; + ctx->v1 = 0x646f72616e646f6dULL ^ k1; + ctx->v2 = 0x6c7967656e657261ULL ^ k0; + ctx->v3 = 0x7465646279746573ULL ^ k1; + + if (ctx->hash_size == SIPHASH_MAX_DIGEST_SIZE) + ctx->v1 ^= 0xee; + + return 1; +} + +void SipHash_Update(SIPHASH *ctx, const unsigned char *in, size_t inlen) +{ + uint64_t m; + const uint8_t *end; + int left; + int i; + uint64_t v0 = ctx->v0; + uint64_t v1 = ctx->v1; + uint64_t v2 = ctx->v2; + uint64_t v3 = ctx->v3; + + ctx->total_inlen += inlen; + + if (ctx->len) { + /* deal with leavings */ + size_t available = SIPHASH_BLOCK_SIZE - ctx->len; + + /* not enough to fill leavings */ + if (inlen < available) { + memcpy(&ctx->leavings[ctx->len], in, inlen); + ctx->len += inlen; + return; + } + + /* copy data into leavings and reduce input */ + memcpy(&ctx->leavings[ctx->len], in, available); + inlen -= available; + in += available; + + /* process leavings */ + m = U8TO64_LE(ctx->leavings); + v3 ^= m; + for (i = 0; i < ctx->crounds; ++i) + SIPROUND; + v0 ^= m; + } + left = inlen & (SIPHASH_BLOCK_SIZE-1); /* gets put into leavings */ + end = in + inlen - left; + + for (; in != end; in += 8) { + m = U8TO64_LE(in); + v3 ^= m; + for (i = 0; i < ctx->crounds; ++i) + SIPROUND; + v0 ^= m; + } + + /* save leavings and other ctx */ + if (left) + memcpy(ctx->leavings, end, left); + ctx->len = left; + + ctx->v0 = v0; + ctx->v1 = v1; + ctx->v2 = v2; + ctx->v3 = v3; +} + +int SipHash_Final(SIPHASH *ctx, unsigned char *out, size_t outlen) +{ + /* finalize hash */ + int i; + uint64_t b = ctx->total_inlen << 56; + uint64_t v0 = ctx->v0; + uint64_t v1 = ctx->v1; + uint64_t v2 = ctx->v2; + uint64_t v3 = ctx->v3; + + if (outlen != (size_t)ctx->hash_size) + return 0; + + switch (ctx->len) { + case 7: + b |= ((uint64_t)ctx->leavings[6]) << 48; + /* fall thru */ + case 6: + b |= ((uint64_t)ctx->leavings[5]) << 40; + /* fall thru */ + case 5: + b |= ((uint64_t)ctx->leavings[4]) << 32; + /* fall thru */ + case 4: + b |= ((uint64_t)ctx->leavings[3]) << 24; + /* fall thru */ + case 3: + b |= ((uint64_t)ctx->leavings[2]) << 16; + /* fall thru */ + case 2: + b |= ((uint64_t)ctx->leavings[1]) << 8; + /* fall thru */ + case 1: + b |= ((uint64_t)ctx->leavings[0]); + case 0: + break; + } + + v3 ^= b; + for (i = 0; i < ctx->crounds; ++i) + SIPROUND; + v0 ^= b; + if (ctx->hash_size == SIPHASH_MAX_DIGEST_SIZE) + v2 ^= 0xee; + else + v2 ^= 0xff; + for (i = 0; i < ctx->drounds; ++i) + SIPROUND; + b = v0 ^ v1 ^ v2 ^ v3; + U64TO8_LE(out, b); + if (ctx->hash_size == SIPHASH_MIN_DIGEST_SIZE) + return 1; + v1 ^= 0xdd; + for (i = 0; i < ctx->drounds; ++i) + SIPROUND; + b = v0 ^ v1 ^ v2 ^ v3; + U64TO8_LE(out + 8, b); + return 1; +} diff --git a/crypto/siphash/siphash_ameth.c b/crypto/siphash/siphash_ameth.c new file mode 100644 index 00000000..d819461f --- /dev/null +++ b/crypto/siphash/siphash_ameth.c @@ -0,0 +1,68 @@ +/* + * Copyright 2007-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 +#include "internal/cryptlib.h" +#include +#include "internal/asn1_int.h" +#include "internal/siphash.h" +#include "siphash_local.h" + +/* + * SIPHASH "ASN1" method. This is just here to indicate the maximum + * SIPHASH output length and to free up a SIPHASH key. + */ + +static int siphash_size(const EVP_PKEY *pkey) +{ + return SIPHASH_MAX_DIGEST_SIZE; +} + +static void siphash_key_free(EVP_PKEY *pkey) +{ + ASN1_OCTET_STRING *os = EVP_PKEY_get0(pkey); + + if (os != NULL) { + if (os->data != NULL) + OPENSSL_cleanse(os->data, os->length); + ASN1_OCTET_STRING_free(os); + } +} + +static int siphash_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2) +{ + /* nothing (including ASN1_PKEY_CTRL_DEFAULT_MD_NID), is supported */ + return -2; +} + +static int siphash_pkey_public_cmp(const EVP_PKEY *a, const EVP_PKEY *b) +{ + return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b)); +} + +const EVP_PKEY_ASN1_METHOD siphash_asn1_meth = { + EVP_PKEY_SIPHASH, + EVP_PKEY_SIPHASH, + 0, + + "SIPHASH", + "OpenSSL SIPHASH method", + + 0, 0, siphash_pkey_public_cmp, 0, + + 0, 0, 0, + + siphash_size, + 0, 0, + 0, 0, 0, 0, 0, 0, 0, + + siphash_key_free, + siphash_pkey_ctrl, + 0, 0 +}; diff --git a/crypto/siphash/siphash_local.h b/crypto/siphash/siphash_local.h new file mode 100644 index 00000000..5ad34764 --- /dev/null +++ b/crypto/siphash/siphash_local.h @@ -0,0 +1,23 @@ +/* + * 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 + */ + +/* Based on https://131002.net/siphash C reference implementation */ + +struct siphash_st { + uint64_t total_inlen; + uint64_t v0; + uint64_t v1; + uint64_t v2; + uint64_t v3; + unsigned int len; + int hash_size; + int crounds; + int drounds; + unsigned char leavings[SIPHASH_BLOCK_SIZE]; +}; diff --git a/crypto/siphash/siphash_pmeth.c b/crypto/siphash/siphash_pmeth.c new file mode 100644 index 00000000..ae16e558 --- /dev/null +++ b/crypto/siphash/siphash_pmeth.c @@ -0,0 +1,206 @@ +/* + * Copyright 2007-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 +#include "internal/cryptlib.h" +#include +#include +#include +#include "internal/siphash.h" +#include "siphash_local.h" +#include "internal/evp_int.h" + +/* SIPHASH pkey context structure */ + +typedef struct siphash_pkey_ctx_st { + ASN1_OCTET_STRING ktmp; /* Temp storage for key */ + SIPHASH ctx; +} SIPHASH_PKEY_CTX; + +static int pkey_siphash_init(EVP_PKEY_CTX *ctx) +{ + SIPHASH_PKEY_CTX *pctx; + + pctx = OPENSSL_zalloc(sizeof(*pctx)); + if (pctx == NULL) + return 0; + pctx->ktmp.type = V_ASN1_OCTET_STRING; + + EVP_PKEY_CTX_set_data(ctx, pctx); + EVP_PKEY_CTX_set0_keygen_info(ctx, NULL, 0); + return 1; +} + +static void pkey_siphash_cleanup(EVP_PKEY_CTX *ctx) +{ + SIPHASH_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx); + + if (pctx != NULL) { + OPENSSL_clear_free(pctx->ktmp.data, pctx->ktmp.length); + OPENSSL_clear_free(pctx, sizeof(*pctx)); + EVP_PKEY_CTX_set_data(ctx, NULL); + } +} + +static int pkey_siphash_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) +{ + SIPHASH_PKEY_CTX *sctx, *dctx; + + /* allocate memory for dst->data and a new SIPHASH_CTX in dst->data->ctx */ + if (!pkey_siphash_init(dst)) + return 0; + sctx = EVP_PKEY_CTX_get_data(src); + dctx = EVP_PKEY_CTX_get_data(dst); + if (ASN1_STRING_get0_data(&sctx->ktmp) != NULL && + !ASN1_STRING_copy(&dctx->ktmp, &sctx->ktmp)) { + /* cleanup and free the SIPHASH_PKEY_CTX in dst->data */ + pkey_siphash_cleanup(dst); + return 0; + } + memcpy(&dctx->ctx, &sctx->ctx, sizeof(SIPHASH)); + return 1; +} + +static int pkey_siphash_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) +{ + ASN1_OCTET_STRING *key; + SIPHASH_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx); + + if (ASN1_STRING_get0_data(&pctx->ktmp) == NULL) + return 0; + key = ASN1_OCTET_STRING_dup(&pctx->ktmp); + if (key == NULL) + return 0; + return EVP_PKEY_assign_SIPHASH(pkey, key); +} + +static int int_update(EVP_MD_CTX *ctx, const void *data, size_t count) +{ + SIPHASH_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(EVP_MD_CTX_pkey_ctx(ctx)); + + SipHash_Update(&pctx->ctx, data, count); + return 1; +} + +static int siphash_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx) +{ + SIPHASH_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx); + const unsigned char* key; + size_t len; + int hash_size; + + key = EVP_PKEY_get0_siphash(EVP_PKEY_CTX_get0_pkey(ctx), &len); + if (key == NULL || len != SIPHASH_KEY_SIZE) + return 0; + EVP_MD_CTX_set_flags(mctx, EVP_MD_CTX_FLAG_NO_INIT); + EVP_MD_CTX_set_update_fn(mctx, int_update); + /* use default rounds (2,4) */ + hash_size = SipHash_hash_size(&pctx->ctx); + return SipHash_Init(&pctx->ctx, key, hash_size, 0, 0); +} +static int siphash_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, + EVP_MD_CTX *mctx) +{ + SIPHASH_PKEY_CTX *pctx = ctx->data; + + *siglen = SipHash_hash_size(&pctx->ctx); + if (sig != NULL) + return SipHash_Final(&pctx->ctx, sig, *siglen); + return 1; +} + +static int pkey_siphash_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) +{ + SIPHASH_PKEY_CTX *pctx = EVP_PKEY_CTX_get_data(ctx); + const unsigned char *key; + size_t len; + int hash_size; + + switch (type) { + + case EVP_PKEY_CTRL_MD: + /* ignore */ + break; + + case EVP_PKEY_CTRL_SET_DIGEST_SIZE: + if (p1 != SIPHASH_MIN_DIGEST_SIZE && + p1 != SIPHASH_MAX_DIGEST_SIZE) { + return 0; + } + /* use default rounds (2,4) */ + return SipHash_Init(&pctx->ctx, ASN1_STRING_get0_data(&pctx->ktmp), p1, 0, 0); + + case EVP_PKEY_CTRL_SET_MAC_KEY: + case EVP_PKEY_CTRL_DIGESTINIT: + if (type == EVP_PKEY_CTRL_SET_MAC_KEY) { + /* user explicitly setting the key */ + key = p2; + len = p1; + } else { + /* user indirectly setting the key via EVP_DigestSignInit */ + key = EVP_PKEY_get0_siphash(EVP_PKEY_CTX_get0_pkey(ctx), &len); + } + if (key == NULL || len != SIPHASH_KEY_SIZE || + !ASN1_OCTET_STRING_set(&pctx->ktmp, key, len)) + return 0; + /* use default rounds (2,4) */ + hash_size = SipHash_hash_size(&pctx->ctx); + return SipHash_Init(&pctx->ctx, ASN1_STRING_get0_data(&pctx->ktmp), hash_size, 0, 0); + + default: + return -2; + + } + return 1; +} + +static int pkey_siphash_ctrl_str(EVP_PKEY_CTX *ctx, + const char *type, const char *value) +{ + if (value == NULL) + return 0; + if (strcmp(type, "key") == 0) + return EVP_PKEY_CTX_str2ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, value); + if (strcmp(type, "hexkey") == 0) + return EVP_PKEY_CTX_hex2ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, value); + return -2; +} + +const EVP_PKEY_METHOD siphash_pkey_meth = { + EVP_PKEY_SIPHASH, + EVP_PKEY_FLAG_SIGCTX_CUSTOM, /* we don't deal with a separate MD */ + pkey_siphash_init, + pkey_siphash_copy, + pkey_siphash_cleanup, + + 0, 0, + + 0, + pkey_siphash_keygen, + + 0, 0, + + 0, 0, + + 0, 0, + + siphash_signctx_init, + siphash_signctx, + + 0, 0, + + 0, 0, + + 0, 0, + + 0, 0, + + pkey_siphash_ctrl, + pkey_siphash_ctrl_str +}; diff --git a/crypto/sm3/build.info b/crypto/sm3/build.info new file mode 100644 index 00000000..6009b194 --- /dev/null +++ b/crypto/sm3/build.info @@ -0,0 +1,2 @@ +LIBS=../../libcrypto +SOURCE[../../libcrypto]=sm3.c m_sm3.c diff --git a/crypto/sm3/m_sm3.c b/crypto/sm3/m_sm3.c new file mode 100644 index 00000000..85538dc8 --- /dev/null +++ b/crypto/sm3/m_sm3.c @@ -0,0 +1,52 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 Ribose Inc. 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 "internal/cryptlib.h" + +#ifndef OPENSSL_NO_SM3 +# include +# include "internal/evp_int.h" +# include "internal/sm3.h" + +static int init(EVP_MD_CTX *ctx) +{ + return sm3_init(EVP_MD_CTX_md_data(ctx)); +} + +static int update(EVP_MD_CTX *ctx, const void *data, size_t count) +{ + return sm3_update(EVP_MD_CTX_md_data(ctx), data, count); +} + +static int final(EVP_MD_CTX *ctx, unsigned char *md) +{ + return sm3_final(md, EVP_MD_CTX_md_data(ctx)); +} + +static const EVP_MD sm3_md = { + NID_sm3, + NID_sm3WithRSAEncryption, + SM3_DIGEST_LENGTH, + 0, + init, + update, + final, + NULL, + NULL, + SM3_CBLOCK, + sizeof(EVP_MD *) + sizeof(SM3_CTX), +}; + +const EVP_MD *EVP_sm3(void) +{ + return &sm3_md; +} + +#endif diff --git a/crypto/sm3/sm3.c b/crypto/sm3/sm3.c new file mode 100644 index 00000000..1588dd11 --- /dev/null +++ b/crypto/sm3/sm3.c @@ -0,0 +1,196 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 Ribose Inc. All Rights Reserved. + * Ported from Ribose contributions from Botan. + * + * 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 +#include "sm3_locl.h" + +int sm3_init(SM3_CTX *c) +{ + memset(c, 0, sizeof(*c)); + c->A = SM3_A; + c->B = SM3_B; + c->C = SM3_C; + c->D = SM3_D; + c->E = SM3_E; + c->F = SM3_F; + c->G = SM3_G; + c->H = SM3_H; + return 1; +} + +void sm3_block_data_order(SM3_CTX *ctx, const void *p, size_t num) +{ + const unsigned char *data = p; + register unsigned MD32_REG_T A, B, C, D, E, F, G, H; + + unsigned MD32_REG_T W00, W01, W02, W03, W04, W05, W06, W07, + W08, W09, W10, W11, W12, W13, W14, W15; + + for (; num--;) { + + A = ctx->A; + B = ctx->B; + C = ctx->C; + D = ctx->D; + E = ctx->E; + F = ctx->F; + G = ctx->G; + H = ctx->H; + + /* + * We have to load all message bytes immediately since SM3 reads + * them slightly out of order. + */ + (void)HOST_c2l(data, W00); + (void)HOST_c2l(data, W01); + (void)HOST_c2l(data, W02); + (void)HOST_c2l(data, W03); + (void)HOST_c2l(data, W04); + (void)HOST_c2l(data, W05); + (void)HOST_c2l(data, W06); + (void)HOST_c2l(data, W07); + (void)HOST_c2l(data, W08); + (void)HOST_c2l(data, W09); + (void)HOST_c2l(data, W10); + (void)HOST_c2l(data, W11); + (void)HOST_c2l(data, W12); + (void)HOST_c2l(data, W13); + (void)HOST_c2l(data, W14); + (void)HOST_c2l(data, W15); + + R1(A, B, C, D, E, F, G, H, 0x79CC4519, W00, W00 ^ W04); + W00 = EXPAND(W00, W07, W13, W03, W10); + R1(D, A, B, C, H, E, F, G, 0xF3988A32, W01, W01 ^ W05); + W01 = EXPAND(W01, W08, W14, W04, W11); + R1(C, D, A, B, G, H, E, F, 0xE7311465, W02, W02 ^ W06); + W02 = EXPAND(W02, W09, W15, W05, W12); + R1(B, C, D, A, F, G, H, E, 0xCE6228CB, W03, W03 ^ W07); + W03 = EXPAND(W03, W10, W00, W06, W13); + R1(A, B, C, D, E, F, G, H, 0x9CC45197, W04, W04 ^ W08); + W04 = EXPAND(W04, W11, W01, W07, W14); + R1(D, A, B, C, H, E, F, G, 0x3988A32F, W05, W05 ^ W09); + W05 = EXPAND(W05, W12, W02, W08, W15); + R1(C, D, A, B, G, H, E, F, 0x7311465E, W06, W06 ^ W10); + W06 = EXPAND(W06, W13, W03, W09, W00); + R1(B, C, D, A, F, G, H, E, 0xE6228CBC, W07, W07 ^ W11); + W07 = EXPAND(W07, W14, W04, W10, W01); + R1(A, B, C, D, E, F, G, H, 0xCC451979, W08, W08 ^ W12); + W08 = EXPAND(W08, W15, W05, W11, W02); + R1(D, A, B, C, H, E, F, G, 0x988A32F3, W09, W09 ^ W13); + W09 = EXPAND(W09, W00, W06, W12, W03); + R1(C, D, A, B, G, H, E, F, 0x311465E7, W10, W10 ^ W14); + W10 = EXPAND(W10, W01, W07, W13, W04); + R1(B, C, D, A, F, G, H, E, 0x6228CBCE, W11, W11 ^ W15); + W11 = EXPAND(W11, W02, W08, W14, W05); + R1(A, B, C, D, E, F, G, H, 0xC451979C, W12, W12 ^ W00); + W12 = EXPAND(W12, W03, W09, W15, W06); + R1(D, A, B, C, H, E, F, G, 0x88A32F39, W13, W13 ^ W01); + W13 = EXPAND(W13, W04, W10, W00, W07); + R1(C, D, A, B, G, H, E, F, 0x11465E73, W14, W14 ^ W02); + W14 = EXPAND(W14, W05, W11, W01, W08); + R1(B, C, D, A, F, G, H, E, 0x228CBCE6, W15, W15 ^ W03); + W15 = EXPAND(W15, W06, W12, W02, W09); + R2(A, B, C, D, E, F, G, H, 0x9D8A7A87, W00, W00 ^ W04); + W00 = EXPAND(W00, W07, W13, W03, W10); + R2(D, A, B, C, H, E, F, G, 0x3B14F50F, W01, W01 ^ W05); + W01 = EXPAND(W01, W08, W14, W04, W11); + R2(C, D, A, B, G, H, E, F, 0x7629EA1E, W02, W02 ^ W06); + W02 = EXPAND(W02, W09, W15, W05, W12); + R2(B, C, D, A, F, G, H, E, 0xEC53D43C, W03, W03 ^ W07); + W03 = EXPAND(W03, W10, W00, W06, W13); + R2(A, B, C, D, E, F, G, H, 0xD8A7A879, W04, W04 ^ W08); + W04 = EXPAND(W04, W11, W01, W07, W14); + R2(D, A, B, C, H, E, F, G, 0xB14F50F3, W05, W05 ^ W09); + W05 = EXPAND(W05, W12, W02, W08, W15); + R2(C, D, A, B, G, H, E, F, 0x629EA1E7, W06, W06 ^ W10); + W06 = EXPAND(W06, W13, W03, W09, W00); + R2(B, C, D, A, F, G, H, E, 0xC53D43CE, W07, W07 ^ W11); + W07 = EXPAND(W07, W14, W04, W10, W01); + R2(A, B, C, D, E, F, G, H, 0x8A7A879D, W08, W08 ^ W12); + W08 = EXPAND(W08, W15, W05, W11, W02); + R2(D, A, B, C, H, E, F, G, 0x14F50F3B, W09, W09 ^ W13); + W09 = EXPAND(W09, W00, W06, W12, W03); + R2(C, D, A, B, G, H, E, F, 0x29EA1E76, W10, W10 ^ W14); + W10 = EXPAND(W10, W01, W07, W13, W04); + R2(B, C, D, A, F, G, H, E, 0x53D43CEC, W11, W11 ^ W15); + W11 = EXPAND(W11, W02, W08, W14, W05); + R2(A, B, C, D, E, F, G, H, 0xA7A879D8, W12, W12 ^ W00); + W12 = EXPAND(W12, W03, W09, W15, W06); + R2(D, A, B, C, H, E, F, G, 0x4F50F3B1, W13, W13 ^ W01); + W13 = EXPAND(W13, W04, W10, W00, W07); + R2(C, D, A, B, G, H, E, F, 0x9EA1E762, W14, W14 ^ W02); + W14 = EXPAND(W14, W05, W11, W01, W08); + R2(B, C, D, A, F, G, H, E, 0x3D43CEC5, W15, W15 ^ W03); + W15 = EXPAND(W15, W06, W12, W02, W09); + R2(A, B, C, D, E, F, G, H, 0x7A879D8A, W00, W00 ^ W04); + W00 = EXPAND(W00, W07, W13, W03, W10); + R2(D, A, B, C, H, E, F, G, 0xF50F3B14, W01, W01 ^ W05); + W01 = EXPAND(W01, W08, W14, W04, W11); + R2(C, D, A, B, G, H, E, F, 0xEA1E7629, W02, W02 ^ W06); + W02 = EXPAND(W02, W09, W15, W05, W12); + R2(B, C, D, A, F, G, H, E, 0xD43CEC53, W03, W03 ^ W07); + W03 = EXPAND(W03, W10, W00, W06, W13); + R2(A, B, C, D, E, F, G, H, 0xA879D8A7, W04, W04 ^ W08); + W04 = EXPAND(W04, W11, W01, W07, W14); + R2(D, A, B, C, H, E, F, G, 0x50F3B14F, W05, W05 ^ W09); + W05 = EXPAND(W05, W12, W02, W08, W15); + R2(C, D, A, B, G, H, E, F, 0xA1E7629E, W06, W06 ^ W10); + W06 = EXPAND(W06, W13, W03, W09, W00); + R2(B, C, D, A, F, G, H, E, 0x43CEC53D, W07, W07 ^ W11); + W07 = EXPAND(W07, W14, W04, W10, W01); + R2(A, B, C, D, E, F, G, H, 0x879D8A7A, W08, W08 ^ W12); + W08 = EXPAND(W08, W15, W05, W11, W02); + R2(D, A, B, C, H, E, F, G, 0x0F3B14F5, W09, W09 ^ W13); + W09 = EXPAND(W09, W00, W06, W12, W03); + R2(C, D, A, B, G, H, E, F, 0x1E7629EA, W10, W10 ^ W14); + W10 = EXPAND(W10, W01, W07, W13, W04); + R2(B, C, D, A, F, G, H, E, 0x3CEC53D4, W11, W11 ^ W15); + W11 = EXPAND(W11, W02, W08, W14, W05); + R2(A, B, C, D, E, F, G, H, 0x79D8A7A8, W12, W12 ^ W00); + W12 = EXPAND(W12, W03, W09, W15, W06); + R2(D, A, B, C, H, E, F, G, 0xF3B14F50, W13, W13 ^ W01); + W13 = EXPAND(W13, W04, W10, W00, W07); + R2(C, D, A, B, G, H, E, F, 0xE7629EA1, W14, W14 ^ W02); + W14 = EXPAND(W14, W05, W11, W01, W08); + R2(B, C, D, A, F, G, H, E, 0xCEC53D43, W15, W15 ^ W03); + W15 = EXPAND(W15, W06, W12, W02, W09); + R2(A, B, C, D, E, F, G, H, 0x9D8A7A87, W00, W00 ^ W04); + W00 = EXPAND(W00, W07, W13, W03, W10); + R2(D, A, B, C, H, E, F, G, 0x3B14F50F, W01, W01 ^ W05); + W01 = EXPAND(W01, W08, W14, W04, W11); + R2(C, D, A, B, G, H, E, F, 0x7629EA1E, W02, W02 ^ W06); + W02 = EXPAND(W02, W09, W15, W05, W12); + R2(B, C, D, A, F, G, H, E, 0xEC53D43C, W03, W03 ^ W07); + W03 = EXPAND(W03, W10, W00, W06, W13); + R2(A, B, C, D, E, F, G, H, 0xD8A7A879, W04, W04 ^ W08); + R2(D, A, B, C, H, E, F, G, 0xB14F50F3, W05, W05 ^ W09); + R2(C, D, A, B, G, H, E, F, 0x629EA1E7, W06, W06 ^ W10); + R2(B, C, D, A, F, G, H, E, 0xC53D43CE, W07, W07 ^ W11); + R2(A, B, C, D, E, F, G, H, 0x8A7A879D, W08, W08 ^ W12); + R2(D, A, B, C, H, E, F, G, 0x14F50F3B, W09, W09 ^ W13); + R2(C, D, A, B, G, H, E, F, 0x29EA1E76, W10, W10 ^ W14); + R2(B, C, D, A, F, G, H, E, 0x53D43CEC, W11, W11 ^ W15); + R2(A, B, C, D, E, F, G, H, 0xA7A879D8, W12, W12 ^ W00); + R2(D, A, B, C, H, E, F, G, 0x4F50F3B1, W13, W13 ^ W01); + R2(C, D, A, B, G, H, E, F, 0x9EA1E762, W14, W14 ^ W02); + R2(B, C, D, A, F, G, H, E, 0x3D43CEC5, W15, W15 ^ W03); + + ctx->A ^= A; + ctx->B ^= B; + ctx->C ^= C; + ctx->D ^= D; + ctx->E ^= E; + ctx->F ^= F; + ctx->G ^= G; + ctx->H ^= H; + } +} + diff --git a/crypto/sm3/sm3_locl.h b/crypto/sm3/sm3_locl.h new file mode 100644 index 00000000..efa6db57 --- /dev/null +++ b/crypto/sm3/sm3_locl.h @@ -0,0 +1,79 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 Ribose Inc. All Rights Reserved. + * Ported from Ribose contributions from Botan. + * + * 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 +#include "internal/sm3.h" + +#define DATA_ORDER_IS_BIG_ENDIAN + +#define HASH_LONG SM3_WORD +#define HASH_CTX SM3_CTX +#define HASH_CBLOCK SM3_CBLOCK +#define HASH_UPDATE sm3_update +#define HASH_TRANSFORM sm3_transform +#define HASH_FINAL sm3_final +#define HASH_MAKE_STRING(c, s) \ + do { \ + unsigned long ll; \ + ll=(c)->A; (void)HOST_l2c(ll, (s)); \ + ll=(c)->B; (void)HOST_l2c(ll, (s)); \ + ll=(c)->C; (void)HOST_l2c(ll, (s)); \ + ll=(c)->D; (void)HOST_l2c(ll, (s)); \ + ll=(c)->E; (void)HOST_l2c(ll, (s)); \ + ll=(c)->F; (void)HOST_l2c(ll, (s)); \ + ll=(c)->G; (void)HOST_l2c(ll, (s)); \ + ll=(c)->H; (void)HOST_l2c(ll, (s)); \ + } while (0) +#define HASH_BLOCK_DATA_ORDER sm3_block_data_order + +void sm3_transform(SM3_CTX *c, const unsigned char *data); + +#include "internal/md32_common.h" + +#define P0(X) (X ^ ROTATE(X, 9) ^ ROTATE(X, 17)) +#define P1(X) (X ^ ROTATE(X, 15) ^ ROTATE(X, 23)) + +#define FF0(X,Y,Z) (X ^ Y ^ Z) +#define GG0(X,Y,Z) (X ^ Y ^ Z) + +#define FF1(X,Y,Z) ((X & Y) | ((X | Y) & Z)) +#define GG1(X,Y,Z) ((Z ^ (X & (Y ^ Z)))) + +#define EXPAND(W0,W7,W13,W3,W10) \ + (P1(W0 ^ W7 ^ ROTATE(W13, 15)) ^ ROTATE(W3, 7) ^ W10) + +#define RND(A, B, C, D, E, F, G, H, TJ, Wi, Wj, FF, GG) \ + do { \ + const SM3_WORD A12 = ROTATE(A, 12); \ + const SM3_WORD A12_SM = A12 + E + TJ; \ + const SM3_WORD SS1 = ROTATE(A12_SM, 7); \ + const SM3_WORD TT1 = FF(A, B, C) + D + (SS1 ^ A12) + (Wj); \ + const SM3_WORD TT2 = GG(E, F, G) + H + SS1 + Wi; \ + B = ROTATE(B, 9); \ + D = TT1; \ + F = ROTATE(F, 19); \ + H = P0(TT2); \ + } while(0) + +#define R1(A,B,C,D,E,F,G,H,TJ,Wi,Wj) \ + RND(A,B,C,D,E,F,G,H,TJ,Wi,Wj,FF0,GG0) + +#define R2(A,B,C,D,E,F,G,H,TJ,Wi,Wj) \ + RND(A,B,C,D,E,F,G,H,TJ,Wi,Wj,FF1,GG1) + +#define SM3_A 0x7380166fUL +#define SM3_B 0x4914b2b9UL +#define SM3_C 0x172442d7UL +#define SM3_D 0xda8a0600UL +#define SM3_E 0xa96f30bcUL +#define SM3_F 0x163138aaUL +#define SM3_G 0xe38dee4dUL +#define SM3_H 0xb0fb0e4eUL diff --git a/crypto/sm4/build.info b/crypto/sm4/build.info new file mode 100644 index 00000000..b65a7d14 --- /dev/null +++ b/crypto/sm4/build.info @@ -0,0 +1,4 @@ +LIBS=../../libcrypto +SOURCE[../../libcrypto]=\ + sm4.c + diff --git a/crypto/sm4/sm4.c b/crypto/sm4/sm4.c new file mode 100644 index 00000000..0c819a4b --- /dev/null +++ b/crypto/sm4/sm4.c @@ -0,0 +1,233 @@ +/* + * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2017 Ribose Inc. All Rights Reserved. + * Ported from Ribose contributions from Botan. + * + * 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 +#include "internal/sm4.h" + +static const uint8_t SM4_S[256] = { + 0xD6, 0x90, 0xE9, 0xFE, 0xCC, 0xE1, 0x3D, 0xB7, 0x16, 0xB6, 0x14, 0xC2, + 0x28, 0xFB, 0x2C, 0x05, 0x2B, 0x67, 0x9A, 0x76, 0x2A, 0xBE, 0x04, 0xC3, + 0xAA, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, 0x9C, 0x42, 0x50, 0xF4, + 0x91, 0xEF, 0x98, 0x7A, 0x33, 0x54, 0x0B, 0x43, 0xED, 0xCF, 0xAC, 0x62, + 0xE4, 0xB3, 0x1C, 0xA9, 0xC9, 0x08, 0xE8, 0x95, 0x80, 0xDF, 0x94, 0xFA, + 0x75, 0x8F, 0x3F, 0xA6, 0x47, 0x07, 0xA7, 0xFC, 0xF3, 0x73, 0x17, 0xBA, + 0x83, 0x59, 0x3C, 0x19, 0xE6, 0x85, 0x4F, 0xA8, 0x68, 0x6B, 0x81, 0xB2, + 0x71, 0x64, 0xDA, 0x8B, 0xF8, 0xEB, 0x0F, 0x4B, 0x70, 0x56, 0x9D, 0x35, + 0x1E, 0x24, 0x0E, 0x5E, 0x63, 0x58, 0xD1, 0xA2, 0x25, 0x22, 0x7C, 0x3B, + 0x01, 0x21, 0x78, 0x87, 0xD4, 0x00, 0x46, 0x57, 0x9F, 0xD3, 0x27, 0x52, + 0x4C, 0x36, 0x02, 0xE7, 0xA0, 0xC4, 0xC8, 0x9E, 0xEA, 0xBF, 0x8A, 0xD2, + 0x40, 0xC7, 0x38, 0xB5, 0xA3, 0xF7, 0xF2, 0xCE, 0xF9, 0x61, 0x15, 0xA1, + 0xE0, 0xAE, 0x5D, 0xA4, 0x9B, 0x34, 0x1A, 0x55, 0xAD, 0x93, 0x32, 0x30, + 0xF5, 0x8C, 0xB1, 0xE3, 0x1D, 0xF6, 0xE2, 0x2E, 0x82, 0x66, 0xCA, 0x60, + 0xC0, 0x29, 0x23, 0xAB, 0x0D, 0x53, 0x4E, 0x6F, 0xD5, 0xDB, 0x37, 0x45, + 0xDE, 0xFD, 0x8E, 0x2F, 0x03, 0xFF, 0x6A, 0x72, 0x6D, 0x6C, 0x5B, 0x51, + 0x8D, 0x1B, 0xAF, 0x92, 0xBB, 0xDD, 0xBC, 0x7F, 0x11, 0xD9, 0x5C, 0x41, + 0x1F, 0x10, 0x5A, 0xD8, 0x0A, 0xC1, 0x31, 0x88, 0xA5, 0xCD, 0x7B, 0xBD, + 0x2D, 0x74, 0xD0, 0x12, 0xB8, 0xE5, 0xB4, 0xB0, 0x89, 0x69, 0x97, 0x4A, + 0x0C, 0x96, 0x77, 0x7E, 0x65, 0xB9, 0xF1, 0x09, 0xC5, 0x6E, 0xC6, 0x84, + 0x18, 0xF0, 0x7D, 0xEC, 0x3A, 0xDC, 0x4D, 0x20, 0x79, 0xEE, 0x5F, 0x3E, + 0xD7, 0xCB, 0x39, 0x48 +}; + +/* + * SM4_SBOX_T[j] == L(SM4_SBOX[j]). + */ +static const uint32_t SM4_SBOX_T[256] = { + 0x8ED55B5B, 0xD0924242, 0x4DEAA7A7, 0x06FDFBFB, 0xFCCF3333, 0x65E28787, + 0xC93DF4F4, 0x6BB5DEDE, 0x4E165858, 0x6EB4DADA, 0x44145050, 0xCAC10B0B, + 0x8828A0A0, 0x17F8EFEF, 0x9C2CB0B0, 0x11051414, 0x872BACAC, 0xFB669D9D, + 0xF2986A6A, 0xAE77D9D9, 0x822AA8A8, 0x46BCFAFA, 0x14041010, 0xCFC00F0F, + 0x02A8AAAA, 0x54451111, 0x5F134C4C, 0xBE269898, 0x6D482525, 0x9E841A1A, + 0x1E061818, 0xFD9B6666, 0xEC9E7272, 0x4A430909, 0x10514141, 0x24F7D3D3, + 0xD5934646, 0x53ECBFBF, 0xF89A6262, 0x927BE9E9, 0xFF33CCCC, 0x04555151, + 0x270B2C2C, 0x4F420D0D, 0x59EEB7B7, 0xF3CC3F3F, 0x1CAEB2B2, 0xEA638989, + 0x74E79393, 0x7FB1CECE, 0x6C1C7070, 0x0DABA6A6, 0xEDCA2727, 0x28082020, + 0x48EBA3A3, 0xC1975656, 0x80820202, 0xA3DC7F7F, 0xC4965252, 0x12F9EBEB, + 0xA174D5D5, 0xB38D3E3E, 0xC33FFCFC, 0x3EA49A9A, 0x5B461D1D, 0x1B071C1C, + 0x3BA59E9E, 0x0CFFF3F3, 0x3FF0CFCF, 0xBF72CDCD, 0x4B175C5C, 0x52B8EAEA, + 0x8F810E0E, 0x3D586565, 0xCC3CF0F0, 0x7D196464, 0x7EE59B9B, 0x91871616, + 0x734E3D3D, 0x08AAA2A2, 0xC869A1A1, 0xC76AADAD, 0x85830606, 0x7AB0CACA, + 0xB570C5C5, 0xF4659191, 0xB2D96B6B, 0xA7892E2E, 0x18FBE3E3, 0x47E8AFAF, + 0x330F3C3C, 0x674A2D2D, 0xB071C1C1, 0x0E575959, 0xE99F7676, 0xE135D4D4, + 0x661E7878, 0xB4249090, 0x360E3838, 0x265F7979, 0xEF628D8D, 0x38596161, + 0x95D24747, 0x2AA08A8A, 0xB1259494, 0xAA228888, 0x8C7DF1F1, 0xD73BECEC, + 0x05010404, 0xA5218484, 0x9879E1E1, 0x9B851E1E, 0x84D75353, 0x00000000, + 0x5E471919, 0x0B565D5D, 0xE39D7E7E, 0x9FD04F4F, 0xBB279C9C, 0x1A534949, + 0x7C4D3131, 0xEE36D8D8, 0x0A020808, 0x7BE49F9F, 0x20A28282, 0xD4C71313, + 0xE8CB2323, 0xE69C7A7A, 0x42E9ABAB, 0x43BDFEFE, 0xA2882A2A, 0x9AD14B4B, + 0x40410101, 0xDBC41F1F, 0xD838E0E0, 0x61B7D6D6, 0x2FA18E8E, 0x2BF4DFDF, + 0x3AF1CBCB, 0xF6CD3B3B, 0x1DFAE7E7, 0xE5608585, 0x41155454, 0x25A38686, + 0x60E38383, 0x16ACBABA, 0x295C7575, 0x34A69292, 0xF7996E6E, 0xE434D0D0, + 0x721A6868, 0x01545555, 0x19AFB6B6, 0xDF914E4E, 0xFA32C8C8, 0xF030C0C0, + 0x21F6D7D7, 0xBC8E3232, 0x75B3C6C6, 0x6FE08F8F, 0x691D7474, 0x2EF5DBDB, + 0x6AE18B8B, 0x962EB8B8, 0x8A800A0A, 0xFE679999, 0xE2C92B2B, 0xE0618181, + 0xC0C30303, 0x8D29A4A4, 0xAF238C8C, 0x07A9AEAE, 0x390D3434, 0x1F524D4D, + 0x764F3939, 0xD36EBDBD, 0x81D65757, 0xB7D86F6F, 0xEB37DCDC, 0x51441515, + 0xA6DD7B7B, 0x09FEF7F7, 0xB68C3A3A, 0x932FBCBC, 0x0F030C0C, 0x03FCFFFF, + 0xC26BA9A9, 0xBA73C9C9, 0xD96CB5B5, 0xDC6DB1B1, 0x375A6D6D, 0x15504545, + 0xB98F3636, 0x771B6C6C, 0x13ADBEBE, 0xDA904A4A, 0x57B9EEEE, 0xA9DE7777, + 0x4CBEF2F2, 0x837EFDFD, 0x55114444, 0xBDDA6767, 0x2C5D7171, 0x45400505, + 0x631F7C7C, 0x50104040, 0x325B6969, 0xB8DB6363, 0x220A2828, 0xC5C20707, + 0xF531C4C4, 0xA88A2222, 0x31A79696, 0xF9CE3737, 0x977AEDED, 0x49BFF6F6, + 0x992DB4B4, 0xA475D1D1, 0x90D34343, 0x5A124848, 0x58BAE2E2, 0x71E69797, + 0x64B6D2D2, 0x70B2C2C2, 0xAD8B2626, 0xCD68A5A5, 0xCB955E5E, 0x624B2929, + 0x3C0C3030, 0xCE945A5A, 0xAB76DDDD, 0x867FF9F9, 0xF1649595, 0x5DBBE6E6, + 0x35F2C7C7, 0x2D092424, 0xD1C61717, 0xD66FB9B9, 0xDEC51B1B, 0x94861212, + 0x78186060, 0x30F3C3C3, 0x897CF5F5, 0x5CEFB3B3, 0xD23AE8E8, 0xACDF7373, + 0x794C3535, 0xA0208080, 0x9D78E5E5, 0x56EDBBBB, 0x235E7D7D, 0xC63EF8F8, + 0x8BD45F5F, 0xE7C82F2F, 0xDD39E4E4, 0x68492121 }; + +static ossl_inline uint32_t rotl(uint32_t a, uint8_t n) +{ + return (a << n) | (a >> (32 - n)); +} + +static ossl_inline uint32_t load_u32_be(const uint8_t *b, uint32_t n) +{ + return ((uint32_t)b[4 * n] << 24) | + ((uint32_t)b[4 * n + 1] << 16) | + ((uint32_t)b[4 * n + 2] << 8) | + ((uint32_t)b[4 * n + 3]); +} + +static ossl_inline void store_u32_be(uint32_t v, uint8_t *b) +{ + b[0] = (uint8_t)(v >> 24); + b[1] = (uint8_t)(v >> 16); + b[2] = (uint8_t)(v >> 8); + b[3] = (uint8_t)(v); +} + +static ossl_inline uint32_t SM4_T_slow(uint32_t X) +{ + uint32_t t = 0; + + t |= ((uint32_t)SM4_S[(uint8_t)(X >> 24)]) << 24; + t |= ((uint32_t)SM4_S[(uint8_t)(X >> 16)]) << 16; + t |= ((uint32_t)SM4_S[(uint8_t)(X >> 8)]) << 8; + t |= SM4_S[(uint8_t)X]; + + /* + * L linear transform + */ + return t ^ rotl(t, 2) ^ rotl(t, 10) ^ rotl(t, 18) ^ rotl(t, 24); +} + +static ossl_inline uint32_t SM4_T(uint32_t X) +{ + return SM4_SBOX_T[(uint8_t)(X >> 24)] ^ + rotl(SM4_SBOX_T[(uint8_t)(X >> 16)], 24) ^ + rotl(SM4_SBOX_T[(uint8_t)(X >> 8)], 16) ^ + rotl(SM4_SBOX_T[(uint8_t)X], 8); +} + +int SM4_set_key(const uint8_t *key, SM4_KEY *ks) +{ + /* + * Family Key + */ + static const uint32_t FK[4] = + { 0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc }; + + /* + * Constant Key + */ + static const uint32_t CK[32] = { + 0x00070E15, 0x1C232A31, 0x383F464D, 0x545B6269, + 0x70777E85, 0x8C939AA1, 0xA8AFB6BD, 0xC4CBD2D9, + 0xE0E7EEF5, 0xFC030A11, 0x181F262D, 0x343B4249, + 0x50575E65, 0x6C737A81, 0x888F969D, 0xA4ABB2B9, + 0xC0C7CED5, 0xDCE3EAF1, 0xF8FF060D, 0x141B2229, + 0x30373E45, 0x4C535A61, 0x686F767D, 0x848B9299, + 0xA0A7AEB5, 0xBCC3CAD1, 0xD8DFE6ED, 0xF4FB0209, + 0x10171E25, 0x2C333A41, 0x484F565D, 0x646B7279 + }; + + uint32_t K[4]; + int i; + + K[0] = load_u32_be(key, 0) ^ FK[0]; + K[1] = load_u32_be(key, 1) ^ FK[1]; + K[2] = load_u32_be(key, 2) ^ FK[2]; + K[3] = load_u32_be(key, 3) ^ FK[3]; + + for (i = 0; i != SM4_KEY_SCHEDULE; ++i) { + uint32_t X = K[(i + 1) % 4] ^ K[(i + 2) % 4] ^ K[(i + 3) % 4] ^ CK[i]; + uint32_t t = 0; + + t |= ((uint32_t)SM4_S[(uint8_t)(X >> 24)]) << 24; + t |= ((uint32_t)SM4_S[(uint8_t)(X >> 16)]) << 16; + t |= ((uint32_t)SM4_S[(uint8_t)(X >> 8)]) << 8; + t |= SM4_S[(uint8_t)X]; + + t = t ^ rotl(t, 13) ^ rotl(t, 23); + K[i % 4] ^= t; + ks->rk[i] = K[i % 4]; + } + + return 1; +} + +#define SM4_RNDS(k0, k1, k2, k3, F) \ + do { \ + B0 ^= F(B1 ^ B2 ^ B3 ^ ks->rk[k0]); \ + B1 ^= F(B0 ^ B2 ^ B3 ^ ks->rk[k1]); \ + B2 ^= F(B0 ^ B1 ^ B3 ^ ks->rk[k2]); \ + B3 ^= F(B0 ^ B1 ^ B2 ^ ks->rk[k3]); \ + } while(0) + +void SM4_encrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks) +{ + uint32_t B0 = load_u32_be(in, 0); + uint32_t B1 = load_u32_be(in, 1); + uint32_t B2 = load_u32_be(in, 2); + uint32_t B3 = load_u32_be(in, 3); + + /* + * Uses byte-wise sbox in the first and last rounds to provide some + * protection from cache based side channels. + */ + SM4_RNDS( 0, 1, 2, 3, SM4_T_slow); + SM4_RNDS( 4, 5, 6, 7, SM4_T); + SM4_RNDS( 8, 9, 10, 11, SM4_T); + SM4_RNDS(12, 13, 14, 15, SM4_T); + SM4_RNDS(16, 17, 18, 19, SM4_T); + SM4_RNDS(20, 21, 22, 23, SM4_T); + SM4_RNDS(24, 25, 26, 27, SM4_T); + SM4_RNDS(28, 29, 30, 31, SM4_T_slow); + + store_u32_be(B3, out); + store_u32_be(B2, out + 4); + store_u32_be(B1, out + 8); + store_u32_be(B0, out + 12); +} + +void SM4_decrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks) +{ + uint32_t B0 = load_u32_be(in, 0); + uint32_t B1 = load_u32_be(in, 1); + uint32_t B2 = load_u32_be(in, 2); + uint32_t B3 = load_u32_be(in, 3); + + SM4_RNDS(31, 30, 29, 28, SM4_T_slow); + SM4_RNDS(27, 26, 25, 24, SM4_T); + SM4_RNDS(23, 22, 21, 20, SM4_T); + SM4_RNDS(19, 18, 17, 16, SM4_T); + SM4_RNDS(15, 14, 13, 12, SM4_T); + SM4_RNDS(11, 10, 9, 8, SM4_T); + SM4_RNDS( 7, 6, 5, 4, SM4_T); + SM4_RNDS( 3, 2, 1, 0, SM4_T_slow); + + store_u32_be(B3, out); + store_u32_be(B2, out + 4); + store_u32_be(B1, out + 8); + store_u32_be(B0, out + 12); +} diff --git a/crypto/sparccpuid.S b/crypto/sparccpuid.S index c6ca2247..95acd2f9 100644 --- a/crypto/sparccpuid.S +++ b/crypto/sparccpuid.S @@ -5,10 +5,6 @@ ! in the file LICENSE in the source distribution or at ! https://www.openssl.org/source/license.html -#ifdef OPENSSL_FIPSCANISTER -#include -#endif - #if defined(__SUNPRO_C) && defined(__sparcv9) # define ABI64 /* They've said -xarch=v9 at command line */ #elif defined(__GNUC__) && defined(__arch64__) diff --git a/crypto/sparcv9cap.c b/crypto/sparcv9cap.c index 61d0334e..c8c56753 100644 --- a/crypto/sparcv9cap.c +++ b/crypto/sparcv9cap.c @@ -15,6 +15,7 @@ #include #include #include +#include "internal/cryptlib.h" #include "sparc_arch.h" @@ -98,7 +99,7 @@ unsigned long _sparcv9_random(void); size_t _sparcv9_vis1_instrument_bus(unsigned int *, size_t); size_t _sparcv9_vis1_instrument_bus2(unsigned int *, size_t, size_t); -unsigned long OPENSSL_rdtsc(void) +uint32_t OPENSSL_rdtsc(void) { if (OPENSSL_sparcv9cap_P[0] & SPARCV9_TICK_PRIVILEGED) #if defined(__sun) && defined(__SVR4) diff --git a/crypto/srp/srp_vfy.c b/crypto/srp/srp_vfy.c index 29b7afcb..eb4a38d4 100644 --- a/crypto/srp/srp_vfy.c +++ b/crypto/srp/srp_vfy.c @@ -19,126 +19,26 @@ # define SRP_RANDOM_SALT_LEN 20 # define MAX_LEN 2500 -static char b64table[] = - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./"; - -/* - * the following two conversion routines have been inspired by code from - * Stanford - */ - /* * Convert a base64 string into raw byte array representation. */ static int t_fromb64(unsigned char *a, size_t alen, const char *src) { - char *loc; - int i, j; - int size; + size_t size = strlen(src); - if (alen == 0 || alen > INT_MAX) + /* Four bytes in src become three bytes output. */ + if (size > INT_MAX || (size / 4) * 3 > alen) return -1; - while (*src && (*src == ' ' || *src == '\t' || *src == '\n')) - ++src; - size = strlen(src); - if (size < 0 || size >= (int)alen) - return -1; - - i = 0; - while (i < size) { - loc = strchr(b64table, src[i]); - if (loc == (char *)0) - break; - else - a[i] = loc - b64table; - ++i; - } - /* if nothing valid to process we have a zero length response */ - if (i == 0) - return 0; - size = i; - i = size - 1; - j = size; - while (1) { - a[j] = a[i]; - if (--i < 0) - break; - a[j] |= (a[i] & 3) << 6; - --j; - a[j] = (unsigned char)((a[i] & 0x3c) >> 2); - if (--i < 0) - break; - a[j] |= (a[i] & 0xf) << 4; - --j; - a[j] = (unsigned char)((a[i] & 0x30) >> 4); - if (--i < 0) - break; - a[j] |= (a[i] << 2); - - a[--j] = 0; - if (--i < 0) - break; - } - while (j <= size && a[j] == 0) - ++j; - i = 0; - while (j <= size) - a[i++] = a[j++]; - return i; + return EVP_DecodeBlock(a, (unsigned char *)src, (int)size); } /* * Convert a raw byte string into a null-terminated base64 ASCII string. */ -static char *t_tob64(char *dst, const unsigned char *src, int size) +static void t_tob64(char *dst, const unsigned char *src, int size) { - int c, pos = size % 3; - unsigned char b0 = 0, b1 = 0, b2 = 0, notleading = 0; - char *olddst = dst; - - switch (pos) { - case 1: - b2 = src[0]; - break; - case 2: - b1 = src[0]; - b2 = src[1]; - break; - } - - while (1) { - c = (b0 & 0xfc) >> 2; - if (notleading || c != 0) { - *dst++ = b64table[c]; - notleading = 1; - } - c = ((b0 & 3) << 4) | ((b1 & 0xf0) >> 4); - if (notleading || c != 0) { - *dst++ = b64table[c]; - notleading = 1; - } - c = ((b1 & 0xf) << 2) | ((b2 & 0xc0) >> 6); - if (notleading || c != 0) { - *dst++ = b64table[c]; - notleading = 1; - } - c = b2 & 0x3f; - if (notleading || c != 0) { - *dst++ = b64table[c]; - notleading = 1; - } - if (pos >= size) - break; - else { - b0 = src[pos++]; - b1 = src[pos++]; - b2 = src[pos++]; - } - } - - *dst++ = '\0'; - return olddst; + EVP_EncodeBlock((unsigned char *)dst, src, size); } void SRP_user_pwd_free(SRP_user_pwd *user_pwd) @@ -474,7 +374,7 @@ static SRP_user_pwd *find_user(SRP_VBASE *vb, char *username) return NULL; } - #if OPENSSL_API_COMPAT < 0x10100000L +# if OPENSSL_API_COMPAT < 0x10100000L /* * DEPRECATED: use SRP_VBASE_get1_by_user instead. * This method ignores the configured seed and fails for an unknown user. @@ -485,7 +385,7 @@ SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username) { return find_user(vb, username); } -#endif +# endif /* * Ownership of the returned pointer is released to the caller. diff --git a/crypto/stack/stack.c b/crypto/stack/stack.c index 43ddf30a..fc755e36 100644 --- a/crypto/stack/stack.c +++ b/crypto/stack/stack.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -12,20 +12,25 @@ #include "internal/numbers.h" #include #include +#include +#include /* For ossl_inline */ + +/* + * The initial number of nodes in the array. + */ +static const int min_nodes = 4; +static const int max_nodes = SIZE_MAX / sizeof(void *) < INT_MAX + ? (int)(SIZE_MAX / sizeof(void *)) + : INT_MAX; struct stack_st { int num; - const char **data; + const void **data; int sorted; - size_t num_alloc; + int num_alloc; OPENSSL_sk_compfunc comp; }; -#undef MIN_NODES -#define MIN_NODES 4 - -#include - OPENSSL_sk_compfunc OPENSSL_sk_set_cmp_func(OPENSSL_STACK *sk, OPENSSL_sk_compfunc c) { OPENSSL_sk_compfunc old = sk->comp; @@ -41,18 +46,22 @@ OPENSSL_STACK *OPENSSL_sk_dup(const OPENSSL_STACK *sk) { OPENSSL_STACK *ret; - if (sk->num < 0) - return NULL; - if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) return NULL; /* direct structure assignment */ *ret = *sk; + if (sk->num == 0) { + /* postpone |ret->data| allocation */ + ret->data = NULL; + ret->num_alloc = 0; + return ret; + } + /* duplicate |sk->data| content */ if ((ret->data = OPENSSL_malloc(sizeof(*ret->data) * sk->num_alloc)) == NULL) goto err; - memcpy(ret->data, sk->data, sizeof(char *) * sk->num); + memcpy(ret->data, sk->data, sizeof(void *) * sk->num); return ret; err: OPENSSL_sk_free(ret); @@ -66,16 +75,20 @@ OPENSSL_STACK *OPENSSL_sk_deep_copy(const OPENSSL_STACK *sk, OPENSSL_STACK *ret; int i; - if (sk->num < 0) - return NULL; - if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) return NULL; /* direct structure assignment */ *ret = *sk; - ret->num_alloc = sk->num > MIN_NODES ? (size_t)sk->num : MIN_NODES; + if (sk->num == 0) { + /* postpone |ret| data allocation */ + ret->data = NULL; + ret->num_alloc = 0; + return ret; + } + + ret->num_alloc = sk->num > min_nodes ? sk->num : min_nodes; ret->data = OPENSSL_zalloc(sizeof(*ret->data) * ret->num_alloc); if (ret->data == NULL) { OPENSSL_free(ret); @@ -98,52 +111,132 @@ OPENSSL_STACK *OPENSSL_sk_deep_copy(const OPENSSL_STACK *sk, OPENSSL_STACK *OPENSSL_sk_new_null(void) { - return OPENSSL_sk_new((OPENSSL_sk_compfunc)NULL); + return OPENSSL_sk_new_reserve(NULL, 0); } OPENSSL_STACK *OPENSSL_sk_new(OPENSSL_sk_compfunc c) { - OPENSSL_STACK *ret; + return OPENSSL_sk_new_reserve(c, 0); +} - if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) - goto err; - if ((ret->data = OPENSSL_zalloc(sizeof(*ret->data) * MIN_NODES)) == NULL) - goto err; - ret->comp = c; - ret->num_alloc = MIN_NODES; - return (ret); +/* + * Calculate the array growth based on the target size. + * + * The growth fraction is a rational number and is defined by a numerator + * and a denominator. According to Andrew Koenig in his paper "Why Are + * Vectors Efficient?" from JOOP 11(5) 1998, this factor should be less + * than the golden ratio (1.618...). + * + * We use 3/2 = 1.5 for simplicity of calculation and overflow checking. + * Another option 8/5 = 1.6 allows for slightly faster growth, although safe + * computation is more difficult. + * + * The limit to avoid overflow is spot on. The modulo three correction term + * ensures that the limit is the largest number than can be expanded by the + * growth factor without exceeding the hard limit. + * + * Do not call it with |current| lower than 2, or it will infinitely loop. + */ +static ossl_inline int compute_growth(int target, int current) +{ + const int limit = (max_nodes / 3) * 2 + (max_nodes % 3 ? 1 : 0); - err: - OPENSSL_free(ret); - return (NULL); + while (current < target) { + /* Check to see if we're at the hard limit */ + if (current >= max_nodes) + return 0; + + /* Expand the size by a factor of 3/2 if it is within range */ + current = current < limit ? current + current / 2 : max_nodes; + } + return current; +} + +/* internal STACK storage allocation */ +static int sk_reserve(OPENSSL_STACK *st, int n, int exact) +{ + const void **tmpdata; + int num_alloc; + + /* Check to see the reservation isn't exceeding the hard limit */ + if (n > max_nodes - st->num) + return 0; + + /* Figure out the new size */ + num_alloc = st->num + n; + if (num_alloc < min_nodes) + num_alloc = min_nodes; + + /* If |st->data| allocation was postponed */ + if (st->data == NULL) { + /* + * At this point, |st->num_alloc| and |st->num| are 0; + * so |num_alloc| value is |n| or |min_nodes| if greater than |n|. + */ + st->data = OPENSSL_zalloc(sizeof(void *) * num_alloc); + if (st->data == NULL) + return 0; + st->num_alloc = num_alloc; + return 1; + } + + if (!exact) { + if (num_alloc <= st->num_alloc) + return 1; + num_alloc = compute_growth(num_alloc, st->num_alloc); + if (num_alloc == 0) + return 0; + } else if (num_alloc == st->num_alloc) { + return 1; + } + + tmpdata = OPENSSL_realloc((void *)st->data, sizeof(void *) * num_alloc); + if (tmpdata == NULL) + return 0; + + st->data = tmpdata; + st->num_alloc = num_alloc; + return 1; +} + +OPENSSL_STACK *OPENSSL_sk_new_reserve(OPENSSL_sk_compfunc c, int n) +{ + OPENSSL_STACK *st = OPENSSL_zalloc(sizeof(OPENSSL_STACK)); + + if (st == NULL) + return NULL; + + st->comp = c; + + if (n <= 0) + return st; + + if (!sk_reserve(st, n, 1)) { + OPENSSL_sk_free(st); + return NULL; + } + + return st; +} + +int OPENSSL_sk_reserve(OPENSSL_STACK *st, int n) +{ + if (st == NULL) + return 0; + + if (n < 0) + return 1; + return sk_reserve(st, n, 1); } int OPENSSL_sk_insert(OPENSSL_STACK *st, const void *data, int loc) { - if (st == NULL || st->num < 0 || st->num == INT_MAX) { + if (st == NULL || st->num == max_nodes) return 0; - } - if (st->num_alloc <= (size_t)(st->num + 1)) { - size_t doub_num_alloc = st->num_alloc * 2; - const char **tmpdata; + if (!sk_reserve(st, 1, 0)) + return 0; - /* Overflow checks */ - if (doub_num_alloc < st->num_alloc) - return 0; - - /* Avoid overflow due to multiplication by sizeof(char *) */ - if (doub_num_alloc > SIZE_MAX / sizeof(char *)) - return 0; - - tmpdata = OPENSSL_realloc((char *)st->data, - sizeof(char *) * doub_num_alloc); - if (tmpdata == NULL) - return 0; - - st->data = tmpdata; - st->num_alloc = doub_num_alloc; - } if ((loc >= st->num) || (loc < 0)) { st->data[st->num] = data; } else { @@ -156,29 +249,34 @@ int OPENSSL_sk_insert(OPENSSL_STACK *st, const void *data, int loc) return st->num; } +static ossl_inline void *internal_delete(OPENSSL_STACK *st, int loc) +{ + const void *ret = st->data[loc]; + + if (loc != st->num - 1) + memmove(&st->data[loc], &st->data[loc + 1], + sizeof(st->data[0]) * (st->num - loc - 1)); + st->num--; + + return (void *)ret; +} + void *OPENSSL_sk_delete_ptr(OPENSSL_STACK *st, const void *p) { int i; for (i = 0; i < st->num; i++) if (st->data[i] == p) - return OPENSSL_sk_delete(st, i); + return internal_delete(st, i); return NULL; } void *OPENSSL_sk_delete(OPENSSL_STACK *st, int loc) { - const char *ret; - if (st == NULL || loc < 0 || loc >= st->num) return NULL; - ret = st->data[loc]; - if (loc != st->num - 1) - memmove(&st->data[loc], &st->data[loc + 1], - sizeof(st->data[0]) * (st->num - loc - 1)); - st->num--; - return (void *)ret; + return internal_delete(st, loc); } static int internal_find(OPENSSL_STACK *st, const void *data, @@ -187,23 +285,27 @@ static int internal_find(OPENSSL_STACK *st, const void *data, const void *r; int i; - if (st == NULL) + if (st == NULL || st->num == 0) return -1; if (st->comp == NULL) { for (i = 0; i < st->num; i++) if (st->data[i] == data) - return (i); - return (-1); + return i; + return -1; + } + + if (!st->sorted) { + if (st->num > 1) + qsort(st->data, st->num, sizeof(void *), st->comp); + st->sorted = 1; /* empty or single-element stack is considered sorted */ } - OPENSSL_sk_sort(st); if (data == NULL) - return (-1); + return -1; r = OBJ_bsearch_ex_(&data, st->data, st->num, sizeof(void *), st->comp, ret_val_options); - if (r == NULL) - return (-1); - return (int)((const char **)r - st->data); + + return r == NULL ? -1 : (int)((const void **)r - st->data); } int OPENSSL_sk_find(OPENSSL_STACK *st, const void *data) @@ -218,37 +320,33 @@ int OPENSSL_sk_find_ex(OPENSSL_STACK *st, const void *data) int OPENSSL_sk_push(OPENSSL_STACK *st, const void *data) { - return (OPENSSL_sk_insert(st, data, st->num)); + if (st == NULL) + return -1; + return OPENSSL_sk_insert(st, data, st->num); } int OPENSSL_sk_unshift(OPENSSL_STACK *st, const void *data) { - return (OPENSSL_sk_insert(st, data, 0)); + return OPENSSL_sk_insert(st, data, 0); } void *OPENSSL_sk_shift(OPENSSL_STACK *st) { - if (st == NULL) - return (NULL); - if (st->num <= 0) - return (NULL); - return (OPENSSL_sk_delete(st, 0)); + if (st == NULL || st->num == 0) + return NULL; + return internal_delete(st, 0); } void *OPENSSL_sk_pop(OPENSSL_STACK *st) { - if (st == NULL) - return (NULL); - if (st->num <= 0) - return (NULL); - return (OPENSSL_sk_delete(st, st->num - 1)); + if (st == NULL || st->num == 0) + return NULL; + return internal_delete(st, st->num - 1); } void OPENSSL_sk_zero(OPENSSL_STACK *st) { - if (st == NULL) - return; - if (st->num <= 0) + if (st == NULL || st->num == 0) return; memset(st->data, 0, sizeof(*st->data) * st->num); st->num = 0; @@ -276,9 +374,7 @@ void OPENSSL_sk_free(OPENSSL_STACK *st) int OPENSSL_sk_num(const OPENSSL_STACK *st) { - if (st == NULL) - return -1; - return st->num; + return st == NULL ? -1 : st->num; } void *OPENSSL_sk_value(const OPENSSL_STACK *st, int i) @@ -293,20 +389,20 @@ void *OPENSSL_sk_set(OPENSSL_STACK *st, int i, const void *data) if (st == NULL || i < 0 || i >= st->num) return NULL; st->data[i] = data; + st->sorted = 0; return (void *)st->data[i]; } void OPENSSL_sk_sort(OPENSSL_STACK *st) { - if (st && !st->sorted && st->comp != NULL) { - qsort(st->data, st->num, sizeof(char *), st->comp); - st->sorted = 1; + if (st != NULL && !st->sorted && st->comp != NULL) { + if (st->num > 1) + qsort(st->data, st->num, sizeof(void *), st->comp); + st->sorted = 1; /* empty or single-element stack is considered sorted */ } } int OPENSSL_sk_is_sorted(const OPENSSL_STACK *st) { - if (st == NULL) - return 1; - return st->sorted; + return st == NULL ? 1 : st->sorted; } diff --git a/crypto/store/build.info b/crypto/store/build.info new file mode 100644 index 00000000..7d882f31 --- /dev/null +++ b/crypto/store/build.info @@ -0,0 +1,4 @@ +LIBS=../../libcrypto +SOURCE[../../libcrypto]=\ + store_err.c store_init.c store_lib.c store_register.c store_strings.c \ + loader_file.c diff --git a/crypto/store/loader_file.c b/crypto/store/loader_file.c new file mode 100644 index 00000000..ea1b3216 --- /dev/null +++ b/crypto/store/loader_file.c @@ -0,0 +1,1436 @@ +/* + * Copyright 2016-2018 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 "e_os.h" +#include +#include +#include +#include + +#include +#include /* For d2i_DSAPrivateKey */ +#include +#include +#include +#include /* For the PKCS8 stuff o.O */ +#include /* For d2i_RSAPrivateKey */ +#include +#include +#include +#include /* For the PKCS8 stuff o.O */ +#include "internal/asn1_int.h" +#include "internal/ctype.h" +#include "internal/o_dir.h" +#include "internal/cryptlib.h" +#include "internal/store_int.h" +#include "store_locl.h" + +#ifdef _WIN32 +# define stat _stat +#endif + +/*- + * Password prompting + * ------------------ + */ + +static char *file_get_pass(const UI_METHOD *ui_method, char *pass, + size_t maxsize, const char *prompt_info, void *data) +{ + UI *ui = UI_new(); + char *prompt = NULL; + + if (ui == NULL) { + OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE); + return NULL; + } + + if (ui_method != NULL) + UI_set_method(ui, ui_method); + UI_add_user_data(ui, data); + + if ((prompt = UI_construct_prompt(ui, "pass phrase", + prompt_info)) == NULL) { + OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE); + pass = NULL; + } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD, + pass, 0, maxsize - 1)) { + OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB); + pass = NULL; + } else { + switch (UI_process(ui)) { + case -2: + OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, + OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED); + pass = NULL; + break; + case -1: + OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB); + pass = NULL; + break; + default: + break; + } + } + + OPENSSL_free(prompt); + UI_free(ui); + return pass; +} + +struct pem_pass_data { + const UI_METHOD *ui_method; + void *data; + const char *prompt_info; +}; + +static int file_fill_pem_pass_data(struct pem_pass_data *pass_data, + const char *prompt_info, + const UI_METHOD *ui_method, void *ui_data) +{ + if (pass_data == NULL) + return 0; + pass_data->ui_method = ui_method; + pass_data->data = ui_data; + pass_data->prompt_info = prompt_info; + return 1; +} + +/* This is used anywhere a pem_password_cb is needed */ +static int file_get_pem_pass(char *buf, int num, int w, void *data) +{ + struct pem_pass_data *pass_data = data; + char *pass = file_get_pass(pass_data->ui_method, buf, num, + pass_data->prompt_info, pass_data->data); + + return pass == NULL ? 0 : strlen(pass); +} + +/*- + * The file scheme decoders + * ------------------------ + * + * Each possible data type has its own decoder, which either operates + * through a given PEM name, or attempts to decode to see if the blob + * it's given is decodable for its data type. The assumption is that + * only the correct data type will match the content. + */ + +/*- + * The try_decode function is called to check if the blob of data can + * be used by this handler, and if it can, decodes it into a supported + * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data. + * Input: + * pem_name: If this blob comes from a PEM file, this holds + * the PEM name. If it comes from another type of + * file, this is NULL. + * pem_header: If this blob comes from a PEM file, this holds + * the PEM headers. If it comes from another type of + * file, this is NULL. + * blob: The blob of data to match with what this handler + * can use. + * len: The length of the blob. + * handler_ctx: For a handler marked repeatable, this pointer can + * be used to create a context for the handler. IT IS + * THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY + * THIS CONTEXT APPROPRIATELY, i.e. create on first call + * and destroy when about to return NULL. + * matchcount: A pointer to an int to count matches for this data. + * Usually becomes 0 (no match) or 1 (match!), but may + * be higher in the (unlikely) event that the data matches + * more than one possibility. The int will always be + * zero when the function is called. + * ui_method: Application UI method for getting a password, pin + * or any other interactive data. + * ui_data: Application data to be passed to ui_method when + * it's called. + * Output: + * a OSSL_STORE_INFO + */ +typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name, + const char *pem_header, + const unsigned char *blob, + size_t len, void **handler_ctx, + int *matchcount, + const UI_METHOD *ui_method, + void *ui_data); +/* + * The eof function should return 1 if there's no more data to be found + * with the handler_ctx, otherwise 0. This is only used when the handler is + * marked repeatable. + */ +typedef int (*file_eof_fn)(void *handler_ctx); +/* + * The destroy_ctx function is used to destroy the handler_ctx that was + * intiated by a repeatable try_decode fuction. This is only used when + * the handler is marked repeatable. + */ +typedef void (*file_destroy_ctx_fn)(void **handler_ctx); + +typedef struct file_handler_st { + const char *name; + file_try_decode_fn try_decode; + file_eof_fn eof; + file_destroy_ctx_fn destroy_ctx; + + /* flags */ + int repeatable; +} FILE_HANDLER; + +/* + * PKCS#12 decoder. It operates by decoding all of the blob content, + * extracting all the interesting data from it and storing them internally, + * then serving them one piece at a time. + */ +static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name, + const char *pem_header, + const unsigned char *blob, + size_t len, void **pctx, + int *matchcount, + const UI_METHOD *ui_method, + void *ui_data) +{ + OSSL_STORE_INFO *store_info = NULL; + STACK_OF(OSSL_STORE_INFO) *ctx = *pctx; + + if (ctx == NULL) { + /* Initial parsing */ + PKCS12 *p12; + int ok = 0; + + if (pem_name != NULL) + /* No match, there is no PEM PKCS12 tag */ + return NULL; + + if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) { + char *pass = NULL; + char tpass[PEM_BUFSIZE]; + EVP_PKEY *pkey = NULL; + X509 *cert = NULL; + STACK_OF(X509) *chain = NULL; + + *matchcount = 1; + + if (PKCS12_verify_mac(p12, "", 0) + || PKCS12_verify_mac(p12, NULL, 0)) { + pass = ""; + } else { + if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE, + "PKCS12 import password", + ui_data)) == NULL) { + OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12, + OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR); + goto p12_end; + } + if (!PKCS12_verify_mac(p12, pass, strlen(pass))) { + OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12, + OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC); + goto p12_end; + } + } + + if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) { + OSSL_STORE_INFO *si_pkey = NULL; + OSSL_STORE_INFO *si_cert = NULL; + OSSL_STORE_INFO *si_ca = NULL; + + if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL + && (si_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL + && sk_OSSL_STORE_INFO_push(ctx, si_pkey) != 0 + && (si_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL + && sk_OSSL_STORE_INFO_push(ctx, si_cert) != 0) { + ok = 1; + si_pkey = NULL; + si_cert = NULL; + + while(sk_X509_num(chain) > 0) { + X509 *ca = sk_X509_value(chain, 0); + + if ((si_ca = OSSL_STORE_INFO_new_CERT(ca)) == NULL + || sk_OSSL_STORE_INFO_push(ctx, si_ca) == 0) { + ok = 0; + break; + } + si_ca = NULL; + (void)sk_X509_shift(chain); + } + } + if (!ok) { + OSSL_STORE_INFO_free(si_ca); + OSSL_STORE_INFO_free(si_cert); + OSSL_STORE_INFO_free(si_pkey); + sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free); + EVP_PKEY_free(pkey); + X509_free(cert); + sk_X509_pop_free(chain, X509_free); + ctx = NULL; + } + *pctx = ctx; + } + } + p12_end: + PKCS12_free(p12); + if (!ok) + return NULL; + } + + if (ctx != NULL) { + *matchcount = 1; + store_info = sk_OSSL_STORE_INFO_shift(ctx); + } + + return store_info; +} + +static int eof_PKCS12(void *ctx_) +{ + STACK_OF(OSSL_STORE_INFO) *ctx = ctx_; + + return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0; +} + +static void destroy_ctx_PKCS12(void **pctx) +{ + STACK_OF(OSSL_STORE_INFO) *ctx = *pctx; + + sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free); + *pctx = NULL; +} + +static FILE_HANDLER PKCS12_handler = { + "PKCS12", + try_decode_PKCS12, + eof_PKCS12, + destroy_ctx_PKCS12, + 1 /* repeatable */ +}; + +/* + * Encrypted PKCS#8 decoder. It operates by just decrypting the given blob + * into a new blob, which is returned as an EMBEDDED STORE_INFO. The whole + * decoding process will then start over with the new blob. + */ +static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name, + const char *pem_header, + const unsigned char *blob, + size_t len, void **pctx, + int *matchcount, + const UI_METHOD *ui_method, + void *ui_data) +{ + X509_SIG *p8 = NULL; + char kbuf[PEM_BUFSIZE]; + char *pass = NULL; + const X509_ALGOR *dalg = NULL; + const ASN1_OCTET_STRING *doct = NULL; + OSSL_STORE_INFO *store_info = NULL; + BUF_MEM *mem = NULL; + unsigned char *new_data = NULL; + int new_data_len; + + if (pem_name != NULL) { + if (strcmp(pem_name, PEM_STRING_PKCS8) != 0) + return NULL; + *matchcount = 1; + } + + if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL) + return NULL; + + *matchcount = 1; + + if ((mem = BUF_MEM_new()) == NULL) { + OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED, + ERR_R_MALLOC_FAILURE); + goto nop8; + } + + if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE, + "PKCS8 decrypt password", ui_data)) == NULL) { + OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED, + OSSL_STORE_R_BAD_PASSWORD_READ); + goto nop8; + } + + X509_SIG_get0(p8, &dalg, &doct); + if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length, + &new_data, &new_data_len, 0)) + goto nop8; + + mem->data = (char *)new_data; + mem->max = mem->length = (size_t)new_data_len; + X509_SIG_free(p8); + + store_info = ossl_store_info_new_EMBEDDED(PEM_STRING_PKCS8INF, mem); + if (store_info == NULL) { + OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED, + ERR_R_MALLOC_FAILURE); + goto nop8; + } + + return store_info; + nop8: + X509_SIG_free(p8); + BUF_MEM_free(mem); + return NULL; +} + +static FILE_HANDLER PKCS8Encrypted_handler = { + "PKCS8Encrypted", + try_decode_PKCS8Encrypted +}; + +/* + * Private key decoder. Decodes all sorts of private keys, both PKCS#8 + * encoded ones and old style PEM ones (with the key type is encoded into + * the PEM name). + */ +int pem_check_suffix(const char *pem_str, const char *suffix); +static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name, + const char *pem_header, + const unsigned char *blob, + size_t len, void **pctx, + int *matchcount, + const UI_METHOD *ui_method, + void *ui_data) +{ + OSSL_STORE_INFO *store_info = NULL; + EVP_PKEY *pkey = NULL; + const EVP_PKEY_ASN1_METHOD *ameth = NULL; + + if (pem_name != NULL) { + if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) { + PKCS8_PRIV_KEY_INFO *p8inf = + d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len); + + *matchcount = 1; + if (p8inf != NULL) + pkey = EVP_PKCS82PKEY(p8inf); + PKCS8_PRIV_KEY_INFO_free(p8inf); + } else { + int slen; + + if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0 + && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name, + slen)) != NULL) { + *matchcount = 1; + pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len); + } + } + } else { + int i; + + for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) { + EVP_PKEY *tmp_pkey = NULL; + const unsigned char *tmp_blob = blob; + + ameth = EVP_PKEY_asn1_get0(i); + if (ameth->pkey_flags & ASN1_PKEY_ALIAS) + continue; + + tmp_pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &tmp_blob, len); + if (tmp_pkey != NULL) { + if (pkey != NULL) + EVP_PKEY_free(tmp_pkey); + else + pkey = tmp_pkey; + (*matchcount)++; + } + } + + if (*matchcount > 1) { + EVP_PKEY_free(pkey); + pkey = NULL; + } + } + if (pkey == NULL) + /* No match */ + return NULL; + + store_info = OSSL_STORE_INFO_new_PKEY(pkey); + if (store_info == NULL) + EVP_PKEY_free(pkey); + + return store_info; +} + +static FILE_HANDLER PrivateKey_handler = { + "PrivateKey", + try_decode_PrivateKey +}; + +/* + * Public key decoder. Only supports SubjectPublicKeyInfo formated keys. + */ +static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name, + const char *pem_header, + const unsigned char *blob, + size_t len, void **pctx, + int *matchcount, + const UI_METHOD *ui_method, + void *ui_data) +{ + OSSL_STORE_INFO *store_info = NULL; + EVP_PKEY *pkey = NULL; + + if (pem_name != NULL) { + if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0) + /* No match */ + return NULL; + *matchcount = 1; + } + + if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) { + *matchcount = 1; + store_info = OSSL_STORE_INFO_new_PKEY(pkey); + } + + return store_info; +} + +static FILE_HANDLER PUBKEY_handler = { + "PUBKEY", + try_decode_PUBKEY +}; + +/* + * Key parameter decoder. + */ +static OSSL_STORE_INFO *try_decode_params(const char *pem_name, + const char *pem_header, + const unsigned char *blob, + size_t len, void **pctx, + int *matchcount, + const UI_METHOD *ui_method, + void *ui_data) +{ + OSSL_STORE_INFO *store_info = NULL; + int slen = 0; + EVP_PKEY *pkey = NULL; + const EVP_PKEY_ASN1_METHOD *ameth = NULL; + int ok = 0; + + if (pem_name != NULL) { + if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) == 0) + return NULL; + *matchcount = 1; + } + + if (slen > 0) { + if ((pkey = EVP_PKEY_new()) == NULL) { + OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB); + return NULL; + } + + + if (EVP_PKEY_set_type_str(pkey, pem_name, slen) + && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL + && ameth->param_decode != NULL + && ameth->param_decode(pkey, &blob, len)) + ok = 1; + } else { + int i; + EVP_PKEY *tmp_pkey = NULL; + + for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) { + const unsigned char *tmp_blob = blob; + + if (tmp_pkey == NULL && (tmp_pkey = EVP_PKEY_new()) == NULL) { + OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB); + break; + } + + ameth = EVP_PKEY_asn1_get0(i); + if (ameth->pkey_flags & ASN1_PKEY_ALIAS) + continue; + + if (EVP_PKEY_set_type(tmp_pkey, ameth->pkey_id) + && (ameth = EVP_PKEY_get0_asn1(tmp_pkey)) != NULL + && ameth->param_decode != NULL + && ameth->param_decode(tmp_pkey, &tmp_blob, len)) { + if (pkey != NULL) + EVP_PKEY_free(tmp_pkey); + else + pkey = tmp_pkey; + tmp_pkey = NULL; + (*matchcount)++; + } + } + + EVP_PKEY_free(tmp_pkey); + if (*matchcount == 1) { + ok = 1; + } + } + + if (ok) + store_info = OSSL_STORE_INFO_new_PARAMS(pkey); + if (store_info == NULL) + EVP_PKEY_free(pkey); + + return store_info; +} + +static FILE_HANDLER params_handler = { + "params", + try_decode_params +}; + +/* + * X.509 certificate decoder. + */ +static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name, + const char *pem_header, + const unsigned char *blob, + size_t len, void **pctx, + int *matchcount, + const UI_METHOD *ui_method, + void *ui_data) +{ + OSSL_STORE_INFO *store_info = NULL; + X509 *cert = NULL; + + /* + * In most cases, we can try to interpret the serialized data as a trusted + * cert (X509 + X509_AUX) and fall back to reading it as a normal cert + * (just X509), but if the PEM name specifically declares it as a trusted + * cert, then no fallback should be engaged. |ignore_trusted| tells if + * the fallback can be used (1) or not (0). + */ + int ignore_trusted = 1; + + if (pem_name != NULL) { + if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0) + ignore_trusted = 0; + else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0 + && strcmp(pem_name, PEM_STRING_X509) != 0) + /* No match */ + return NULL; + *matchcount = 1; + } + + if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL + || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL)) { + *matchcount = 1; + store_info = OSSL_STORE_INFO_new_CERT(cert); + } + + if (store_info == NULL) + X509_free(cert); + + return store_info; +} + +static FILE_HANDLER X509Certificate_handler = { + "X509Certificate", + try_decode_X509Certificate +}; + +/* + * X.509 CRL decoder. + */ +static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name, + const char *pem_header, + const unsigned char *blob, + size_t len, void **pctx, + int *matchcount, + const UI_METHOD *ui_method, + void *ui_data) +{ + OSSL_STORE_INFO *store_info = NULL; + X509_CRL *crl = NULL; + + if (pem_name != NULL) { + if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0) + /* No match */ + return NULL; + *matchcount = 1; + } + + if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) { + *matchcount = 1; + store_info = OSSL_STORE_INFO_new_CRL(crl); + } + + if (store_info == NULL) + X509_CRL_free(crl); + + return store_info; +} + +static FILE_HANDLER X509CRL_handler = { + "X509CRL", + try_decode_X509CRL +}; + +/* + * To finish it all off, we collect all the handlers. + */ +static const FILE_HANDLER *file_handlers[] = { + &PKCS12_handler, + &PKCS8Encrypted_handler, + &X509Certificate_handler, + &X509CRL_handler, + ¶ms_handler, + &PUBKEY_handler, + &PrivateKey_handler, +}; + + +/*- + * The loader itself + * ----------------- + */ + +struct ossl_store_loader_ctx_st { + enum { + is_raw = 0, + is_pem, + is_dir + } type; + int errcnt; +#define FILE_FLAG_SECMEM (1<<0) + unsigned int flags; + union { + struct { /* Used with is_raw and is_pem */ + BIO *file; + + /* + * The following are used when the handler is marked as + * repeatable + */ + const FILE_HANDLER *last_handler; + void *last_handler_ctx; + } file; + struct { /* Used with is_dir */ + OPENSSL_DIR_CTX *ctx; + int end_reached; + char *uri; + + /* + * When a search expression is given, these are filled in. + * |search_name| contains the file basename to look for. + * The string is exactly 8 characters long. + */ + char search_name[9]; + + /* + * The directory reading utility we have combines opening with + * reading the first name. To make sure we can detect the end + * at the right time, we read early and cache the name. + */ + const char *last_entry; + int last_errno; + } dir; + } _; + + /* Expected object type. May be unspecified */ + int expected_type; +}; + +static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx) +{ + if (ctx->type == is_dir) { + OPENSSL_free(ctx->_.dir.uri); + } else { + if (ctx->_.file.last_handler != NULL) { + ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx); + ctx->_.file.last_handler_ctx = NULL; + ctx->_.file.last_handler = NULL; + } + } + OPENSSL_free(ctx); +} + +static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader, + const char *uri, + const UI_METHOD *ui_method, + void *ui_data) +{ + OSSL_STORE_LOADER_CTX *ctx = NULL; + struct stat st; + struct { + const char *path; + unsigned int check_absolute:1; + } path_data[2]; + size_t path_data_n = 0, i; + const char *path; + + /* + * First step, just take the URI as is. + */ + path_data[path_data_n].check_absolute = 0; + path_data[path_data_n++].path = uri; + + /* + * Second step, if the URI appears to start with the 'file' scheme, + * extract the path and make that the second path to check. + * There's a special case if the URI also contains an authority, then + * the full URI shouldn't be used as a path anywhere. + */ + if (strncasecmp(uri, "file:", 5) == 0) { + const char *p = &uri[5]; + + if (strncmp(&uri[5], "//", 2) == 0) { + path_data_n--; /* Invalidate using the full URI */ + if (strncasecmp(&uri[7], "localhost/", 10) == 0) { + p = &uri[16]; + } else if (uri[7] == '/') { + p = &uri[7]; + } else { + OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, + OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED); + return NULL; + } + } + + path_data[path_data_n].check_absolute = 1; +#ifdef _WIN32 + /* Windows file: URIs with a drive letter start with a / */ + if (p[0] == '/' && p[2] == ':' && p[3] == '/') { + char c = ossl_tolower(p[1]); + + if (c >= 'a' && c <= 'z') { + p++; + /* We know it's absolute, so no need to check */ + path_data[path_data_n].check_absolute = 0; + } + } +#endif + path_data[path_data_n++].path = p; + } + + + for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) { + /* + * If the scheme "file" was an explicit part of the URI, the path must + * be absolute. So says RFC 8089 + */ + if (path_data[i].check_absolute && path_data[i].path[0] != '/') { + OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, + OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE); + ERR_add_error_data(1, path_data[i].path); + return NULL; + } + + if (stat(path_data[i].path, &st) < 0) { + SYSerr(SYS_F_STAT, errno); + ERR_add_error_data(1, path_data[i].path); + } else { + path = path_data[i].path; + } + } + if (path == NULL) { + return NULL; + } + + /* Successfully found a working path, clear possible collected errors */ + ERR_clear_error(); + + ctx = OPENSSL_zalloc(sizeof(*ctx)); + if (ctx == NULL) { + OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE); + return NULL; + } + + if ((st.st_mode & S_IFDIR) == S_IFDIR) { + /* + * Try to copy everything, even if we know that some of them must be + * NULL for the moment. This prevents errors in the future, when more + * components may be used. + */ + ctx->_.dir.uri = OPENSSL_strdup(uri); + ctx->type = is_dir; + + if (ctx->_.dir.uri == NULL) + goto err; + + ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path); + ctx->_.dir.last_errno = errno; + if (ctx->_.dir.last_entry == NULL) { + if (ctx->_.dir.last_errno != 0) { + char errbuf[256]; + errno = ctx->_.dir.last_errno; + openssl_strerror_r(errno, errbuf, sizeof(errbuf)); + OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_SYS_LIB); + ERR_add_error_data(1, errbuf); + goto err; + } + ctx->_.dir.end_reached = 1; + } + } else { + BIO *buff = NULL; + char peekbuf[4096] = { 0, }; + + if ((buff = BIO_new(BIO_f_buffer())) == NULL + || (ctx->_.file.file = BIO_new_file(path, "rb")) == NULL) { + BIO_free_all(buff); + goto err; + } + + ctx->_.file.file = BIO_push(buff, ctx->_.file.file); + if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) { + peekbuf[sizeof(peekbuf) - 1] = '\0'; + if (strstr(peekbuf, "-----BEGIN ") != NULL) + ctx->type = is_pem; + } + } + + return ctx; + err: + OSSL_STORE_LOADER_CTX_free(ctx); + return NULL; +} + +static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args) +{ + int ret = 1; + + switch (cmd) { + case OSSL_STORE_C_USE_SECMEM: + { + int on = *(va_arg(args, int *)); + + switch (on) { + case 0: + ctx->flags &= ~FILE_FLAG_SECMEM; + break; + case 1: + ctx->flags |= FILE_FLAG_SECMEM; + break; + default: + OSSL_STOREerr(OSSL_STORE_F_FILE_CTRL, + ERR_R_PASSED_INVALID_ARGUMENT); + ret = 0; + break; + } + } + break; + default: + break; + } + + return ret; +} + +static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected) +{ + ctx->expected_type = expected; + return 1; +} + +static int file_find(OSSL_STORE_LOADER_CTX *ctx, OSSL_STORE_SEARCH *search) +{ + /* + * If ctx == NULL, the library is looking to know if this loader supports + * the given search type. + */ + + if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) { + unsigned long hash = 0; + + if (ctx == NULL) + return 1; + + if (ctx->type != is_dir) { + OSSL_STOREerr(OSSL_STORE_F_FILE_FIND, + OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES); + return 0; + } + + hash = X509_NAME_hash(OSSL_STORE_SEARCH_get0_name(search)); + BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name), + "%08lx", hash); + return 1; + } + + if (ctx != NULL) + OSSL_STOREerr(OSSL_STORE_F_FILE_FIND, + OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE); + return 0; +} + +/* Internal function to decode an already opened PEM file */ +OSSL_STORE_LOADER_CTX *ossl_store_file_attach_pem_bio_int(BIO *bp) +{ + OSSL_STORE_LOADER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); + + if (ctx == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT, + ERR_R_MALLOC_FAILURE); + return NULL; + } + + ctx->_.file.file = bp; + ctx->type = is_pem; + + return ctx; +} + +static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx, + const char *pem_name, + const char *pem_header, + unsigned char *data, size_t len, + const UI_METHOD *ui_method, + void *ui_data, int *matchcount) +{ + OSSL_STORE_INFO *result = NULL; + BUF_MEM *new_mem = NULL; + char *new_pem_name = NULL; + int t = 0; + + again: + { + size_t i = 0; + void *handler_ctx = NULL; + const FILE_HANDLER **matching_handlers = + OPENSSL_zalloc(sizeof(*matching_handlers) + * OSSL_NELEM(file_handlers)); + + if (matching_handlers == NULL) { + OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE, + ERR_R_MALLOC_FAILURE); + goto err; + } + + *matchcount = 0; + for (i = 0; i < OSSL_NELEM(file_handlers); i++) { + const FILE_HANDLER *handler = file_handlers[i]; + int try_matchcount = 0; + void *tmp_handler_ctx = NULL; + OSSL_STORE_INFO *tmp_result = + handler->try_decode(pem_name, pem_header, data, len, + &tmp_handler_ctx, &try_matchcount, + ui_method, ui_data); + + if (try_matchcount > 0) { + + matching_handlers[*matchcount] = handler; + + if (handler_ctx) + handler->destroy_ctx(&handler_ctx); + handler_ctx = tmp_handler_ctx; + + if ((*matchcount += try_matchcount) > 1) { + /* more than one match => ambiguous, kill any result */ + OSSL_STORE_INFO_free(result); + OSSL_STORE_INFO_free(tmp_result); + if (handler->destroy_ctx != NULL) + handler->destroy_ctx(&handler_ctx); + handler_ctx = NULL; + tmp_result = NULL; + result = NULL; + } + if (result == NULL) + result = tmp_result; + } + } + + if (*matchcount == 1 && matching_handlers[0]->repeatable) { + ctx->_.file.last_handler = matching_handlers[0]; + ctx->_.file.last_handler_ctx = handler_ctx; + } + + OPENSSL_free(matching_handlers); + } + + err: + OPENSSL_free(new_pem_name); + BUF_MEM_free(new_mem); + + if (result != NULL + && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) { + pem_name = new_pem_name = + ossl_store_info_get0_EMBEDDED_pem_name(result); + new_mem = ossl_store_info_get0_EMBEDDED_buffer(result); + data = (unsigned char *)new_mem->data; + len = new_mem->length; + OPENSSL_free(result); + result = NULL; + goto again; + } + + if (result != NULL) + ERR_clear_error(); + + return result; +} + +static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx, + const UI_METHOD *ui_method, + void *ui_data) +{ + OSSL_STORE_INFO *result = NULL; + int try_matchcount = 0; + + if (ctx->_.file.last_handler != NULL) { + result = + ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0, + &ctx->_.file.last_handler_ctx, + &try_matchcount, + ui_method, ui_data); + + if (result == NULL) { + ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx); + ctx->_.file.last_handler_ctx = NULL; + ctx->_.file.last_handler = NULL; + } + } + return result; +} + +static void pem_free_flag(void *pem_data, int secure, size_t num) +{ + if (secure) + OPENSSL_secure_clear_free(pem_data, num); + else + OPENSSL_free(pem_data); +} +static int file_read_pem(BIO *bp, char **pem_name, char **pem_header, + unsigned char **data, long *len, + const UI_METHOD *ui_method, + void *ui_data, int secure) +{ + int i = secure + ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len, + PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE) + : PEM_read_bio(bp, pem_name, pem_header, data, len); + + if (i <= 0) + return 0; + + /* + * 10 is the number of characters in "Proc-Type:", which + * PEM_get_EVP_CIPHER_INFO() requires to be present. + * If the PEM header has less characters than that, it's + * not worth spending cycles on it. + */ + if (strlen(*pem_header) > 10) { + EVP_CIPHER_INFO cipher; + struct pem_pass_data pass_data; + + if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher) + || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method, ui_data) + || !PEM_do_header(&cipher, *data, len, file_get_pem_pass, + &pass_data)) { + return 0; + } + } + return 1; +} + +static int file_read_asn1(BIO *bp, unsigned char **data, long *len) +{ + BUF_MEM *mem = NULL; + + if (asn1_d2i_read_bio(bp, &mem) < 0) + return 0; + + *data = (unsigned char *)mem->data; + *len = (long)mem->length; + OPENSSL_free(mem); + + return 1; +} + +static int ends_with_dirsep(const char *uri) +{ + if (*uri != '\0') + uri += strlen(uri) - 1; +#if defined __VMS + if (*uri == ']' || *uri == '>' || *uri == ':') + return 1; +#elif defined _WIN32 + if (*uri == '\\') + return 1; +#endif + return *uri == '/'; +} + +static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name, + char **data) +{ + assert(name != NULL); + assert(data != NULL); + { + const char *pathsep = ends_with_dirsep(ctx->_.dir.uri) ? "" : "/"; + long calculated_length = strlen(ctx->_.dir.uri) + strlen(pathsep) + + strlen(name) + 1 /* \0 */; + + *data = OPENSSL_zalloc(calculated_length); + if (*data == NULL) { + OSSL_STOREerr(OSSL_STORE_F_FILE_NAME_TO_URI, ERR_R_MALLOC_FAILURE); + return 0; + } + + OPENSSL_strlcat(*data, ctx->_.dir.uri, calculated_length); + OPENSSL_strlcat(*data, pathsep, calculated_length); + OPENSSL_strlcat(*data, name, calculated_length); + } + return 1; +} + +static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name) +{ + const char *p = NULL; + + /* If there are no search criteria, all names are accepted */ + if (ctx->_.dir.search_name[0] == '\0') + return 1; + + /* If the expected type isn't supported, no name is accepted */ + if (ctx->expected_type != 0 + && ctx->expected_type != OSSL_STORE_INFO_CERT + && ctx->expected_type != OSSL_STORE_INFO_CRL) + return 0; + + /* + * First, check the basename + */ + if (strncasecmp(name, ctx->_.dir.search_name, + sizeof(ctx->_.dir.search_name) - 1) != 0 + || name[sizeof(ctx->_.dir.search_name) - 1] != '.') + return 0; + p = &name[sizeof(ctx->_.dir.search_name)]; + + /* + * Then, if the expected type is a CRL, check that the extension starts + * with 'r' + */ + if (*p == 'r') { + p++; + if (ctx->expected_type != 0 + && ctx->expected_type != OSSL_STORE_INFO_CRL) + return 0; + } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) { + return 0; + } + + /* + * Last, check that the rest of the extension is a decimal number, at + * least one digit long. + */ + if (!isdigit(*p)) + return 0; + while (isdigit(*p)) + p++; + +# ifdef __VMS + /* + * One extra step here, check for a possible generation number. + */ + if (*p == ';') + for (p++; *p != '\0'; p++) + if (!isdigit(*p)) + break; +# endif + + /* + * If we've reached the end of the string at this point, we've successfully + * found a fitting file name. + */ + return *p == '\0'; +} + +static int file_eof(OSSL_STORE_LOADER_CTX *ctx); +static int file_error(OSSL_STORE_LOADER_CTX *ctx); +static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx, + const UI_METHOD *ui_method, void *ui_data) +{ + OSSL_STORE_INFO *result = NULL; + + ctx->errcnt = 0; + ERR_clear_error(); + + if (ctx->type == is_dir) { + do { + char *newname = NULL; + + if (ctx->_.dir.last_entry == NULL) { + if (!ctx->_.dir.end_reached) { + char errbuf[256]; + assert(ctx->_.dir.last_errno != 0); + errno = ctx->_.dir.last_errno; + ctx->errcnt++; + openssl_strerror_r(errno, errbuf, sizeof(errbuf)); + OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_SYS_LIB); + ERR_add_error_data(1, errbuf); + } + return NULL; + } + + if (ctx->_.dir.last_entry[0] != '.' + && file_name_check(ctx, ctx->_.dir.last_entry) + && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname)) + return NULL; + + /* + * On the first call (with a NULL context), OPENSSL_DIR_read() + * cares about the second argument. On the following calls, it + * only cares that it isn't NULL. Therefore, we can safely give + * it our URI here. + */ + ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, + ctx->_.dir.uri); + ctx->_.dir.last_errno = errno; + if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0) + ctx->_.dir.end_reached = 1; + + if (newname != NULL + && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) { + OPENSSL_free(newname); + OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_OSSL_STORE_LIB); + return NULL; + } + } while (result == NULL && !file_eof(ctx)); + } else { + int matchcount = -1; + + again: + result = file_load_try_repeat(ctx, ui_method, ui_data); + if (result != NULL) + return result; + + if (file_eof(ctx)) + return NULL; + + do { + char *pem_name = NULL; /* PEM record name */ + char *pem_header = NULL; /* PEM record header */ + unsigned char *data = NULL; /* DER encoded data */ + long len = 0; /* DER encoded data length */ + + matchcount = -1; + if (ctx->type == is_pem) { + if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header, + &data, &len, ui_method, ui_data, + (ctx->flags & FILE_FLAG_SECMEM) != 0)) { + ctx->errcnt++; + goto endloop; + } + } else { + if (!file_read_asn1(ctx->_.file.file, &data, &len)) { + ctx->errcnt++; + goto endloop; + } + } + + result = file_load_try_decode(ctx, pem_name, pem_header, data, len, + ui_method, ui_data, &matchcount); + + if (result != NULL) + goto endloop; + + /* + * If a PEM name matches more than one handler, the handlers are + * badly coded. + */ + if (!ossl_assert(pem_name == NULL || matchcount <= 1)) { + ctx->errcnt++; + goto endloop; + } + + if (matchcount > 1) { + OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, + OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE); + } else if (matchcount == 1) { + /* + * If there are other errors on the stack, they already show + * what the problem is. + */ + if (ERR_peek_error() == 0) { + OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, + OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE); + if (pem_name != NULL) + ERR_add_error_data(3, "PEM type is '", pem_name, "'"); + } + } + if (matchcount > 0) + ctx->errcnt++; + + endloop: + pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0); + pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0); + pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len); + } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx)); + + /* We bail out on ambiguity */ + if (matchcount > 1) + return NULL; + + if (result != NULL + && ctx->expected_type != 0 + && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) { + OSSL_STORE_INFO_free(result); + goto again; + } + } + + return result; +} + +static int file_error(OSSL_STORE_LOADER_CTX *ctx) +{ + return ctx->errcnt > 0; +} + +static int file_eof(OSSL_STORE_LOADER_CTX *ctx) +{ + if (ctx->type == is_dir) + return ctx->_.dir.end_reached; + + if (ctx->_.file.last_handler != NULL + && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx)) + return 0; + return BIO_eof(ctx->_.file.file); +} + +static int file_close(OSSL_STORE_LOADER_CTX *ctx) +{ + if (ctx->type == is_dir) { + OPENSSL_DIR_end(&ctx->_.dir.ctx); + } else { + BIO_free_all(ctx->_.file.file); + } + OSSL_STORE_LOADER_CTX_free(ctx); + return 1; +} + +int ossl_store_file_detach_pem_bio_int(OSSL_STORE_LOADER_CTX *ctx) +{ + OSSL_STORE_LOADER_CTX_free(ctx); + return 1; +} + +static OSSL_STORE_LOADER file_loader = + { + "file", + NULL, + file_open, + file_ctrl, + file_expect, + file_find, + file_load, + file_eof, + file_error, + file_close + }; + +static void store_file_loader_deinit(void) +{ + ossl_store_unregister_loader_int(file_loader.scheme); +} + +int ossl_store_file_loader_init(void) +{ + int ret = ossl_store_register_loader_int(&file_loader); + + OPENSSL_atexit(store_file_loader_deinit); + return ret; +} diff --git a/crypto/store/store_err.c b/crypto/store/store_err.c new file mode 100644 index 00000000..5a8a8404 --- /dev/null +++ b/crypto/store/store_err.c @@ -0,0 +1,146 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2018 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 +#include + +#ifndef OPENSSL_NO_ERR + +static const ERR_STRING_DATA OSSL_STORE_str_functs[] = { + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_FILE_CTRL, 0), "file_ctrl"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_FILE_FIND, 0), "file_find"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_FILE_GET_PASS, 0), + "file_get_pass"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_FILE_LOAD, 0), "file_load"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_FILE_LOAD_TRY_DECODE, 0), + "file_load_try_decode"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_FILE_NAME_TO_URI, 0), + "file_name_to_uri"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_FILE_OPEN, 0), "file_open"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_ATTACH_PEM_BIO, 0), + "ossl_store_attach_pem_bio"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_EXPECT, 0), + "OSSL_STORE_expect"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT, 0), + "ossl_store_file_attach_pem_bio_int"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_FIND, 0), + "OSSL_STORE_find"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_GET0_LOADER_INT, 0), + "ossl_store_get0_loader_int"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_GET1_CERT, 0), + "OSSL_STORE_INFO_get1_CERT"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_GET1_CRL, 0), + "OSSL_STORE_INFO_get1_CRL"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME, 0), + "OSSL_STORE_INFO_get1_NAME"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME_DESCRIPTION, 0), + "OSSL_STORE_INFO_get1_NAME_description"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_GET1_PARAMS, 0), + "OSSL_STORE_INFO_get1_PARAMS"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_GET1_PKEY, 0), + "OSSL_STORE_INFO_get1_PKEY"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_NEW_CERT, 0), + "OSSL_STORE_INFO_new_CERT"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_NEW_CRL, 0), + "OSSL_STORE_INFO_new_CRL"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_NEW_EMBEDDED, 0), + "ossl_store_info_new_EMBEDDED"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_NEW_NAME, 0), + "OSSL_STORE_INFO_new_NAME"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_NEW_PARAMS, 0), + "OSSL_STORE_INFO_new_PARAMS"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_NEW_PKEY, 0), + "OSSL_STORE_INFO_new_PKEY"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INFO_SET0_NAME_DESCRIPTION, 0), + "OSSL_STORE_INFO_set0_NAME_description"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_INIT_ONCE, 0), + "ossl_store_init_once"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_LOADER_NEW, 0), + "OSSL_STORE_LOADER_new"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_OPEN, 0), + "OSSL_STORE_open"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_OPEN_INT, 0), ""}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_REGISTER_LOADER_INT, 0), + "ossl_store_register_loader_int"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ALIAS, 0), + "OSSL_STORE_SEARCH_by_alias"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ISSUER_SERIAL, 0), + "OSSL_STORE_SEARCH_by_issuer_serial"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT, 0), + "OSSL_STORE_SEARCH_by_key_fingerprint"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_SEARCH_BY_NAME, 0), + "OSSL_STORE_SEARCH_by_name"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_OSSL_STORE_UNREGISTER_LOADER_INT, 0), + "ossl_store_unregister_loader_int"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_TRY_DECODE_PARAMS, 0), + "try_decode_params"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_TRY_DECODE_PKCS12, 0), + "try_decode_PKCS12"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED, 0), + "try_decode_PKCS8Encrypted"}, + {0, NULL} +}; + +static const ERR_STRING_DATA OSSL_STORE_str_reasons[] = { + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE), + "ambiguous content type"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_BAD_PASSWORD_READ), + "bad password read"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC), + "error verifying pkcs12 mac"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_FINGERPRINT_SIZE_DOES_NOT_MATCH_DIGEST), + "fingerprint size does not match digest"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_INVALID_SCHEME), + "invalid scheme"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_IS_NOT_A), "is not a"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_LOADER_INCOMPLETE), + "loader incomplete"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_LOADING_STARTED), + "loading started"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_CERTIFICATE), + "not a certificate"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_CRL), "not a crl"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_KEY), "not a key"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_A_NAME), "not a name"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_NOT_PARAMETERS), + "not parameters"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR), + "passphrase callback error"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE), + "path must be absolute"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES), + "search only supported for directories"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED), + "ui process interrupted or cancelled"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNREGISTERED_SCHEME), + "unregistered scheme"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE), + "unsupported content type"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNSUPPORTED_OPERATION), + "unsupported operation"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE), + "unsupported search type"}, + {ERR_PACK(ERR_LIB_OSSL_STORE, 0, OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED), + "uri authority unsupported"}, + {0, NULL} +}; + +#endif + +int ERR_load_OSSL_STORE_strings(void) +{ +#ifndef OPENSSL_NO_ERR + if (ERR_func_error_string(OSSL_STORE_str_functs[0].error) == NULL) { + ERR_load_strings_const(OSSL_STORE_str_functs); + ERR_load_strings_const(OSSL_STORE_str_reasons); + } +#endif + return 1; +} diff --git a/crypto/store/store_init.c b/crypto/store/store_init.c new file mode 100644 index 00000000..4b531086 --- /dev/null +++ b/crypto/store/store_init.c @@ -0,0 +1,33 @@ +/* + * Copyright 2016-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 +#include "internal/store.h" +#include "store_locl.h" + +static CRYPTO_ONCE store_init = CRYPTO_ONCE_STATIC_INIT; +DEFINE_RUN_ONCE_STATIC(do_store_init) +{ + return OPENSSL_init_crypto(0, NULL) + && ossl_store_file_loader_init(); +} + +int ossl_store_init_once() +{ + if (!RUN_ONCE(&store_init, do_store_init)) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INIT_ONCE, ERR_R_MALLOC_FAILURE); + return 0; + } + return 1; +} + +void ossl_store_cleanup_int(void) +{ + ossl_store_destroy_loaders_int(); +} diff --git a/crypto/store/store_lib.c b/crypto/store/store_lib.c new file mode 100644 index 00000000..1c435476 --- /dev/null +++ b/crypto/store/store_lib.c @@ -0,0 +1,681 @@ +/* + * Copyright 2016-2018 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 "e_os.h" +#include +#include +#include + +#include "e_os.h" + +#include +#include +#include +#include "internal/thread_once.h" +#include "internal/store_int.h" +#include "store_locl.h" + +struct ossl_store_ctx_st { + const OSSL_STORE_LOADER *loader; + OSSL_STORE_LOADER_CTX *loader_ctx; + const UI_METHOD *ui_method; + void *ui_data; + OSSL_STORE_post_process_info_fn post_process; + void *post_process_data; + int expected_type; + + /* 0 before the first STORE_load(), 1 otherwise */ + int loading; +}; + +OSSL_STORE_CTX *OSSL_STORE_open(const char *uri, const UI_METHOD *ui_method, + void *ui_data, + OSSL_STORE_post_process_info_fn post_process, + void *post_process_data) +{ + const OSSL_STORE_LOADER *loader = NULL; + OSSL_STORE_LOADER_CTX *loader_ctx = NULL; + OSSL_STORE_CTX *ctx = NULL; + char scheme_copy[256], *p, *schemes[2]; + size_t schemes_n = 0; + size_t i; + + /* + * Put the file scheme first. If the uri does represent an existing file, + * possible device name and all, then it should be loaded. Only a failed + * attempt at loading a local file should have us try something else. + */ + schemes[schemes_n++] = "file"; + + /* + * Now, check if we have something that looks like a scheme, and add it + * as a second scheme. However, also check if there's an authority start + * (://), because that will invalidate the previous file scheme. Also, + * check that this isn't actually the file scheme, as there's no point + * going through that one twice! + */ + OPENSSL_strlcpy(scheme_copy, uri, sizeof(scheme_copy)); + if ((p = strchr(scheme_copy, ':')) != NULL) { + *p++ = '\0'; + if (strcasecmp(scheme_copy, "file") != 0) { + if (strncmp(p, "//", 2) == 0) + schemes_n--; /* Invalidate the file scheme */ + schemes[schemes_n++] = scheme_copy; + } + } + + ERR_set_mark(); + + /* Try each scheme until we find one that could open the URI */ + for (i = 0; loader_ctx == NULL && i < schemes_n; i++) { + if ((loader = ossl_store_get0_loader_int(schemes[i])) != NULL) + loader_ctx = loader->open(loader, uri, ui_method, ui_data); + } + if (loader_ctx == NULL) + goto err; + + if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_OPEN, ERR_R_MALLOC_FAILURE); + goto err; + } + + ctx->loader = loader; + ctx->loader_ctx = loader_ctx; + ctx->ui_method = ui_method; + ctx->ui_data = ui_data; + ctx->post_process = post_process; + ctx->post_process_data = post_process_data; + + /* + * If the attempt to open with the 'file' scheme loader failed and the + * other scheme loader succeeded, the failure to open with the 'file' + * scheme loader leaves an error on the error stack. Let's remove it. + */ + ERR_pop_to_mark(); + + return ctx; + + err: + ERR_clear_last_mark(); + if (loader_ctx != NULL) { + /* + * We ignore a returned error because we will return NULL anyway in + * this case, so if something goes wrong when closing, that'll simply + * just add another entry on the error stack. + */ + (void)loader->close(loader_ctx); + } + return NULL; +} + +int OSSL_STORE_ctrl(OSSL_STORE_CTX *ctx, int cmd, ...) +{ + va_list args; + int ret; + + va_start(args, cmd); + ret = OSSL_STORE_vctrl(ctx, cmd, args); + va_end(args); + + return ret; +} + +int OSSL_STORE_vctrl(OSSL_STORE_CTX *ctx, int cmd, va_list args) +{ + if (ctx->loader->ctrl != NULL) + return ctx->loader->ctrl(ctx->loader_ctx, cmd, args); + return 0; +} + +int OSSL_STORE_expect(OSSL_STORE_CTX *ctx, int expected_type) +{ + if (ctx->loading) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_EXPECT, + OSSL_STORE_R_LOADING_STARTED); + return 0; + } + + ctx->expected_type = expected_type; + if (ctx->loader->expect != NULL) + return ctx->loader->expect(ctx->loader_ctx, expected_type); + return 1; +} + +int OSSL_STORE_find(OSSL_STORE_CTX *ctx, OSSL_STORE_SEARCH *search) +{ + if (ctx->loading) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_FIND, + OSSL_STORE_R_LOADING_STARTED); + return 0; + } + if (ctx->loader->find == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_FIND, + OSSL_STORE_R_UNSUPPORTED_OPERATION); + return 0; + } + + return ctx->loader->find(ctx->loader_ctx, search); +} + +OSSL_STORE_INFO *OSSL_STORE_load(OSSL_STORE_CTX *ctx) +{ + OSSL_STORE_INFO *v = NULL; + + ctx->loading = 1; + again: + if (OSSL_STORE_eof(ctx)) + return NULL; + + v = ctx->loader->load(ctx->loader_ctx, ctx->ui_method, ctx->ui_data); + + if (ctx->post_process != NULL && v != NULL) { + v = ctx->post_process(v, ctx->post_process_data); + + /* + * By returning NULL, the callback decides that this object should + * be ignored. + */ + if (v == NULL) + goto again; + } + + if (v != NULL && ctx->expected_type != 0) { + int returned_type = OSSL_STORE_INFO_get_type(v); + + if (returned_type != OSSL_STORE_INFO_NAME && returned_type != 0) { + /* + * Soft assert here so those who want to harsly weed out faulty + * loaders can do so using a debugging version of libcrypto. + */ + if (ctx->loader->expect != NULL) + assert(ctx->expected_type == returned_type); + + if (ctx->expected_type != returned_type) { + OSSL_STORE_INFO_free(v); + goto again; + } + } + } + + return v; +} + +int OSSL_STORE_error(OSSL_STORE_CTX *ctx) +{ + return ctx->loader->error(ctx->loader_ctx); +} + +int OSSL_STORE_eof(OSSL_STORE_CTX *ctx) +{ + return ctx->loader->eof(ctx->loader_ctx); +} + +int OSSL_STORE_close(OSSL_STORE_CTX *ctx) +{ + int loader_ret = ctx->loader->close(ctx->loader_ctx); + + OPENSSL_free(ctx); + return loader_ret; +} + +/* + * Functions to generate OSSL_STORE_INFOs, one function for each type we + * support having in them as well as a generic constructor. + * + * In all cases, ownership of the object is transfered to the OSSL_STORE_INFO + * and will therefore be freed when the OSSL_STORE_INFO is freed. + */ +static OSSL_STORE_INFO *store_info_new(int type, void *data) +{ + OSSL_STORE_INFO *info = OPENSSL_zalloc(sizeof(*info)); + + if (info == NULL) + return NULL; + + info->type = type; + info->_.data = data; + return info; +} + +OSSL_STORE_INFO *OSSL_STORE_INFO_new_NAME(char *name) +{ + OSSL_STORE_INFO *info = store_info_new(OSSL_STORE_INFO_NAME, NULL); + + if (info == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_NEW_NAME, + ERR_R_MALLOC_FAILURE); + return NULL; + } + + info->_.name.name = name; + info->_.name.desc = NULL; + + return info; +} + +int OSSL_STORE_INFO_set0_NAME_description(OSSL_STORE_INFO *info, char *desc) +{ + if (info->type != OSSL_STORE_INFO_NAME) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_SET0_NAME_DESCRIPTION, + ERR_R_PASSED_INVALID_ARGUMENT); + return 0; + } + + info->_.name.desc = desc; + + return 1; +} +OSSL_STORE_INFO *OSSL_STORE_INFO_new_PARAMS(EVP_PKEY *params) +{ + OSSL_STORE_INFO *info = store_info_new(OSSL_STORE_INFO_PARAMS, params); + + if (info == NULL) + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_NEW_PARAMS, + ERR_R_MALLOC_FAILURE); + return info; +} + +OSSL_STORE_INFO *OSSL_STORE_INFO_new_PKEY(EVP_PKEY *pkey) +{ + OSSL_STORE_INFO *info = store_info_new(OSSL_STORE_INFO_PKEY, pkey); + + if (info == NULL) + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_NEW_PKEY, + ERR_R_MALLOC_FAILURE); + return info; +} + +OSSL_STORE_INFO *OSSL_STORE_INFO_new_CERT(X509 *x509) +{ + OSSL_STORE_INFO *info = store_info_new(OSSL_STORE_INFO_CERT, x509); + + if (info == NULL) + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_NEW_CERT, + ERR_R_MALLOC_FAILURE); + return info; +} + +OSSL_STORE_INFO *OSSL_STORE_INFO_new_CRL(X509_CRL *crl) +{ + OSSL_STORE_INFO *info = store_info_new(OSSL_STORE_INFO_CRL, crl); + + if (info == NULL) + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_NEW_CRL, + ERR_R_MALLOC_FAILURE); + return info; +} + +/* + * Functions to try to extract data from a OSSL_STORE_INFO. + */ +int OSSL_STORE_INFO_get_type(const OSSL_STORE_INFO *info) +{ + return info->type; +} + +const char *OSSL_STORE_INFO_get0_NAME(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_NAME) + return info->_.name.name; + return NULL; +} + +char *OSSL_STORE_INFO_get1_NAME(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_NAME) { + char *ret = OPENSSL_strdup(info->_.name.name); + + if (ret == NULL) + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME, + ERR_R_MALLOC_FAILURE); + return ret; + } + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME, + OSSL_STORE_R_NOT_A_NAME); + return NULL; +} + +const char *OSSL_STORE_INFO_get0_NAME_description(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_NAME) + return info->_.name.desc; + return NULL; +} + +char *OSSL_STORE_INFO_get1_NAME_description(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_NAME) { + char *ret = OPENSSL_strdup(info->_.name.desc + ? info->_.name.desc : ""); + + if (ret == NULL) + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME_DESCRIPTION, + ERR_R_MALLOC_FAILURE); + return ret; + } + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME_DESCRIPTION, + OSSL_STORE_R_NOT_A_NAME); + return NULL; +} + +EVP_PKEY *OSSL_STORE_INFO_get0_PARAMS(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_PARAMS) + return info->_.params; + return NULL; +} + +EVP_PKEY *OSSL_STORE_INFO_get1_PARAMS(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_PARAMS) { + EVP_PKEY_up_ref(info->_.params); + return info->_.params; + } + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_GET1_PARAMS, + OSSL_STORE_R_NOT_PARAMETERS); + return NULL; +} + +EVP_PKEY *OSSL_STORE_INFO_get0_PKEY(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_PKEY) + return info->_.pkey; + return NULL; +} + +EVP_PKEY *OSSL_STORE_INFO_get1_PKEY(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_PKEY) { + EVP_PKEY_up_ref(info->_.pkey); + return info->_.pkey; + } + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_GET1_PKEY, + OSSL_STORE_R_NOT_A_KEY); + return NULL; +} + +X509 *OSSL_STORE_INFO_get0_CERT(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_CERT) + return info->_.x509; + return NULL; +} + +X509 *OSSL_STORE_INFO_get1_CERT(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_CERT) { + X509_up_ref(info->_.x509); + return info->_.x509; + } + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_GET1_CERT, + OSSL_STORE_R_NOT_A_CERTIFICATE); + return NULL; +} + +X509_CRL *OSSL_STORE_INFO_get0_CRL(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_CRL) + return info->_.crl; + return NULL; +} + +X509_CRL *OSSL_STORE_INFO_get1_CRL(const OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_CRL) { + X509_CRL_up_ref(info->_.crl); + return info->_.crl; + } + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_GET1_CRL, + OSSL_STORE_R_NOT_A_CRL); + return NULL; +} + +/* + * Free the OSSL_STORE_INFO + */ +void OSSL_STORE_INFO_free(OSSL_STORE_INFO *info) +{ + if (info != NULL) { + switch (info->type) { + case OSSL_STORE_INFO_EMBEDDED: + BUF_MEM_free(info->_.embedded.blob); + OPENSSL_free(info->_.embedded.pem_name); + break; + case OSSL_STORE_INFO_NAME: + OPENSSL_free(info->_.name.name); + OPENSSL_free(info->_.name.desc); + break; + case OSSL_STORE_INFO_PARAMS: + EVP_PKEY_free(info->_.params); + break; + case OSSL_STORE_INFO_PKEY: + EVP_PKEY_free(info->_.pkey); + break; + case OSSL_STORE_INFO_CERT: + X509_free(info->_.x509); + break; + case OSSL_STORE_INFO_CRL: + X509_CRL_free(info->_.crl); + break; + } + OPENSSL_free(info); + } +} + +int OSSL_STORE_supports_search(OSSL_STORE_CTX *ctx, int search_type) +{ + OSSL_STORE_SEARCH tmp_search; + + if (ctx->loader->find == NULL) + return 0; + tmp_search.search_type = search_type; + return ctx->loader->find(NULL, &tmp_search); +} + +/* Search term constructors */ +OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_name(X509_NAME *name) +{ + OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); + + if (search == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_SEARCH_BY_NAME, + ERR_R_MALLOC_FAILURE); + return NULL; + } + + search->search_type = OSSL_STORE_SEARCH_BY_NAME; + search->name = name; + return search; +} + +OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_issuer_serial(X509_NAME *name, + const ASN1_INTEGER *serial) +{ + OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); + + if (search == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ISSUER_SERIAL, + ERR_R_MALLOC_FAILURE); + return NULL; + } + + search->search_type = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; + search->name = name; + search->serial = serial; + return search; +} + +OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_key_fingerprint(const EVP_MD *digest, + const unsigned char + *bytes, size_t len) +{ + OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); + + if (search == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT, + ERR_R_MALLOC_FAILURE); + return NULL; + } + + if (digest != NULL && len != (size_t)EVP_MD_size(digest)) { + char buf1[20], buf2[20]; + + BIO_snprintf(buf1, sizeof(buf1), "%d", EVP_MD_size(digest)); + BIO_snprintf(buf2, sizeof(buf2), "%zu", len); + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT, + OSSL_STORE_R_FINGERPRINT_SIZE_DOES_NOT_MATCH_DIGEST); + ERR_add_error_data(5, EVP_MD_name(digest), " size is ", buf1, + ", fingerprint size is ", buf2); + } + + search->search_type = OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT; + search->digest = digest; + search->string = bytes; + search->stringlength = len; + return search; +} + +OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_alias(const char *alias) +{ + OSSL_STORE_SEARCH *search = OPENSSL_zalloc(sizeof(*search)); + + if (search == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ALIAS, + ERR_R_MALLOC_FAILURE); + return NULL; + } + + search->search_type = OSSL_STORE_SEARCH_BY_ALIAS; + search->string = (const unsigned char *)alias; + search->stringlength = strlen(alias); + return search; +} + +/* Search term destructor */ +void OSSL_STORE_SEARCH_free(OSSL_STORE_SEARCH *search) +{ + OPENSSL_free(search); +} + +/* Search term accessors */ +int OSSL_STORE_SEARCH_get_type(const OSSL_STORE_SEARCH *criterion) +{ + return criterion->search_type; +} + +X509_NAME *OSSL_STORE_SEARCH_get0_name(OSSL_STORE_SEARCH *criterion) +{ + return criterion->name; +} + +const ASN1_INTEGER *OSSL_STORE_SEARCH_get0_serial(const OSSL_STORE_SEARCH + *criterion) +{ + return criterion->serial; +} + +const unsigned char *OSSL_STORE_SEARCH_get0_bytes(const OSSL_STORE_SEARCH + *criterion, size_t *length) +{ + *length = criterion->stringlength; + return criterion->string; +} + +const char *OSSL_STORE_SEARCH_get0_string(const OSSL_STORE_SEARCH *criterion) +{ + return (const char *)criterion->string; +} + +const EVP_MD *OSSL_STORE_SEARCH_get0_digest(const OSSL_STORE_SEARCH *criterion) +{ + return criterion->digest; +} + +/* Internal functions */ +OSSL_STORE_INFO *ossl_store_info_new_EMBEDDED(const char *new_pem_name, + BUF_MEM *embedded) +{ + OSSL_STORE_INFO *info = store_info_new(OSSL_STORE_INFO_EMBEDDED, NULL); + + if (info == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_NEW_EMBEDDED, + ERR_R_MALLOC_FAILURE); + return NULL; + } + + info->_.embedded.blob = embedded; + info->_.embedded.pem_name = + new_pem_name == NULL ? NULL : OPENSSL_strdup(new_pem_name); + + if (new_pem_name != NULL && info->_.embedded.pem_name == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_INFO_NEW_EMBEDDED, + ERR_R_MALLOC_FAILURE); + OSSL_STORE_INFO_free(info); + info = NULL; + } + + return info; +} + +BUF_MEM *ossl_store_info_get0_EMBEDDED_buffer(OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_EMBEDDED) + return info->_.embedded.blob; + return NULL; +} + +char *ossl_store_info_get0_EMBEDDED_pem_name(OSSL_STORE_INFO *info) +{ + if (info->type == OSSL_STORE_INFO_EMBEDDED) + return info->_.embedded.pem_name; + return NULL; +} + +OSSL_STORE_CTX *ossl_store_attach_pem_bio(BIO *bp, const UI_METHOD *ui_method, + void *ui_data) +{ + OSSL_STORE_CTX *ctx = NULL; + const OSSL_STORE_LOADER *loader = NULL; + OSSL_STORE_LOADER_CTX *loader_ctx = NULL; + + if ((loader = ossl_store_get0_loader_int("file")) == NULL + || ((loader_ctx = ossl_store_file_attach_pem_bio_int(bp)) == NULL)) + goto done; + if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_ATTACH_PEM_BIO, + ERR_R_MALLOC_FAILURE); + goto done; + } + + ctx->loader = loader; + ctx->loader_ctx = loader_ctx; + loader_ctx = NULL; + ctx->ui_method = ui_method; + ctx->ui_data = ui_data; + ctx->post_process = NULL; + ctx->post_process_data = NULL; + + done: + if (loader_ctx != NULL) + /* + * We ignore a returned error because we will return NULL anyway in + * this case, so if something goes wrong when closing, that'll simply + * just add another entry on the error stack. + */ + (void)loader->close(loader_ctx); + return ctx; +} + +int ossl_store_detach_pem_bio(OSSL_STORE_CTX *ctx) +{ + int loader_ret = ossl_store_file_detach_pem_bio_int(ctx->loader_ctx); + + OPENSSL_free(ctx); + return loader_ret; +} diff --git a/crypto/store/store_locl.h b/crypto/store/store_locl.h new file mode 100644 index 00000000..369dcb33 --- /dev/null +++ b/crypto/store/store_locl.h @@ -0,0 +1,132 @@ +/* + * Copyright 2016-2018 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 "internal/thread_once.h" +#include +#include +#include +#include +#include +#include + +/*- + * OSSL_STORE_INFO stuff + * --------------------- + */ + +struct ossl_store_info_st { + int type; + union { + void *data; /* used internally as generic pointer */ + + struct { + BUF_MEM *blob; + char *pem_name; + } embedded; /* when type == OSSL_STORE_INFO_EMBEDDED */ + + struct { + char *name; + char *desc; + } name; /* when type == OSSL_STORE_INFO_NAME */ + + EVP_PKEY *params; /* when type == OSSL_STORE_INFO_PARAMS */ + EVP_PKEY *pkey; /* when type == OSSL_STORE_INFO_PKEY */ + X509 *x509; /* when type == OSSL_STORE_INFO_CERT */ + X509_CRL *crl; /* when type == OSSL_STORE_INFO_CRL */ + } _; +}; + +DEFINE_STACK_OF(OSSL_STORE_INFO) + +/* + * EMBEDDED is a special type of OSSL_STORE_INFO, specially for the file + * handlers. It should never reach a calling application or any engine. + * However, it can be used by a FILE_HANDLER's try_decode function to signal + * that it has decoded the incoming blob into a new blob, and that the + * attempted decoding should be immediately restarted with the new blob, using + * the new PEM name. + */ +/* + * Because this is an internal type, we don't make it public. + */ +#define OSSL_STORE_INFO_EMBEDDED -1 +OSSL_STORE_INFO *ossl_store_info_new_EMBEDDED(const char *new_pem_name, + BUF_MEM *embedded); +BUF_MEM *ossl_store_info_get0_EMBEDDED_buffer(OSSL_STORE_INFO *info); +char *ossl_store_info_get0_EMBEDDED_pem_name(OSSL_STORE_INFO *info); + +/*- + * OSSL_STORE_SEARCH stuff + * ----------------------- + */ + +struct ossl_store_search_st { + int search_type; + + /* + * Used by OSSL_STORE_SEARCH_BY_NAME and + * OSSL_STORE_SEARCH_BY_ISSUER_SERIAL + */ + X509_NAME *name; + + /* Used by OSSL_STORE_SEARCH_BY_ISSUER_SERIAL */ + const ASN1_INTEGER *serial; + + /* Used by OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT */ + const EVP_MD *digest; + + /* + * Used by OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT and + * OSSL_STORE_SEARCH_BY_ALIAS + */ + const unsigned char *string; + size_t stringlength; +}; + +/*- + * OSSL_STORE_LOADER stuff + * ----------------------- + */ + +int ossl_store_register_loader_int(OSSL_STORE_LOADER *loader); +OSSL_STORE_LOADER *ossl_store_unregister_loader_int(const char *scheme); + +/* loader stuff */ +struct ossl_store_loader_st { + const char *scheme; + ENGINE *engine; + OSSL_STORE_open_fn open; + OSSL_STORE_ctrl_fn ctrl; + OSSL_STORE_expect_fn expect; + OSSL_STORE_find_fn find; + OSSL_STORE_load_fn load; + OSSL_STORE_eof_fn eof; + OSSL_STORE_error_fn error; + OSSL_STORE_close_fn close; +}; +DEFINE_LHASH_OF(OSSL_STORE_LOADER); + +const OSSL_STORE_LOADER *ossl_store_get0_loader_int(const char *scheme); +void ossl_store_destroy_loaders_int(void); + +/*- + * OSSL_STORE init stuff + * --------------------- + */ + +int ossl_store_init_once(void); +int ossl_store_file_loader_init(void); + +/*- + * 'file' scheme stuff + * ------------------- + */ + +OSSL_STORE_LOADER_CTX *ossl_store_file_attach_pem_bio_int(BIO *bp); +int ossl_store_file_detach_pem_bio_int(OSSL_STORE_LOADER_CTX *ctx); diff --git a/crypto/store/store_register.c b/crypto/store/store_register.c new file mode 100644 index 00000000..e68cb3c5 --- /dev/null +++ b/crypto/store/store_register.c @@ -0,0 +1,297 @@ +/* + * Copyright 2016-2018 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 +#include "internal/ctype.h" +#include + +#include +#include +#include "store_locl.h" + +static CRYPTO_RWLOCK *registry_lock; +static CRYPTO_ONCE registry_init = CRYPTO_ONCE_STATIC_INIT; + +DEFINE_RUN_ONCE_STATIC(do_registry_init) +{ + registry_lock = CRYPTO_THREAD_lock_new(); + return registry_lock != NULL; +} + +/* + * Functions for manipulating OSSL_STORE_LOADERs + */ + +OSSL_STORE_LOADER *OSSL_STORE_LOADER_new(ENGINE *e, const char *scheme) +{ + OSSL_STORE_LOADER *res = NULL; + + /* + * We usually don't check NULL arguments. For loaders, though, the + * scheme is crucial and must never be NULL, or the user will get + * mysterious errors when trying to register the created loader + * later on. + */ + if (scheme == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_LOADER_NEW, + OSSL_STORE_R_INVALID_SCHEME); + return NULL; + } + + if ((res = OPENSSL_zalloc(sizeof(*res))) == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_LOADER_NEW, ERR_R_MALLOC_FAILURE); + return NULL; + } + + res->engine = e; + res->scheme = scheme; + return res; +} + +const ENGINE *OSSL_STORE_LOADER_get0_engine(const OSSL_STORE_LOADER *loader) +{ + return loader->engine; +} + +const char *OSSL_STORE_LOADER_get0_scheme(const OSSL_STORE_LOADER *loader) +{ + return loader->scheme; +} + +int OSSL_STORE_LOADER_set_open(OSSL_STORE_LOADER *loader, + OSSL_STORE_open_fn open_function) +{ + loader->open = open_function; + return 1; +} + +int OSSL_STORE_LOADER_set_ctrl(OSSL_STORE_LOADER *loader, + OSSL_STORE_ctrl_fn ctrl_function) +{ + loader->ctrl = ctrl_function; + return 1; +} + +int OSSL_STORE_LOADER_set_expect(OSSL_STORE_LOADER *loader, + OSSL_STORE_expect_fn expect_function) +{ + loader->expect = expect_function; + return 1; +} + +int OSSL_STORE_LOADER_set_find(OSSL_STORE_LOADER *loader, + OSSL_STORE_find_fn find_function) +{ + loader->find = find_function; + return 1; +} + +int OSSL_STORE_LOADER_set_load(OSSL_STORE_LOADER *loader, + OSSL_STORE_load_fn load_function) +{ + loader->load = load_function; + return 1; +} + +int OSSL_STORE_LOADER_set_eof(OSSL_STORE_LOADER *loader, + OSSL_STORE_eof_fn eof_function) +{ + loader->eof = eof_function; + return 1; +} + +int OSSL_STORE_LOADER_set_error(OSSL_STORE_LOADER *loader, + OSSL_STORE_error_fn error_function) +{ + loader->error = error_function; + return 1; +} + +int OSSL_STORE_LOADER_set_close(OSSL_STORE_LOADER *loader, + OSSL_STORE_close_fn close_function) +{ + loader->close = close_function; + return 1; +} + +void OSSL_STORE_LOADER_free(OSSL_STORE_LOADER *loader) +{ + OPENSSL_free(loader); +} + +/* + * Functions for registering OSSL_STORE_LOADERs + */ + +static unsigned long store_loader_hash(const OSSL_STORE_LOADER *v) +{ + return OPENSSL_LH_strhash(v->scheme); +} + +static int store_loader_cmp(const OSSL_STORE_LOADER *a, + const OSSL_STORE_LOADER *b) +{ + assert(a->scheme != NULL && b->scheme != NULL); + return strcmp(a->scheme, b->scheme); +} + +static LHASH_OF(OSSL_STORE_LOADER) *loader_register = NULL; + +int ossl_store_register_loader_int(OSSL_STORE_LOADER *loader) +{ + const char *scheme = loader->scheme; + int ok = 0; + + /* + * Check that the given scheme conforms to correct scheme syntax as per + * RFC 3986: + * + * scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + */ + if (ossl_isalpha(*scheme)) + while (*scheme != '\0' + && (ossl_isalpha(*scheme) + || ossl_isdigit(*scheme) + || strchr("+-.", *scheme) != NULL)) + scheme++; + if (*scheme != '\0') { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_REGISTER_LOADER_INT, + OSSL_STORE_R_INVALID_SCHEME); + ERR_add_error_data(2, "scheme=", loader->scheme); + return 0; + } + + /* Check that functions we absolutely require are present */ + if (loader->open == NULL || loader->load == NULL || loader->eof == NULL + || loader->error == NULL || loader->close == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_REGISTER_LOADER_INT, + OSSL_STORE_R_LOADER_INCOMPLETE); + return 0; + } + + if (!RUN_ONCE(®istry_init, do_registry_init)) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_REGISTER_LOADER_INT, + ERR_R_MALLOC_FAILURE); + return 0; + } + CRYPTO_THREAD_write_lock(registry_lock); + + if (loader_register == NULL) { + loader_register = lh_OSSL_STORE_LOADER_new(store_loader_hash, + store_loader_cmp); + } + + if (loader_register != NULL + && (lh_OSSL_STORE_LOADER_insert(loader_register, loader) != NULL + || lh_OSSL_STORE_LOADER_error(loader_register) == 0)) + ok = 1; + + CRYPTO_THREAD_unlock(registry_lock); + + return ok; +} +int OSSL_STORE_register_loader(OSSL_STORE_LOADER *loader) +{ + if (!ossl_store_init_once()) + return 0; + return ossl_store_register_loader_int(loader); +} + +const OSSL_STORE_LOADER *ossl_store_get0_loader_int(const char *scheme) +{ + OSSL_STORE_LOADER template; + OSSL_STORE_LOADER *loader = NULL; + + template.scheme = scheme; + template.open = NULL; + template.load = NULL; + template.eof = NULL; + template.close = NULL; + + if (!ossl_store_init_once()) + return NULL; + + if (!RUN_ONCE(®istry_init, do_registry_init)) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_GET0_LOADER_INT, + ERR_R_MALLOC_FAILURE); + return NULL; + } + CRYPTO_THREAD_write_lock(registry_lock); + + loader = lh_OSSL_STORE_LOADER_retrieve(loader_register, &template); + + if (loader == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_GET0_LOADER_INT, + OSSL_STORE_R_UNREGISTERED_SCHEME); + ERR_add_error_data(2, "scheme=", scheme); + } + + CRYPTO_THREAD_unlock(registry_lock); + + return loader; +} + +OSSL_STORE_LOADER *ossl_store_unregister_loader_int(const char *scheme) +{ + OSSL_STORE_LOADER template; + OSSL_STORE_LOADER *loader = NULL; + + template.scheme = scheme; + template.open = NULL; + template.load = NULL; + template.eof = NULL; + template.close = NULL; + + if (!RUN_ONCE(®istry_init, do_registry_init)) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_UNREGISTER_LOADER_INT, + ERR_R_MALLOC_FAILURE); + return NULL; + } + CRYPTO_THREAD_write_lock(registry_lock); + + loader = lh_OSSL_STORE_LOADER_delete(loader_register, &template); + + if (loader == NULL) { + OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_UNREGISTER_LOADER_INT, + OSSL_STORE_R_UNREGISTERED_SCHEME); + ERR_add_error_data(2, "scheme=", scheme); + } + + CRYPTO_THREAD_unlock(registry_lock); + + return loader; +} +OSSL_STORE_LOADER *OSSL_STORE_unregister_loader(const char *scheme) +{ + if (!ossl_store_init_once()) + return 0; + return ossl_store_unregister_loader_int(scheme); +} + +void ossl_store_destroy_loaders_int(void) +{ + assert(lh_OSSL_STORE_LOADER_num_items(loader_register) == 0); + lh_OSSL_STORE_LOADER_free(loader_register); + loader_register = NULL; + CRYPTO_THREAD_lock_free(registry_lock); + registry_lock = NULL; +} + +/* + * Functions to list OSSL_STORE loaders + */ + +IMPLEMENT_LHASH_DOALL_ARG_CONST(OSSL_STORE_LOADER, void); +int OSSL_STORE_do_all_loaders(void (*do_function) (const OSSL_STORE_LOADER + *loader, void *do_arg), + void *do_arg) +{ + lh_OSSL_STORE_LOADER_doall_void(loader_register, do_function, do_arg); + return 1; +} diff --git a/crypto/store/store_strings.c b/crypto/store/store_strings.c new file mode 100644 index 00000000..76cf3164 --- /dev/null +++ b/crypto/store/store_strings.c @@ -0,0 +1,28 @@ +/* + * Copyright 2016-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 + +static char *type_strings[] = { + "Name", /* OSSL_STORE_INFO_NAME */ + "Parameters", /* OSSL_STORE_INFO_PARAMS */ + "Pkey", /* OSSL_STORE_INFO_PKEY */ + "Certificate", /* OSSL_STORE_INFO_CERT */ + "CRL" /* OSSL_STORE_INFO_CRL */ +}; + +const char *OSSL_STORE_INFO_type_string(int type) +{ + int types = sizeof(type_strings) / sizeof(type_strings[0]); + + if (type < 1 || type > types) + return NULL; + + return type_strings[type - 1]; +} diff --git a/crypto/threads_none.c b/crypto/threads_none.c index 72bf25b0..30ed4e69 100644 --- a/crypto/threads_none.c +++ b/crypto/threads_none.c @@ -8,6 +8,7 @@ */ #include +#include "internal/cryptlib.h" #if !defined(OPENSSL_THREADS) || defined(CRYPTO_TDEBUG) @@ -24,19 +25,22 @@ CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void) int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock) { - OPENSSL_assert(*(unsigned int *)lock == 1); + if (!ossl_assert(*(unsigned int *)lock == 1)) + return 0; return 1; } int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock) { - OPENSSL_assert(*(unsigned int *)lock == 1); + if (!ossl_assert(*(unsigned int *)lock == 1)) + return 0; return 1; } int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock) { - OPENSSL_assert(*(unsigned int *)lock == 1); + if (!ossl_assert(*(unsigned int *)lock == 1)) + return 0; return 1; } @@ -121,4 +125,21 @@ int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock) return 1; } +int CRYPTO_atomic_read(int *val, int *ret, CRYPTO_RWLOCK *lock) +{ + *ret = *val; + return 1; +} + +int CRYPTO_atomic_write(int *val, int n, CRYPTO_RWLOCK *lock) +{ + *val = n; + return 1; +} + +int openssl_init_fork_handlers(void) +{ + return 0; +} + #endif diff --git a/crypto/threads_pthread.c b/crypto/threads_pthread.c index 151013e4..3aeef216 100644 --- a/crypto/threads_pthread.c +++ b/crypto/threads_pthread.c @@ -8,6 +8,7 @@ */ #include +#include "internal/cryptlib.h" #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && !defined(OPENSSL_SYS_WINDOWS) @@ -168,4 +169,60 @@ int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock) return 1; } +int CRYPTO_atomic_read(int *val, int *ret, CRYPTO_RWLOCK *lock) +{ +# if defined(__GNUC__) && defined(__ATOMIC_ACQUIRE) + if (__atomic_is_lock_free(sizeof(*val), val)) { + __atomic_load(val, ret, __ATOMIC_ACQUIRE); + return 1; + } +# endif + if (!CRYPTO_THREAD_read_lock(lock)) + return 0; + + *ret = *val; + + if (!CRYPTO_THREAD_unlock(lock)) + return 0; + + return 1; +} + +int CRYPTO_atomic_write(int *val, int n, CRYPTO_RWLOCK *lock) +{ +# if defined(__GNUC__) && defined(__ATOMIC_RELEASE) + if (__atomic_is_lock_free(sizeof(*val), val)) { + __atomic_store(val, &n, __ATOMIC_RELEASE); + return 1; + } +# endif + if (!CRYPTO_THREAD_write_lock(lock)) + return 0; + + *val = n; + + if (!CRYPTO_THREAD_unlock(lock)) + return 0; + + return 1; +} + +# ifdef OPENSSL_SYS_UNIX +static pthread_once_t fork_once_control = PTHREAD_ONCE_INIT; + +static void fork_once_func(void) +{ + pthread_atfork(OPENSSL_fork_prepare, + OPENSSL_fork_parent, OPENSSL_fork_child); +} +# endif + +int openssl_init_fork_handlers(void) +{ +# ifdef OPENSSL_SYS_UNIX + if (pthread_once(&fork_once_control, fork_once_func) == 0) + return 1; +# endif + return 0; +} #endif diff --git a/crypto/threads_win.c b/crypto/threads_win.c index 4e0de908..f222aa5d 100644 --- a/crypto/threads_win.c +++ b/crypto/threads_win.c @@ -133,4 +133,21 @@ int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock) return 1; } +int CRYPTO_atomic_read(int *val, int *ret, CRYPTO_RWLOCK *lock) +{ + *ret = InterlockedCompareExchange(val, 0, 0); + return 1; +} + +int CRYPTO_atomic_write(int *val, int n, CRYPTO_RWLOCK *lock) +{ + InterlockedExchange(val, n); + return 1; +} + +int openssl_init_fork_handlers(void) +{ + return 0; +} + #endif diff --git a/crypto/ts/ts_asn1.c b/crypto/ts/ts_asn1.c index e60675ab..87072070 100644 --- a/crypto/ts/ts_asn1.c +++ b/crypto/ts/ts_asn1.c @@ -225,6 +225,23 @@ ASN1_SEQUENCE(ESS_SIGNING_CERT) = { IMPLEMENT_ASN1_FUNCTIONS_const(ESS_SIGNING_CERT) IMPLEMENT_ASN1_DUP_FUNCTION(ESS_SIGNING_CERT) +ASN1_SEQUENCE(ESS_CERT_ID_V2) = { + ASN1_OPT(ESS_CERT_ID_V2, hash_alg, X509_ALGOR), + ASN1_SIMPLE(ESS_CERT_ID_V2, hash, ASN1_OCTET_STRING), + ASN1_OPT(ESS_CERT_ID_V2, issuer_serial, ESS_ISSUER_SERIAL) +} static_ASN1_SEQUENCE_END(ESS_CERT_ID_V2) + +IMPLEMENT_ASN1_FUNCTIONS_const(ESS_CERT_ID_V2) +IMPLEMENT_ASN1_DUP_FUNCTION(ESS_CERT_ID_V2) + +ASN1_SEQUENCE(ESS_SIGNING_CERT_V2) = { + ASN1_SEQUENCE_OF(ESS_SIGNING_CERT_V2, cert_ids, ESS_CERT_ID_V2), + ASN1_SEQUENCE_OF_OPT(ESS_SIGNING_CERT_V2, policy_info, POLICYINFO) +} static_ASN1_SEQUENCE_END(ESS_SIGNING_CERT_V2) + +IMPLEMENT_ASN1_FUNCTIONS_const(ESS_SIGNING_CERT_V2) +IMPLEMENT_ASN1_DUP_FUNCTION(ESS_SIGNING_CERT_V2) + /* Getting encapsulated TS_TST_INFO object from PKCS7. */ TS_TST_INFO *PKCS7_to_TS_TST_INFO(PKCS7 *token) { diff --git a/crypto/ts/ts_conf.c b/crypto/ts/ts_conf.c index f5f3934d..625089a5 100644 --- a/crypto/ts/ts_conf.c +++ b/crypto/ts/ts_conf.c @@ -37,6 +37,7 @@ #define ENV_CLOCK_PRECISION_DIGITS "clock_precision_digits" #define ENV_VALUE_YES "yes" #define ENV_VALUE_NO "no" +#define ENV_ESS_CERT_ID_ALG "ess_cert_id_alg" /* Function definitions for certificate and key loading. */ @@ -466,3 +467,27 @@ int TS_CONF_set_ess_cert_id_chain(CONF *conf, const char *section, return ts_CONF_add_flag(conf, section, ENV_ESS_CERT_ID_CHAIN, TS_ESS_CERT_ID_CHAIN, ctx); } + +int TS_CONF_set_ess_cert_id_digest(CONF *conf, const char *section, + TS_RESP_CTX *ctx) +{ + int ret = 0; + const EVP_MD *cert_md = NULL; + const char *md = NCONF_get_string(conf, section, ENV_ESS_CERT_ID_ALG); + + if (md == NULL) + md = "sha1"; + + cert_md = EVP_get_digestbyname(md); + if (cert_md == NULL) { + ts_CONF_invalid(section, ENV_ESS_CERT_ID_ALG); + goto err; + } + + if (!TS_RESP_CTX_set_ess_cert_id_digest(ctx, cert_md)) + goto err; + + ret = 1; +err: + return ret; +} diff --git a/crypto/ts/ts_err.c b/crypto/ts/ts_err.c index a6d73a17..1f3854d8 100644 --- a/crypto/ts/ts_err.c +++ b/crypto/ts/ts_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,124 +8,165 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_TS,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_TS,0,reason) - -static ERR_STRING_DATA TS_str_functs[] = { - {ERR_FUNC(TS_F_DEF_SERIAL_CB), "def_serial_cb"}, - {ERR_FUNC(TS_F_DEF_TIME_CB), "def_time_cb"}, - {ERR_FUNC(TS_F_ESS_ADD_SIGNING_CERT), "ESS_add_signing_cert"}, - {ERR_FUNC(TS_F_ESS_CERT_ID_NEW_INIT), "ess_CERT_ID_new_init"}, - {ERR_FUNC(TS_F_ESS_SIGNING_CERT_NEW_INIT), "ess_SIGNING_CERT_new_init"}, - {ERR_FUNC(TS_F_INT_TS_RESP_VERIFY_TOKEN), "int_ts_RESP_verify_token"}, - {ERR_FUNC(TS_F_PKCS7_TO_TS_TST_INFO), "PKCS7_to_TS_TST_INFO"}, - {ERR_FUNC(TS_F_TS_ACCURACY_SET_MICROS), "TS_ACCURACY_set_micros"}, - {ERR_FUNC(TS_F_TS_ACCURACY_SET_MILLIS), "TS_ACCURACY_set_millis"}, - {ERR_FUNC(TS_F_TS_ACCURACY_SET_SECONDS), "TS_ACCURACY_set_seconds"}, - {ERR_FUNC(TS_F_TS_CHECK_IMPRINTS), "ts_check_imprints"}, - {ERR_FUNC(TS_F_TS_CHECK_NONCES), "ts_check_nonces"}, - {ERR_FUNC(TS_F_TS_CHECK_POLICY), "ts_check_policy"}, - {ERR_FUNC(TS_F_TS_CHECK_SIGNING_CERTS), "ts_check_signing_certs"}, - {ERR_FUNC(TS_F_TS_CHECK_STATUS_INFO), "ts_check_status_info"}, - {ERR_FUNC(TS_F_TS_COMPUTE_IMPRINT), "ts_compute_imprint"}, - {ERR_FUNC(TS_F_TS_CONF_INVALID), "ts_CONF_invalid"}, - {ERR_FUNC(TS_F_TS_CONF_LOAD_CERT), "TS_CONF_load_cert"}, - {ERR_FUNC(TS_F_TS_CONF_LOAD_CERTS), "TS_CONF_load_certs"}, - {ERR_FUNC(TS_F_TS_CONF_LOAD_KEY), "TS_CONF_load_key"}, - {ERR_FUNC(TS_F_TS_CONF_LOOKUP_FAIL), "ts_CONF_lookup_fail"}, - {ERR_FUNC(TS_F_TS_CONF_SET_DEFAULT_ENGINE), "TS_CONF_set_default_engine"}, - {ERR_FUNC(TS_F_TS_GET_STATUS_TEXT), "ts_get_status_text"}, - {ERR_FUNC(TS_F_TS_MSG_IMPRINT_SET_ALGO), "TS_MSG_IMPRINT_set_algo"}, - {ERR_FUNC(TS_F_TS_REQ_SET_MSG_IMPRINT), "TS_REQ_set_msg_imprint"}, - {ERR_FUNC(TS_F_TS_REQ_SET_NONCE), "TS_REQ_set_nonce"}, - {ERR_FUNC(TS_F_TS_REQ_SET_POLICY_ID), "TS_REQ_set_policy_id"}, - {ERR_FUNC(TS_F_TS_RESP_CREATE_RESPONSE), "TS_RESP_create_response"}, - {ERR_FUNC(TS_F_TS_RESP_CREATE_TST_INFO), "ts_RESP_create_tst_info"}, - {ERR_FUNC(TS_F_TS_RESP_CTX_ADD_FAILURE_INFO), +static const ERR_STRING_DATA TS_str_functs[] = { + {ERR_PACK(ERR_LIB_TS, TS_F_DEF_SERIAL_CB, 0), "def_serial_cb"}, + {ERR_PACK(ERR_LIB_TS, TS_F_DEF_TIME_CB, 0), "def_time_cb"}, + {ERR_PACK(ERR_LIB_TS, TS_F_ESS_ADD_SIGNING_CERT, 0), + "ess_add_signing_cert"}, + {ERR_PACK(ERR_LIB_TS, TS_F_ESS_ADD_SIGNING_CERT_V2, 0), + "ess_add_signing_cert_v2"}, + {ERR_PACK(ERR_LIB_TS, TS_F_ESS_CERT_ID_NEW_INIT, 0), + "ess_CERT_ID_new_init"}, + {ERR_PACK(ERR_LIB_TS, TS_F_ESS_CERT_ID_V2_NEW_INIT, 0), + "ess_cert_id_v2_new_init"}, + {ERR_PACK(ERR_LIB_TS, TS_F_ESS_SIGNING_CERT_NEW_INIT, 0), + "ess_SIGNING_CERT_new_init"}, + {ERR_PACK(ERR_LIB_TS, TS_F_ESS_SIGNING_CERT_V2_NEW_INIT, 0), + "ess_signing_cert_v2_new_init"}, + {ERR_PACK(ERR_LIB_TS, TS_F_INT_TS_RESP_VERIFY_TOKEN, 0), + "int_ts_RESP_verify_token"}, + {ERR_PACK(ERR_LIB_TS, TS_F_PKCS7_TO_TS_TST_INFO, 0), + "PKCS7_to_TS_TST_INFO"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_ACCURACY_SET_MICROS, 0), + "TS_ACCURACY_set_micros"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_ACCURACY_SET_MILLIS, 0), + "TS_ACCURACY_set_millis"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_ACCURACY_SET_SECONDS, 0), + "TS_ACCURACY_set_seconds"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CHECK_IMPRINTS, 0), "ts_check_imprints"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CHECK_NONCES, 0), "ts_check_nonces"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CHECK_POLICY, 0), "ts_check_policy"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CHECK_SIGNING_CERTS, 0), + "ts_check_signing_certs"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CHECK_STATUS_INFO, 0), + "ts_check_status_info"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_COMPUTE_IMPRINT, 0), "ts_compute_imprint"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_INVALID, 0), "ts_CONF_invalid"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_LOAD_CERT, 0), "TS_CONF_load_cert"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_LOAD_CERTS, 0), "TS_CONF_load_certs"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_LOAD_KEY, 0), "TS_CONF_load_key"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_LOOKUP_FAIL, 0), "ts_CONF_lookup_fail"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_SET_DEFAULT_ENGINE, 0), + "TS_CONF_set_default_engine"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_GET_STATUS_TEXT, 0), "ts_get_status_text"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_MSG_IMPRINT_SET_ALGO, 0), + "TS_MSG_IMPRINT_set_algo"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_REQ_SET_MSG_IMPRINT, 0), + "TS_REQ_set_msg_imprint"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_REQ_SET_NONCE, 0), "TS_REQ_set_nonce"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_REQ_SET_POLICY_ID, 0), + "TS_REQ_set_policy_id"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CREATE_RESPONSE, 0), + "TS_RESP_create_response"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CREATE_TST_INFO, 0), + "ts_RESP_create_tst_info"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_ADD_FAILURE_INFO, 0), "TS_RESP_CTX_add_failure_info"}, - {ERR_FUNC(TS_F_TS_RESP_CTX_ADD_MD), "TS_RESP_CTX_add_md"}, - {ERR_FUNC(TS_F_TS_RESP_CTX_ADD_POLICY), "TS_RESP_CTX_add_policy"}, - {ERR_FUNC(TS_F_TS_RESP_CTX_NEW), "TS_RESP_CTX_new"}, - {ERR_FUNC(TS_F_TS_RESP_CTX_SET_ACCURACY), "TS_RESP_CTX_set_accuracy"}, - {ERR_FUNC(TS_F_TS_RESP_CTX_SET_CERTS), "TS_RESP_CTX_set_certs"}, - {ERR_FUNC(TS_F_TS_RESP_CTX_SET_DEF_POLICY), "TS_RESP_CTX_set_def_policy"}, - {ERR_FUNC(TS_F_TS_RESP_CTX_SET_SIGNER_CERT), + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_ADD_MD, 0), "TS_RESP_CTX_add_md"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_ADD_POLICY, 0), + "TS_RESP_CTX_add_policy"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_NEW, 0), "TS_RESP_CTX_new"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_SET_ACCURACY, 0), + "TS_RESP_CTX_set_accuracy"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_SET_CERTS, 0), + "TS_RESP_CTX_set_certs"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_SET_DEF_POLICY, 0), + "TS_RESP_CTX_set_def_policy"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_SET_SIGNER_CERT, 0), "TS_RESP_CTX_set_signer_cert"}, - {ERR_FUNC(TS_F_TS_RESP_CTX_SET_STATUS_INFO), + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_SET_STATUS_INFO, 0), "TS_RESP_CTX_set_status_info"}, - {ERR_FUNC(TS_F_TS_RESP_GET_POLICY), "ts_RESP_get_policy"}, - {ERR_FUNC(TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION), + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_GET_POLICY, 0), "ts_RESP_get_policy"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION, 0), "TS_RESP_set_genTime_with_precision"}, - {ERR_FUNC(TS_F_TS_RESP_SET_STATUS_INFO), "TS_RESP_set_status_info"}, - {ERR_FUNC(TS_F_TS_RESP_SET_TST_INFO), "TS_RESP_set_tst_info"}, - {ERR_FUNC(TS_F_TS_RESP_SIGN), "ts_RESP_sign"}, - {ERR_FUNC(TS_F_TS_RESP_VERIFY_SIGNATURE), "TS_RESP_verify_signature"}, - {ERR_FUNC(TS_F_TS_TST_INFO_SET_ACCURACY), "TS_TST_INFO_set_accuracy"}, - {ERR_FUNC(TS_F_TS_TST_INFO_SET_MSG_IMPRINT), + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_SET_STATUS_INFO, 0), + "TS_RESP_set_status_info"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_SET_TST_INFO, 0), + "TS_RESP_set_tst_info"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_SIGN, 0), "ts_RESP_sign"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_VERIFY_SIGNATURE, 0), + "TS_RESP_verify_signature"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_ACCURACY, 0), + "TS_TST_INFO_set_accuracy"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_MSG_IMPRINT, 0), "TS_TST_INFO_set_msg_imprint"}, - {ERR_FUNC(TS_F_TS_TST_INFO_SET_NONCE), "TS_TST_INFO_set_nonce"}, - {ERR_FUNC(TS_F_TS_TST_INFO_SET_POLICY_ID), "TS_TST_INFO_set_policy_id"}, - {ERR_FUNC(TS_F_TS_TST_INFO_SET_SERIAL), "TS_TST_INFO_set_serial"}, - {ERR_FUNC(TS_F_TS_TST_INFO_SET_TIME), "TS_TST_INFO_set_time"}, - {ERR_FUNC(TS_F_TS_TST_INFO_SET_TSA), "TS_TST_INFO_set_tsa"}, - {ERR_FUNC(TS_F_TS_VERIFY), "TS_VERIFY"}, - {ERR_FUNC(TS_F_TS_VERIFY_CERT), "ts_verify_cert"}, - {ERR_FUNC(TS_F_TS_VERIFY_CTX_NEW), "TS_VERIFY_CTX_new"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_NONCE, 0), + "TS_TST_INFO_set_nonce"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_POLICY_ID, 0), + "TS_TST_INFO_set_policy_id"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_SERIAL, 0), + "TS_TST_INFO_set_serial"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_TIME, 0), + "TS_TST_INFO_set_time"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_TSA, 0), "TS_TST_INFO_set_tsa"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_VERIFY, 0), ""}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_VERIFY_CERT, 0), "ts_verify_cert"}, + {ERR_PACK(ERR_LIB_TS, TS_F_TS_VERIFY_CTX_NEW, 0), "TS_VERIFY_CTX_new"}, {0, NULL} }; -static ERR_STRING_DATA TS_str_reasons[] = { - {ERR_REASON(TS_R_BAD_PKCS7_TYPE), "bad pkcs7 type"}, - {ERR_REASON(TS_R_BAD_TYPE), "bad type"}, - {ERR_REASON(TS_R_CANNOT_LOAD_CERT), "cannot load certificate"}, - {ERR_REASON(TS_R_CANNOT_LOAD_KEY), "cannot load private key"}, - {ERR_REASON(TS_R_CERTIFICATE_VERIFY_ERROR), "certificate verify error"}, - {ERR_REASON(TS_R_COULD_NOT_SET_ENGINE), "could not set engine"}, - {ERR_REASON(TS_R_COULD_NOT_SET_TIME), "could not set time"}, - {ERR_REASON(TS_R_DETACHED_CONTENT), "detached content"}, - {ERR_REASON(TS_R_ESS_ADD_SIGNING_CERT_ERROR), - "ess add signing cert error"}, - {ERR_REASON(TS_R_ESS_SIGNING_CERTIFICATE_ERROR), - "ess signing certificate error"}, - {ERR_REASON(TS_R_INVALID_NULL_POINTER), "invalid null pointer"}, - {ERR_REASON(TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE), - "invalid signer certificate purpose"}, - {ERR_REASON(TS_R_MESSAGE_IMPRINT_MISMATCH), "message imprint mismatch"}, - {ERR_REASON(TS_R_NONCE_MISMATCH), "nonce mismatch"}, - {ERR_REASON(TS_R_NONCE_NOT_RETURNED), "nonce not returned"}, - {ERR_REASON(TS_R_NO_CONTENT), "no content"}, - {ERR_REASON(TS_R_NO_TIME_STAMP_TOKEN), "no time stamp token"}, - {ERR_REASON(TS_R_PKCS7_ADD_SIGNATURE_ERROR), "pkcs7 add signature error"}, - {ERR_REASON(TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR), - "pkcs7 add signed attr error"}, - {ERR_REASON(TS_R_PKCS7_TO_TS_TST_INFO_FAILED), - "pkcs7 to ts tst info failed"}, - {ERR_REASON(TS_R_POLICY_MISMATCH), "policy mismatch"}, - {ERR_REASON(TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), - "private key does not match certificate"}, - {ERR_REASON(TS_R_RESPONSE_SETUP_ERROR), "response setup error"}, - {ERR_REASON(TS_R_SIGNATURE_FAILURE), "signature failure"}, - {ERR_REASON(TS_R_THERE_MUST_BE_ONE_SIGNER), "there must be one signer"}, - {ERR_REASON(TS_R_TIME_SYSCALL_ERROR), "time syscall error"}, - {ERR_REASON(TS_R_TOKEN_NOT_PRESENT), "token not present"}, - {ERR_REASON(TS_R_TOKEN_PRESENT), "token present"}, - {ERR_REASON(TS_R_TSA_NAME_MISMATCH), "tsa name mismatch"}, - {ERR_REASON(TS_R_TSA_UNTRUSTED), "tsa untrusted"}, - {ERR_REASON(TS_R_TST_INFO_SETUP_ERROR), "tst info setup error"}, - {ERR_REASON(TS_R_TS_DATASIGN), "ts datasign"}, - {ERR_REASON(TS_R_UNACCEPTABLE_POLICY), "unacceptable policy"}, - {ERR_REASON(TS_R_UNSUPPORTED_MD_ALGORITHM), "unsupported md algorithm"}, - {ERR_REASON(TS_R_UNSUPPORTED_VERSION), "unsupported version"}, - {ERR_REASON(TS_R_VAR_BAD_VALUE), "var bad value"}, - {ERR_REASON(TS_R_VAR_LOOKUP_FAILURE), "cannot find config variable"}, - {ERR_REASON(TS_R_WRONG_CONTENT_TYPE), "wrong content type"}, +static const ERR_STRING_DATA TS_str_reasons[] = { + {ERR_PACK(ERR_LIB_TS, 0, TS_R_BAD_PKCS7_TYPE), "bad pkcs7 type"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_BAD_TYPE), "bad type"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_CANNOT_LOAD_CERT), "cannot load certificate"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_CANNOT_LOAD_KEY), "cannot load private key"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_CERTIFICATE_VERIFY_ERROR), + "certificate verify error"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_COULD_NOT_SET_ENGINE), + "could not set engine"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_COULD_NOT_SET_TIME), "could not set time"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_DETACHED_CONTENT), "detached content"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_ESS_ADD_SIGNING_CERT_ERROR), + "ess add signing cert error"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR), + "ess add signing cert v2 error"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_ESS_SIGNING_CERTIFICATE_ERROR), + "ess signing certificate error"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_INVALID_NULL_POINTER), + "invalid null pointer"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE), + "invalid signer certificate purpose"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_MESSAGE_IMPRINT_MISMATCH), + "message imprint mismatch"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_NONCE_MISMATCH), "nonce mismatch"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_NONCE_NOT_RETURNED), "nonce not returned"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_NO_CONTENT), "no content"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_NO_TIME_STAMP_TOKEN), "no time stamp token"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_PKCS7_ADD_SIGNATURE_ERROR), + "pkcs7 add signature error"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR), + "pkcs7 add signed attr error"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_PKCS7_TO_TS_TST_INFO_FAILED), + "pkcs7 to ts tst info failed"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_POLICY_MISMATCH), "policy mismatch"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), + "private key does not match certificate"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_RESPONSE_SETUP_ERROR), + "response setup error"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_SIGNATURE_FAILURE), "signature failure"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_THERE_MUST_BE_ONE_SIGNER), + "there must be one signer"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_TIME_SYSCALL_ERROR), "time syscall error"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_TOKEN_NOT_PRESENT), "token not present"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_TOKEN_PRESENT), "token present"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_TSA_NAME_MISMATCH), "tsa name mismatch"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_TSA_UNTRUSTED), "tsa untrusted"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_TST_INFO_SETUP_ERROR), + "tst info setup error"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_TS_DATASIGN), "ts datasign"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_UNACCEPTABLE_POLICY), "unacceptable policy"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_UNSUPPORTED_MD_ALGORITHM), + "unsupported md algorithm"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_UNSUPPORTED_VERSION), "unsupported version"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_VAR_BAD_VALUE), "var bad value"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_VAR_LOOKUP_FAILURE), + "cannot find config variable"}, + {ERR_PACK(ERR_LIB_TS, 0, TS_R_WRONG_CONTENT_TYPE), "wrong content type"}, {0, NULL} }; @@ -134,10 +175,9 @@ static ERR_STRING_DATA TS_str_reasons[] = { int ERR_load_TS_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(TS_str_functs[0].error) == NULL) { - ERR_load_strings(0, TS_str_functs); - ERR_load_strings(0, TS_str_reasons); + ERR_load_strings_const(TS_str_functs); + ERR_load_strings_const(TS_str_reasons); } #endif return 1; diff --git a/crypto/ts/ts_lcl.h b/crypto/ts/ts_lcl.h index d0c3cf81..771784fe 100644 --- a/crypto/ts/ts_lcl.h +++ b/crypto/ts/ts_lcl.h @@ -131,11 +131,39 @@ struct ESS_signing_cert { STACK_OF(POLICYINFO) *policy_info; }; +/*- + * ESSCertIDv2 ::= SEQUENCE { + * hashAlgorithm AlgorithmIdentifier + * DEFAULT {algorithm id-sha256}, + * certHash Hash, + * issuerSerial IssuerSerial OPTIONAL + * } + */ + +struct ESS_cert_id_v2_st { + X509_ALGOR *hash_alg; /* Default: SHA-256 */ + ASN1_OCTET_STRING *hash; + ESS_ISSUER_SERIAL *issuer_serial; +}; + +/*- + * SigningCertificateV2 ::= SEQUENCE { + * certs SEQUENCE OF ESSCertIDv2, + * policies SEQUENCE OF PolicyInformation OPTIONAL + * } + */ + +struct ESS_signing_cert_v2_st { + STACK_OF(ESS_CERT_ID_V2) *cert_ids; + STACK_OF(POLICYINFO) *policy_info; +}; + struct TS_resp_ctx { X509 *signer_cert; EVP_PKEY *signer_key; const EVP_MD *signer_md; + const EVP_MD *ess_cert_id_digest; STACK_OF(X509) *certs; /* Certs to include in signed data. */ STACK_OF(ASN1_OBJECT) *policies; /* Acceptable policies. */ ASN1_OBJECT *default_policy; /* It may appear in policies, too. */ diff --git a/crypto/ts/ts_rsp_sign.c b/crypto/ts/ts_rsp_sign.c index aea7b922..65699562 100644 --- a/crypto/ts/ts_rsp_sign.c +++ b/crypto/ts/ts_rsp_sign.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-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 @@ -7,12 +7,9 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" #include "internal/cryptlib.h" -#if defined(OPENSSL_SYS_UNIX) -# include -#endif - #include #include #include @@ -35,7 +32,16 @@ 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 int ess_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc); + +static ESS_SIGNING_CERT_V2 *ess_signing_cert_v2_new_init(const EVP_MD *hash_alg, + X509 *signcert, + STACK_OF(X509) + *certs); +static ESS_CERT_ID_V2 *ess_cert_id_v2_new_init(const EVP_MD *hash_alg, + X509 *cert, int issuer_needed); +static int ess_add_signing_cert_v2(PKCS7_SIGNER_INFO *si, + ESS_SIGNING_CERT_V2 *sc); static ASN1_GENERALIZEDTIME *TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *, long, long, @@ -628,6 +634,7 @@ static int ts_RESP_sign(TS_RESP_CTX *ctx) PKCS7 *p7 = NULL; PKCS7_SIGNER_INFO *si; STACK_OF(X509) *certs; /* Certificates to include in sc. */ + ESS_SIGNING_CERT_V2 *sc2 = NULL; ESS_SIGNING_CERT *sc = NULL; ASN1_OBJECT *oid; BIO *p7bio = NULL; @@ -671,11 +678,24 @@ static int ts_RESP_sign(TS_RESP_CTX *ctx) } certs = ctx->flags & TS_ESS_CERT_ID_CHAIN ? ctx->certs : NULL; - if ((sc = ess_SIGNING_CERT_new_init(ctx->signer_cert, certs)) == NULL) - goto err; - if (!ESS_add_signing_cert(si, sc)) { - TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_ERROR); - goto err; + if (ctx->ess_cert_id_digest == EVP_sha1()) { + if ((sc = ess_SIGNING_CERT_new_init(ctx->signer_cert, certs)) == NULL) + goto err; + + if (!ess_add_signing_cert(si, sc)) { + TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_ERROR); + goto err; + } + } else { + sc2 = ess_signing_cert_v2_new_init(ctx->ess_cert_id_digest, + ctx->signer_cert, certs); + if (sc2 == NULL) + goto err; + + if (!ess_add_signing_cert_v2(si, sc2)) { + TSerr(TS_F_TS_RESP_SIGN, TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR); + goto err; + } } if (!ts_TST_INFO_content_new(p7)) @@ -703,6 +723,7 @@ static int ts_RESP_sign(TS_RESP_CTX *ctx) "Error during signature " "generation."); BIO_free_all(p7bio); + ESS_SIGNING_CERT_V2_free(sc2); ESS_SIGNING_CERT_free(sc); PKCS7_free(p7); return ret; @@ -806,7 +827,7 @@ static int ts_TST_INFO_content_new(PKCS7 *p7) return 0; } -static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc) +static int ess_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc) { ASN1_STRING *seq = NULL; unsigned char *p, *pp = NULL; @@ -835,9 +856,133 @@ static int ESS_add_signing_cert(PKCS7_SIGNER_INFO *si, ESS_SIGNING_CERT *sc) return 0; } -static ASN1_GENERALIZEDTIME -*TS_RESP_set_genTime_with_precision(ASN1_GENERALIZEDTIME *asn1_time, - long sec, long usec, unsigned precision) +static ESS_SIGNING_CERT_V2 *ess_signing_cert_v2_new_init(const EVP_MD *hash_alg, + X509 *signcert, + STACK_OF(X509) *certs) +{ + ESS_CERT_ID_V2 *cid = NULL; + ESS_SIGNING_CERT_V2 *sc = NULL; + int i; + + if ((sc = ESS_SIGNING_CERT_V2_new()) == NULL) + goto err; + if ((cid = ess_cert_id_v2_new_init(hash_alg, signcert, 0)) == NULL) + goto err; + if (!sk_ESS_CERT_ID_V2_push(sc->cert_ids, cid)) + goto err; + cid = NULL; + + for (i = 0; i < sk_X509_num(certs); ++i) { + X509 *cert = sk_X509_value(certs, i); + + if ((cid = ess_cert_id_v2_new_init(hash_alg, cert, 1)) == NULL) + goto err; + if (!sk_ESS_CERT_ID_V2_push(sc->cert_ids, cid)) + goto err; + cid = NULL; + } + + return sc; + err: + ESS_SIGNING_CERT_V2_free(sc); + ESS_CERT_ID_V2_free(cid); + TSerr(TS_F_ESS_SIGNING_CERT_V2_NEW_INIT, ERR_R_MALLOC_FAILURE); + return NULL; +} + +static ESS_CERT_ID_V2 *ess_cert_id_v2_new_init(const EVP_MD *hash_alg, + X509 *cert, int issuer_needed) +{ + ESS_CERT_ID_V2 *cid = NULL; + GENERAL_NAME *name = NULL; + unsigned char hash[EVP_MAX_MD_SIZE]; + unsigned int hash_len = sizeof(hash); + X509_ALGOR *alg = NULL; + + memset(hash, 0, sizeof(hash)); + + if ((cid = ESS_CERT_ID_V2_new()) == NULL) + goto err; + + if (hash_alg != EVP_sha256()) { + alg = X509_ALGOR_new(); + if (alg == NULL) + goto err; + X509_ALGOR_set_md(alg, hash_alg); + if (alg->algorithm == NULL) + goto err; + cid->hash_alg = alg; + alg = NULL; + } else { + cid->hash_alg = NULL; + } + + if (!X509_digest(cert, hash_alg, hash, &hash_len)) + goto err; + + if (!ASN1_OCTET_STRING_set(cid->hash, hash, hash_len)) + goto err; + + if (issuer_needed) { + if ((cid->issuer_serial = ESS_ISSUER_SERIAL_new()) == NULL) + goto err; + if ((name = GENERAL_NAME_new()) == NULL) + goto err; + name->type = GEN_DIRNAME; + if ((name->d.dirn = X509_NAME_dup(X509_get_issuer_name(cert))) == NULL) + goto err; + if (!sk_GENERAL_NAME_push(cid->issuer_serial->issuer, name)) + goto err; + name = NULL; /* Ownership is lost. */ + ASN1_INTEGER_free(cid->issuer_serial->serial); + cid->issuer_serial->serial = + ASN1_INTEGER_dup(X509_get_serialNumber(cert)); + if (cid->issuer_serial->serial == NULL) + goto err; + } + + return cid; + err: + X509_ALGOR_free(alg); + GENERAL_NAME_free(name); + ESS_CERT_ID_V2_free(cid); + TSerr(TS_F_ESS_CERT_ID_V2_NEW_INIT, ERR_R_MALLOC_FAILURE); + return NULL; +} + +static int ess_add_signing_cert_v2(PKCS7_SIGNER_INFO *si, + ESS_SIGNING_CERT_V2 *sc) +{ + ASN1_STRING *seq = NULL; + unsigned char *p, *pp = NULL; + int len = i2d_ESS_SIGNING_CERT_V2(sc, NULL); + + if ((pp = OPENSSL_malloc(len)) == NULL) { + TSerr(TS_F_ESS_ADD_SIGNING_CERT_V2, ERR_R_MALLOC_FAILURE); + goto err; + } + + p = pp; + i2d_ESS_SIGNING_CERT_V2(sc, &p); + if ((seq = ASN1_STRING_new()) == NULL || !ASN1_STRING_set(seq, pp, len)) { + TSerr(TS_F_ESS_ADD_SIGNING_CERT_V2, ERR_R_MALLOC_FAILURE); + goto err; + } + + OPENSSL_free(pp); + pp = NULL; + return PKCS7_add_signed_attribute(si, + NID_id_smime_aa_signingCertificateV2, + 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; @@ -902,3 +1047,9 @@ static ASN1_GENERALIZEDTIME TSerr(TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION, TS_R_COULD_NOT_SET_TIME); return NULL; } + +int TS_RESP_CTX_set_ess_cert_id_digest(TS_RESP_CTX *ctx, const EVP_MD *md) +{ + ctx->ess_cert_id_digest = md; + return 1; +} diff --git a/crypto/ts/ts_rsp_verify.c b/crypto/ts/ts_rsp_verify.c index 2755dd0e..9deda81b 100644 --- a/crypto/ts/ts_rsp_verify.c +++ b/crypto/ts/ts_rsp_verify.c @@ -37,6 +37,8 @@ static int ts_check_nonces(const ASN1_INTEGER *a, TS_TST_INFO *tst_info); static int ts_check_signer_name(GENERAL_NAME *tsa_name, X509 *signer); static int ts_find_name(STACK_OF(GENERAL_NAME) *gen_names, GENERAL_NAME *name); +static int ts_find_cert_v2(STACK_OF(ESS_CERT_ID_V2) *cert_ids, X509 *cert); +static ESS_SIGNING_CERT_V2 *ess_get_signing_cert_v2(PKCS7_SIGNER_INFO *si); /* * This must be large enough to hold all values in ts_status_text (with @@ -201,34 +203,57 @@ static int ts_check_signing_certs(PKCS7_SIGNER_INFO *si, { ESS_SIGNING_CERT *ss = ess_get_signing_cert(si); STACK_OF(ESS_CERT_ID) *cert_ids = NULL; + ESS_SIGNING_CERT_V2 *ssv2 = ess_get_signing_cert_v2(si); + STACK_OF(ESS_CERT_ID_V2) *cert_ids_v2 = NULL; X509 *cert; int i = 0; int ret = 0; - if (!ss) - goto err; - cert_ids = ss->cert_ids; - cert = sk_X509_value(chain, 0); - if (ts_find_cert(cert_ids, cert) != 0) - goto err; + if (ss != NULL) { + cert_ids = ss->cert_ids; + cert = sk_X509_value(chain, 0); + if (ts_find_cert(cert_ids, cert) != 0) + goto err; - /* - * Check the other certificates of the chain if there are more than one - * certificate ids in cert_ids. - */ - if (sk_ESS_CERT_ID_num(cert_ids) > 1) { - for (i = 1; i < sk_X509_num(chain); ++i) { - cert = sk_X509_value(chain, i); - if (ts_find_cert(cert_ids, cert) < 0) - goto err; + /* + * Check the other certificates of the chain if there are more than one + * certificate ids in cert_ids. + */ + if (sk_ESS_CERT_ID_num(cert_ids) > 1) { + for (i = 1; i < sk_X509_num(chain); ++i) { + cert = sk_X509_value(chain, i); + if (ts_find_cert(cert_ids, cert) < 0) + goto err; + } } + } else if (ssv2 != NULL) { + cert_ids_v2 = ssv2->cert_ids; + cert = sk_X509_value(chain, 0); + if (ts_find_cert_v2(cert_ids_v2, cert) != 0) + goto err; + + /* + * Check the other certificates of the chain if there are more than one + * certificate ids in cert_ids. + */ + if (sk_ESS_CERT_ID_V2_num(cert_ids_v2) > 1) { + for (i = 1; i < sk_X509_num(chain); ++i) { + cert = sk_X509_value(chain, i); + if (ts_find_cert_v2(cert_ids_v2, cert) < 0) + goto err; + } + } + } else { + goto err; } + ret = 1; err: if (!ret) TSerr(TS_F_TS_CHECK_SIGNING_CERTS, TS_R_ESS_SIGNING_CERTIFICATE_ERROR); ESS_SIGNING_CERT_free(ss); + ESS_SIGNING_CERT_V2_free(ssv2); return ret; } @@ -243,6 +268,18 @@ static ESS_SIGNING_CERT *ess_get_signing_cert(PKCS7_SIGNER_INFO *si) return d2i_ESS_SIGNING_CERT(NULL, &p, attr->value.sequence->length); } +static ESS_SIGNING_CERT_V2 *ess_get_signing_cert_v2(PKCS7_SIGNER_INFO *si) +{ + ASN1_TYPE *attr; + const unsigned char *p; + + attr = PKCS7_get_signed_attribute(si, NID_id_smime_aa_signingCertificateV2); + if (attr == NULL) + return NULL; + p = attr->value.sequence->data; + return d2i_ESS_SIGNING_CERT_V2(NULL, &p, attr->value.sequence->length); +} + /* Returns < 0 if certificate is not found, certificate index otherwise. */ static int ts_find_cert(STACK_OF(ESS_CERT_ID) *cert_ids, X509 *cert) { @@ -272,6 +309,38 @@ static int ts_find_cert(STACK_OF(ESS_CERT_ID) *cert_ids, X509 *cert) return -1; } +/* Returns < 0 if certificate is not found, certificate index otherwise. */ +static int ts_find_cert_v2(STACK_OF(ESS_CERT_ID_V2) *cert_ids, X509 *cert) +{ + int i; + unsigned char cert_digest[EVP_MAX_MD_SIZE]; + unsigned int len; + + /* Look for cert in the cert_ids vector. */ + for (i = 0; i < sk_ESS_CERT_ID_V2_num(cert_ids); ++i) { + ESS_CERT_ID_V2 *cid = sk_ESS_CERT_ID_V2_value(cert_ids, i); + const EVP_MD *md; + + if (cid->hash_alg != NULL) + md = EVP_get_digestbyobj(cid->hash_alg->algorithm); + else + md = EVP_sha256(); + + X509_digest(cert, md, cert_digest, &len); + if (cid->hash->length != (int)len) + return -1; + + if (memcmp(cid->hash->data, cert_digest, cid->hash->length) == 0) { + ESS_ISSUER_SERIAL *is = cid->issuer_serial; + + if (is == NULL || !ts_issuer_serial_cmp(is, cert)) + return i; + } + } + + return -1; +} + static int ts_issuer_serial_cmp(ESS_ISSUER_SERIAL *is, X509 *cert) { GENERAL_NAME *issuer; @@ -480,7 +549,7 @@ static char *ts_get_status_text(STACK_OF(ASN1_UTF8STRING) *text) return result; } -static int ts_check_policy(const ASN1_OBJECT *req_oid, +static int ts_check_policy(const ASN1_OBJECT *req_oid, const TS_TST_INFO *tst_info) { const ASN1_OBJECT *resp_oid = tst_info->policy_id; diff --git a/crypto/txt_db/txt_db.c b/crypto/txt_db/txt_db.c index cf932a52..d6859629 100644 --- a/crypto/txt_db/txt_db.c +++ b/crypto/txt_db/txt_db.c @@ -124,7 +124,7 @@ TXT_DB *TXT_DB_read(BIO *in, int num) OPENSSL_free(ret->qual); OPENSSL_free(ret); } - return (NULL); + return NULL; } OPENSSL_STRING *TXT_DB_get_by_index(TXT_DB *db, int idx, @@ -135,16 +135,16 @@ OPENSSL_STRING *TXT_DB_get_by_index(TXT_DB *db, int idx, if (idx >= db->num_fields) { db->error = DB_ERROR_INDEX_OUT_OF_RANGE; - return (NULL); + return NULL; } lh = db->index[idx]; if (lh == NULL) { db->error = DB_ERROR_NO_INDEX; - return (NULL); + return NULL; } ret = lh_OPENSSL_STRING_retrieve(lh, value); db->error = DB_ERROR_OK; - return (ret); + return ret; } int TXT_DB_create_index(TXT_DB *db, int field, int (*qual) (OPENSSL_STRING *), @@ -156,12 +156,12 @@ int TXT_DB_create_index(TXT_DB *db, int field, int (*qual) (OPENSSL_STRING *), if (field >= db->num_fields) { db->error = DB_ERROR_INDEX_OUT_OF_RANGE; - return (0); + return 0; } /* FIXME: we lose type checking at this point */ if ((idx = (LHASH_OF(OPENSSL_STRING) *)OPENSSL_LH_new(hash, cmp)) == NULL) { db->error = DB_ERROR_MALLOC; - return (0); + return 0; } n = sk_OPENSSL_PSTRING_num(db->data); for (i = 0; i < n; i++) { @@ -173,18 +173,18 @@ int TXT_DB_create_index(TXT_DB *db, int field, int (*qual) (OPENSSL_STRING *), db->arg1 = sk_OPENSSL_PSTRING_find(db->data, k); db->arg2 = i; lh_OPENSSL_STRING_free(idx); - return (0); + return 0; } if (lh_OPENSSL_STRING_retrieve(idx, r) == NULL) { db->error = DB_ERROR_MALLOC; lh_OPENSSL_STRING_free(idx); - return (0); + return 0; } } lh_OPENSSL_STRING_free(db->index[field]); db->index[field] = idx; db->qual[field] = qual; - return (1); + return 1; } long TXT_DB_write(BIO *out, TXT_DB *db) @@ -231,7 +231,7 @@ long TXT_DB_write(BIO *out, TXT_DB *db) ret = tot; err: BUF_MEM_free(buf); - return (ret); + return ret; } int TXT_DB_insert(TXT_DB *db, OPENSSL_STRING *row) @@ -264,7 +264,7 @@ int TXT_DB_insert(TXT_DB *db, OPENSSL_STRING *row) } if (!sk_OPENSSL_PSTRING_push(db->data, row)) goto err1; - return (1); + return 1; err1: db->error = DB_ERROR_MALLOC; @@ -276,7 +276,7 @@ int TXT_DB_insert(TXT_DB *db, OPENSSL_STRING *row) } } err: - return (0); + return 0; } void TXT_DB_free(TXT_DB *db) diff --git a/crypto/ui/build.info b/crypto/ui/build.info index fcb45af7..c5d17fb7 100644 --- a/crypto/ui/build.info +++ b/crypto/ui/build.info @@ -1,3 +1,3 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=\ - ui_err.c ui_lib.c ui_openssl.c ui_util.c + ui_err.c ui_lib.c ui_openssl.c ui_null.c ui_util.c diff --git a/crypto/ui/ui_err.c b/crypto/ui/ui_err.c index c8640fea..e69163c4 100644 --- a/crypto/ui/ui_err.c +++ b/crypto/ui/ui_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,52 +8,58 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_UI,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_UI,0,reason) - -static ERR_STRING_DATA UI_str_functs[] = { - {ERR_FUNC(UI_F_CLOSE_CONSOLE), "close_console"}, - {ERR_FUNC(UI_F_ECHO_CONSOLE), "echo_console"}, - {ERR_FUNC(UI_F_GENERAL_ALLOCATE_BOOLEAN), "general_allocate_boolean"}, - {ERR_FUNC(UI_F_GENERAL_ALLOCATE_PROMPT), "general_allocate_prompt"}, - {ERR_FUNC(UI_F_NOECHO_CONSOLE), "noecho_console"}, - {ERR_FUNC(UI_F_OPEN_CONSOLE), "open_console"}, - {ERR_FUNC(UI_F_UI_CREATE_METHOD), "UI_create_method"}, - {ERR_FUNC(UI_F_UI_CTRL), "UI_ctrl"}, - {ERR_FUNC(UI_F_UI_DUP_ERROR_STRING), "UI_dup_error_string"}, - {ERR_FUNC(UI_F_UI_DUP_INFO_STRING), "UI_dup_info_string"}, - {ERR_FUNC(UI_F_UI_DUP_INPUT_BOOLEAN), "UI_dup_input_boolean"}, - {ERR_FUNC(UI_F_UI_DUP_INPUT_STRING), "UI_dup_input_string"}, - {ERR_FUNC(UI_F_UI_DUP_VERIFY_STRING), "UI_dup_verify_string"}, - {ERR_FUNC(UI_F_UI_GET0_RESULT), "UI_get0_result"}, - {ERR_FUNC(UI_F_UI_NEW_METHOD), "UI_new_method"}, - {ERR_FUNC(UI_F_UI_PROCESS), "UI_process"}, - {ERR_FUNC(UI_F_UI_SET_RESULT), "UI_set_result"}, +static const ERR_STRING_DATA UI_str_functs[] = { + {ERR_PACK(ERR_LIB_UI, UI_F_CLOSE_CONSOLE, 0), "close_console"}, + {ERR_PACK(ERR_LIB_UI, UI_F_ECHO_CONSOLE, 0), "echo_console"}, + {ERR_PACK(ERR_LIB_UI, UI_F_GENERAL_ALLOCATE_BOOLEAN, 0), + "general_allocate_boolean"}, + {ERR_PACK(ERR_LIB_UI, UI_F_GENERAL_ALLOCATE_PROMPT, 0), + "general_allocate_prompt"}, + {ERR_PACK(ERR_LIB_UI, UI_F_NOECHO_CONSOLE, 0), "noecho_console"}, + {ERR_PACK(ERR_LIB_UI, UI_F_OPEN_CONSOLE, 0), "open_console"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_CREATE_METHOD, 0), "UI_create_method"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_CTRL, 0), "UI_ctrl"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_DUP_ERROR_STRING, 0), "UI_dup_error_string"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_DUP_INFO_STRING, 0), "UI_dup_info_string"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_DUP_INPUT_BOOLEAN, 0), + "UI_dup_input_boolean"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_DUP_INPUT_STRING, 0), "UI_dup_input_string"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_DUP_USER_DATA, 0), "UI_dup_user_data"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_DUP_VERIFY_STRING, 0), + "UI_dup_verify_string"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_GET0_RESULT, 0), "UI_get0_result"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_GET_RESULT_LENGTH, 0), + "UI_get_result_length"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_NEW_METHOD, 0), "UI_new_method"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_PROCESS, 0), "UI_process"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_SET_RESULT, 0), "UI_set_result"}, + {ERR_PACK(ERR_LIB_UI, UI_F_UI_SET_RESULT_EX, 0), "UI_set_result_ex"}, {0, NULL} }; -static ERR_STRING_DATA UI_str_reasons[] = { - {ERR_REASON(UI_R_COMMON_OK_AND_CANCEL_CHARACTERS), - "common ok and cancel characters"}, - {ERR_REASON(UI_R_INDEX_TOO_LARGE), "index too large"}, - {ERR_REASON(UI_R_INDEX_TOO_SMALL), "index too small"}, - {ERR_REASON(UI_R_NO_RESULT_BUFFER), "no result buffer"}, - {ERR_REASON(UI_R_PROCESSING_ERROR), "processing error"}, - {ERR_REASON(UI_R_RESULT_TOO_LARGE), "result too large"}, - {ERR_REASON(UI_R_RESULT_TOO_SMALL), "result too small"}, - {ERR_REASON(UI_R_SYSASSIGN_ERROR), "sys$assign error"}, - {ERR_REASON(UI_R_SYSDASSGN_ERROR), "sys$dassgn error"}, - {ERR_REASON(UI_R_SYSQIOW_ERROR), "sys$qiow error"}, - {ERR_REASON(UI_R_UNKNOWN_CONTROL_COMMAND), "unknown control command"}, - {ERR_REASON(UI_R_UNKNOWN_TTYGET_ERRNO_VALUE), - "unknown ttyget errno value"}, +static const ERR_STRING_DATA UI_str_reasons[] = { + {ERR_PACK(ERR_LIB_UI, 0, UI_R_COMMON_OK_AND_CANCEL_CHARACTERS), + "common ok and cancel characters"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_INDEX_TOO_LARGE), "index too large"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_INDEX_TOO_SMALL), "index too small"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_NO_RESULT_BUFFER), "no result buffer"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_PROCESSING_ERROR), "processing error"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_RESULT_TOO_LARGE), "result too large"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_RESULT_TOO_SMALL), "result too small"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_SYSASSIGN_ERROR), "sys$assign error"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_SYSDASSGN_ERROR), "sys$dassgn error"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_SYSQIOW_ERROR), "sys$qiow error"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_UNKNOWN_CONTROL_COMMAND), + "unknown control command"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_UNKNOWN_TTYGET_ERRNO_VALUE), + "unknown ttyget errno value"}, + {ERR_PACK(ERR_LIB_UI, 0, UI_R_USER_DATA_DUPLICATION_UNSUPPORTED), + "user data duplication unsupported"}, {0, NULL} }; @@ -62,10 +68,9 @@ static ERR_STRING_DATA UI_str_reasons[] = { int ERR_load_UI_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(UI_str_functs[0].error) == NULL) { - ERR_load_strings(0, UI_str_functs); - ERR_load_strings(0, UI_str_reasons); + ERR_load_strings_const(UI_str_functs); + ERR_load_strings_const(UI_str_reasons); } #endif return 1; diff --git a/crypto/ui/ui_lib.c b/crypto/ui/ui_lib.c index 464dac42..98519877 100644 --- a/crypto/ui/ui_lib.c +++ b/crypto/ui/ui_lib.c @@ -17,7 +17,7 @@ UI *UI_new(void) { - return (UI_new_method(NULL)); + return UI_new_method(NULL); } UI *UI_new_method(const UI_METHOD *method) @@ -37,9 +37,10 @@ UI *UI_new_method(const UI_METHOD *method) } if (method == NULL) - ret->meth = UI_get_default_method(); - else - ret->meth = method; + method = UI_get_default_method(); + if (method == NULL) + method = UI_null(); + ret->meth = method; if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_UI, ret, &ret->ex_data)) { OPENSSL_free(ret); @@ -58,7 +59,11 @@ static void free_string(UI_STRING *uis) OPENSSL_free((char *)uis->_.boolean_data.ok_chars); OPENSSL_free((char *)uis->_.boolean_data.cancel_chars); break; - default: + case UIT_NONE: + case UIT_PROMPT: + case UIT_VERIFY: + case UIT_ERROR: + case UIT_INFO: break; } } @@ -69,6 +74,9 @@ void UI_free(UI *ui) { if (ui == NULL) return; + if ((ui->flags & UI_FLAG_DUPL_DATA) != 0) { + ui->meth->ui_destroy_data(ui, ui->user_data); + } sk_UI_STRING_pop_free(ui->strings, free_string); CRYPTO_free_ex_data(CRYPTO_EX_INDEX_UI, ui, &ui->ex_data); CRYPTO_THREAD_lock_free(ui->lock); @@ -383,10 +391,38 @@ char *UI_construct_prompt(UI *ui, const char *object_desc, void *UI_add_user_data(UI *ui, void *user_data) { void *old_data = ui->user_data; + + if ((ui->flags & UI_FLAG_DUPL_DATA) != 0) { + ui->meth->ui_destroy_data(ui, old_data); + old_data = NULL; + } ui->user_data = user_data; + ui->flags &= ~UI_FLAG_DUPL_DATA; return old_data; } +int UI_dup_user_data(UI *ui, void *user_data) +{ + void *duplicate = NULL; + + if (ui->meth->ui_duplicate_data == NULL + || ui->meth->ui_destroy_data == NULL) { + UIerr(UI_F_UI_DUP_USER_DATA, UI_R_USER_DATA_DUPLICATION_UNSUPPORTED); + return -1; + } + + duplicate = ui->meth->ui_duplicate_data(ui, user_data); + if (duplicate == NULL) { + UIerr(UI_F_UI_DUP_USER_DATA, ERR_R_MALLOC_FAILURE); + return -1; + } + + (void)UI_add_user_data(ui, duplicate); + ui->flags |= UI_FLAG_DUPL_DATA; + + return 0; +} + void *UI_get0_user_data(UI *ui) { return ui->user_data; @@ -405,6 +441,19 @@ const char *UI_get0_result(UI *ui, int i) return UI_get0_result_string(sk_UI_STRING_value(ui->strings, i)); } +int UI_get_result_length(UI *ui, int i) +{ + if (i < 0) { + UIerr(UI_F_UI_GET_RESULT_LENGTH, UI_R_INDEX_TOO_SMALL); + return -1; + } + if (i >= sk_UI_STRING_num(ui->strings)) { + UIerr(UI_F_UI_GET_RESULT_LENGTH, UI_R_INDEX_TOO_LARGE); + return -1; + } + return UI_get_result_string_length(sk_UI_STRING_value(ui->strings, i)); +} + static int print_error(const char *str, size_t len, UI *ui) { UI_STRING uis; @@ -523,12 +572,12 @@ int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f) (void)) int UI_set_ex_data(UI *r, int idx, void *arg) { - return (CRYPTO_set_ex_data(&r->ex_data, idx, arg)); + return CRYPTO_set_ex_data(&r->ex_data, idx, arg); } void *UI_get_ex_data(UI *r, int idx) { - return (CRYPTO_get_ex_data(&r->ex_data, idx)); + return CRYPTO_get_ex_data(&r->ex_data, idx); } const UI_METHOD *UI_get_method(UI *ui) @@ -544,15 +593,17 @@ const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth) UI_METHOD *UI_create_method(const char *name) { - UI_METHOD *ui_method = OPENSSL_zalloc(sizeof(*ui_method)); + UI_METHOD *ui_method = NULL; - if (ui_method != NULL) { - ui_method->name = OPENSSL_strdup(name); - if (ui_method->name == NULL) { - OPENSSL_free(ui_method); - UIerr(UI_F_UI_CREATE_METHOD, ERR_R_MALLOC_FAILURE); - return NULL; - } + if ((ui_method = OPENSSL_zalloc(sizeof(*ui_method))) == NULL + || (ui_method->name = OPENSSL_strdup(name)) == NULL + || !CRYPTO_new_ex_data(CRYPTO_EX_INDEX_UI_METHOD, ui_method, + &ui_method->ex_data)) { + if (ui_method) + OPENSSL_free(ui_method->name); + OPENSSL_free(ui_method); + UIerr(UI_F_UI_CREATE_METHOD, ERR_R_MALLOC_FAILURE); + return NULL; } return ui_method; } @@ -564,6 +615,10 @@ UI_METHOD *UI_create_method(const char *name) */ void UI_destroy_method(UI_METHOD *ui_method) { + if (ui_method == NULL) + return; + CRYPTO_free_ex_data(CRYPTO_EX_INDEX_UI_METHOD, ui_method, + &ui_method->ex_data); OPENSSL_free(ui_method->name); ui_method->name = NULL; OPENSSL_free(ui_method); @@ -616,6 +671,18 @@ int UI_method_set_closer(UI_METHOD *method, int (*closer) (UI *ui)) return -1; } +int UI_method_set_data_duplicator(UI_METHOD *method, + void *(*duplicator) (UI *ui, void *ui_data), + void (*destructor)(UI *ui, void *ui_data)) +{ + if (method != NULL) { + method->ui_duplicate_data = duplicator; + method->ui_destroy_data = destructor; + return 0; + } + return -1; +} + int UI_method_set_prompt_constructor(UI_METHOD *method, char *(*prompt_constructor) (UI *ui, const char @@ -630,50 +697,73 @@ int UI_method_set_prompt_constructor(UI_METHOD *method, return -1; } -int (*UI_method_get_opener(UI_METHOD *method)) (UI *) +int UI_method_set_ex_data(UI_METHOD *method, int idx, void *data) +{ + return CRYPTO_set_ex_data(&method->ex_data, idx, data); +} + +int (*UI_method_get_opener(const UI_METHOD *method)) (UI *) { if (method != NULL) return method->ui_open_session; return NULL; } -int (*UI_method_get_writer(UI_METHOD *method)) (UI *, UI_STRING *) +int (*UI_method_get_writer(const UI_METHOD *method)) (UI *, UI_STRING *) { if (method != NULL) return method->ui_write_string; return NULL; } -int (*UI_method_get_flusher(UI_METHOD *method)) (UI *) +int (*UI_method_get_flusher(const UI_METHOD *method)) (UI *) { if (method != NULL) return method->ui_flush; return NULL; } -int (*UI_method_get_reader(UI_METHOD *method)) (UI *, UI_STRING *) +int (*UI_method_get_reader(const UI_METHOD *method)) (UI *, UI_STRING *) { if (method != NULL) return method->ui_read_string; return NULL; } -int (*UI_method_get_closer(UI_METHOD *method)) (UI *) +int (*UI_method_get_closer(const UI_METHOD *method)) (UI *) { if (method != NULL) return method->ui_close_session; return NULL; } -char *(*UI_method_get_prompt_constructor(UI_METHOD *method)) (UI *, - const char *, - const char *) +char *(*UI_method_get_prompt_constructor(const UI_METHOD *method)) + (UI *, const char *, const char *) { if (method != NULL) return method->ui_construct_prompt; return NULL; } +void *(*UI_method_get_data_duplicator(const UI_METHOD *method)) (UI *, void *) +{ + if (method != NULL) + return method->ui_duplicate_data; + return NULL; +} + +void (*UI_method_get_data_destructor(const UI_METHOD *method)) (UI *, void *) +{ + if (method != NULL) + return method->ui_destroy_data; + return NULL; +} + +const void *UI_method_get_ex_data(const UI_METHOD *method, int idx) +{ + return CRYPTO_get_ex_data(&method->ex_data, idx); +} + enum UI_string_types UI_get_string_type(UI_STRING *uis) { return uis->type; @@ -694,9 +784,14 @@ const char *UI_get0_action_string(UI_STRING *uis) switch (uis->type) { case UIT_BOOLEAN: return uis->_.boolean_data.action_desc; - default: - return NULL; + case UIT_PROMPT: + case UIT_NONE: + case UIT_VERIFY: + case UIT_INFO: + case UIT_ERROR: + break; } + return NULL; } const char *UI_get0_result_string(UI_STRING *uis) @@ -705,9 +800,28 @@ const char *UI_get0_result_string(UI_STRING *uis) case UIT_PROMPT: case UIT_VERIFY: return uis->result_buf; - default: - return NULL; + case UIT_NONE: + case UIT_BOOLEAN: + case UIT_INFO: + case UIT_ERROR: + break; } + return NULL; +} + +int UI_get_result_string_length(UI_STRING *uis) +{ + switch (uis->type) { + case UIT_PROMPT: + case UIT_VERIFY: + return uis->result_len; + case UIT_NONE: + case UIT_BOOLEAN: + case UIT_INFO: + case UIT_ERROR: + break; + } + return -1; } const char *UI_get0_test_string(UI_STRING *uis) @@ -715,9 +829,14 @@ const char *UI_get0_test_string(UI_STRING *uis) switch (uis->type) { case UIT_VERIFY: return uis->_.string_data.test_buf; - default: - return NULL; + case UIT_NONE: + case UIT_BOOLEAN: + case UIT_INFO: + case UIT_ERROR: + case UIT_PROMPT: + break; } + return NULL; } int UI_get_result_minsize(UI_STRING *uis) @@ -726,9 +845,13 @@ int UI_get_result_minsize(UI_STRING *uis) case UIT_PROMPT: case UIT_VERIFY: return uis->_.string_data.result_minsize; - default: - return -1; + case UIT_NONE: + case UIT_INFO: + case UIT_ERROR: + case UIT_BOOLEAN: + break; } + return -1; } int UI_get_result_maxsize(UI_STRING *uis) @@ -737,15 +860,29 @@ int UI_get_result_maxsize(UI_STRING *uis) case UIT_PROMPT: case UIT_VERIFY: return uis->_.string_data.result_maxsize; - default: - return -1; + case UIT_NONE: + case UIT_INFO: + case UIT_ERROR: + case UIT_BOOLEAN: + break; } + return -1; } int UI_set_result(UI *ui, UI_STRING *uis, const char *result) { - int l = strlen(result); +#if 0 + /* + * This is placed here solely to preserve UI_F_UI_SET_RESULT + * To be removed for OpenSSL 1.2.0 + */ + UIerr(UI_F_UI_SET_RESULT, ERR_R_DISABLED); +#endif + return UI_set_result_ex(ui, uis, result, strlen(result)); +} +int UI_set_result_ex(UI *ui, UI_STRING *uis, const char *result, int len) +{ ui->flags &= ~UI_FLAG_REDOABLE; switch (uis->type) { @@ -760,16 +897,16 @@ int UI_set_result(UI *ui, UI_STRING *uis, const char *result) BIO_snprintf(number2, sizeof(number2), "%d", uis->_.string_data.result_maxsize); - if (l < uis->_.string_data.result_minsize) { + if (len < uis->_.string_data.result_minsize) { ui->flags |= UI_FLAG_REDOABLE; - UIerr(UI_F_UI_SET_RESULT, UI_R_RESULT_TOO_SMALL); + UIerr(UI_F_UI_SET_RESULT_EX, UI_R_RESULT_TOO_SMALL); ERR_add_error_data(5, "You must type in ", number1, " to ", number2, " characters"); return -1; } - if (l > uis->_.string_data.result_maxsize) { + if (len > uis->_.string_data.result_maxsize) { ui->flags |= UI_FLAG_REDOABLE; - UIerr(UI_F_UI_SET_RESULT, UI_R_RESULT_TOO_LARGE); + UIerr(UI_F_UI_SET_RESULT_EX, UI_R_RESULT_TOO_LARGE); ERR_add_error_data(5, "You must type in ", number1, " to ", number2, " characters"); return -1; @@ -777,19 +914,21 @@ int UI_set_result(UI *ui, UI_STRING *uis, const char *result) } if (uis->result_buf == NULL) { - UIerr(UI_F_UI_SET_RESULT, UI_R_NO_RESULT_BUFFER); + UIerr(UI_F_UI_SET_RESULT_EX, UI_R_NO_RESULT_BUFFER); return -1; } - OPENSSL_strlcpy(uis->result_buf, result, - uis->_.string_data.result_maxsize + 1); + memcpy(uis->result_buf, result, len); + if (len <= uis->_.string_data.result_maxsize) + uis->result_buf[len] = '\0'; + uis->result_len = len; break; case UIT_BOOLEAN: { const char *p; if (uis->result_buf == NULL) { - UIerr(UI_F_UI_SET_RESULT, UI_R_NO_RESULT_BUFFER); + UIerr(UI_F_UI_SET_RESULT_EX, UI_R_NO_RESULT_BUFFER); return -1; } @@ -805,7 +944,9 @@ int UI_set_result(UI *ui, UI_STRING *uis, const char *result) } } } - default: + case UIT_NONE: + case UIT_INFO: + case UIT_ERROR: break; } return 0; diff --git a/crypto/ui/ui_locl.h b/crypto/ui/ui_locl.h index 2953739b..19b33b8f 100644 --- a/crypto/ui/ui_locl.h +++ b/crypto/ui/ui_locl.h @@ -37,6 +37,12 @@ struct ui_method_st { int (*ui_flush) (UI *ui); int (*ui_read_string) (UI *ui, UI_STRING *uis); int (*ui_close_session) (UI *ui); + /* + * Duplicate the ui_data that often comes alongside a ui_method. This + * allows some backends to save away UI information for later use. + */ + void *(*ui_duplicate_data) (UI *ui, void *ui_data); + void (*ui_destroy_data) (UI *ui, void *ui_data); /* * Construct a prompt in a user-defined manner. object_desc is a textual * short description of the object, for example "pass phrase", and @@ -46,6 +52,10 @@ struct ui_method_st { */ char *(*ui_construct_prompt) (UI *ui, const char *object_desc, const char *object_name); + /* + * UI_METHOD specific application data. + */ + CRYPTO_EX_DATA ex_data; }; struct ui_string_st { @@ -61,6 +71,7 @@ struct ui_string_st { * Otherwise, it may be allocated by the UI * routine, meaning result_minsize is going * to be overwritten. */ + size_t result_len; union { struct { int result_minsize; /* Input: minimum required size of the @@ -88,6 +99,7 @@ struct ui_st { void *user_data; CRYPTO_EX_DATA ex_data; # define UI_FLAG_REDOABLE 0x0001 +# define UI_FLAG_DUPL_DATA 0x0002 /* user_data was duplicated */ # define UI_FLAG_PRINT_ERRORS 0x0100 int flags; diff --git a/crypto/ui/ui_null.c b/crypto/ui/ui_null.c new file mode 100644 index 00000000..9e5f6fca --- /dev/null +++ b/crypto/ui/ui_null.c @@ -0,0 +1,26 @@ +/* + * 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 "ui_locl.h" + +static const UI_METHOD ui_null = { + "OpenSSL NULL UI", + NULL, /* opener */ + NULL, /* writer */ + NULL, /* flusher */ + NULL, /* reader */ + NULL, /* closer */ + NULL +}; + +/* The method with all the built-in thingies */ +const UI_METHOD *UI_null(void) +{ + return &ui_null; +} diff --git a/crypto/ui/ui_openssl.c b/crypto/ui/ui_openssl.c index 8fa8deca..3ccd8a72 100644 --- a/crypto/ui/ui_openssl.c +++ b/crypto/ui/ui_openssl.c @@ -1,5 +1,5 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-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 @@ -7,66 +7,68 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" #include #include +#include +#ifndef OPENSSL_NO_UI_CONSOLE /* * 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_SYS_VXWORKS) -# include -#endif - -#if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS) -# ifndef _POSIX_C_SOURCE -# define _POSIX_C_SOURCE 2 +# if defined(OPENSSL_SYS_VXWORKS) +# include # endif -#endif -#include -#include -#include -#include -#if !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_VMS) -# ifdef OPENSSL_UNISTD -# include OPENSSL_UNISTD -# else -# include +# if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS) +# ifndef _POSIX_C_SOURCE +# define _POSIX_C_SOURCE 2 +# endif # endif +# include +# include +# include +# include + +# if !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_VMS) +# ifdef OPENSSL_UNISTD +# include OPENSSL_UNISTD +# else +# include +# 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) +# if defined(_POSIX_VERSION) + +# define SIGACTION +# if !defined(TERMIOS) && !defined(TERMIO) && !defined(SGTTY) +# define TERMIOS +# endif -# define SIGACTION -# if !defined(TERMIOS) && !defined(TERMIO) && !defined(SGTTY) -# define TERMIOS # endif - # endif -#endif -/* 06-Apr-92 Luke Brennan Support for VMS */ -#include "ui_locl.h" -#include "internal/cryptlib.h" +# include "ui_locl.h" +# include "internal/cryptlib.h" -#ifdef OPENSSL_SYS_VMS /* prototypes for sys$whatever */ -# include -# ifdef __DECC -# pragma message disable DOLLARID +# ifdef OPENSSL_SYS_VMS /* prototypes for sys$whatever */ +# include +# ifdef __DECC +# pragma message disable DOLLARID +# endif # endif -#endif -#ifdef WIN_CONSOLE_BUG -# include -# ifndef OPENSSL_SYS_WINCE -# include +# ifdef WIN_CONSOLE_BUG +# include +# ifndef OPENSSL_SYS_WINCE +# include +# endif # endif -#endif /* * There are 6 types of terminal interface supported, TERMIO, TERMIOS, VMS, @@ -80,81 +82,81 @@ * may eventually opt to remove it's use entirely. */ -#if !defined(TERMIOS) && !defined(TERMIO) && !defined(SGTTY) +# if !defined(TERMIOS) && !defined(TERMIO) && !defined(SGTTY) -# if defined(_LIBC) -# undef TERMIOS -# define TERMIO -# undef SGTTY +# if defined(_LIBC) +# undef TERMIOS +# define TERMIO +# undef SGTTY /* * We know that VMS, MSDOS, VXWORKS, use entirely other mechanisms. */ -# elif !defined(OPENSSL_SYS_VMS) \ +# elif !defined(OPENSSL_SYS_VMS) \ && !defined(OPENSSL_SYS_MSDOS) \ && !defined(OPENSSL_SYS_VXWORKS) -# define TERMIOS -# undef TERMIO -# undef SGTTY +# define TERMIOS +# undef TERMIO +# undef SGTTY +# endif + # endif -#endif +# ifdef TERMIOS +# include +# 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 TERMIOS -# include -# 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 +# 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 TERMIO -# include -# 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 +# 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 -#ifdef SGTTY -# include -# 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) +# include +# endif -#if !defined(_LIBC) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_VMS) -# include -#endif +# ifdef OPENSSL_SYS_MSDOS +# include +# endif -#ifdef OPENSSL_SYS_MSDOS -# include -#endif - -#ifdef OPENSSL_SYS_VMS -# include -# include -# include -# include +# ifdef OPENSSL_SYS_VMS +# include +# include +# include +# include struct IOSB { short iosb$w_value; short iosb$w_count; long iosb$l_info; }; -#endif +# endif -#ifndef NX509_SIG -# define NX509_SIG 32 -#endif +# ifndef NX509_SIG +# define NX509_SIG 32 +# endif /* Define globals. They are protected by a lock */ -#ifdef SIGACTION +# ifdef SIGACTION static struct sigaction savsig[NX509_SIG]; -#else +# else static void (*savsig[NX509_SIG]) (int); -#endif +# endif -#ifdef OPENSSL_SYS_VMS +# 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 @@ -162,26 +164,26 @@ static long tty_orig[3], tty_new[3]; /* XXX Is there any guarantee that this * structures? */ static long status; static unsigned short channel = 0; -#elif defined(_WIN32) && !defined(_WIN32_WCE) +# elif defined(_WIN32) && !defined(_WIN32_WCE) static DWORD tty_orig, tty_new; -#else -# if !defined(OPENSSL_SYS_MSDOS) || defined(__DJGPP__) +# else +# if !defined(OPENSSL_SYS_MSDOS) || defined(__DJGPP__) static TTY_STRUCT tty_orig, tty_new; +# endif # endif -#endif static FILE *tty_in, *tty_out; static int is_a_tty; /* Declare static functions */ -#if !defined(OPENSSL_SYS_WINCE) +# if !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(_WIN32) +# endif +# if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) static int noecho_fgets(char *buf, int size, FILE *tty); -#endif +# 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); @@ -192,34 +194,6 @@ 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 -}; - -static const UI_METHOD *default_UI_meth = &ui_openssl; - -void UI_set_default_method(const UI_METHOD *meth) -{ - default_UI_meth = meth; -} - -const UI_METHOD *UI_get_default_method(void) -{ - return default_UI_meth; -} - -/* 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. @@ -232,7 +206,10 @@ static int write_string(UI *ui, UI_STRING *uis) fputs(UI_get0_output_string(uis), tty_out); fflush(tty_out); break; - default: + case UIT_NONE: + case UIT_PROMPT: + case UIT_VERIFY: + case UIT_BOOLEAN: break; } return 1; @@ -269,17 +246,19 @@ static int read_string(UI *ui, UI_STRING *uis) return 0; } break; - default: + case UIT_NONE: + case UIT_INFO: + case UIT_ERROR: break; } return 1; } -#if !defined(OPENSSL_SYS_WINCE) +# if !defined(OPENSSL_SYS_WINCE) /* Internal functions to read a string without echoing */ static int read_till_nl(FILE *in) { -# define SIZE 4 +# define SIZE 4 char buf[SIZE + 1]; do { @@ -290,7 +269,7 @@ static int read_till_nl(FILE *in) } static volatile sig_atomic_t intr_signal; -#endif +# endif static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl) { @@ -298,7 +277,7 @@ static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl) int ok; char result[BUFSIZ]; int maxsize = BUFSIZ - 1; -#if !defined(OPENSSL_SYS_WINCE) +# if !defined(OPENSSL_SYS_WINCE) char *p = NULL; int echo_eol = !echo; @@ -314,10 +293,10 @@ static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl) ps = 2; result[0] = '\0'; -# if defined(_WIN32) +# if defined(_WIN32) if (is_a_tty) { DWORD numread; -# if defined(CP_UTF8) +# if defined(CP_UTF8) if (GetEnvironmentVariableW(L"OPENSSL_WIN32_UTF8", NULL, 0) != 0) { WCHAR wresult[BUFSIZ]; @@ -337,7 +316,7 @@ static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl) OPENSSL_cleanse(wresult, sizeof(wresult)); } } else -# endif +# endif if (ReadConsoleA(GetStdHandle(STD_INPUT_HANDLE), result, maxsize, &numread, NULL)) { if (numread >= 2 && @@ -349,12 +328,12 @@ static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl) p = result; } } else -# elif defined(OPENSSL_SYS_MSDOS) +# elif defined(OPENSSL_SYS_MSDOS) if (!echo) { noecho_fgets(result, maxsize, tty_in); p = result; /* FIXME: noecho_fgets doesn't return errors */ } else -# endif +# endif p = fgets(result, maxsize, tty_in); if (p == NULL) goto error; @@ -380,9 +359,9 @@ static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl) if (ps >= 1) popsig(); -#else +# else ok = 1; -#endif +# endif OPENSSL_cleanse(result, BUFSIZ); return ok; @@ -394,10 +373,10 @@ static int open_console(UI *ui) CRYPTO_THREAD_write_lock(ui->lock); is_a_tty = 1; -#if defined(OPENSSL_SYS_VXWORKS) +# if defined(OPENSSL_SYS_VXWORKS) tty_in = stdin; tty_out = stderr; -#elif defined(_WIN32) && !defined(_WIN32_WCE) +# elif defined(_WIN32) && !defined(_WIN32_WCE) if ((tty_out = fopen("conout$", "w")) == NULL) tty_out = stderr; @@ -408,35 +387,35 @@ static int open_console(UI *ui) if ((tty_in = fopen("conin$", "r")) == NULL) tty_in = stdin; } -#else -# ifdef OPENSSL_SYS_MSDOS -# define DEV_TTY "con" # else -# define DEV_TTY "/dev/tty" -# endif +# 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 +# endif -#if defined(TTY_get) && !defined(OPENSSL_SYS_VMS) +# if defined(TTY_get) && !defined(OPENSSL_SYS_VMS) if (TTY_get(fileno(tty_in), &tty_orig) == -1) { -# ifdef ENOTTY +# ifdef ENOTTY if (errno == ENOTTY) is_a_tty = 0; else -# endif -# ifdef EINVAL +# endif +# ifdef EINVAL /* - * Ariel Glenn ariel@columbia.edu reports that solaris can return - * EINVAL instead. This should be ok + * Ariel Glenn reports that solaris can return EINVAL instead. + * This should be ok */ if (errno == EINVAL) is_a_tty = 0; else -# endif -# ifdef ENODEV +# endif +# ifdef ENODEV /* * MacOS X returns ENODEV (Operation not supported by device), * which seems appropriate. @@ -444,7 +423,7 @@ static int open_console(UI *ui) if (errno == ENODEV) is_a_tty = 0; else -# endif +# endif { char tmp_num[10]; BIO_snprintf(tmp_num, sizeof(tmp_num) - 1, "%d", errno); @@ -454,8 +433,8 @@ static int open_console(UI *ui) return 0; } } -#endif -#ifdef OPENSSL_SYS_VMS +# endif +# ifdef OPENSSL_SYS_VMS status = sys$assign(&terminal, &channel, 0, 0); /* if there isn't a TT device, something is very wrong */ @@ -474,22 +453,22 @@ static int open_console(UI *ui) /* 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 +# endif return 1; } static int noecho_console(UI *ui) { -#ifdef TTY_FLAGS +# ifdef TTY_FLAGS memcpy(&(tty_new), &(tty_orig), sizeof(tty_orig)); tty_new.TTY_FLAGS &= ~ECHO; -#endif +# endif -#if defined(TTY_set) && !defined(OPENSSL_SYS_VMS) +# 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 +# endif +# ifdef OPENSSL_SYS_VMS if (is_a_tty) { tty_new[0] = tty_orig[0]; tty_new[1] = tty_orig[1] | TT$M_NOECHO; @@ -509,29 +488,29 @@ static int noecho_console(UI *ui) return 0; } } -#endif -#if defined(_WIN32) && !defined(_WIN32_WCE) +# endif +# if defined(_WIN32) && !defined(_WIN32_WCE) if (is_a_tty) { tty_new = tty_orig; tty_new &= ~ENABLE_ECHO_INPUT; SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), tty_new); } -#endif +# endif return 1; } static int echo_console(UI *ui) { -#if defined(TTY_set) && !defined(OPENSSL_SYS_VMS) +# if defined(TTY_set) && !defined(OPENSSL_SYS_VMS) memcpy(&(tty_new), &(tty_orig), sizeof(tty_orig)); tty_new.TTY_FLAGS |= ECHO; -#endif +# endif -#if defined(TTY_set) && !defined(OPENSSL_SYS_VMS) +# 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 +# endif +# ifdef OPENSSL_SYS_VMS if (is_a_tty) { tty_new[0] = tty_orig[0]; tty_new[1] = tty_orig[1] & ~TT$M_NOECHO; @@ -551,14 +530,14 @@ static int echo_console(UI *ui) return 0; } } -#endif -#if defined(_WIN32) && !defined(_WIN32_WCE) +# endif +# if defined(_WIN32) && !defined(_WIN32_WCE) if (is_a_tty) { tty_new = tty_orig; tty_new |= ENABLE_ECHO_INPUT; SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), tty_new); } -#endif +# endif return 1; } @@ -568,7 +547,7 @@ static int close_console(UI *ui) fclose(tty_in); if (tty_out != stderr) fclose(tty_out); -#ifdef OPENSSL_SYS_VMS +# ifdef OPENSSL_SYS_VMS status = sys$dassgn(channel); if (status != SS$_NORMAL) { char tmp_num[12]; @@ -578,97 +557,97 @@ static int close_console(UI *ui) ERR_add_error_data(2, "status=", tmp_num); return 0; } -#endif +# endif CRYPTO_THREAD_unlock(ui->lock); return 1; } -#if !defined(OPENSSL_SYS_WINCE) +# if !defined(OPENSSL_SYS_WINCE) /* Internal functions to handle signals and act on them */ static void pushsig(void) { -# ifndef OPENSSL_SYS_WIN32 +# ifndef OPENSSL_SYS_WIN32 int i; -# endif -# ifdef SIGACTION +# endif +# ifdef SIGACTION struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = recsig; -# endif +# endif -# ifdef OPENSSL_SYS_WIN32 +# 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 +# else for (i = 1; i < NX509_SIG; i++) { -# ifdef SIGUSR1 +# ifdef SIGUSR1 if (i == SIGUSR1) continue; -# endif -# ifdef SIGUSR2 +# endif +# ifdef SIGUSR2 if (i == SIGUSR2) continue; -# endif -# ifdef SIGKILL +# endif +# ifdef SIGKILL if (i == SIGKILL) /* We can't make any action on that. */ continue; -# endif -# ifdef SIGACTION +# endif +# ifdef SIGACTION sigaction(i, &sa, &savsig[i]); -# else +# else savsig[i] = signal(i, recsig); -# endif +# endif } -# endif +# endif -# ifdef SIGWINCH +# ifdef SIGWINCH signal(SIGWINCH, SIG_DFL); -# endif +# endif } static void popsig(void) { -# ifdef OPENSSL_SYS_WIN32 +# 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 +# else int i; for (i = 1; i < NX509_SIG; i++) { -# ifdef SIGUSR1 +# ifdef SIGUSR1 if (i == SIGUSR1) continue; -# endif -# ifdef SIGUSR2 +# endif +# ifdef SIGUSR2 if (i == SIGUSR2) continue; -# endif -# ifdef SIGACTION +# endif +# ifdef SIGACTION sigaction(i, &savsig[i], NULL); -# else +# else signal(i, savsig[i]); -# endif +# endif } -# endif +# endif } static void recsig(int i) { intr_signal = i; } -#endif +# endif /* Internal functions specific for Windows */ -#if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) +# if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) static int noecho_fgets(char *buf, int size, FILE *tty) { int i; @@ -681,11 +660,11 @@ static int noecho_fgets(char *buf, int size, FILE *tty) break; } size--; -# if defined(_WIN32) +# if defined(_WIN32) i = _getch(); -# else +# else i = getch(); -# endif +# endif if (i == '\r') i = '\n'; *(p++) = i; @@ -694,7 +673,7 @@ static int noecho_fgets(char *buf, int size, FILE *tty) break; } } -# ifdef WIN_CONSOLE_BUG +# 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 @@ -706,7 +685,41 @@ static int noecho_fgets(char *buf, int size, FILE *tty) inh = GetStdHandle(STD_INPUT_HANDLE); FlushConsoleInputBuffer(inh); } -# endif - return (strlen(buf)); +# endif + return strlen(buf); } +# endif + +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 console thingies */ +UI_METHOD *UI_OpenSSL(void) +{ + return &ui_openssl; +} + +static const UI_METHOD *default_UI_meth = &ui_openssl; + +#else + +static const UI_METHOD *default_UI_meth = NULL; + #endif + +void UI_set_default_method(const UI_METHOD *meth) +{ + default_UI_meth = meth; +} + +const UI_METHOD *UI_get_default_method(void) +{ + return default_UI_meth; +} diff --git a/crypto/ui/ui_util.c b/crypto/ui/ui_util.c index 3b51db92..b379324f 100644 --- a/crypto/ui/ui_util.c +++ b/crypto/ui/ui_util.c @@ -8,6 +8,7 @@ */ #include +#include "internal/thread_once.h" #include "ui_locl.h" #ifndef BUFSIZ @@ -24,7 +25,7 @@ int UI_UTIL_read_pw_string(char *buf, int length, const char *prompt, UI_UTIL_read_pw(buf, buff, (length > BUFSIZ) ? BUFSIZ : length, prompt, verify); OPENSSL_cleanse(buff, BUFSIZ); - return (ret); + return ret; } int UI_UTIL_read_pw(char *buf, char *buff, int size, const char *prompt, @@ -47,5 +48,115 @@ int UI_UTIL_read_pw(char *buf, char *buff, int size, const char *prompt, } if (ok > 0) ok = 0; - return (ok); + return ok; +} + +/* + * Wrapper around pem_password_cb, a method to help older APIs use newer + * ones. + */ +struct pem_password_cb_data { + pem_password_cb *cb; + int rwflag; +}; + +static void ui_new_method_data(void *parent, void *ptr, CRYPTO_EX_DATA *ad, + int idx, long argl, void *argp) +{ + /* + * Do nothing, the data is allocated externally and assigned later with + * CRYPTO_set_ex_data() + */ +} + +static int ui_dup_method_data(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from, + void *from_d, int idx, long argl, void *argp) +{ + void **pptr = (void **)from_d; + if (*pptr != NULL) + *pptr = OPENSSL_memdup(*pptr, sizeof(struct pem_password_cb_data)); + return 1; +} + +static void ui_free_method_data(void *parent, void *ptr, CRYPTO_EX_DATA *ad, + int idx, long argl, void *argp) +{ + OPENSSL_free(ptr); +} + +static CRYPTO_ONCE get_index_once = CRYPTO_ONCE_STATIC_INIT; +static int ui_method_data_index = -1; +DEFINE_RUN_ONCE_STATIC(ui_method_data_index_init) +{ + ui_method_data_index = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI_METHOD, + 0, NULL, ui_new_method_data, + ui_dup_method_data, + ui_free_method_data); + return 1; +} + +static int ui_open(UI *ui) +{ + return 1; +} +static int ui_read(UI *ui, UI_STRING *uis) +{ + switch (UI_get_string_type(uis)) { + case UIT_PROMPT: + { + char result[PEM_BUFSIZE + 1]; + const struct pem_password_cb_data *data = + UI_method_get_ex_data(UI_get_method(ui), ui_method_data_index); + int maxsize = UI_get_result_maxsize(uis); + int len = data->cb(result, + maxsize > PEM_BUFSIZE ? PEM_BUFSIZE : maxsize, + data->rwflag, UI_get0_user_data(ui)); + + if (len >= 0) + result[len] = '\0'; + if (len <= 0) + return len; + if (UI_set_result_ex(ui, uis, result, len) >= 0) + return 1; + return 0; + } + case UIT_VERIFY: + case UIT_NONE: + case UIT_BOOLEAN: + case UIT_INFO: + case UIT_ERROR: + break; + } + return 1; +} +static int ui_write(UI *ui, UI_STRING *uis) +{ + return 1; +} +static int ui_close(UI *ui) +{ + return 1; +} + +UI_METHOD *UI_UTIL_wrap_read_pem_callback(pem_password_cb *cb, int rwflag) +{ + struct pem_password_cb_data *data = NULL; + UI_METHOD *ui_method = NULL; + + if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL + || (ui_method = UI_create_method("PEM password callback wrapper")) == NULL + || UI_method_set_opener(ui_method, ui_open) < 0 + || UI_method_set_reader(ui_method, ui_read) < 0 + || UI_method_set_writer(ui_method, ui_write) < 0 + || UI_method_set_closer(ui_method, ui_close) < 0 + || !RUN_ONCE(&get_index_once, ui_method_data_index_init) + || UI_method_set_ex_data(ui_method, ui_method_data_index, data) < 0) { + UI_destroy_method(ui_method); + OPENSSL_free(data); + return NULL; + } + data->rwflag = rwflag; + data->cb = cb; + + return ui_method; } diff --git a/crypto/uid.c b/crypto/uid.c index 12df8a4e..4e1890f2 100644 --- a/crypto/uid.c +++ b/crypto/uid.c @@ -10,7 +10,7 @@ #include #include -#if defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ > 2) +#if defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ > 2) || defined(__DragonFly__) # include OPENSSL_UNISTD @@ -19,7 +19,7 @@ int OPENSSL_issetugid(void) return issetugid(); } -#elif defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) +#elif defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI) int OPENSSL_issetugid(void) { diff --git a/crypto/whrlpool/asm/wp-mmx.pl b/crypto/whrlpool/asm/wp-mmx.pl index f63945c8..2241c6f0 100644 --- a/crypto/whrlpool/asm/wp-mmx.pl +++ b/crypto/whrlpool/asm/wp-mmx.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. Rights for redistribution and usage in source and binary # forms are granted according to the OpenSSL license. # ==================================================================== @@ -31,7 +31,7 @@ # multiplying 64 by CPU clock frequency and dividing by relevant # value from the given table: # -# $SCALE=2/8 icc8 gcc3 +# $SCALE=2/8 icc8 gcc3 # Intel P4 3200/4600 4600(*) 6400 # Intel PIII 2900/3000 4900 5400 # AMD K[78] 2500/1800 9900 8200(**) @@ -59,7 +59,7 @@ require "x86asm.pl"; $output=pop; open STDOUT,">$output"; -&asm_init($ARGV[0],"wp-mmx.pl"); +&asm_init($ARGV[0]); sub L() { &data_byte(@_); } sub LL() @@ -502,6 +502,6 @@ for($i=0;$i<8;$i++) { &L(0xca,0x2d,0xbf,0x07,0xad,0x5a,0x83,0x33); &function_end_B("whirlpool_block_mmx"); -&asm_finish(); +&asm_finish(); close STDOUT; diff --git a/crypto/whrlpool/asm/wp-x86_64.pl b/crypto/whrlpool/asm/wp-x86_64.pl index c0b21d13..fe23d8ca 100644 --- a/crypto/whrlpool/asm/wp-x86_64.pl +++ b/crypto/whrlpool/asm/wp-x86_64.pl @@ -8,7 +8,7 @@ # # ==================================================================== -# Written by Andy Polyakov for the OpenSSL +# Written by Andy Polyakov for the OpenSSL # project. Rights for redistribution and usage in source and binary # forms are granted according to the OpenSSL license. # ==================================================================== @@ -66,14 +66,22 @@ $code=<<___; .type $func,\@function,3 .align 16 $func: +.cfi_startproc + mov %rsp,%rax +.cfi_def_cfa_register %rax push %rbx +.cfi_push %rbx push %rbp +.cfi_push %rbp push %r12 +.cfi_push %r12 push %r13 +.cfi_push %r13 push %r14 +.cfi_push %r14 push %r15 +.cfi_push %r15 - mov %rsp,%r11 sub \$128+40,%rsp and \$-64,%rsp @@ -81,7 +89,8 @@ $func: mov %rdi,0(%r10) # save parameter block mov %rsi,8(%r10) mov %rdx,16(%r10) - mov %r11,32(%r10) # saved stack pointer + mov %rax,32(%r10) # saved stack pointer +.cfi_cfa_expression %rsp+`128+32`,deref,+8 .Lprologue: mov %r10,%rbx @@ -205,15 +214,24 @@ $code.=<<___; jmp .Louterloop .Lalldone: mov 32(%rbx),%rsi # restore saved pointer - mov (%rsi),%r15 - mov 8(%rsi),%r14 - mov 16(%rsi),%r13 - mov 24(%rsi),%r12 - mov 32(%rsi),%rbp - mov 40(%rsi),%rbx - lea 48(%rsi),%rsp +.cfi_def_cfa %rsi,8 + mov -48(%rsi),%r15 +.cfi_restore %r15 + mov -40(%rsi),%r14 +.cfi_restore %r14 + mov -32(%rsi),%r13 +.cfi_restore %r13 + mov -24(%rsi),%r12 +.cfi_restore %r12 + mov -16(%rsi),%rbp +.cfi_restore %rbp + mov -8(%rsi),%rbx +.cfi_restore %rbx + lea (%rsi),%rsp +.cfi_def_cfa_register %rsp .Lepilogue: ret +.cfi_endproc .size $func,.-$func .align 64 @@ -526,7 +544,6 @@ se_handler: jae .Lin_prologue mov 128+32(%rax),%rax # pull saved stack pointer - lea 48(%rax),%rax mov -8(%rax),%rbx mov -16(%rax),%rbp diff --git a/crypto/whrlpool/build.info b/crypto/whrlpool/build.info index 7f3a19ea..4b167b50 100644 --- a/crypto/whrlpool/build.info +++ b/crypto/whrlpool/build.info @@ -1,7 +1,8 @@ LIBS=../../libcrypto SOURCE[../../libcrypto]=wp_dgst.c {- $target{wp_asm_src} -} -GENERATE[wp-mmx.s]=asm/wp-mmx.pl $(PERLASM_SCHEME) $(CFLAGS) $(LIB_CFLAGS) $(PROCESSOR) +GENERATE[wp-mmx.s]=asm/wp-mmx.pl \ + $(PERLASM_SCHEME) $(LIB_CFLAGS) $(LIB_CPPFLAGS) $(PROCESSOR) DEPEND[wp-mmx.s]=../perlasm/x86asm.pl GENERATE[wp-x86_64.s]=asm/wp-x86_64.pl $(PERLASM_SCHEME) diff --git a/crypto/whrlpool/wp_block.c b/crypto/whrlpool/wp_block.c index b29f037b..0cc92a3b 100644 --- a/crypto/whrlpool/wp_block.c +++ b/crypto/whrlpool/wp_block.c @@ -10,14 +10,6 @@ /** * The Whirlpool hashing function. * - *

- * References - * - *

- * References - * - *

- * The Whirlpool algorithm was developed by - * Paulo S. L. M. Barreto and - * Vincent Rijmen. - * * See * P.S.L.M. Barreto, V. Rijmen, * ``The Whirlpool hashing function,'' @@ -67,7 +59,7 @@ int WHIRLPOOL_Init(WHIRLPOOL_CTX *c) { memset(c, 0, sizeof(*c)); - return (1); + return 1; } int WHIRLPOOL_Update(WHIRLPOOL_CTX *c, const void *_inp, size_t bytes) @@ -88,7 +80,7 @@ int WHIRLPOOL_Update(WHIRLPOOL_CTX *c, const void *_inp, size_t bytes) if (bytes) WHIRLPOOL_BitUpdate(c, inp, bytes * 8); - return (1); + return 1; } void WHIRLPOOL_BitUpdate(WHIRLPOOL_CTX *c, const void *_inp, size_t bits) @@ -247,9 +239,9 @@ int WHIRLPOOL_Final(unsigned char *md, WHIRLPOOL_CTX *c) if (md) { memcpy(md, c->H.c, WHIRLPOOL_DIGEST_LENGTH); OPENSSL_cleanse(c, sizeof(*c)); - return (1); + return 1; } - return (0); + return 0; } unsigned char *WHIRLPOOL(const void *inp, size_t bytes, unsigned char *md) @@ -262,5 +254,5 @@ unsigned char *WHIRLPOOL(const void *inp, size_t bytes, unsigned char *md) WHIRLPOOL_Init(&ctx); WHIRLPOOL_Update(&ctx, inp, bytes); WHIRLPOOL_Final(md, &ctx); - return (md); + return md; } diff --git a/crypto/x509/by_dir.c b/crypto/x509/by_dir.c index 21672a7e..f64cf384 100644 --- a/crypto/x509/by_dir.c +++ b/crypto/x509/by_dir.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -7,19 +7,17 @@ * https://www.openssl.org/source/license.html */ +#include "e_os.h" +#include "internal/cryptlib.h" #include #include #include #include -#include "internal/cryptlib.h" - #ifndef OPENSSL_NO_POSIX_IO # include #endif - -#include #include #include "internal/x509_int.h" #include "x509_lcl.h" @@ -63,7 +61,7 @@ static X509_LOOKUP_METHOD x509_dir_lookup = { X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void) { - return (&x509_dir_lookup); + return &x509_dir_lookup; } static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, @@ -91,7 +89,7 @@ static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl, ret = add_cert_dir(ld, argp, (int)argl); break; } - return (ret); + return ret; } static int new_dir(X509_LOOKUP *lu) @@ -150,7 +148,9 @@ static void free_dir(X509_LOOKUP *lu) static int add_cert_dir(BY_DIR *ctx, const char *dir, int type) { - const char *s, *p; + int j; + size_t len; + const char *s, *ss, *p; if (dir == NULL || !*dir) { X509err(X509_F_ADD_CERT_DIR, X509_R_INVALID_DIRECTORY); @@ -162,17 +162,14 @@ static int add_cert_dir(BY_DIR *ctx, const char *dir, int type) do { if ((*p == LIST_SEPARATOR_CHAR) || (*p == '\0')) { BY_DIR_ENTRY *ent; - int j; - size_t len; - const char *ss = s; + ss = s; s = p + 1; len = p - ss; if (len == 0) continue; for (j = 0; j < sk_BY_DIR_ENTRY_num(ctx->dirs); j++) { ent = sk_BY_DIR_ENTRY_value(ctx->dirs, j); - if (strlen(ent->dir) == len && - strncmp(ent->dir, ss, len) == 0) + if (strlen(ent->dir) == len && strncmp(ent->dir, ss, len) == 0) break; } if (j < sk_BY_DIR_ENTRY_num(ctx->dirs)) @@ -219,7 +216,7 @@ static int get_cert_by_subject(X509_LOOKUP *xl, X509_LOOKUP_TYPE type, const char *postfix = ""; if (name == NULL) - return (0); + return 0; stmp.type = type; if (type == X509_LU_X509) { @@ -371,6 +368,13 @@ static int get_cert_by_subject(X509_LOOKUP *xl, X509_LOOKUP_TYPE type, ok = 1; ret->type = tmp->type; memcpy(&ret->data, &tmp->data, sizeof(ret->data)); + + /* + * Clear any errors that might have been raised processing empty + * or malformed files. + */ + ERR_clear_error(); + /* * If we were going to up the reference count, we would need to * do it on a perl 'type' basis @@ -382,5 +386,5 @@ static int get_cert_by_subject(X509_LOOKUP *xl, X509_LOOKUP_TYPE type, } finish: BUF_MEM_free(b); - return (ok); + return ok; } diff --git a/crypto/x509/by_file.c b/crypto/x509/by_file.c index 0bcc6af3..52955b6a 100644 --- a/crypto/x509/by_file.c +++ b/crypto/x509/by_file.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -12,7 +12,6 @@ #include #include "internal/cryptlib.h" -#include #include #include #include @@ -35,7 +34,7 @@ static X509_LOOKUP_METHOD x509_file_lookup = { X509_LOOKUP_METHOD *X509_LOOKUP_file(void) { - return (&x509_file_lookup); + return &x509_file_lookup; } static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, @@ -69,7 +68,7 @@ static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, } break; } - return (ok); + return ok; } int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type) @@ -79,8 +78,6 @@ int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type) int i, count = 0; X509 *x = NULL; - if (file == NULL) - return (1); in = BIO_new(BIO_s_file()); if ((in == NULL) || (BIO_read_filename(in, file) <= 0)) { @@ -123,10 +120,12 @@ int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type) X509err(X509_F_X509_LOAD_CERT_FILE, X509_R_BAD_X509_FILETYPE); goto err; } + if (ret == 0) + X509err(X509_F_X509_LOAD_CERT_FILE, X509_R_NO_CERTIFICATE_FOUND); err: X509_free(x); BIO_free(in); - return (ret); + return ret; } int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type) @@ -136,8 +135,6 @@ int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type) int i, count = 0; X509_CRL *x = NULL; - if (file == NULL) - return (1); in = BIO_new(BIO_s_file()); if ((in == NULL) || (BIO_read_filename(in, file) <= 0)) { @@ -180,10 +177,12 @@ int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type) X509err(X509_F_X509_LOAD_CRL_FILE, X509_R_BAD_X509_FILETYPE); goto err; } + if (ret == 0) + X509err(X509_F_X509_LOAD_CRL_FILE, X509_R_NO_CRL_FOUND); err: X509_CRL_free(x); BIO_free(in); - return (ret); + return ret; } int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type) @@ -192,6 +191,7 @@ int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type) X509_INFO *itmp; BIO *in; int i, count = 0; + if (type != X509_FILETYPE_PEM) return X509_load_cert_file(ctx, file, type); in = BIO_new_file(file, "r"); @@ -208,14 +208,20 @@ int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type) for (i = 0; i < sk_X509_INFO_num(inf); i++) { itmp = sk_X509_INFO_value(inf, i); if (itmp->x509) { - X509_STORE_add_cert(ctx->store_ctx, itmp->x509); + if (!X509_STORE_add_cert(ctx->store_ctx, itmp->x509)) + goto err; count++; } if (itmp->crl) { - X509_STORE_add_crl(ctx->store_ctx, itmp->crl); + if (!X509_STORE_add_crl(ctx->store_ctx, itmp->crl)) + goto err; count++; } } + if (count == 0) + X509err(X509_F_X509_LOAD_CERT_CRL_FILE, + X509_R_NO_CERTIFICATE_OR_CRL_FOUND); + err: sk_X509_INFO_pop_free(inf, X509_INFO_free); return count; } diff --git a/crypto/x509/t_crl.c b/crypto/x509/t_crl.c index f3ca6db8..8e262912 100644 --- a/crypto/x509/t_crl.c +++ b/crypto/x509/t_crl.c @@ -23,16 +23,21 @@ int X509_CRL_print_fp(FILE *fp, X509_CRL *x) if ((b = BIO_new(BIO_s_file())) == NULL) { X509err(X509_F_X509_CRL_PRINT_FP, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = X509_CRL_print(b, x); BIO_free(b); - return (ret); + return ret; } #endif int X509_CRL_print(BIO *out, X509_CRL *x) +{ + return X509_CRL_print_ex(out, x, XN_FLAG_COMPAT); +} + +int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag) { STACK_OF(X509_REVOKED) *rev; X509_REVOKED *r; @@ -40,7 +45,6 @@ int X509_CRL_print(BIO *out, X509_CRL *x) const ASN1_BIT_STRING *sig; long l; int i; - char *p; BIO_printf(out, "Certificate Revocation List (CRL):\n"); l = X509_CRL_get_version(x); @@ -49,10 +53,11 @@ int X509_CRL_print(BIO *out, X509_CRL *x) else BIO_printf(out, "%8sVersion unknown (%ld)\n", "", l); X509_CRL_get0_signature(x, &sig, &sig_alg); + BIO_puts(out, " "); X509_signature_print(out, sig_alg, NULL); - p = X509_NAME_oneline(X509_CRL_get_issuer(x), NULL, 0); - BIO_printf(out, "%8sIssuer: %s\n", "", p); - OPENSSL_free(p); + BIO_printf(out, "%8sIssuer: ", ""); + X509_NAME_print_ex(out, X509_CRL_get_issuer(x), 0, nmflag); + BIO_puts(out, "\n"); BIO_printf(out, "%8sLast Update: ", ""); ASN1_TIME_print(out, X509_CRL_get0_lastUpdate(x)); BIO_printf(out, "\n%8sNext Update: ", ""); diff --git a/crypto/x509/t_req.c b/crypto/x509/t_req.c index 77ce8108..2d4c591b 100644 --- a/crypto/x509/t_req.c +++ b/crypto/x509/t_req.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-2018 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 @@ -25,12 +25,12 @@ int X509_REQ_print_fp(FILE *fp, X509_REQ *x) if ((b = BIO_new(BIO_s_file())) == NULL) { X509err(X509_F_X509_REQ_PRINT_FP, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = X509_REQ_print(b, x); BIO_free(b); - return (ret); + return ret; } #endif @@ -93,10 +93,12 @@ int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflags, pkey = X509_REQ_get0_pubkey(x); if (pkey == NULL) { - BIO_printf(bp, "%12sUnable to load Public Key\n", ""); + if (BIO_printf(bp, "%12sUnable to load Public Key\n", "") <= 0) + goto err; ERR_print_errors(bp); } else { - EVP_PKEY_print_public(bp, pkey, 16, NULL); + if (EVP_PKEY_print_public(bp, pkey, 16, NULL) <= 0) + goto err; } } @@ -135,16 +137,22 @@ int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflags, goto err; if (BIO_puts(bp, ":") <= 0) goto err; - if ((type == V_ASN1_PRINTABLESTRING) || - (type == V_ASN1_T61STRING) || - (type == V_ASN1_UTF8STRING) || - (type == V_ASN1_IA5STRING)) { + switch (type) { + case V_ASN1_PRINTABLESTRING: + case V_ASN1_T61STRING: + case V_ASN1_NUMERICSTRING: + case V_ASN1_UTF8STRING: + case V_ASN1_IA5STRING: if (BIO_write(bp, (char *)bs->data, bs->length) - != bs->length) + != bs->length) goto err; - BIO_puts(bp, "\n"); - } else { - BIO_puts(bp, "unable to print attribute\n"); + if (BIO_puts(bp, "\n") <= 0) + goto err; + break; + default: + if (BIO_puts(bp, "unable to print attribute\n") <= 0) + goto err; + break; } if (++ii < count) goto get_next; @@ -154,7 +162,8 @@ int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflags, if (!(cflag & X509_FLAG_NO_EXTENSIONS)) { exts = X509_REQ_get_extensions(x); if (exts) { - BIO_printf(bp, "%8sRequested Extensions:\n", ""); + if (BIO_printf(bp, "%8sRequested Extensions:\n", "") <= 0) + goto err; for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) { ASN1_OBJECT *obj; X509_EXTENSION *ex; @@ -163,13 +172,16 @@ int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflags, if (BIO_printf(bp, "%12s", "") <= 0) goto err; obj = X509_EXTENSION_get_object(ex); - i2a_ASN1_OBJECT(bp, obj); + if (i2a_ASN1_OBJECT(bp, obj) <= 0) + goto err; critical = X509_EXTENSION_get_critical(ex); if (BIO_printf(bp, ": %s\n", critical ? "critical" : "") <= 0) goto err; if (!X509V3_EXT_print(bp, ex, cflag, 16)) { - BIO_printf(bp, "%16s", ""); - ASN1_STRING_print(bp, X509_EXTENSION_get_data(ex)); + if (BIO_printf(bp, "%16s", "") <= 0 + || ASN1_STRING_print(bp, + X509_EXTENSION_get_data(ex)) <= 0) + goto err; } if (BIO_write(bp, "\n", 1) <= 0) goto err; @@ -186,10 +198,10 @@ int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflags, goto err; } - return (1); + return 1; err: X509err(X509_F_X509_REQ_PRINT_EX, ERR_R_BUF_LIB); - return (0); + return 0; } int X509_REQ_print(BIO *bp, X509_REQ *x) diff --git a/crypto/x509/t_x509.c b/crypto/x509/t_x509.c index c7ced67f..ccacbe7c 100644 --- a/crypto/x509/t_x509.c +++ b/crypto/x509/t_x509.c @@ -30,12 +30,12 @@ int X509_print_ex_fp(FILE *fp, X509 *x, unsigned long nmflag, if ((b = BIO_new(BIO_s_file())) == NULL) { X509err(X509_F_X509_PRINT_EX_FP, ERR_R_BUF_LIB); - return (0); + return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = X509_print_ex(b, x, nmflag, cflag); BIO_free(b); - return (ret); + return ret; } #endif @@ -119,6 +119,9 @@ int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, if (!(cflag & X509_FLAG_NO_SIGNAME)) { const X509_ALGOR *tsig_alg = X509_get0_tbs_sigalg(x); + + if (BIO_puts(bp, " ") <= 0) + goto err; if (X509_signature_print(bp, tsig_alg, NULL) <= 0) goto err; } @@ -212,7 +215,7 @@ int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, ret = 1; err: OPENSSL_free(m); - return (ret); + return ret; } int X509_ocspid_print(BIO *bp, X509 *x) @@ -266,10 +269,10 @@ int X509_ocspid_print(BIO *bp, X509 *x) } BIO_printf(bp, "\n"); - return (1); + return 1; err: OPENSSL_free(der); - return (0); + return 0; } int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent) diff --git a/crypto/x509/x509_att.c b/crypto/x509/x509_att.c index 836bca50..63895efe 100644 --- a/crypto/x509/x509_att.c +++ b/crypto/x509/x509_att.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,7 +9,7 @@ #include #include "internal/cryptlib.h" -#include +#include #include #include #include @@ -28,8 +28,8 @@ int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid, const ASN1_OBJECT *obj = OBJ_nid2obj(nid); if (obj == NULL) - return (-2); - return (X509at_get_attr_by_OBJ(x, obj, lastpos)); + return -2; + return X509at_get_attr_by_OBJ(x, obj, lastpos); } int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk, @@ -39,7 +39,7 @@ int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk, X509_ATTRIBUTE *ex; if (sk == NULL) - return (-1); + return -1; lastpos++; if (lastpos < 0) lastpos = 0; @@ -47,17 +47,17 @@ int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk, for (; lastpos < n; lastpos++) { ex = sk_X509_ATTRIBUTE_value(sk, lastpos); if (OBJ_cmp(ex->object, obj) == 0) - return (lastpos); + return lastpos; } - return (-1); + return -1; } X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc) { if (x == NULL || sk_X509_ATTRIBUTE_num(x) <= loc || loc < 0) return NULL; - else - return sk_X509_ATTRIBUTE_value(x, loc); + + return sk_X509_ATTRIBUTE_value(x, loc); } X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc) @@ -65,9 +65,9 @@ X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc) X509_ATTRIBUTE *ret; if (x == NULL || sk_X509_ATTRIBUTE_num(x) <= loc || loc < 0) - return (NULL); + return NULL; ret = sk_X509_ATTRIBUTE_delete(x, loc); - return (ret); + return ret; } STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x, @@ -93,13 +93,13 @@ STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x, goto err; if (*x == NULL) *x = sk; - return (sk); + return sk; err: X509err(X509_F_X509AT_ADD1_ATTR, ERR_R_MALLOC_FAILURE); err2: X509_ATTRIBUTE_free(new_attr); sk_X509_ATTRIBUTE_free(sk); - return (NULL); + return NULL; } STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE) @@ -175,12 +175,12 @@ X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid, obj = OBJ_nid2obj(nid); if (obj == NULL) { X509err(X509_F_X509_ATTRIBUTE_CREATE_BY_NID, X509_R_UNKNOWN_NID); - return (NULL); + return NULL; } ret = X509_ATTRIBUTE_create_by_OBJ(attr, obj, atrtype, data, len); if (ret == NULL) ASN1_OBJECT_free(obj); - return (ret); + return ret; } X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr, @@ -194,7 +194,7 @@ X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr, if ((ret = X509_ATTRIBUTE_new()) == NULL) { X509err(X509_F_X509_ATTRIBUTE_CREATE_BY_OBJ, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } } else ret = *attr; @@ -206,11 +206,11 @@ X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr, if ((attr != NULL) && (*attr == NULL)) *attr = ret; - return (ret); + return ret; err: if ((attr == NULL) || (ret != *attr)) X509_ATTRIBUTE_free(ret); - return (NULL); + return NULL; } X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr, @@ -226,7 +226,7 @@ X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr, X509err(X509_F_X509_ATTRIBUTE_CREATE_BY_TXT, X509_R_INVALID_FIELD_NAME); ERR_add_error_data(2, "name=", atrname); - return (NULL); + return NULL; } nattr = X509_ATTRIBUTE_create_by_OBJ(attr, obj, type, bytes, len); ASN1_OBJECT_free(obj); @@ -236,7 +236,7 @@ X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr, int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj) { if ((attr == NULL) || (obj == NULL)) - return (0); + return 0; ASN1_OBJECT_free(attr->object); attr->object = OBJ_dup(obj); return attr->object != NULL; @@ -303,8 +303,8 @@ int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr) ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr) { if (attr == NULL) - return (NULL); - return (attr->object); + return NULL; + return attr->object; } void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, diff --git a/crypto/x509/x509_cmp.c b/crypto/x509/x509_cmp.c index 01056356..3d4931be 100644 --- a/crypto/x509/x509_cmp.c +++ b/crypto/x509/x509_cmp.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,7 +8,6 @@ */ #include -#include #include "internal/cryptlib.h" #include #include @@ -25,8 +24,8 @@ int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b) bi = &b->cert_info; i = ASN1_INTEGER_cmp(&ai->serialNumber, &bi->serialNumber); if (i) - return (i); - return (X509_NAME_cmp(ai->issuer, bi->issuer)); + return i; + return X509_NAME_cmp(ai->issuer, bi->issuer); } #ifndef OPENSSL_NO_MD5 @@ -56,23 +55,23 @@ unsigned long X509_issuer_and_serial_hash(X509 *a) ) & 0xffffffffL; err: EVP_MD_CTX_free(ctx); - return (ret); + return ret; } #endif int X509_issuer_name_cmp(const X509 *a, const X509 *b) { - return (X509_NAME_cmp(a->cert_info.issuer, b->cert_info.issuer)); + return X509_NAME_cmp(a->cert_info.issuer, b->cert_info.issuer); } int X509_subject_name_cmp(const X509 *a, const X509 *b) { - return (X509_NAME_cmp(a->cert_info.subject, b->cert_info.subject)); + return X509_NAME_cmp(a->cert_info.subject, b->cert_info.subject); } int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b) { - return (X509_NAME_cmp(a->crl.issuer, b->crl.issuer)); + return X509_NAME_cmp(a->crl.issuer, b->crl.issuer); } int X509_CRL_match(const X509_CRL *a, const X509_CRL *b) @@ -82,24 +81,24 @@ int X509_CRL_match(const X509_CRL *a, const X509_CRL *b) X509_NAME *X509_get_issuer_name(const X509 *a) { - return (a->cert_info.issuer); + return a->cert_info.issuer; } unsigned long X509_issuer_name_hash(X509 *x) { - return (X509_NAME_hash(x->cert_info.issuer)); + return X509_NAME_hash(x->cert_info.issuer); } #ifndef OPENSSL_NO_MD5 unsigned long X509_issuer_name_hash_old(X509 *x) { - return (X509_NAME_hash_old(x->cert_info.issuer)); + return X509_NAME_hash_old(x->cert_info.issuer); } #endif X509_NAME *X509_get_subject_name(const X509 *a) { - return (a->cert_info.subject); + return a->cert_info.subject; } ASN1_INTEGER *X509_get_serialNumber(X509 *a) @@ -114,13 +113,13 @@ const ASN1_INTEGER *X509_get0_serialNumber(const X509 *a) unsigned long X509_subject_name_hash(X509 *x) { - return (X509_NAME_hash(x->cert_info.subject)); + return X509_NAME_hash(x->cert_info.subject); } #ifndef OPENSSL_NO_MD5 unsigned long X509_subject_name_hash_old(X509 *x) { - return (X509_NAME_hash_old(x->cert_info.subject)); + return X509_NAME_hash_old(x->cert_info.subject); } #endif @@ -195,7 +194,7 @@ unsigned long X509_NAME_hash(X509_NAME *x) ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) | ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L) ) & 0xffffffffL; - return (ret); + return ret; } #ifndef OPENSSL_NO_MD5 @@ -224,7 +223,7 @@ unsigned long X509_NAME_hash_old(X509_NAME *x) ) & 0xffffffffL; EVP_MD_CTX_free(md_ctx); - return (ret); + return ret; } #endif @@ -244,9 +243,9 @@ X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, X509_NAME *name, for (i = 0; i < sk_X509_num(sk); i++) { x509 = sk_X509_value(sk, i); if (X509_issuer_and_serial_cmp(x509, &x) == 0) - return (x509); + return x509; } - return (NULL); + return NULL; } X509 *X509_find_by_subject(STACK_OF(X509) *sk, X509_NAME *name) @@ -257,9 +256,9 @@ X509 *X509_find_by_subject(STACK_OF(X509) *sk, X509_NAME *name) for (i = 0; i < sk_X509_num(sk); i++) { x509 = sk_X509_value(sk, i); if (X509_NAME_cmp(X509_get_subject_name(x509), name) == 0) - return (x509); + return x509; } - return (NULL); + return NULL; } EVP_PKEY *X509_get0_pubkey(const X509 *x) diff --git a/crypto/x509/x509_d2.c b/crypto/x509/x509_d2.c index cb03dbfa..099ffda1 100644 --- a/crypto/x509/x509_d2.c +++ b/crypto/x509/x509_d2.c @@ -18,18 +18,18 @@ int X509_STORE_set_default_paths(X509_STORE *ctx) lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_file()); if (lookup == NULL) - return (0); + return 0; X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT); lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_hash_dir()); if (lookup == NULL) - return (0); + return 0; X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT); /* clear any errors */ ERR_clear_error(); - return (1); + return 1; } int X509_STORE_load_locations(X509_STORE *ctx, const char *file, @@ -40,18 +40,18 @@ int X509_STORE_load_locations(X509_STORE *ctx, const char *file, if (file != NULL) { lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_file()); if (lookup == NULL) - return (0); + return 0; if (X509_LOOKUP_load_file(lookup, file, X509_FILETYPE_PEM) != 1) - return (0); + return 0; } if (path != NULL) { lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_hash_dir()); if (lookup == NULL) - return (0); + return 0; if (X509_LOOKUP_add_dir(lookup, path, X509_FILETYPE_PEM) != 1) - return (0); + return 0; } if ((path == NULL) && (file == NULL)) - return (0); - return (1); + return 0; + return 1; } diff --git a/crypto/x509/x509_def.c b/crypto/x509/x509_def.c index d11358e3..bfa8d7d8 100644 --- a/crypto/x509/x509_def.c +++ b/crypto/x509/x509_def.c @@ -14,30 +14,30 @@ const char *X509_get_default_private_dir(void) { - return (X509_PRIVATE_DIR); + return X509_PRIVATE_DIR; } const char *X509_get_default_cert_area(void) { - return (X509_CERT_AREA); + return X509_CERT_AREA; } const char *X509_get_default_cert_dir(void) { - return (X509_CERT_DIR); + return X509_CERT_DIR; } const char *X509_get_default_cert_file(void) { - return (X509_CERT_FILE); + return X509_CERT_FILE; } const char *X509_get_default_cert_dir_env(void) { - return (X509_CERT_DIR_EVP); + return X509_CERT_DIR_EVP; } const char *X509_get_default_cert_file_env(void) { - return (X509_CERT_FILE_EVP); + return X509_CERT_FILE_EVP; } diff --git a/crypto/x509/x509_err.c b/crypto/x509/x509_err.c index 3f4b8ef0..84c726f4 100644 --- a/crypto/x509/x509_err.c +++ b/crypto/x509/x509_err.c @@ -1,6 +1,6 @@ /* * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,122 +8,148 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_X509,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_X509,0,reason) - -static ERR_STRING_DATA X509_str_functs[] = { - {ERR_FUNC(X509_F_ADD_CERT_DIR), "add_cert_dir"}, - {ERR_FUNC(X509_F_BUILD_CHAIN), "build_chain"}, - {ERR_FUNC(X509_F_BY_FILE_CTRL), "by_file_ctrl"}, - {ERR_FUNC(X509_F_CHECK_NAME_CONSTRAINTS), "check_name_constraints"}, - {ERR_FUNC(X509_F_CHECK_POLICY), "check_policy"}, - {ERR_FUNC(X509_F_DANE_I2D), "dane_i2d"}, - {ERR_FUNC(X509_F_DIR_CTRL), "dir_ctrl"}, - {ERR_FUNC(X509_F_GET_CERT_BY_SUBJECT), "get_cert_by_subject"}, - {ERR_FUNC(X509_F_NETSCAPE_SPKI_B64_DECODE), "NETSCAPE_SPKI_b64_decode"}, - {ERR_FUNC(X509_F_NETSCAPE_SPKI_B64_ENCODE), "NETSCAPE_SPKI_b64_encode"}, - {ERR_FUNC(X509_F_X509AT_ADD1_ATTR), "X509at_add1_attr"}, - {ERR_FUNC(X509_F_X509V3_ADD_EXT), "X509v3_add_ext"}, - {ERR_FUNC(X509_F_X509_ATTRIBUTE_CREATE_BY_NID), +static const ERR_STRING_DATA X509_str_functs[] = { + {ERR_PACK(ERR_LIB_X509, X509_F_ADD_CERT_DIR, 0), "add_cert_dir"}, + {ERR_PACK(ERR_LIB_X509, X509_F_BUILD_CHAIN, 0), "build_chain"}, + {ERR_PACK(ERR_LIB_X509, X509_F_BY_FILE_CTRL, 0), "by_file_ctrl"}, + {ERR_PACK(ERR_LIB_X509, X509_F_CHECK_NAME_CONSTRAINTS, 0), + "check_name_constraints"}, + {ERR_PACK(ERR_LIB_X509, X509_F_CHECK_POLICY, 0), "check_policy"}, + {ERR_PACK(ERR_LIB_X509, X509_F_DANE_I2D, 0), "dane_i2d"}, + {ERR_PACK(ERR_LIB_X509, X509_F_DIR_CTRL, 0), "dir_ctrl"}, + {ERR_PACK(ERR_LIB_X509, X509_F_GET_CERT_BY_SUBJECT, 0), + "get_cert_by_subject"}, + {ERR_PACK(ERR_LIB_X509, X509_F_NETSCAPE_SPKI_B64_DECODE, 0), + "NETSCAPE_SPKI_b64_decode"}, + {ERR_PACK(ERR_LIB_X509, X509_F_NETSCAPE_SPKI_B64_ENCODE, 0), + "NETSCAPE_SPKI_b64_encode"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509AT_ADD1_ATTR, 0), "X509at_add1_attr"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509V3_ADD_EXT, 0), "X509v3_add_ext"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_ATTRIBUTE_CREATE_BY_NID, 0), "X509_ATTRIBUTE_create_by_NID"}, - {ERR_FUNC(X509_F_X509_ATTRIBUTE_CREATE_BY_OBJ), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_ATTRIBUTE_CREATE_BY_OBJ, 0), "X509_ATTRIBUTE_create_by_OBJ"}, - {ERR_FUNC(X509_F_X509_ATTRIBUTE_CREATE_BY_TXT), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_ATTRIBUTE_CREATE_BY_TXT, 0), "X509_ATTRIBUTE_create_by_txt"}, - {ERR_FUNC(X509_F_X509_ATTRIBUTE_GET0_DATA), "X509_ATTRIBUTE_get0_data"}, - {ERR_FUNC(X509_F_X509_ATTRIBUTE_SET1_DATA), "X509_ATTRIBUTE_set1_data"}, - {ERR_FUNC(X509_F_X509_CHECK_PRIVATE_KEY), "X509_check_private_key"}, - {ERR_FUNC(X509_F_X509_CRL_DIFF), "X509_CRL_diff"}, - {ERR_FUNC(X509_F_X509_CRL_PRINT_FP), "X509_CRL_print_fp"}, - {ERR_FUNC(X509_F_X509_EXTENSION_CREATE_BY_NID), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_ATTRIBUTE_GET0_DATA, 0), + "X509_ATTRIBUTE_get0_data"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_ATTRIBUTE_SET1_DATA, 0), + "X509_ATTRIBUTE_set1_data"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_CHECK_PRIVATE_KEY, 0), + "X509_check_private_key"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_CRL_DIFF, 0), "X509_CRL_diff"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_CRL_PRINT_FP, 0), "X509_CRL_print_fp"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_EXTENSION_CREATE_BY_NID, 0), "X509_EXTENSION_create_by_NID"}, - {ERR_FUNC(X509_F_X509_EXTENSION_CREATE_BY_OBJ), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_EXTENSION_CREATE_BY_OBJ, 0), "X509_EXTENSION_create_by_OBJ"}, - {ERR_FUNC(X509_F_X509_GET_PUBKEY_PARAMETERS), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_GET_PUBKEY_PARAMETERS, 0), "X509_get_pubkey_parameters"}, - {ERR_FUNC(X509_F_X509_LOAD_CERT_CRL_FILE), "X509_load_cert_crl_file"}, - {ERR_FUNC(X509_F_X509_LOAD_CERT_FILE), "X509_load_cert_file"}, - {ERR_FUNC(X509_F_X509_LOAD_CRL_FILE), "X509_load_crl_file"}, - {ERR_FUNC(X509_F_X509_NAME_ADD_ENTRY), "X509_NAME_add_entry"}, - {ERR_FUNC(X509_F_X509_NAME_ENTRY_CREATE_BY_NID), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_LOAD_CERT_CRL_FILE, 0), + "X509_load_cert_crl_file"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_LOAD_CERT_FILE, 0), + "X509_load_cert_file"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_LOAD_CRL_FILE, 0), + "X509_load_crl_file"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_NAME_ADD_ENTRY, 0), + "X509_NAME_add_entry"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_NAME_ENTRY_CREATE_BY_NID, 0), "X509_NAME_ENTRY_create_by_NID"}, - {ERR_FUNC(X509_F_X509_NAME_ENTRY_CREATE_BY_TXT), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_NAME_ENTRY_CREATE_BY_TXT, 0), "X509_NAME_ENTRY_create_by_txt"}, - {ERR_FUNC(X509_F_X509_NAME_ENTRY_SET_OBJECT), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_NAME_ENTRY_SET_OBJECT, 0), "X509_NAME_ENTRY_set_object"}, - {ERR_FUNC(X509_F_X509_NAME_ONELINE), "X509_NAME_oneline"}, - {ERR_FUNC(X509_F_X509_NAME_PRINT), "X509_NAME_print"}, - {ERR_FUNC(X509_F_X509_OBJECT_NEW), "X509_OBJECT_new"}, - {ERR_FUNC(X509_F_X509_PRINT_EX_FP), "X509_print_ex_fp"}, - {ERR_FUNC(X509_F_X509_PUBKEY_DECODE), "x509_pubkey_decode"}, - {ERR_FUNC(X509_F_X509_PUBKEY_GET0), "X509_PUBKEY_get0"}, - {ERR_FUNC(X509_F_X509_PUBKEY_SET), "X509_PUBKEY_set"}, - {ERR_FUNC(X509_F_X509_REQ_CHECK_PRIVATE_KEY), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_NAME_ONELINE, 0), "X509_NAME_oneline"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_NAME_PRINT, 0), "X509_NAME_print"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_OBJECT_NEW, 0), "X509_OBJECT_new"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_PRINT_EX_FP, 0), "X509_print_ex_fp"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_PUBKEY_DECODE, 0), + "x509_pubkey_decode"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_PUBKEY_GET0, 0), "X509_PUBKEY_get0"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_PUBKEY_SET, 0), "X509_PUBKEY_set"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_REQ_CHECK_PRIVATE_KEY, 0), "X509_REQ_check_private_key"}, - {ERR_FUNC(X509_F_X509_REQ_PRINT_EX), "X509_REQ_print_ex"}, - {ERR_FUNC(X509_F_X509_REQ_PRINT_FP), "X509_REQ_print_fp"}, - {ERR_FUNC(X509_F_X509_REQ_TO_X509), "X509_REQ_to_X509"}, - {ERR_FUNC(X509_F_X509_STORE_ADD_CERT), "X509_STORE_add_cert"}, - {ERR_FUNC(X509_F_X509_STORE_ADD_CRL), "X509_STORE_add_crl"}, - {ERR_FUNC(X509_F_X509_STORE_CTX_GET1_ISSUER), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_REQ_PRINT_EX, 0), "X509_REQ_print_ex"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_REQ_PRINT_FP, 0), "X509_REQ_print_fp"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_REQ_TO_X509, 0), "X509_REQ_to_X509"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_STORE_ADD_CERT, 0), + "X509_STORE_add_cert"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_STORE_ADD_CRL, 0), + "X509_STORE_add_crl"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_STORE_CTX_GET1_ISSUER, 0), "X509_STORE_CTX_get1_issuer"}, - {ERR_FUNC(X509_F_X509_STORE_CTX_INIT), "X509_STORE_CTX_init"}, - {ERR_FUNC(X509_F_X509_STORE_CTX_NEW), "X509_STORE_CTX_new"}, - {ERR_FUNC(X509_F_X509_STORE_CTX_PURPOSE_INHERIT), + {ERR_PACK(ERR_LIB_X509, X509_F_X509_STORE_CTX_INIT, 0), + "X509_STORE_CTX_init"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_STORE_CTX_NEW, 0), + "X509_STORE_CTX_new"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_STORE_CTX_PURPOSE_INHERIT, 0), "X509_STORE_CTX_purpose_inherit"}, - {ERR_FUNC(X509_F_X509_TO_X509_REQ), "X509_to_X509_REQ"}, - {ERR_FUNC(X509_F_X509_TRUST_ADD), "X509_TRUST_add"}, - {ERR_FUNC(X509_F_X509_TRUST_SET), "X509_TRUST_set"}, - {ERR_FUNC(X509_F_X509_VERIFY_CERT), "X509_verify_cert"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_TO_X509_REQ, 0), "X509_to_X509_REQ"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_TRUST_ADD, 0), "X509_TRUST_add"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_TRUST_SET, 0), "X509_TRUST_set"}, + {ERR_PACK(ERR_LIB_X509, X509_F_X509_VERIFY_CERT, 0), "X509_verify_cert"}, {0, NULL} }; -static ERR_STRING_DATA X509_str_reasons[] = { - {ERR_REASON(X509_R_AKID_MISMATCH), "akid mismatch"}, - {ERR_REASON(X509_R_BAD_SELECTOR), "bad selector"}, - {ERR_REASON(X509_R_BAD_X509_FILETYPE), "bad x509 filetype"}, - {ERR_REASON(X509_R_BASE64_DECODE_ERROR), "base64 decode error"}, - {ERR_REASON(X509_R_CANT_CHECK_DH_KEY), "cant check dh key"}, - {ERR_REASON(X509_R_CERT_ALREADY_IN_HASH_TABLE), - "cert already in hash table"}, - {ERR_REASON(X509_R_CRL_ALREADY_DELTA), "crl already delta"}, - {ERR_REASON(X509_R_CRL_VERIFY_FAILURE), "crl verify failure"}, - {ERR_REASON(X509_R_IDP_MISMATCH), "idp mismatch"}, - {ERR_REASON(X509_R_INVALID_DIRECTORY), "invalid directory"}, - {ERR_REASON(X509_R_INVALID_FIELD_NAME), "invalid field name"}, - {ERR_REASON(X509_R_INVALID_TRUST), "invalid trust"}, - {ERR_REASON(X509_R_ISSUER_MISMATCH), "issuer mismatch"}, - {ERR_REASON(X509_R_KEY_TYPE_MISMATCH), "key type mismatch"}, - {ERR_REASON(X509_R_KEY_VALUES_MISMATCH), "key values mismatch"}, - {ERR_REASON(X509_R_LOADING_CERT_DIR), "loading cert dir"}, - {ERR_REASON(X509_R_LOADING_DEFAULTS), "loading defaults"}, - {ERR_REASON(X509_R_METHOD_NOT_SUPPORTED), "method not supported"}, - {ERR_REASON(X509_R_NAME_TOO_LONG), "name too long"}, - {ERR_REASON(X509_R_NEWER_CRL_NOT_NEWER), "newer crl not newer"}, - {ERR_REASON(X509_R_NO_CERT_SET_FOR_US_TO_VERIFY), - "no cert set for us to verify"}, - {ERR_REASON(X509_R_NO_CRL_NUMBER), "no crl number"}, - {ERR_REASON(X509_R_PUBLIC_KEY_DECODE_ERROR), "public key decode error"}, - {ERR_REASON(X509_R_PUBLIC_KEY_ENCODE_ERROR), "public key encode error"}, - {ERR_REASON(X509_R_SHOULD_RETRY), "should retry"}, - {ERR_REASON(X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN), - "unable to find parameters in chain"}, - {ERR_REASON(X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY), - "unable to get certs public key"}, - {ERR_REASON(X509_R_UNKNOWN_KEY_TYPE), "unknown key type"}, - {ERR_REASON(X509_R_UNKNOWN_NID), "unknown nid"}, - {ERR_REASON(X509_R_UNKNOWN_PURPOSE_ID), "unknown purpose id"}, - {ERR_REASON(X509_R_UNKNOWN_TRUST_ID), "unknown trust id"}, - {ERR_REASON(X509_R_UNSUPPORTED_ALGORITHM), "unsupported algorithm"}, - {ERR_REASON(X509_R_WRONG_LOOKUP_TYPE), "wrong lookup type"}, - {ERR_REASON(X509_R_WRONG_TYPE), "wrong type"}, +static const ERR_STRING_DATA X509_str_reasons[] = { + {ERR_PACK(ERR_LIB_X509, 0, X509_R_AKID_MISMATCH), "akid mismatch"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_BAD_SELECTOR), "bad selector"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_BAD_X509_FILETYPE), "bad x509 filetype"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_BASE64_DECODE_ERROR), + "base64 decode error"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_CANT_CHECK_DH_KEY), "cant check dh key"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_CERT_ALREADY_IN_HASH_TABLE), + "cert already in hash table"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_CRL_ALREADY_DELTA), "crl already delta"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_CRL_VERIFY_FAILURE), + "crl verify failure"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_IDP_MISMATCH), "idp mismatch"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_DIRECTORY), "invalid directory"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_FIELD_NAME), + "invalid field name"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_TRUST), "invalid trust"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_ISSUER_MISMATCH), "issuer mismatch"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_KEY_TYPE_MISMATCH), "key type mismatch"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_KEY_VALUES_MISMATCH), + "key values mismatch"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_LOADING_CERT_DIR), "loading cert dir"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_LOADING_DEFAULTS), "loading defaults"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_METHOD_NOT_SUPPORTED), + "method not supported"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_NAME_TOO_LONG), "name too long"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_NEWER_CRL_NOT_NEWER), + "newer crl not newer"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CERTIFICATE_FOUND), + "no certificate found"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CERTIFICATE_OR_CRL_FOUND), + "no certificate or crl found"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY), + "no cert set for us to verify"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CRL_FOUND), "no crl found"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CRL_NUMBER), "no crl number"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_PUBLIC_KEY_DECODE_ERROR), + "public key decode error"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_PUBLIC_KEY_ENCODE_ERROR), + "public key encode error"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_SHOULD_RETRY), "should retry"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN), + "unable to find parameters in chain"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY), + "unable to get certs public key"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_KEY_TYPE), "unknown key type"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_NID), "unknown nid"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_PURPOSE_ID), + "unknown purpose id"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_TRUST_ID), "unknown trust id"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_UNSUPPORTED_ALGORITHM), + "unsupported algorithm"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_WRONG_LOOKUP_TYPE), "wrong lookup type"}, + {ERR_PACK(ERR_LIB_X509, 0, X509_R_WRONG_TYPE), "wrong type"}, {0, NULL} }; @@ -132,10 +158,9 @@ static ERR_STRING_DATA X509_str_reasons[] = { int ERR_load_X509_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(X509_str_functs[0].error) == NULL) { - ERR_load_strings(0, X509_str_functs); - ERR_load_strings(0, X509_str_reasons); + ERR_load_strings_const(X509_str_functs); + ERR_load_strings_const(X509_str_reasons); } #endif return 1; diff --git a/crypto/x509/x509_ext.c b/crypto/x509/x509_ext.c index 3c590798..2db84376 100644 --- a/crypto/x509/x509_ext.c +++ b/crypto/x509/x509_ext.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,7 +9,6 @@ #include #include "internal/cryptlib.h" -#include #include #include #include @@ -19,33 +18,33 @@ int X509_CRL_get_ext_count(const X509_CRL *x) { - return (X509v3_get_ext_count(x->crl.extensions)); + return X509v3_get_ext_count(x->crl.extensions); } int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos) { - return (X509v3_get_ext_by_NID(x->crl.extensions, nid, lastpos)); + return X509v3_get_ext_by_NID(x->crl.extensions, nid, lastpos); } int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj, int lastpos) { - return (X509v3_get_ext_by_OBJ(x->crl.extensions, obj, lastpos)); + return X509v3_get_ext_by_OBJ(x->crl.extensions, obj, lastpos); } int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos) { - return (X509v3_get_ext_by_critical(x->crl.extensions, crit, lastpos)); + return X509v3_get_ext_by_critical(x->crl.extensions, crit, lastpos); } X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc) { - return (X509v3_get_ext(x->crl.extensions, loc)); + return X509v3_get_ext(x->crl.extensions, loc); } X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc) { - return (X509v3_delete_ext(x->crl.extensions, loc)); + return X509v3_delete_ext(x->crl.extensions, loc); } void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx) @@ -66,17 +65,17 @@ int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc) int X509_get_ext_count(const X509 *x) { - return (X509v3_get_ext_count(x->cert_info.extensions)); + return X509v3_get_ext_count(x->cert_info.extensions); } int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos) { - return (X509v3_get_ext_by_NID(x->cert_info.extensions, nid, lastpos)); + return X509v3_get_ext_by_NID(x->cert_info.extensions, nid, lastpos); } int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos) { - return (X509v3_get_ext_by_OBJ(x->cert_info.extensions, obj, lastpos)); + return X509v3_get_ext_by_OBJ(x->cert_info.extensions, obj, lastpos); } int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos) @@ -87,12 +86,12 @@ int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos) X509_EXTENSION *X509_get_ext(const X509 *x, int loc) { - return (X509v3_get_ext(x->cert_info.extensions, loc)); + return X509v3_get_ext(x->cert_info.extensions, loc); } X509_EXTENSION *X509_delete_ext(X509 *x, int loc) { - return (X509v3_delete_ext(x->cert_info.extensions, loc)); + return X509v3_delete_ext(x->cert_info.extensions, loc); } int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc) @@ -114,33 +113,33 @@ int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit, int X509_REVOKED_get_ext_count(const X509_REVOKED *x) { - return (X509v3_get_ext_count(x->extensions)); + return X509v3_get_ext_count(x->extensions); } int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos) { - return (X509v3_get_ext_by_NID(x->extensions, nid, lastpos)); + return X509v3_get_ext_by_NID(x->extensions, nid, lastpos); } int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj, int lastpos) { - return (X509v3_get_ext_by_OBJ(x->extensions, obj, lastpos)); + return X509v3_get_ext_by_OBJ(x->extensions, obj, lastpos); } int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit, int lastpos) { - return (X509v3_get_ext_by_critical(x->extensions, crit, lastpos)); + return X509v3_get_ext_by_critical(x->extensions, crit, lastpos); } X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc) { - return (X509v3_get_ext(x->extensions, loc)); + return X509v3_get_ext(x->extensions, loc); } X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc) { - return (X509v3_delete_ext(x->extensions, loc)); + return X509v3_delete_ext(x->extensions, loc); } int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc) diff --git a/crypto/x509/x509_lcl.h b/crypto/x509/x509_lcl.h index 40bd102f..401f2e9f 100644 --- a/crypto/x509/x509_lcl.h +++ b/crypto/x509/x509_lcl.h @@ -7,6 +7,8 @@ * https://www.openssl.org/source/license.html */ +#include "internal/refcount.h" + /* * This structure holds all parameters associated with a verify operation by * including an X509_VERIFY_PARAM structure in related structures the @@ -130,7 +132,7 @@ struct x509_store_st { STACK_OF(X509_CRL) *(*lookup_crls) (X509_STORE_CTX *ctx, X509_NAME *nm); int (*cleanup) (X509_STORE_CTX *ctx); CRYPTO_EX_DATA ex_data; - int references; + CRYPTO_REF_COUNT references; CRYPTO_RWLOCK *lock; }; @@ -140,3 +142,6 @@ DEFINE_STACK_OF(BY_DIR_HASH) DEFINE_STACK_OF(BY_DIR_ENTRY) typedef STACK_OF(X509_NAME_ENTRY) STACK_OF_X509_NAME_ENTRY; DEFINE_STACK_OF(STACK_OF_X509_NAME_ENTRY) + +void x509_set_signature_info(X509_SIG_INFO *siginf, const X509_ALGOR *alg, + const ASN1_STRING *sig); diff --git a/crypto/x509/x509_lu.c b/crypto/x509/x509_lu.c index 90f23520..b8845f1e 100644 --- a/crypto/x509/x509_lu.c +++ b/crypto/x509/x509_lu.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,7 +9,7 @@ #include #include "internal/cryptlib.h" -#include +#include "internal/refcount.h" #include #include "internal/x509_int.h" #include @@ -132,7 +132,7 @@ static int x509_object_cmp(const X509_OBJECT *const *a, case X509_LU_CRL: ret = X509_CRL_cmp((*a)->data.crl, (*b)->data.crl); break; - default: + case X509_LU_NONE: /* abort(); */ return 0; } @@ -181,7 +181,7 @@ void X509_STORE_free(X509_STORE *vfy) if (vfy == NULL) return; - CRYPTO_atomic_add(&vfy->references, -1, &i, vfy->lock); + CRYPTO_DOWN_REF(&vfy->references, &i, vfy->lock); REF_PRINT_COUNT("X509_STORE", vfy); if (i > 0) return; @@ -206,7 +206,7 @@ int X509_STORE_up_ref(X509_STORE *vfy) { int i; - if (CRYPTO_atomic_add(&vfy->references, 1, &i, vfy->lock) <= 0) + if (CRYPTO_UP_REF(&vfy->references, &i, vfy->lock) <= 0) return 0; REF_PRINT_COUNT("X509_STORE", a); @@ -290,26 +290,29 @@ int X509_STORE_CTX_get_by_subject(X509_STORE_CTX *vs, X509_LOOKUP_TYPE type, return 1; } -int X509_STORE_add_cert(X509_STORE *ctx, X509 *x) -{ +static int x509_store_add(X509_STORE *ctx, void *x, int crl) { X509_OBJECT *obj; - int ret = 1, added = 1; + int ret = 0, added = 0; if (x == NULL) return 0; obj = X509_OBJECT_new(); if (obj == NULL) return 0; - obj->type = X509_LU_X509; - obj->data.x509 = x; + + if (crl) { + obj->type = X509_LU_CRL; + obj->data.crl = (X509_CRL *)x; + } else { + obj->type = X509_LU_X509; + obj->data.x509 = (X509 *)x; + } X509_OBJECT_up_ref_count(obj); CRYPTO_THREAD_write_lock(ctx->lock); if (X509_OBJECT_retrieve_match(ctx->objs, obj)) { - X509err(X509_F_X509_STORE_ADD_CERT, - X509_R_CERT_ALREADY_IN_HASH_TABLE); - ret = 0; + ret = 1; } else { added = sk_X509_OBJECT_push(ctx->objs, obj); ret = added != 0; @@ -317,52 +320,34 @@ int X509_STORE_add_cert(X509_STORE *ctx, X509 *x) CRYPTO_THREAD_unlock(ctx->lock); - if (!ret) /* obj not pushed */ + if (added == 0) /* obj not pushed */ X509_OBJECT_free(obj); - if (!added) /* on push failure */ - X509err(X509_F_X509_STORE_ADD_CERT, ERR_R_MALLOC_FAILURE); return ret; } +int X509_STORE_add_cert(X509_STORE *ctx, X509 *x) +{ + if (!x509_store_add(ctx, x, 0)) { + X509err(X509_F_X509_STORE_ADD_CERT, ERR_R_MALLOC_FAILURE); + return 0; + } + return 1; +} + int X509_STORE_add_crl(X509_STORE *ctx, X509_CRL *x) { - X509_OBJECT *obj; - int ret = 1, added = 1; - - if (x == NULL) - return 0; - obj = X509_OBJECT_new(); - if (obj == NULL) - return 0; - obj->type = X509_LU_CRL; - obj->data.crl = x; - X509_OBJECT_up_ref_count(obj); - - CRYPTO_THREAD_write_lock(ctx->lock); - - if (X509_OBJECT_retrieve_match(ctx->objs, obj)) { - X509err(X509_F_X509_STORE_ADD_CRL, X509_R_CERT_ALREADY_IN_HASH_TABLE); - ret = 0; - } else { - added = sk_X509_OBJECT_push(ctx->objs, obj); - ret = added != 0; - } - - CRYPTO_THREAD_unlock(ctx->lock); - - if (!ret) /* obj not pushed */ - X509_OBJECT_free(obj); - if (!added) /* on push failure */ + if (!x509_store_add(ctx, x, 1)) { X509err(X509_F_X509_STORE_ADD_CRL, ERR_R_MALLOC_FAILURE); - - return ret; + return 0; + } + return 1; } int X509_OBJECT_up_ref_count(X509_OBJECT *a) { switch (a->type) { - default: + case X509_LU_NONE: break; case X509_LU_X509: return X509_up_ref(a->data.x509); @@ -409,7 +394,7 @@ void X509_OBJECT_free(X509_OBJECT *a) if (a == NULL) return; switch (a->type) { - default: + case X509_LU_NONE: break; case X509_LU_X509: X509_free(a->data.x509); @@ -439,7 +424,7 @@ static int x509_object_idx_cnt(STACK_OF(X509_OBJECT) *h, X509_LOOKUP_TYPE type, stmp.data.crl = &crl_s; crl_s.crl.issuer = name; break; - default: + case X509_LU_NONE: /* abort(); */ return -1; } diff --git a/crypto/x509/x509_obj.c b/crypto/x509/x509_obj.c index 55dc778b..85c39415 100644 --- a/crypto/x509/x509_obj.c +++ b/crypto/x509/x509_obj.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,7 +9,6 @@ #include #include "internal/cryptlib.h" -#include #include #include #include @@ -173,10 +172,10 @@ char *X509_NAME_oneline(const X509_NAME *a, char *buf, int len) p = buf; if (i == 0) *p = '\0'; - return (p); + return p; err: X509err(X509_F_X509_NAME_ONELINE, ERR_R_MALLOC_FAILURE); end: BUF_MEM_free(b); - return (NULL); + return NULL; } diff --git a/crypto/x509/x509_req.c b/crypto/x509/x509_req.c index 7b88dbcd..0bdbb81d 100644 --- a/crypto/x509/x509_req.c +++ b/crypto/x509/x509_req.c @@ -54,24 +54,24 @@ X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md) if (!X509_REQ_sign(ret, pkey, md)) goto err; } - return (ret); + return ret; err: X509_REQ_free(ret); - return (NULL); + return NULL; } EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req) { if (req == NULL) - return (NULL); - return (X509_PUBKEY_get(req->req_info.pubkey)); + return NULL; + return X509_PUBKEY_get(req->req_info.pubkey); } EVP_PKEY *X509_REQ_get0_pubkey(X509_REQ *req) { if (req == NULL) return NULL; - return (X509_PUBKEY_get0(req->req_info.pubkey)); + return X509_PUBKEY_get0(req->req_info.pubkey); } X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req) @@ -115,7 +115,7 @@ int X509_REQ_check_private_key(X509_REQ *x, EVP_PKEY *k) } EVP_PKEY_free(xk); - return (ok); + return ok; } /* @@ -158,7 +158,7 @@ STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req) const unsigned char *p; if ((req == NULL) || !ext_nids) - return (NULL); + return NULL; for (pnid = ext_nids; *pnid != NID_undef; pnid++) { idx = X509_REQ_get_attr_by_NID(req, *pnid, -1); if (idx == -1) diff --git a/crypto/x509/x509_set.c b/crypto/x509/x509_set.c index c0ea4188..3ab6bf35 100644 --- a/crypto/x509/x509_set.c +++ b/crypto/x509/x509_set.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,26 +9,30 @@ #include #include "internal/cryptlib.h" +#include "internal/refcount.h" #include #include #include #include +#include +#include "internal/asn1_int.h" #include "internal/x509_int.h" +#include "x509_lcl.h" int X509_set_version(X509 *x, long version) { if (x == NULL) - return (0); + return 0; if (version == 0) { ASN1_INTEGER_free(x->cert_info.version); x->cert_info.version = NULL; - return (1); + return 1; } if (x->cert_info.version == NULL) { if ((x->cert_info.version = ASN1_INTEGER_new()) == NULL) - return (0); + return 0; } - return (ASN1_INTEGER_set(x->cert_info.version, version)); + return ASN1_INTEGER_set(x->cert_info.version, version); } int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial) @@ -46,15 +50,15 @@ int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial) int X509_set_issuer_name(X509 *x, X509_NAME *name) { if (x == NULL) - return (0); - return (X509_NAME_set(&x->cert_info.issuer, name)); + return 0; + return X509_NAME_set(&x->cert_info.issuer, name); } int X509_set_subject_name(X509 *x, X509_NAME *name) { if (x == NULL) - return (0); - return (X509_NAME_set(&x->cert_info.subject, name)); + return 0; + return X509_NAME_set(&x->cert_info.subject, name); } int x509_set1_time(ASN1_TIME **ptm, const ASN1_TIME *tm) @@ -88,15 +92,15 @@ int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm) int X509_set_pubkey(X509 *x, EVP_PKEY *pkey) { if (x == NULL) - return (0); - return (X509_PUBKEY_set(&(x->cert_info.key), pkey)); + return 0; + return X509_PUBKEY_set(&(x->cert_info.key), pkey); } int X509_up_ref(X509 *x) { int i; - if (CRYPTO_atomic_add(&x->references, 1, &i, x->lock) <= 0) + if (CRYPTO_UP_REF(&x->references, &i, x->lock) <= 0) return 0; REF_PRINT_COUNT("X509", x); @@ -157,3 +161,77 @@ const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x) { return &x->cert_info.signature; } + +int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid, + int *secbits, uint32_t *flags) +{ + if (mdnid != NULL) + *mdnid = siginf->mdnid; + if (pknid != NULL) + *pknid = siginf->pknid; + if (secbits != NULL) + *secbits = siginf->secbits; + if (flags != NULL) + *flags = siginf->flags; + return (siginf->flags & X509_SIG_INFO_VALID) != 0; +} + +void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid, + int secbits, uint32_t flags) +{ + siginf->mdnid = mdnid; + siginf->pknid = pknid; + siginf->secbits = secbits; + siginf->flags = flags; +} + +int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits, + uint32_t *flags) +{ + X509_check_purpose(x, -1, -1); + return X509_SIG_INFO_get(&x->siginf, mdnid, pknid, secbits, flags); +} + +static void x509_sig_info_init(X509_SIG_INFO *siginf, const X509_ALGOR *alg, + const ASN1_STRING *sig) +{ + int pknid, mdnid; + const EVP_MD *md; + + siginf->mdnid = NID_undef; + siginf->pknid = NID_undef; + siginf->secbits = -1; + siginf->flags = 0; + if (!OBJ_find_sigid_algs(OBJ_obj2nid(alg->algorithm), &mdnid, &pknid) + || pknid == NID_undef) + return; + siginf->pknid = pknid; + if (mdnid == NID_undef) { + /* If we have one, use a custom handler for this algorithm */ + const EVP_PKEY_ASN1_METHOD *ameth = EVP_PKEY_asn1_find(NULL, pknid); + if (ameth == NULL || ameth->siginf_set == NULL + || ameth->siginf_set(siginf, alg, sig) == 0) + return; + siginf->flags |= X509_SIG_INFO_VALID; + return; + } + siginf->flags |= X509_SIG_INFO_VALID; + siginf->mdnid = mdnid; + md = EVP_get_digestbynid(mdnid); + if (md == NULL) + return; + /* Security bits: half number of bits in digest */ + siginf->secbits = EVP_MD_size(md) * 4; + switch (mdnid) { + case NID_sha1: + case NID_sha256: + case NID_sha384: + case NID_sha512: + siginf->flags |= X509_SIG_INFO_TLS; + } +} + +void x509_init_sig_info(X509 *x) +{ + x509_sig_info_init(&x->siginf, &x->sig_alg, &x->signature); +} diff --git a/crypto/x509/x509_txt.c b/crypto/x509/x509_txt.c index 66e5fcd0..4755b39e 100644 --- a/crypto/x509/x509_txt.c +++ b/crypto/x509/x509_txt.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -12,7 +12,6 @@ #include #include "internal/cryptlib.h" -#include #include #include #include @@ -23,155 +22,161 @@ const char *X509_verify_cert_error_string(long n) { switch ((int)n) { case X509_V_OK: - return ("ok"); + return "ok"; case X509_V_ERR_UNSPECIFIED: - return ("unspecified certificate verification error"); + return "unspecified certificate verification error"; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: - return ("unable to get issuer certificate"); + return "unable to get issuer certificate"; case X509_V_ERR_UNABLE_TO_GET_CRL: - return ("unable to get certificate CRL"); + return "unable to get certificate CRL"; case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: - return ("unable to decrypt certificate's signature"); + return "unable to decrypt certificate's signature"; case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: - return ("unable to decrypt CRL's 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"); + return "unable to decode issuer public key"; case X509_V_ERR_CERT_SIGNATURE_FAILURE: - return ("certificate signature failure"); + return "certificate signature failure"; case X509_V_ERR_CRL_SIGNATURE_FAILURE: - return ("CRL signature failure"); + return "CRL signature failure"; case X509_V_ERR_CERT_NOT_YET_VALID: - return ("certificate is not yet valid"); + return "certificate is not yet valid"; case X509_V_ERR_CERT_HAS_EXPIRED: - return ("certificate has expired"); + return "certificate has expired"; case X509_V_ERR_CRL_NOT_YET_VALID: - return ("CRL is not yet valid"); + return "CRL is not yet valid"; case X509_V_ERR_CRL_HAS_EXPIRED: - return ("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"); + 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"); + 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"); + 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"); + return "format error in CRL's nextUpdate field"; case X509_V_ERR_OUT_OF_MEM: - return ("out of memory"); + return "out of memory"; case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: - return ("self signed certificate"); + return "self signed certificate"; case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: - return ("self signed certificate in certificate 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"); + return "unable to get local issuer certificate"; case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: - return ("unable to verify the first certificate"); + return "unable to verify the first certificate"; case X509_V_ERR_CERT_CHAIN_TOO_LONG: - return ("certificate chain too long"); + return "certificate chain too long"; case X509_V_ERR_CERT_REVOKED: - return ("certificate revoked"); + return "certificate revoked"; case X509_V_ERR_INVALID_CA: - return ("invalid CA certificate"); + return "invalid CA certificate"; case X509_V_ERR_PATH_LENGTH_EXCEEDED: - return ("path length constraint exceeded"); + return "path length constraint exceeded"; case X509_V_ERR_INVALID_PURPOSE: - return ("unsupported certificate purpose"); + return "unsupported certificate purpose"; case X509_V_ERR_CERT_UNTRUSTED: - return ("certificate not trusted"); + return "certificate not trusted"; case X509_V_ERR_CERT_REJECTED: - return ("certificate rejected"); + return "certificate rejected"; case X509_V_ERR_SUBJECT_ISSUER_MISMATCH: - return ("subject issuer mismatch"); + return "subject issuer mismatch"; case X509_V_ERR_AKID_SKID_MISMATCH: - return ("authority and subject key identifier mismatch"); + return "authority and subject key identifier mismatch"; case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: - return ("authority and issuer serial number mismatch"); + return "authority and issuer serial number mismatch"; case X509_V_ERR_KEYUSAGE_NO_CERTSIGN: - return ("key usage does not include certificate signing"); + return "key usage does not include certificate signing"; case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: - return ("unable to get CRL issuer certificate"); + return "unable to get CRL issuer certificate"; case X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: - return ("unhandled critical extension"); + return "unhandled critical extension"; case X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: - return ("key usage does not include CRL signing"); + return "key usage does not include CRL signing"; case X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: - return ("unhandled critical CRL extension"); + return "unhandled critical CRL extension"; case X509_V_ERR_INVALID_NON_CA: - return ("invalid non-CA certificate (has CA markings)"); + return "invalid non-CA certificate (has CA markings)"; case X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED: - return ("proxy path length constraint exceeded"); + return "proxy path length constraint exceeded"; case X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: - return ("key usage does not include digital signature"); + return "key usage does not include digital signature"; case X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED: return - ("proxy certificates not allowed, please set the appropriate flag"); + "proxy certificates not allowed, please set the appropriate flag"; case X509_V_ERR_INVALID_EXTENSION: - return ("invalid or inconsistent certificate extension"); + return "invalid or inconsistent certificate extension"; case X509_V_ERR_INVALID_POLICY_EXTENSION: - return ("invalid or inconsistent certificate policy extension"); + return "invalid or inconsistent certificate policy extension"; case X509_V_ERR_NO_EXPLICIT_POLICY: - return ("no explicit policy"); + return "no explicit policy"; case X509_V_ERR_DIFFERENT_CRL_SCOPE: - return ("Different CRL scope"); + return "Different CRL scope"; case X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE: - return ("Unsupported extension feature"); + return "Unsupported extension feature"; case X509_V_ERR_UNNESTED_RESOURCE: - return ("RFC 3779 resource not subset of parent's resources"); + return "RFC 3779 resource not subset of parent's resources"; case X509_V_ERR_PERMITTED_VIOLATION: - return ("permitted subtree violation"); + return "permitted subtree violation"; case X509_V_ERR_EXCLUDED_VIOLATION: - return ("excluded subtree violation"); + return "excluded subtree violation"; case X509_V_ERR_SUBTREE_MINMAX: - return ("name constraints minimum and maximum not supported"); + return "name constraints minimum and maximum not supported"; case X509_V_ERR_APPLICATION_VERIFICATION: - return ("application verification failure"); + return "application verification failure"; case X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: - return ("unsupported name constraint type"); + return "unsupported name constraint type"; case X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: - return ("unsupported or invalid name constraint syntax"); + return "unsupported or invalid name constraint syntax"; case X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: - return ("unsupported or invalid name syntax"); + return "unsupported or invalid name syntax"; case X509_V_ERR_CRL_PATH_VALIDATION_ERROR: - return ("CRL path validation error"); + return "CRL path validation error"; case X509_V_ERR_PATH_LOOP: - return ("Path Loop"); + return "Path Loop"; case X509_V_ERR_SUITE_B_INVALID_VERSION: - return ("Suite B: certificate version invalid"); + return "Suite B: certificate version invalid"; case X509_V_ERR_SUITE_B_INVALID_ALGORITHM: - return ("Suite B: invalid public key algorithm"); + return "Suite B: invalid public key algorithm"; case X509_V_ERR_SUITE_B_INVALID_CURVE: - return ("Suite B: invalid ECC curve"); + return "Suite B: invalid ECC curve"; case X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM: - return ("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"); + 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"); + return "Suite B: cannot sign P-384 with P-256"; case X509_V_ERR_HOSTNAME_MISMATCH: - return ("Hostname mismatch"); + return "Hostname mismatch"; case X509_V_ERR_EMAIL_MISMATCH: - return ("Email address mismatch"); + return "Email address mismatch"; case X509_V_ERR_IP_ADDRESS_MISMATCH: - return ("IP address mismatch"); + return "IP address mismatch"; case X509_V_ERR_DANE_NO_MATCH: - return ("No matching DANE TLSA records"); + return "No matching DANE TLSA records"; case X509_V_ERR_EE_KEY_TOO_SMALL: - return ("EE certificate key too weak"); + return "EE certificate key too weak"; case X509_V_ERR_CA_KEY_TOO_SMALL: - return ("CA certificate key too weak"); + return "CA certificate key too weak"; case X509_V_ERR_CA_MD_TOO_WEAK: - return ("CA signature digest algorithm too weak"); + return "CA signature digest algorithm too weak"; case X509_V_ERR_INVALID_CALL: - return ("Invalid certificate verification context"); + return "Invalid certificate verification context"; case X509_V_ERR_STORE_LOOKUP: - return ("Issuer certificate lookup error"); + return "Issuer certificate lookup error"; case X509_V_ERR_NO_VALID_SCTS: - return ("Certificate Transparency required, but no valid SCTs found"); + return "Certificate Transparency required, but no valid SCTs found"; case X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION: - return ("proxy subject name violation"); + return "proxy subject name violation"; + case X509_V_ERR_OCSP_VERIFY_NEEDED: + return "OCSP verification needed"; + case X509_V_ERR_OCSP_VERIFY_FAILED: + return "OCSP verification failed"; + case X509_V_ERR_OCSP_CERT_UNKNOWN: + return "OCSP unknown cert"; default: /* Printing an error number into a static buffer is not thread-safe */ - return ("unknown certificate verification error"); + return "unknown certificate verification error"; } } diff --git a/crypto/x509/x509_v3.c b/crypto/x509/x509_v3.c index 19016bb1..75ae767d 100644 --- a/crypto/x509/x509_v3.c +++ b/crypto/x509/x509_v3.c @@ -9,7 +9,7 @@ #include #include "internal/cryptlib.h" -#include +#include #include #include #include @@ -20,8 +20,8 @@ int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x) { if (x == NULL) - return (0); - return (sk_X509_EXTENSION_num(x)); + return 0; + return sk_X509_EXTENSION_num(x); } int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x, int nid, @@ -31,8 +31,8 @@ int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x, int nid, obj = OBJ_nid2obj(nid); if (obj == NULL) - return (-2); - return (X509v3_get_ext_by_OBJ(x, obj, lastpos)); + return -2; + return X509v3_get_ext_by_OBJ(x, obj, lastpos); } int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *sk, @@ -42,7 +42,7 @@ int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *sk, X509_EXTENSION *ex; if (sk == NULL) - return (-1); + return -1; lastpos++; if (lastpos < 0) lastpos = 0; @@ -50,9 +50,9 @@ int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *sk, for (; lastpos < n; lastpos++) { ex = sk_X509_EXTENSION_value(sk, lastpos); if (OBJ_cmp(ex->object, obj) == 0) - return (lastpos); + return lastpos; } - return (-1); + return -1; } int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *sk, int crit, @@ -62,7 +62,7 @@ int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *sk, int crit, X509_EXTENSION *ex; if (sk == NULL) - return (-1); + return -1; lastpos++; if (lastpos < 0) lastpos = 0; @@ -70,9 +70,9 @@ int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *sk, int crit, for (; lastpos < n; lastpos++) { ex = sk_X509_EXTENSION_value(sk, lastpos); if (((ex->critical > 0) && crit) || ((ex->critical <= 0) && !crit)) - return (lastpos); + return lastpos; } - return (-1); + return -1; } X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc) @@ -88,9 +88,9 @@ 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); + return NULL; ret = sk_X509_EXTENSION_delete(x, loc); - return (ret); + return ret; } STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x, @@ -123,14 +123,14 @@ STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x, goto err; if (*x == NULL) *x = sk; - return (sk); + return sk; err: X509err(X509_F_X509V3_ADD_EXT, ERR_R_MALLOC_FAILURE); err2: X509_EXTENSION_free(new_ex); if (x != NULL && *x == NULL) sk_X509_EXTENSION_free(sk); - return (NULL); + return NULL; } X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex, int nid, @@ -143,12 +143,12 @@ X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex, int nid, obj = OBJ_nid2obj(nid); if (obj == NULL) { X509err(X509_F_X509_EXTENSION_CREATE_BY_NID, X509_R_UNKNOWN_NID); - return (NULL); + return NULL; } ret = X509_EXTENSION_create_by_OBJ(ex, obj, crit, data); if (ret == NULL) ASN1_OBJECT_free(obj); - return (ret); + return ret; } X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex, @@ -161,7 +161,7 @@ X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex, if ((ret = X509_EXTENSION_new()) == NULL) { X509err(X509_F_X509_EXTENSION_CREATE_BY_OBJ, ERR_R_MALLOC_FAILURE); - return (NULL); + return NULL; } } else ret = *ex; @@ -175,17 +175,17 @@ X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex, if ((ex != NULL) && (*ex == NULL)) *ex = ret; - return (ret); + return ret; err: if ((ex == NULL) || (ret != *ex)) X509_EXTENSION_free(ret); - return (NULL); + return NULL; } int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj) { if ((ex == NULL) || (obj == NULL)) - return (0); + return 0; ASN1_OBJECT_free(ex->object); ex->object = OBJ_dup(obj); return ex->object != NULL; @@ -194,9 +194,9 @@ int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj) int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit) { if (ex == NULL) - return (0); + return 0; ex->critical = (crit) ? 0xFF : -1; - return (1); + return 1; } int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data) @@ -204,31 +204,31 @@ int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data) int i; if (ex == NULL) - return (0); + return 0; i = ASN1_OCTET_STRING_set(&ex->value, data->data, data->length); if (!i) - return (0); - return (1); + return 0; + return 1; } ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex) { if (ex == NULL) - return (NULL); - return (ex->object); + return NULL; + return ex->object; } ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ex) { if (ex == NULL) - return (NULL); + return NULL; return &ex->value; } int X509_EXTENSION_get_critical(const X509_EXTENSION *ex) { if (ex == NULL) - return (0); + return 0; if (ex->critical > 0) return 1; return 0; diff --git a/crypto/x509/x509_vfy.c b/crypto/x509/x509_vfy.c index 3018c69a..9ebda1bb 100644 --- a/crypto/x509/x509_vfy.c +++ b/crypto/x509/x509_vfy.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -12,17 +12,17 @@ #include #include +#include "internal/ctype.h" #include "internal/cryptlib.h" #include -#include #include #include #include #include #include #include -#include -#include +#include "internal/dane.h" +#include "internal/x509_int.h" #include "x509_lcl.h" /* CRL score values */ @@ -1756,119 +1756,67 @@ int X509_cmp_current_time(const ASN1_TIME *ctm) int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time) { - char *str; - ASN1_TIME atm; - long offset; - char buff1[24], buff2[24], *p; - int i, j, remaining; + static const size_t utctime_length = sizeof("YYMMDDHHMMSSZ") - 1; + static const size_t generalizedtime_length = sizeof("YYYYMMDDHHMMSSZ") - 1; + ASN1_TIME *asn1_cmp_time = NULL; + int i, day, sec, ret = 0; - p = buff1; - remaining = ctm->length; - str = (char *)ctm->data; /* - * Note that the following (historical) code allows much more slack in the - * time format than RFC5280. In RFC5280, the representation is fixed: + * Note that ASN.1 allows much more slack in the time format than RFC5280. + * In RFC5280, the representation is fixed: * UTCTime: YYMMDDHHMMSSZ * GeneralizedTime: YYYYMMDDHHMMSSZ + * + * We do NOT currently enforce the following RFC 5280 requirement: + * "CAs conforming to this profile MUST always encode certificate + * validity dates through the year 2049 as UTCTime; certificate validity + * dates in 2050 or later MUST be encoded as GeneralizedTime." */ - if (ctm->type == V_ASN1_UTCTIME) { - /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */ - int min_length = sizeof("YYMMDDHHMMZ") - 1; - int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1; - if (remaining < min_length || remaining > max_length) + switch (ctm->type) { + case V_ASN1_UTCTIME: + if (ctm->length != (int)(utctime_length)) return 0; - memcpy(p, str, 10); - p += 10; - str += 10; - remaining -= 10; - } else { - /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */ - int min_length = sizeof("YYYYMMDDHHMMZ") - 1; - int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1; - if (remaining < min_length || remaining > max_length) + break; + case V_ASN1_GENERALIZEDTIME: + if (ctm->length != (int)(generalizedtime_length)) return 0; - memcpy(p, str, 12); - p += 12; - str += 12; - remaining -= 12; - } - - if ((*str == 'Z') || (*str == '-') || (*str == '+')) { - *(p++) = '0'; - *(p++) = '0'; - } else { - /* SS (seconds) */ - if (remaining < 2) - return 0; - *(p++) = *(str++); - *(p++) = *(str++); - remaining -= 2; - /* - * Skip any (up to three) fractional seconds... - * TODO(emilia): in RFC5280, fractional seconds are forbidden. - * Can we just kill them altogether? - */ - if (remaining && *str == '.') { - str++; - remaining--; - for (i = 0; i < 3 && remaining; i++, str++, remaining--) { - if (*str < '0' || *str > '9') - break; - } - } - - } - *(p++) = 'Z'; - *(p++) = '\0'; - - /* We now need either a terminating 'Z' or an offset. */ - if (!remaining) + break; + default: return 0; - if (*str == 'Z') { - if (remaining != 1) - return 0; - offset = 0; - } else { - /* (+-)HHMM */ - if ((*str != '+') && (*str != '-')) - return 0; - /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */ - if (remaining != 5) - return 0; - if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' || - str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9') - return 0; - offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60; - offset += (str[3] - '0') * 10 + (str[4] - '0'); - if (*str == '-') - offset = -offset; } - atm.type = ctm->type; - atm.flags = 0; - atm.length = sizeof(buff2); - atm.data = (unsigned char *)buff2; - if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL) + /** + * Verify the format: the ASN.1 functions we use below allow a more + * flexible format than what's mandated by RFC 5280. + * Digit and date ranges will be verified in the conversion methods. + */ + for (i = 0; i < ctm->length - 1; i++) { + if (!ossl_isdigit(ctm->data[i])) + return 0; + } + if (ctm->data[ctm->length - 1] != 'Z') return 0; - if (ctm->type == V_ASN1_UTCTIME) { - i = (buff1[0] - '0') * 10 + (buff1[1] - '0'); - if (i < 50) - i += 100; /* cf. RFC 2459 */ - j = (buff2[0] - '0') * 10 + (buff2[1] - '0'); - if (j < 50) - j += 100; + /* + * There is ASN1_UTCTIME_cmp_time_t but no + * ASN1_GENERALIZEDTIME_cmp_time_t or ASN1_TIME_cmp_time_t, + * so we go through ASN.1 + */ + asn1_cmp_time = X509_time_adj(NULL, 0, cmp_time); + if (asn1_cmp_time == NULL) + goto err; + if (!ASN1_TIME_diff(&day, &sec, ctm, asn1_cmp_time)) + goto err; - if (i < j) - return -1; - if (i > j) - return 1; - } - i = strcmp(buff1, buff2); - if (i == 0) /* wait a second then return younger :-) */ - return -1; - else - return i; + /* + * X509_cmp_time comparison is <=. + * The return value 0 is reserved for errors. + */ + ret = (day >= 0 && sec >= 0) ? -1 : 1; + + err: + ASN1_TIME_free(asn1_cmp_time); + return ret; } ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj) @@ -2896,7 +2844,11 @@ static int build_chain(X509_STORE_CTX *ctx) int i; /* Our chain starts with a single untrusted element. */ - OPENSSL_assert(num == 1 && ctx->num_untrusted == num); + if (!ossl_assert(num == 1 && ctx->num_untrusted == num)) { + X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR); + ctx->error = X509_V_ERR_UNSPECIFIED; + return 0; + } #define S_DOUNTRUSTED (1 << 0) /* Search untrusted chain */ #define S_DOTRUSTED (1 << 1) /* Search trusted store */ @@ -3033,7 +2985,14 @@ static int build_chain(X509_STORE_CTX *ctx) * certificate among the ones from the trust store. */ if ((search & S_DOALTERNATE) != 0) { - OPENSSL_assert(num > i && i > 0 && ss == 0); + if (!ossl_assert(num > i && i > 0 && ss == 0)) { + X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR); + X509_free(xtmp); + trust = X509_TRUST_REJECTED; + ctx->error = X509_V_ERR_UNSPECIFIED; + search = 0; + continue; + } search &= ~S_DOALTERNATE; for (; num > i; --num) X509_free(sk_X509_pop(ctx->chain)); @@ -3096,7 +3055,13 @@ static int build_chain(X509_STORE_CTX *ctx) * certificate with ctx->num_untrusted <= num. */ if (ok) { - OPENSSL_assert(ctx->num_untrusted <= num); + if (!ossl_assert(ctx->num_untrusted <= num)) { + X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR); + trust = X509_TRUST_REJECTED; + ctx->error = X509_V_ERR_UNSPECIFIED; + search = 0; + continue; + } search &= ~S_DOUNTRUSTED; switch (trust = check_trust(ctx, num)) { case X509_TRUST_TRUSTED: @@ -3135,7 +3100,13 @@ static int build_chain(X509_STORE_CTX *ctx) */ if ((search & S_DOUNTRUSTED) != 0) { num = sk_X509_num(ctx->chain); - OPENSSL_assert(num == ctx->num_untrusted); + if (!ossl_assert(num == ctx->num_untrusted)) { + X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR); + trust = X509_TRUST_REJECTED; + ctx->error = X509_V_ERR_UNSPECIFIED; + search = 0; + continue; + } x = sk_X509_value(ctx->chain, num-1); /* @@ -3254,8 +3225,6 @@ static int check_key_level(X509_STORE_CTX *ctx, X509 *cert) */ static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert) { - int nid = X509_get_signature_nid(cert); - int mdnid = NID_undef; int secbits = -1; int level = ctx->param->auth_level; @@ -3264,14 +3233,8 @@ static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert) if (level > NUM_AUTH_LEVELS) level = NUM_AUTH_LEVELS; - /* Lookup signature algorithm digest */ - if (nid && OBJ_find_sigid_algs(nid, &mdnid, NULL)) { - const EVP_MD *md; - - /* Assume 4 bits of collision resistance for each hash octet */ - if (mdnid != NID_undef && (md = EVP_get_digestbynid(mdnid)) != NULL) - secbits = EVP_MD_size(md) * 4; - } + if (!X509_get_signature_info(cert, NULL, NULL, &secbits, NULL)) + return 0; return secbits >= minbits_table[level - 1]; } diff --git a/crypto/x509/x509_vpm.c b/crypto/x509/x509_vpm.c index b5067220..033ec423 100644 --- a/crypto/x509/x509_vpm.c +++ b/crypto/x509/x509_vpm.c @@ -1,5 +1,5 @@ /* - * Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2004-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 @@ -11,7 +11,6 @@ #include "internal/cryptlib.h" #include -#include #include #include #include @@ -79,33 +78,6 @@ static int int_x509_param_set_hosts(X509_VERIFY_PARAM *vpm, int mode, return 1; } -static void x509_verify_param_zero(X509_VERIFY_PARAM *param) -{ - if (!param) - return; - param->name = NULL; - param->purpose = 0; - param->trust = X509_TRUST_DEFAULT; - /* - * param->inh_flags = X509_VP_FLAG_DEFAULT; - */ - param->inh_flags = 0; - param->flags = 0; - param->depth = -1; - param->auth_level = -1; /* -1 means unset, 0 is explicit */ - sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free); - param->policies = NULL; - sk_OPENSSL_STRING_pop_free(param->hosts, str_free); - param->hosts = NULL; - OPENSSL_free(param->peername); - param->peername = NULL; - OPENSSL_free(param->email); - param->email = NULL; - param->emaillen = 0; - OPENSSL_free(param->ip); - param->ip = NULL; - param->iplen = 0; -} X509_VERIFY_PARAM *X509_VERIFY_PARAM_new(void) { @@ -114,15 +86,25 @@ X509_VERIFY_PARAM *X509_VERIFY_PARAM_new(void) param = OPENSSL_zalloc(sizeof(*param)); if (param == NULL) return NULL; - x509_verify_param_zero(param); + param->trust = X509_TRUST_DEFAULT; + /* + * param->inh_flags = X509_VP_FLAG_DEFAULT; + */ + param->inh_flags = 0; + param->depth = -1; + param->auth_level = -1; /* -1 means unset, 0 is explicit */ return param; } void X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param) { - if (!param) + if (param == NULL) return; - x509_verify_param_zero(param); + sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free); + sk_OPENSSL_STRING_pop_free(param->hosts, str_free); + OPENSSL_free(param->peername); + OPENSSL_free(param->email); + OPENSSL_free(param->ip); OPENSSL_free(param); } diff --git a/crypto/x509/x509cset.c b/crypto/x509/x509cset.c index 20578596..7645ce37 100644 --- a/crypto/x509/x509cset.c +++ b/crypto/x509/x509cset.c @@ -1,5 +1,5 @@ /* - * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2001-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 @@ -9,6 +9,7 @@ #include #include "internal/cryptlib.h" +#include "internal/refcount.h" #include #include #include @@ -18,19 +19,19 @@ int X509_CRL_set_version(X509_CRL *x, long version) { if (x == NULL) - return (0); + return 0; if (x->crl.version == NULL) { if ((x->crl.version = ASN1_INTEGER_new()) == NULL) - return (0); + return 0; } - return (ASN1_INTEGER_set(x->crl.version, version)); + return ASN1_INTEGER_set(x->crl.version, version); } int X509_CRL_set_issuer_name(X509_CRL *x, X509_NAME *name) { if (x == NULL) - return (0); - return (X509_NAME_set(&x->crl.issuer, name)); + return 0; + return X509_NAME_set(&x->crl.issuer, name); } int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm) @@ -67,7 +68,7 @@ int X509_CRL_up_ref(X509_CRL *crl) { int i; - if (CRYPTO_atomic_add(&crl->references, 1, &i, crl->lock) <= 0) + if (CRYPTO_UP_REF(&crl->references, &i, crl->lock) <= 0) return 0; REF_PRINT_COUNT("X509_CRL", crl); @@ -141,7 +142,7 @@ int X509_REVOKED_set_revocationDate(X509_REVOKED *x, ASN1_TIME *tm) ASN1_TIME *in; if (x == NULL) - return (0); + return 0; in = x->revocationDate; if (in != tm) { in = ASN1_STRING_dup(tm); @@ -163,7 +164,7 @@ int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial) ASN1_INTEGER *in; if (x == NULL) - return (0); + return 0; in = &x->serialNumber; if (in != serial) return ASN1_STRING_copy(in, serial); diff --git a/crypto/x509/x509name.c b/crypto/x509/x509name.c index f87dc7db..bde5db40 100644 --- a/crypto/x509/x509name.c +++ b/crypto/x509/x509name.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,7 +9,7 @@ #include #include "internal/cryptlib.h" -#include +#include #include #include #include @@ -22,8 +22,8 @@ int X509_NAME_get_text_by_NID(X509_NAME *name, int nid, char *buf, int len) obj = OBJ_nid2obj(nid); if (obj == NULL) - return (-1); - return (X509_NAME_get_text_by_OBJ(name, obj, buf, len)); + return -1; + return X509_NAME_get_text_by_OBJ(name, obj, buf, len); } int X509_NAME_get_text_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, char *buf, @@ -34,21 +34,21 @@ int X509_NAME_get_text_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, char *buf i = X509_NAME_get_index_by_OBJ(name, obj, -1); if (i < 0) - return (-1); + return -1; data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i)); i = (data->length > (len - 1)) ? (len - 1) : data->length; if (buf == NULL) - return (data->length); + return data->length; memcpy(buf, data->data, i); buf[i] = '\0'; - return (i); + return i; } int X509_NAME_entry_count(const X509_NAME *name) { if (name == NULL) - return (0); - return (sk_X509_NAME_ENTRY_num(name->entries)); + return 0; + return sk_X509_NAME_ENTRY_num(name->entries); } int X509_NAME_get_index_by_NID(X509_NAME *name, int nid, int lastpos) @@ -57,8 +57,8 @@ int X509_NAME_get_index_by_NID(X509_NAME *name, int nid, int lastpos) obj = OBJ_nid2obj(nid); if (obj == NULL) - return (-2); - return (X509_NAME_get_index_by_OBJ(name, obj, lastpos)); + return -2; + return X509_NAME_get_index_by_OBJ(name, obj, lastpos); } /* NOTE: you should be passing -1, not 0 as lastpos */ @@ -69,7 +69,7 @@ int X509_NAME_get_index_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int last STACK_OF(X509_NAME_ENTRY) *sk; if (name == NULL) - return (-1); + return -1; if (lastpos < 0) lastpos = -1; sk = name->entries; @@ -77,18 +77,18 @@ int X509_NAME_get_index_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int last for (lastpos++; lastpos < n; lastpos++) { ne = sk_X509_NAME_ENTRY_value(sk, lastpos); if (OBJ_cmp(ne->object, obj) == 0) - return (lastpos); + return lastpos; } - return (-1); + return -1; } X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc) { if (name == NULL || sk_X509_NAME_ENTRY_num(name->entries) <= loc || loc < 0) - return (NULL); - else - return (sk_X509_NAME_ENTRY_value(name->entries, loc)); + return NULL; + + return sk_X509_NAME_ENTRY_value(name->entries, loc); } X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc) @@ -99,13 +99,14 @@ X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc) if (name == NULL || sk_X509_NAME_ENTRY_num(name->entries) <= loc || loc < 0) - return (NULL); + return NULL; + sk = name->entries; ret = sk_X509_NAME_ENTRY_delete(sk, loc); n = sk_X509_NAME_ENTRY_num(sk); name->modified = 1; if (loc == n) - return (ret); + return ret; /* else we need to fixup the set field */ if (loc != 0) @@ -127,7 +128,7 @@ X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc) if (set_prev + 1 < set_next) for (i = loc; i < n; i++) sk_X509_NAME_ENTRY_value(sk, i)->set--; - return (ret); + return ret; } int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type, @@ -136,6 +137,7 @@ int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type { X509_NAME_ENTRY *ne; int ret; + ne = X509_NAME_ENTRY_create_by_OBJ(NULL, obj, type, bytes, len); if (!ne) return 0; @@ -184,7 +186,7 @@ int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne, int loc, STACK_OF(X509_NAME_ENTRY) *sk; if (name == NULL) - return (0); + return 0; sk = name->entries; n = sk_X509_NAME_ENTRY_num(sk); if (loc > n) @@ -230,10 +232,10 @@ int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne, int loc, for (i = loc + 1; i < n; i++) sk_X509_NAME_ENTRY_value(sk, i - 1)->set += 1; } - return (1); + return 1; err: X509_NAME_ENTRY_free(new_name); - return (0); + return 0; } X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne, @@ -249,7 +251,7 @@ X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne, X509err(X509_F_X509_NAME_ENTRY_CREATE_BY_TXT, X509_R_INVALID_FIELD_NAME); ERR_add_error_data(2, "name=", field); - return (NULL); + return NULL; } nentry = X509_NAME_ENTRY_create_by_OBJ(ne, obj, type, bytes, len); ASN1_OBJECT_free(obj); @@ -267,7 +269,7 @@ X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid, obj = OBJ_nid2obj(nid); if (obj == NULL) { X509err(X509_F_X509_NAME_ENTRY_CREATE_BY_NID, X509_R_UNKNOWN_NID); - return (NULL); + return NULL; } nentry = X509_NAME_ENTRY_create_by_OBJ(ne, obj, type, bytes, len); ASN1_OBJECT_free(obj); @@ -283,7 +285,7 @@ X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne, if ((ne == NULL) || (*ne == NULL)) { if ((ret = X509_NAME_ENTRY_new()) == NULL) - return (NULL); + return NULL; } else ret = *ne; @@ -294,11 +296,11 @@ X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne, if ((ne != NULL) && (*ne == NULL)) *ne = ret; - return (ret); + return ret; err: if ((ne == NULL) || (ret != *ne)) X509_NAME_ENTRY_free(ret); - return (NULL); + return NULL; } int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj) @@ -306,7 +308,7 @@ int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj) if ((ne == NULL) || (obj == NULL)) { X509err(X509_F_X509_NAME_ENTRY_SET_OBJECT, ERR_R_PASSED_NULL_PARAMETER); - return (0); + return 0; } ASN1_OBJECT_free(ne->object); ne->object = OBJ_dup(obj); @@ -319,7 +321,7 @@ int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type, int i; if ((ne == NULL) || ((bytes == NULL) && (len != 0))) - return (0); + return 0; if ((type > 0) && (type & MBSTRING_FLAG)) return ASN1_STRING_set_by_NID(&ne->value, bytes, len, type, @@ -328,28 +330,28 @@ int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type, len = strlen((const char *)bytes); i = ASN1_STRING_set(ne->value, bytes, len); if (!i) - return (0); + return 0; if (type != V_ASN1_UNDEF) { if (type == V_ASN1_APP_CHOOSE) ne->value->type = ASN1_PRINTABLE_type(bytes, len); else ne->value->type = type; } - return (1); + return 1; } ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne) { if (ne == NULL) - return (NULL); - return (ne->object); + return NULL; + return ne->object; } ASN1_STRING *X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne) { if (ne == NULL) - return (NULL); - return (ne->value); + return NULL; + return ne->value; } int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne) diff --git a/crypto/x509/x509rset.c b/crypto/x509/x509rset.c index 6dee297a..e8921b82 100644 --- a/crypto/x509/x509rset.c +++ b/crypto/x509/x509rset.c @@ -18,23 +18,23 @@ int X509_REQ_set_version(X509_REQ *x, long version) { if (x == NULL) - return (0); + return 0; x->req_info.enc.modified = 1; - return (ASN1_INTEGER_set(x->req_info.version, version)); + return ASN1_INTEGER_set(x->req_info.version, version); } int X509_REQ_set_subject_name(X509_REQ *x, X509_NAME *name) { if (x == NULL) - return (0); + return 0; x->req_info.enc.modified = 1; - return (X509_NAME_set(&x->req_info.subject, name)); + return X509_NAME_set(&x->req_info.subject, name); } int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey) { if (x == NULL) - return (0); + return 0; x->req_info.enc.modified = 1; - return (X509_PUBKEY_set(&x->req_info.pubkey, pkey)); + return X509_PUBKEY_set(&x->req_info.pubkey, pkey); } diff --git a/crypto/x509/x509spki.c b/crypto/x509/x509spki.c index b142485d..fd8162af 100644 --- a/crypto/x509/x509spki.c +++ b/crypto/x509/x509spki.c @@ -14,15 +14,15 @@ int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey) { if ((x == NULL) || (x->spkac == NULL)) - return (0); - return (X509_PUBKEY_set(&(x->spkac->pubkey), pkey)); + return 0; + return X509_PUBKEY_set(&(x->spkac->pubkey), pkey); } EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x) { if ((x == NULL) || (x->spkac == NULL)) - return (NULL); - return (X509_PUBKEY_get(x->spkac->pubkey)); + return NULL; + return X509_PUBKEY_get(x->spkac->pubkey); } /* Load a Netscape SPKI from a base64 encoded string */ diff --git a/crypto/x509/x509type.c b/crypto/x509/x509type.c index aca83552..37f4d312 100644 --- a/crypto/x509/x509type.c +++ b/crypto/x509/x509type.c @@ -19,7 +19,7 @@ int X509_certificate_type(const X509 *x, const EVP_PKEY *pkey) int ret = 0, i; if (x == NULL) - return (0); + return 0; if (pkey == NULL) pk = X509_get0_pubkey(x); @@ -27,7 +27,7 @@ int X509_certificate_type(const X509 *x, const EVP_PKEY *pkey) pk = pkey; if (pk == NULL) - return (0); + return 0; switch (EVP_PKEY_id(pk)) { case EVP_PKEY_RSA: @@ -41,6 +41,9 @@ int X509_certificate_type(const X509 *x, const EVP_PKEY *pkey) case EVP_PKEY_EC: ret = EVP_PK_EC | EVP_PKT_SIGN | EVP_PKT_EXCH; break; + case EVP_PKEY_ED25519: + ret = EVP_PKT_SIGN; + break; case EVP_PKEY_DH: ret = EVP_PK_DH | EVP_PKT_EXCH; break; @@ -73,5 +76,5 @@ int X509_certificate_type(const X509 *x, const EVP_PKEY *pkey) } } - return (ret); + return ret; } diff --git a/crypto/x509/x_all.c b/crypto/x509/x_all.c index 42bd1611..24e41146 100644 --- a/crypto/x509/x_all.c +++ b/crypto/x509/x_all.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -9,7 +9,6 @@ #include #include "internal/cryptlib.h" -#include #include #include #include diff --git a/crypto/x509/x_attrib.c b/crypto/x509/x_attrib.c index 35f4aeef..9a41e547 100644 --- a/crypto/x509/x_attrib.c +++ b/crypto/x509/x_attrib.c @@ -39,7 +39,7 @@ X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value) ASN1_TYPE *val = NULL; if ((ret = X509_ATTRIBUTE_new()) == NULL) - return (NULL); + return NULL; ret->object = OBJ_nid2obj(nid); if ((val = ASN1_TYPE_new()) == NULL) goto err; @@ -47,9 +47,9 @@ X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value) goto err; ASN1_TYPE_set(val, atrtype, value); - return (ret); + return ret; err: X509_ATTRIBUTE_free(ret); ASN1_TYPE_free(val); - return (NULL); + return NULL; } diff --git a/crypto/x509/x_name.c b/crypto/x509/x_name.c index 0af5df5c..d36a9d37 100644 --- a/crypto/x509/x_name.c +++ b/crypto/x509/x_name.c @@ -1,5 +1,5 @@ /* - * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1995-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 @@ -8,7 +8,7 @@ */ #include -#include +#include "internal/ctype.h" #include "internal/cryptlib.h" #include #include @@ -398,11 +398,12 @@ static int asn1_string_canon(ASN1_STRING *out, const ASN1_STRING *in) /* * Convert string in place to canonical form. Ultimately we may need to * handle a wider range of characters but for now ignore anything with - * MSB set and rely on the isspace() and tolower() functions. + * MSB set and rely on the ossl_isspace() to fail on bad characters without + * needing isascii or range checks as well. */ /* Ignore leading spaces */ - while ((len > 0) && !(*from & 0x80) && isspace(*from)) { + while (len > 0 && ossl_isspace(*from)) { from++; len--; } @@ -410,7 +411,7 @@ static int asn1_string_canon(ASN1_STRING *out, const ASN1_STRING *in) to = from + len; /* Ignore trailing spaces */ - while ((len > 0) && !(to[-1] & 0x80) && isspace(to[-1])) { + while (len > 0 && ossl_isspace(to[-1])) { to--; len--; } @@ -419,13 +420,13 @@ static int asn1_string_canon(ASN1_STRING *out, const ASN1_STRING *in) i = 0; while (i < len) { - /* If MSB set just copy across */ - if (*from & 0x80) { + /* If not ASCII set just copy across */ + if (!ossl_isascii(*from)) { *to++ = *from++; i++; } /* Collapse multiple spaces */ - else if (isspace(*from)) { + else if (ossl_isspace(*from)) { /* Copy one space across */ *to++ = ' '; /* @@ -437,9 +438,9 @@ static int asn1_string_canon(ASN1_STRING *out, const ASN1_STRING *in) from++; i++; } - while (!(*from & 0x80) && isspace(*from)); + while (ossl_isspace(*from)); } else { - *to++ = tolower(*from); + *to++ = ossl_tolower(*from); from++; i++; } @@ -497,19 +498,10 @@ int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase) c = s; for (;;) { -#ifndef CHARSET_EBCDIC if (((*s == '/') && - ((s[1] >= 'A') && (s[1] <= 'Z') && ((s[2] == '=') || - ((s[2] >= 'A') - && (s[2] <= 'Z') - && (s[3] == '=')) + (ossl_isupper(s[1]) && ((s[2] == '=') || + (ossl_isupper(s[2]) && (s[3] == '=')) ))) || (*s == '\0')) -#else - if (((*s == '/') && - (isupper(s[1]) && ((s[2] == '=') || - (isupper(s[2]) && (s[3] == '=')) - ))) || (*s == '\0')) -#endif { i = s - c; if (BIO_write(bp, c, i) != i) diff --git a/crypto/x509/x_pubkey.c b/crypto/x509/x_pubkey.c index cc692834..73977cd8 100644 --- a/crypto/x509/x_pubkey.c +++ b/crypto/x509/x_pubkey.c @@ -61,7 +61,7 @@ int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey) X509_PUBKEY *pk = NULL; if (x == NULL) - return (0); + return 0; if ((pk = X509_PUBKEY_new()) == NULL) goto error; @@ -206,7 +206,7 @@ int i2d_PUBKEY(EVP_PKEY *a, unsigned char **pp) if (!a) return 0; if (!X509_PUBKEY_set(&xpk, a)) - return 0; + return -1; ret = i2d_X509_PUBKEY(xpk, pp); X509_PUBKEY_free(xpk); return ret; @@ -246,7 +246,7 @@ int i2d_RSA_PUBKEY(RSA *a, unsigned char **pp) pktmp = EVP_PKEY_new(); if (pktmp == NULL) { ASN1err(ASN1_F_I2D_RSA_PUBKEY, ERR_R_MALLOC_FAILURE); - return 0; + return -1; } EVP_PKEY_set1_RSA(pktmp, a); ret = i2d_PUBKEY(pktmp, pp); @@ -286,7 +286,7 @@ int i2d_DSA_PUBKEY(DSA *a, unsigned char **pp) pktmp = EVP_PKEY_new(); if (pktmp == NULL) { ASN1err(ASN1_F_I2D_DSA_PUBKEY, ERR_R_MALLOC_FAILURE); - return 0; + return -1; } EVP_PKEY_set1_DSA(pktmp, a); ret = i2d_PUBKEY(pktmp, pp); @@ -304,17 +304,17 @@ EC_KEY *d2i_EC_PUBKEY(EC_KEY **a, const unsigned char **pp, long length) q = *pp; pkey = d2i_PUBKEY(NULL, &q, length); if (!pkey) - return (NULL); + return NULL; key = EVP_PKEY_get1_EC_KEY(pkey); EVP_PKEY_free(pkey); if (!key) - return (NULL); + return NULL; *pp = q; if (a) { EC_KEY_free(*a); *a = key; } - return (key); + return key; } int i2d_EC_PUBKEY(EC_KEY *a, unsigned char **pp) @@ -322,15 +322,15 @@ int i2d_EC_PUBKEY(EC_KEY *a, unsigned char **pp) EVP_PKEY *pktmp; int ret; if (!a) - return (0); + return 0; if ((pktmp = EVP_PKEY_new()) == NULL) { ASN1err(ASN1_F_I2D_EC_PUBKEY, ERR_R_MALLOC_FAILURE); - return (0); + return -1; } EVP_PKEY_set1_EC_KEY(pktmp, a); ret = i2d_PUBKEY(pktmp, pp); EVP_PKEY_free(pktmp); - return (ret); + return ret; } #endif diff --git a/crypto/x509/x_x509.c b/crypto/x509/x_x509.c index 6783fd87..c28fdda7 100644 --- a/crypto/x509/x_x509.c +++ b/crypto/x509/x_x509.c @@ -89,12 +89,12 @@ IMPLEMENT_ASN1_DUP_FUNCTION(X509) int X509_set_ex_data(X509 *r, int idx, void *arg) { - return (CRYPTO_set_ex_data(&r->ex_data, idx, arg)); + return CRYPTO_set_ex_data(&r->ex_data, idx, arg); } void *X509_get_ex_data(X509 *r, int idx) { - return (CRYPTO_get_ex_data(&r->ex_data, idx)); + return CRYPTO_get_ex_data(&r->ex_data, idx); } /* @@ -145,8 +145,6 @@ static int i2d_x509_aux_internal(X509 *a, unsigned char **pp) int length, tmplen; unsigned char *start = pp != NULL ? *pp : NULL; - OPENSSL_assert(pp == NULL || *pp != NULL); - /* * This might perturb *pp on error, but fixing that belongs in i2d_X509() * not here. It should be that if a == NULL length is zero, but we check diff --git a/crypto/x509v3/build.info b/crypto/x509v3/build.info index 452a8b03..4ab64884 100644 --- a/crypto/x509v3/build.info +++ b/crypto/x509v3/build.info @@ -5,4 +5,4 @@ SOURCE[../../libcrypto]=\ v3_int.c v3_enum.c v3_sxnet.c v3_cpols.c v3_crld.c v3_purp.c v3_info.c \ v3_akeya.c v3_pmaps.c v3_pcons.c v3_ncons.c v3_pcia.c v3_pci.c \ pcy_cache.c pcy_node.c pcy_data.c pcy_map.c pcy_tree.c pcy_lib.c \ - v3_asid.c v3_addr.c v3_tlsf.c + v3_asid.c v3_addr.c v3_tlsf.c v3_admis.c diff --git a/crypto/x509v3/ext_dat.h b/crypto/x509v3/ext_dat.h index c9ede960..762e264b 100644 --- a/crypto/x509v3/ext_dat.h +++ b/crypto/x509v3/ext_dat.h @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-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 @@ -22,3 +22,4 @@ extern const X509V3_EXT_METHOD v3_name_constraints, v3_inhibit_anyp, v3_idp; extern const X509V3_EXT_METHOD v3_addr, v3_asid; extern const X509V3_EXT_METHOD v3_ct_scts[3]; extern const X509V3_EXT_METHOD v3_tls_feature; +extern const X509V3_EXT_METHOD v3_ext_admission; diff --git a/crypto/x509v3/pcy_data.c b/crypto/x509v3/pcy_data.c index cf1d635e..757b101d 100644 --- a/crypto/x509v3/pcy_data.c +++ b/crypto/x509v3/pcy_data.c @@ -17,7 +17,7 @@ void policy_data_free(X509_POLICY_DATA *data) { - if (!data) + if (data == NULL) return; ASN1_OBJECT_free(data->valid_policy); /* Don't free qualifiers if shared */ @@ -40,11 +40,11 @@ X509_POLICY_DATA *policy_data_new(POLICYINFO *policy, { X509_POLICY_DATA *ret; ASN1_OBJECT *id; - if (!policy && !cid) + if (policy == NULL && cid == NULL) return NULL; if (cid) { id = OBJ_dup(cid); - if (!id) + if (id == NULL) return NULL; } else id = NULL; diff --git a/crypto/x509v3/standard_exts.h b/crypto/x509v3/standard_exts.h new file mode 100644 index 00000000..944f4de0 --- /dev/null +++ b/crypto/x509v3/standard_exts.h @@ -0,0 +1,78 @@ +/* + * Copyright 1999-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 + */ + +/* + * This table will be searched using OBJ_bsearch so it *must* kept in order + * of the ext_nid values. + */ + +static const X509V3_EXT_METHOD *standard_exts[] = { + &v3_nscert, + &v3_ns_ia5_list[0], + &v3_ns_ia5_list[1], + &v3_ns_ia5_list[2], + &v3_ns_ia5_list[3], + &v3_ns_ia5_list[4], + &v3_ns_ia5_list[5], + &v3_ns_ia5_list[6], + &v3_skey_id, + &v3_key_usage, + &v3_pkey_usage_period, + &v3_alt[0], + &v3_alt[1], + &v3_bcons, + &v3_crl_num, + &v3_cpols, + &v3_akey_id, + &v3_crld, + &v3_ext_ku, + &v3_delta_crl, + &v3_crl_reason, +#ifndef OPENSSL_NO_OCSP + &v3_crl_invdate, +#endif + &v3_sxnet, + &v3_info, +#ifndef OPENSSL_NO_RFC3779 + &v3_addr, + &v3_asid, +#endif +#ifndef OPENSSL_NO_OCSP + &v3_ocsp_nonce, + &v3_ocsp_crlid, + &v3_ocsp_accresp, + &v3_ocsp_nocheck, + &v3_ocsp_acutoff, + &v3_ocsp_serviceloc, +#endif + &v3_sinfo, + &v3_policy_constraints, +#ifndef OPENSSL_NO_OCSP + &v3_crl_hold, +#endif + &v3_pci, + &v3_name_constraints, + &v3_policy_mappings, + &v3_inhibit_anyp, + &v3_idp, + &v3_alt[2], + &v3_freshest_crl, +#ifndef OPENSSL_NO_CT + &v3_ct_scts[0], + &v3_ct_scts[1], + &v3_ct_scts[2], +#endif + &v3_tls_feature, + &v3_ext_admission +}; + +/* Number of standard extensions */ + +#define STANDARD_EXTENSION_COUNT OSSL_NELEM(standard_exts) + diff --git a/crypto/x509v3/tabtest.c b/crypto/x509v3/tabtest.c deleted file mode 100644 index a33a63a7..00000000 --- a/crypto/x509v3/tabtest.c +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 1999-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 - */ - -/* - * Simple program to check the ext_dat.h is correct and print out problems if - * it is not. - */ - -#include - -#include - -#include "ext_dat.h" - -main() -{ - int i, prev = -1, bad = 0; - X509V3_EXT_METHOD **tmp; - i = OSSL_NELEM(standard_exts); - if (i != STANDARD_EXTENSION_COUNT) - fprintf(stderr, "Extension number invalid expecting %d\n", i); - tmp = standard_exts; - for (i = 0; i < STANDARD_EXTENSION_COUNT; i++, tmp++) { - if ((*tmp)->ext_nid < prev) - bad = 1; - prev = (*tmp)->ext_nid; - - } - if (bad) { - tmp = standard_exts; - fprintf(stderr, "Extensions out of order!\n"); - for (i = 0; i < STANDARD_EXTENSION_COUNT; i++, tmp++) - printf("%d : %s\n", (*tmp)->ext_nid, OBJ_nid2sn((*tmp)->ext_nid)); - } else - fprintf(stderr, "Order OK\n"); -} diff --git a/crypto/x509v3/v3_addr.c b/crypto/x509v3/v3_addr.c index c5183a17..bb58e048 100644 --- a/crypto/x509v3/v3_addr.c +++ b/crypto/x509v3/v3_addr.c @@ -342,7 +342,8 @@ static int range_should_be_prefix(const unsigned char *min, unsigned char mask; int i, j; - OPENSSL_assert(memcmp(min, max, length) <= 0); + if (memcmp(min, max, length) <= 0) + return -1; for (i = 0; i < length && min[i] == max[i]; i++) ; for (j = length - 1; j >= 0 && min[j] == 0x00 && max[j] == 0xFF; j--) ; if (i < j) @@ -431,7 +432,6 @@ static int make_addressRange(IPAddressOrRange **result, if ((aor = IPAddressOrRange_new()) == NULL) return 0; aor->type = IPAddressOrRange_addressRange; - OPENSSL_assert(aor->u.addressRange == NULL); if ((aor->u.addressRange = IPAddressRange_new()) == NULL) goto err; if (aor->u.addressRange->min == NULL && @@ -498,7 +498,6 @@ static IPAddressFamily *make_IPAddressFamily(IPAddrBlocks *addr, for (i = 0; i < sk_IPAddressFamily_num(addr); i++) { f = sk_IPAddressFamily_value(addr, i); - OPENSSL_assert(f->addressFamily->data != NULL); if (f->addressFamily->length == keylen && !memcmp(f->addressFamily->data, key, keylen)) return f; @@ -877,7 +876,8 @@ int X509v3_addr_canonize(IPAddrBlocks *addr) } (void)sk_IPAddressFamily_set_cmp_func(addr, IPAddressFamily_cmp); sk_IPAddressFamily_sort(addr); - OPENSSL_assert(X509v3_addr_is_canonical(addr)); + if (!ossl_assert(X509v3_addr_is_canonical(addr))) + return 0; return 1; } @@ -1182,9 +1182,13 @@ static int addr_validate_path_internal(X509_STORE_CTX *ctx, int i, j, ret = 1; X509 *x; - OPENSSL_assert(chain != NULL && sk_X509_num(chain) > 0); - OPENSSL_assert(ctx != NULL || ext != NULL); - OPENSSL_assert(ctx == NULL || ctx->verify_cb != NULL); + if (!ossl_assert(chain != NULL && sk_X509_num(chain) > 0) + || !ossl_assert(ctx != NULL || ext != NULL) + || !ossl_assert(ctx == NULL || ctx->verify_cb != NULL)) { + if (ctx != NULL) + ctx->error = X509_V_ERR_UNSPECIFIED; + return 0; + } /* * Figure out where to start. If we don't have an extension to @@ -1197,7 +1201,6 @@ static int addr_validate_path_internal(X509_STORE_CTX *ctx, } else { i = 0; x = sk_X509_value(chain, i); - OPENSSL_assert(x != NULL); if ((ext = x->rfc3779_addr) == NULL) goto done; } @@ -1207,7 +1210,8 @@ static int addr_validate_path_internal(X509_STORE_CTX *ctx, if ((child = sk_IPAddressFamily_dup(ext)) == NULL) { X509V3err(X509V3_F_ADDR_VALIDATE_PATH_INTERNAL, ERR_R_MALLOC_FAILURE); - ctx->error = X509_V_ERR_OUT_OF_MEM; + if (ctx != NULL) + ctx->error = X509_V_ERR_OUT_OF_MEM; ret = 0; goto done; } @@ -1218,7 +1222,6 @@ static int addr_validate_path_internal(X509_STORE_CTX *ctx, */ for (i++; i < sk_X509_num(chain); i++) { x = sk_X509_value(chain, i); - OPENSSL_assert(x != NULL); if (!X509v3_addr_is_canonical(x->rfc3779_addr)) validation_err(X509_V_ERR_INVALID_EXTENSION); if (x->rfc3779_addr == NULL) { @@ -1262,7 +1265,6 @@ static int addr_validate_path_internal(X509_STORE_CTX *ctx, /* * Trust anchor can't inherit. */ - OPENSSL_assert(x != NULL); if (x->rfc3779_addr != NULL) { for (j = 0; j < sk_IPAddressFamily_num(x->rfc3779_addr); j++) { IPAddressFamily *fp = @@ -1285,6 +1287,12 @@ static int addr_validate_path_internal(X509_STORE_CTX *ctx, */ int X509v3_addr_validate_path(X509_STORE_CTX *ctx) { + if (ctx->chain == NULL + || sk_X509_num(ctx->chain) == 0 + || ctx->verify_cb == NULL) { + ctx->error = X509_V_ERR_UNSPECIFIED; + return 0; + } return addr_validate_path_internal(ctx, ctx->chain, NULL); } diff --git a/crypto/x509v3/v3_admis.c b/crypto/x509v3/v3_admis.c new file mode 100644 index 00000000..c8e75191 --- /dev/null +++ b/crypto/x509v3/v3_admis.c @@ -0,0 +1,356 @@ +/* + * Copyright 2017-2018 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 +#include "internal/cryptlib.h" +#include +#include +#include +#include + +#include + +#include + +#include "v3_admis.h" +#include "ext_dat.h" + + +ASN1_SEQUENCE(NAMING_AUTHORITY) = { + ASN1_OPT(NAMING_AUTHORITY, namingAuthorityId, ASN1_OBJECT), + ASN1_OPT(NAMING_AUTHORITY, namingAuthorityUrl, ASN1_IA5STRING), + ASN1_OPT(NAMING_AUTHORITY, namingAuthorityText, DIRECTORYSTRING), +} ASN1_SEQUENCE_END(NAMING_AUTHORITY) + +ASN1_SEQUENCE(PROFESSION_INFO) = { + ASN1_EXP_OPT(PROFESSION_INFO, namingAuthority, NAMING_AUTHORITY, 0), + ASN1_SEQUENCE_OF(PROFESSION_INFO, professionItems, DIRECTORYSTRING), + ASN1_SEQUENCE_OF_OPT(PROFESSION_INFO, professionOIDs, ASN1_OBJECT), + ASN1_OPT(PROFESSION_INFO, registrationNumber, ASN1_PRINTABLESTRING), + ASN1_OPT(PROFESSION_INFO, addProfessionInfo, ASN1_OCTET_STRING), +} ASN1_SEQUENCE_END(PROFESSION_INFO) + +ASN1_SEQUENCE(ADMISSIONS) = { + ASN1_EXP_OPT(ADMISSIONS, admissionAuthority, GENERAL_NAME, 0), + ASN1_EXP_OPT(ADMISSIONS, namingAuthority, NAMING_AUTHORITY, 1), + ASN1_SEQUENCE_OF(ADMISSIONS, professionInfos, PROFESSION_INFO), +} ASN1_SEQUENCE_END(ADMISSIONS) + +ASN1_SEQUENCE(ADMISSION_SYNTAX) = { + ASN1_OPT(ADMISSION_SYNTAX, admissionAuthority, GENERAL_NAME), + ASN1_SEQUENCE_OF(ADMISSION_SYNTAX, contentsOfAdmissions, ADMISSIONS), +} ASN1_SEQUENCE_END(ADMISSION_SYNTAX) + +IMPLEMENT_ASN1_FUNCTIONS(NAMING_AUTHORITY) +IMPLEMENT_ASN1_FUNCTIONS(PROFESSION_INFO) +IMPLEMENT_ASN1_FUNCTIONS(ADMISSIONS) +IMPLEMENT_ASN1_FUNCTIONS(ADMISSION_SYNTAX) + +static int i2r_ADMISSION_SYNTAX(const struct v3_ext_method *method, void *in, + BIO *bp, int ind); + +const X509V3_EXT_METHOD v3_ext_admission = { + NID_x509ExtAdmission, /* .ext_nid = */ + 0, /* .ext_flags = */ + ASN1_ITEM_ref(ADMISSION_SYNTAX), /* .it = */ + NULL, NULL, NULL, NULL, + NULL, /* .i2s = */ + NULL, /* .s2i = */ + NULL, /* .i2v = */ + NULL, /* .v2i = */ + &i2r_ADMISSION_SYNTAX, /* .i2r = */ + NULL, /* .r2i = */ + NULL /* extension-specific data */ +}; + + +static int i2r_NAMING_AUTHORITY(const struct v3_ext_method *method, void *in, + BIO *bp, int ind) +{ + NAMING_AUTHORITY * namingAuthority = (NAMING_AUTHORITY*) in; + + if (namingAuthority == NULL) + return 0; + + if (namingAuthority->namingAuthorityId == NULL + && namingAuthority->namingAuthorityText == NULL + && namingAuthority->namingAuthorityUrl == NULL) + return 0; + + if (BIO_printf(bp, "%*snamingAuthority: ", ind, "") <= 0) + goto err; + + if (namingAuthority->namingAuthorityId != NULL) { + char objbuf[128]; + const char *ln = OBJ_nid2ln(OBJ_obj2nid(namingAuthority->namingAuthorityId)); + + if (BIO_printf(bp, "%*s admissionAuthorityId: ", ind, "") <= 0) + goto err; + + OBJ_obj2txt(objbuf, sizeof(objbuf), namingAuthority->namingAuthorityId, 1); + + if (BIO_printf(bp, "%s%s%s%s\n", ln ? ln : "", + ln ? " (" : "", objbuf, ln ? ")" : "") <= 0) + goto err; + } + if (namingAuthority->namingAuthorityText != NULL) { + if (BIO_printf(bp, "%*s namingAuthorityText: ", ind, "") <= 0 + || ASN1_STRING_print(bp, namingAuthority->namingAuthorityText) <= 0 + || BIO_printf(bp, "\n") <= 0) + goto err; + } + if (namingAuthority->namingAuthorityUrl != NULL ) { + if (BIO_printf(bp, "%*s namingAuthorityUrl: ", ind, "") <= 0 + || ASN1_STRING_print(bp, namingAuthority->namingAuthorityUrl) <= 0 + || BIO_printf(bp, "\n") <= 0) + goto err; + } + return 1; + +err: + return 0; +} + +static int i2r_ADMISSION_SYNTAX(const struct v3_ext_method *method, void *in, + BIO *bp, int ind) +{ + ADMISSION_SYNTAX * admission = (ADMISSION_SYNTAX *)in; + int i, j, k; + + if (admission->admissionAuthority != NULL) { + if (BIO_printf(bp, "%*sadmissionAuthority:\n", ind, "") <= 0 + || BIO_printf(bp, "%*s ", ind, "") <= 0 + || GENERAL_NAME_print(bp, admission->admissionAuthority) <= 0 + || BIO_printf(bp, "\n") <= 0) + goto err; + } + + for (i = 0; i < sk_ADMISSIONS_num(admission->contentsOfAdmissions); i++) { + ADMISSIONS* entry = sk_ADMISSIONS_value(admission->contentsOfAdmissions, i); + + if (BIO_printf(bp, "%*sEntry %0d:\n", ind, "", 1 + i) <= 0) goto err; + + if (entry->admissionAuthority != NULL) { + if (BIO_printf(bp, "%*s admissionAuthority:\n", ind, "") <= 0 + || BIO_printf(bp, "%*s ", ind, "") <= 0 + || GENERAL_NAME_print(bp, entry->admissionAuthority) <= 0 + || BIO_printf(bp, "\n") <= 0) + goto err; + } + + if (entry->namingAuthority != NULL) { + if (i2r_NAMING_AUTHORITY(method, entry->namingAuthority, bp, ind) <= 0) + goto err; + } + + for (j = 0; j < sk_PROFESSION_INFO_num(entry->professionInfos); j++) { + PROFESSION_INFO* pinfo = sk_PROFESSION_INFO_value(entry->professionInfos, j); + + if (BIO_printf(bp, "%*s Profession Info Entry %0d:\n", ind, "", 1 + j) <= 0) + goto err; + + if (pinfo->registrationNumber != NULL) { + if (BIO_printf(bp, "%*s registrationNumber: ", ind, "") <= 0 + || ASN1_STRING_print(bp, pinfo->registrationNumber) <= 0 + || BIO_printf(bp, "\n") <= 0) + goto err; + } + + if (pinfo->namingAuthority != NULL) { + if (i2r_NAMING_AUTHORITY(method, pinfo->namingAuthority, bp, ind + 2) <= 0) + goto err; + } + + if (pinfo->professionItems != NULL) { + + if (BIO_printf(bp, "%*s Info Entries:\n", ind, "") <= 0) + goto err; + for (k = 0; k < sk_ASN1_STRING_num(pinfo->professionItems); k++) { + ASN1_STRING* val = sk_ASN1_STRING_value(pinfo->professionItems, k); + + if (BIO_printf(bp, "%*s ", ind, "") <= 0 + || ASN1_STRING_print(bp, val) <= 0 + || BIO_printf(bp, "\n") <= 0) + goto err; + } + } + + if (pinfo->professionOIDs != NULL) { + if (BIO_printf(bp, "%*s Profession OIDs:\n", ind, "") <= 0) + goto err; + for (k = 0; k < sk_ASN1_OBJECT_num(pinfo->professionOIDs); k++) { + ASN1_OBJECT* obj = sk_ASN1_OBJECT_value(pinfo->professionOIDs, k); + const char *ln = OBJ_nid2ln(OBJ_obj2nid(obj)); + char objbuf[128]; + + OBJ_obj2txt(objbuf, sizeof(objbuf), obj, 1); + if (BIO_printf(bp, "%*s %s%s%s%s\n", ind, "", + ln ? ln : "", ln ? " (" : "", + objbuf, ln ? ")" : "") <= 0) + goto err; + } + } + } + } + return 1; + +err: + return -1; +} + +const ASN1_OBJECT *NAMING_AUTHORITY_get0_authorityId(const NAMING_AUTHORITY *n) +{ + return n->namingAuthorityId; +} + +void NAMING_AUTHORITY_set0_authorityId(NAMING_AUTHORITY *n, ASN1_OBJECT* id) +{ + ASN1_OBJECT_free(n->namingAuthorityId); + n->namingAuthorityId = id; +} + +const ASN1_IA5STRING *NAMING_AUTHORITY_get0_authorityURL( + const NAMING_AUTHORITY *n) +{ + return n->namingAuthorityUrl; +} + +void NAMING_AUTHORITY_set0_authorityURL(NAMING_AUTHORITY *n, ASN1_IA5STRING* u) +{ + ASN1_IA5STRING_free(n->namingAuthorityUrl); + n->namingAuthorityUrl = u; +} + +const ASN1_STRING *NAMING_AUTHORITY_get0_authorityText( + const NAMING_AUTHORITY *n) +{ + return n->namingAuthorityText; +} + +void NAMING_AUTHORITY_set0_authorityText(NAMING_AUTHORITY *n, ASN1_STRING* t) +{ + ASN1_IA5STRING_free(n->namingAuthorityText); + n->namingAuthorityText = t; +} + +const GENERAL_NAME *ADMISSION_SYNTAX_get0_admissionAuthority(const ADMISSION_SYNTAX *as) +{ + return as->admissionAuthority; +} + +void ADMISSION_SYNTAX_set0_admissionAuthority(ADMISSION_SYNTAX *as, + GENERAL_NAME *aa) +{ + GENERAL_NAME_free(as->admissionAuthority); + as->admissionAuthority = aa; +} + +const STACK_OF(ADMISSIONS) *ADMISSION_SYNTAX_get0_contentsOfAdmissions(const ADMISSION_SYNTAX *as) +{ + return as->contentsOfAdmissions; +} + +void ADMISSION_SYNTAX_set0_contentsOfAdmissions(ADMISSION_SYNTAX *as, + STACK_OF(ADMISSIONS) *a) +{ + sk_ADMISSIONS_pop_free(as->contentsOfAdmissions, ADMISSIONS_free); + as->contentsOfAdmissions = a; +} + +const GENERAL_NAME *ADMISSIONS_get0_admissionAuthority(const ADMISSIONS *a) +{ + return a->admissionAuthority; +} + +void ADMISSIONS_set0_admissionAuthority(ADMISSIONS *a, GENERAL_NAME *aa) +{ + GENERAL_NAME_free(a->admissionAuthority); + a->admissionAuthority = aa; +} + +const NAMING_AUTHORITY *ADMISSIONS_get0_namingAuthority(const ADMISSIONS *a) +{ + return a->namingAuthority; +} + +void ADMISSIONS_set0_namingAuthority(ADMISSIONS *a, NAMING_AUTHORITY *na) +{ + NAMING_AUTHORITY_free(a->namingAuthority); + a->namingAuthority = na; +} + +const PROFESSION_INFOS *ADMISSIONS_get0_professionInfos(const ADMISSIONS *a) +{ + return a->professionInfos; +} + +void ADMISSIONS_set0_professionInfos(ADMISSIONS *a, PROFESSION_INFOS *pi) +{ + sk_PROFESSION_INFO_pop_free(a->professionInfos, PROFESSION_INFO_free); + a->professionInfos = pi; +} + +const ASN1_OCTET_STRING *PROFESSION_INFO_get0_addProfessionInfo(const PROFESSION_INFO *pi) +{ + return pi->addProfessionInfo; +} + +void PROFESSION_INFO_set0_addProfessionInfo(PROFESSION_INFO *pi, + ASN1_OCTET_STRING *aos) +{ + ASN1_OCTET_STRING_free(pi->addProfessionInfo); + pi->addProfessionInfo = aos; +} + +const NAMING_AUTHORITY *PROFESSION_INFO_get0_namingAuthority(const PROFESSION_INFO *pi) +{ + return pi->namingAuthority; +} + +void PROFESSION_INFO_set0_namingAuthority(PROFESSION_INFO *pi, + NAMING_AUTHORITY *na) +{ + NAMING_AUTHORITY_free(pi->namingAuthority); + pi->namingAuthority = na; +} + +const STACK_OF(ASN1_STRING) *PROFESSION_INFO_get0_professionItems(const PROFESSION_INFO *pi) +{ + return pi->professionItems; +} + +void PROFESSION_INFO_set0_professionItems(PROFESSION_INFO *pi, + STACK_OF(ASN1_STRING) *as) +{ + sk_ASN1_STRING_pop_free(pi->professionItems, ASN1_STRING_free); + pi->professionItems = as; +} + +const STACK_OF(ASN1_OBJECT) *PROFESSION_INFO_get0_professionOIDs(const PROFESSION_INFO *pi) +{ + return pi->professionOIDs; +} + +void PROFESSION_INFO_set0_professionOIDs(PROFESSION_INFO *pi, + STACK_OF(ASN1_OBJECT) *po) +{ + sk_ASN1_OBJECT_pop_free(pi->professionOIDs, ASN1_OBJECT_free); + pi->professionOIDs = po; +} + +const ASN1_PRINTABLESTRING *PROFESSION_INFO_get0_registrationNumber(const PROFESSION_INFO *pi) +{ + return pi->registrationNumber; +} + +void PROFESSION_INFO_set0_registrationNumber(PROFESSION_INFO *pi, + ASN1_PRINTABLESTRING *rn) +{ + ASN1_PRINTABLESTRING_free(pi->registrationNumber); + pi->registrationNumber = rn; +} diff --git a/crypto/x509v3/v3_admis.h b/crypto/x509v3/v3_admis.h new file mode 100644 index 00000000..2f1e76d7 --- /dev/null +++ b/crypto/x509v3/v3_admis.h @@ -0,0 +1,45 @@ +/* + * Copyright 2017-2018 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 + */ + +#ifndef HEADER_V3_ADMISSION_H +# define HEADER_V3_ADMISSION_H + +#ifdef __cplusplus +extern "C" { +#endif + +struct NamingAuthority_st { + ASN1_OBJECT* namingAuthorityId; + ASN1_IA5STRING* namingAuthorityUrl; + ASN1_STRING* namingAuthorityText; /* i.e. DIRECTORYSTRING */ +}; + +struct ProfessionInfo_st { + NAMING_AUTHORITY* namingAuthority; + STACK_OF(ASN1_STRING)* professionItems; /* i.e. DIRECTORYSTRING */ + STACK_OF(ASN1_OBJECT)* professionOIDs; + ASN1_PRINTABLESTRING* registrationNumber; + ASN1_OCTET_STRING* addProfessionInfo; +}; + +struct Admissions_st { + GENERAL_NAME* admissionAuthority; + NAMING_AUTHORITY* namingAuthority; + STACK_OF(PROFESSION_INFO)* professionInfos; +}; + +struct AdmissionSyntax_st { + GENERAL_NAME* admissionAuthority; + STACK_OF(ADMISSIONS)* contentsOfAdmissions; +}; + +#ifdef __cplusplus +} +#endif +#endif diff --git a/crypto/x509v3/v3_alt.c b/crypto/x509v3/v3_alt.c index a35d3376..832e6d12 100644 --- a/crypto/x509v3/v3_alt.c +++ b/crypto/x509v3/v3_alt.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-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 @@ -68,6 +68,7 @@ STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method, unsigned char *p; char oline[256], htmp[5]; int i; + switch (gen->type) { case GEN_OTHERNAME: if (!X509V3_add_value("othername", "", &ret)) @@ -100,7 +101,7 @@ STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method, break; case GEN_DIRNAME: - if (X509_NAME_oneline(gen->d.dirn, oline, 256) == NULL + if (X509_NAME_oneline(gen->d.dirn, oline, sizeof(oline)) == NULL || !X509V3_add_value("DirName", oline, &ret)) return NULL; break; @@ -108,8 +109,8 @@ STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method, case GEN_IPADD: p = gen->d.ip->data; if (gen->d.ip->length == 4) - BIO_snprintf(oline, sizeof(oline), - "%d.%d.%d.%d", p[0], p[1], p[2], p[3]); + 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++) { @@ -201,25 +202,28 @@ 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; + const int num = sk_CONF_VALUE_num(nval); + GENERAL_NAMES *gens = sk_GENERAL_NAME_new_reserve(NULL, num); int i; - if ((gens = sk_GENERAL_NAME_new_null()) == NULL) { + if (gens == NULL) { X509V3err(X509V3_F_V2I_ISSUER_ALT, ERR_R_MALLOC_FAILURE); + sk_GENERAL_NAME_free(gens); return NULL; } - for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { - cnf = sk_CONF_VALUE_value(nval, i); + for (i = 0; i < num; i++) { + CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i); + if (!name_cmp(cnf->name, "issuer") && cnf->value && strcmp(cnf->value, "copy") == 0) { if (!copy_issuer(ctx, gens)) goto err; } else { - GENERAL_NAME *gen; - if ((gen = v2i_GENERAL_NAME(method, ctx, cnf)) == NULL) + GENERAL_NAME *gen = v2i_GENERAL_NAME(method, ctx, cnf); + + if (gen == NULL) goto err; - sk_GENERAL_NAME_push(gens, gen); + sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */ } } return gens; @@ -235,7 +239,7 @@ static int copy_issuer(X509V3_CTX *ctx, GENERAL_NAMES *gens) GENERAL_NAMES *ialt; GENERAL_NAME *gen; X509_EXTENSION *ext; - int i; + int i, num; if (ctx && (ctx->flags == CTX_TEST)) return 1; @@ -252,12 +256,15 @@ static int copy_issuer(X509V3_CTX *ctx, GENERAL_NAMES *gens) goto err; } - for (i = 0; i < sk_GENERAL_NAME_num(ialt); i++) { + num = sk_GENERAL_NAME_num(ialt); + if (!sk_GENERAL_NAME_reserve(gens, num)) { + X509V3err(X509V3_F_COPY_ISSUER, ERR_R_MALLOC_FAILURE); + goto err; + } + + for (i = 0; i < num; 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_push(gens, gen); /* no failure as it was reserved */ } sk_GENERAL_NAME_free(ialt); @@ -272,15 +279,19 @@ static GENERAL_NAMES *v2i_subject_alt(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { - GENERAL_NAMES *gens = NULL; + GENERAL_NAMES *gens; CONF_VALUE *cnf; + const int num = sk_CONF_VALUE_num(nval); int i; - if ((gens = sk_GENERAL_NAME_new_null()) == NULL) { + gens = sk_GENERAL_NAME_new_reserve(NULL, num); + if (gens == NULL) { X509V3err(X509V3_F_V2I_SUBJECT_ALT, ERR_R_MALLOC_FAILURE); + sk_GENERAL_NAME_free(gens); return NULL; } - for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { + + for (i = 0; i < num; i++) { cnf = sk_CONF_VALUE_value(nval, i); if (!name_cmp(cnf->name, "email") && cnf->value && strcmp(cnf->value, "copy") == 0) { @@ -294,7 +305,7 @@ static GENERAL_NAMES *v2i_subject_alt(X509V3_EXT_METHOD *method, GENERAL_NAME *gen; if ((gen = v2i_GENERAL_NAME(method, ctx, cnf)) == NULL) goto err; - sk_GENERAL_NAME_push(gens, gen); + sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */ } } return gens; @@ -313,10 +324,12 @@ static int copy_email(X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p) ASN1_IA5STRING *email = NULL; X509_NAME_ENTRY *ne; GENERAL_NAME *gen = NULL; - int i; + int i = -1; + if (ctx != NULL && ctx->flags == CTX_TEST) return 1; - if (!ctx || (!ctx->subject_cert && !ctx->subject_req)) { + if (ctx == NULL + || (ctx->subject_cert == NULL && ctx->subject_req == NULL)) { X509V3err(X509V3_F_COPY_EMAIL, X509V3_R_NO_SUBJECT_DETAILS); goto err; } @@ -327,7 +340,6 @@ static int copy_email(X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p) 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); @@ -364,19 +376,23 @@ 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; + GENERAL_NAMES *gens; CONF_VALUE *cnf; + const int num = sk_CONF_VALUE_num(nval); int i; - if ((gens = sk_GENERAL_NAME_new_null()) == NULL) { + gens = sk_GENERAL_NAME_new_reserve(NULL, num); + if (gens == NULL) { X509V3err(X509V3_F_V2I_GENERAL_NAMES, ERR_R_MALLOC_FAILURE); + sk_GENERAL_NAME_free(gens); return NULL; } - for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { + + for (i = 0; i < num; i++) { cnf = sk_CONF_VALUE_value(nval, i); if ((gen = v2i_GENERAL_NAME(method, ctx, cnf)) == NULL) goto err; - sk_GENERAL_NAME_push(gens, gen); + sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */ } return gens; err: diff --git a/crypto/x509v3/v3_asid.c b/crypto/x509v3/v3_asid.c index af4fcf4c..089f2ae2 100644 --- a/crypto/x509v3/v3_asid.c +++ b/crypto/x509v3/v3_asid.c @@ -1,5 +1,5 @@ /* - * Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2006-2018 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 @@ -11,6 +11,7 @@ * Implementation of RFC 3779 section 3.2. */ +#include #include #include #include "internal/cryptlib.h" @@ -123,13 +124,13 @@ static int ASIdOrRange_cmp(const ASIdOrRange *const *a_, { const ASIdOrRange *a = *a_, *b = *b_; - OPENSSL_assert((a->type == ASIdOrRange_id && a->u.id != NULL) || - (a->type == ASIdOrRange_range && a->u.range != NULL && - a->u.range->min != NULL && a->u.range->max != NULL)); + assert((a->type == ASIdOrRange_id && a->u.id != NULL) || + (a->type == ASIdOrRange_range && a->u.range != NULL && + a->u.range->min != NULL && a->u.range->max != NULL)); - OPENSSL_assert((b->type == ASIdOrRange_id && b->u.id != NULL) || - (b->type == ASIdOrRange_range && b->u.range != NULL && - b->u.range->min != NULL && b->u.range->max != NULL)); + assert((b->type == ASIdOrRange_id && b->u.id != NULL) || + (b->type == ASIdOrRange_range && b->u.range != NULL && + b->u.range->min != NULL && b->u.range->max != NULL)); if (a->type == ASIdOrRange_id && b->type == ASIdOrRange_id) return ASN1_INTEGER_cmp(a->u.id, b->u.id); @@ -167,7 +168,6 @@ int X509v3_asid_add_inherit(ASIdentifiers *asid, int which) if (*choice == NULL) { if ((*choice = ASIdentifierChoice_new()) == NULL) return 0; - OPENSSL_assert((*choice)->u.inherit == NULL); if (((*choice)->u.inherit = ASN1_NULL_new()) == NULL) return 0; (*choice)->type = ASIdentifierChoice_inherit; @@ -200,7 +200,6 @@ int X509v3_asid_add_id_or_range(ASIdentifiers *asid, if (*choice == NULL) { if ((*choice = ASIdentifierChoice_new()) == NULL) return 0; - OPENSSL_assert((*choice)->u.asIdsOrRanges == NULL); (*choice)->u.asIdsOrRanges = sk_ASIdOrRange_new(ASIdOrRange_cmp); if ((*choice)->u.asIdsOrRanges == NULL) return 0; @@ -232,20 +231,23 @@ int X509v3_asid_add_id_or_range(ASIdentifiers *asid, /* * Extract min and max values from an ASIdOrRange. */ -static void extract_min_max(ASIdOrRange *aor, - ASN1_INTEGER **min, ASN1_INTEGER **max) +static int extract_min_max(ASIdOrRange *aor, + ASN1_INTEGER **min, ASN1_INTEGER **max) { - OPENSSL_assert(aor != NULL && min != NULL && max != NULL); + if (!ossl_assert(aor != NULL)) + return 0; switch (aor->type) { case ASIdOrRange_id: *min = aor->u.id; *max = aor->u.id; - return; + return 1; case ASIdOrRange_range: *min = aor->u.range->min; *max = aor->u.range->max; - return; + return 1; } + + return 0; } /* @@ -279,8 +281,9 @@ static int ASIdentifierChoice_is_canonical(ASIdentifierChoice *choice) ASN1_INTEGER *a_min = NULL, *a_max = NULL, *b_min = NULL, *b_max = NULL; - extract_min_max(a, &a_min, &a_max); - extract_min_max(b, &b_min, &b_max); + if (!extract_min_max(a, &a_min, &a_max) + || !extract_min_max(b, &b_min, &b_max)) + goto done; /* * Punt misordered list, overlapping start, or inverted range. @@ -318,8 +321,8 @@ static int ASIdentifierChoice_is_canonical(ASIdentifierChoice *choice) ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); ASN1_INTEGER *a_min, *a_max; if (a != NULL && a->type == ASIdOrRange_range) { - extract_min_max(a, &a_min, &a_max); - if (ASN1_INTEGER_cmp(a_min, a_max) > 0) + if (!extract_min_max(a, &a_min, &a_max) + || ASN1_INTEGER_cmp(a_min, a_max) > 0) goto done; } } @@ -382,13 +385,15 @@ static int ASIdentifierChoice_canonize(ASIdentifierChoice *choice) ASN1_INTEGER *a_min = NULL, *a_max = NULL, *b_min = NULL, *b_max = NULL; - extract_min_max(a, &a_min, &a_max); - extract_min_max(b, &b_min, &b_max); + if (!extract_min_max(a, &a_min, &a_max) + || !extract_min_max(b, &b_min, &b_max)) + goto done; /* * Make sure we're properly sorted (paranoia). */ - OPENSSL_assert(ASN1_INTEGER_cmp(a_min, b_min) <= 0); + if (!ossl_assert(ASN1_INTEGER_cmp(a_min, b_min) <= 0)) + goto done; /* * Punt inverted ranges. @@ -464,13 +469,15 @@ static int ASIdentifierChoice_canonize(ASIdentifierChoice *choice) ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); ASN1_INTEGER *a_min, *a_max; if (a != NULL && a->type == ASIdOrRange_range) { - extract_min_max(a, &a_min, &a_max); - if (ASN1_INTEGER_cmp(a_min, a_max) > 0) + if (!extract_min_max(a, &a_min, &a_max) + || ASN1_INTEGER_cmp(a_min, a_max) > 0) goto done; } } - OPENSSL_assert(ASIdentifierChoice_is_canonical(choice)); /* Paranoia */ + /* Paranoia */ + if (!ossl_assert(ASIdentifierChoice_is_canonical(choice))) + goto done; ret = 1; @@ -655,11 +662,14 @@ static int asid_contains(ASIdOrRanges *parent, ASIdOrRanges *child) p = 0; for (c = 0; c < sk_ASIdOrRange_num(child); c++) { - extract_min_max(sk_ASIdOrRange_value(child, c), &c_min, &c_max); + if (!extract_min_max(sk_ASIdOrRange_value(child, c), &c_min, &c_max)) + return 0; for (;; p++) { if (p >= sk_ASIdOrRange_num(parent)) return 0; - extract_min_max(sk_ASIdOrRange_value(parent, p), &p_min, &p_max); + if (!extract_min_max(sk_ASIdOrRange_value(parent, p), &p_min, + &p_max)) + return 0; if (ASN1_INTEGER_cmp(p_max, c_max) < 0) continue; if (ASN1_INTEGER_cmp(p_min, c_min) > 0) @@ -715,9 +725,14 @@ static int asid_validate_path_internal(X509_STORE_CTX *ctx, int i, ret = 1, inherit_as = 0, inherit_rdi = 0; X509 *x; - OPENSSL_assert(chain != NULL && sk_X509_num(chain) > 0); - OPENSSL_assert(ctx != NULL || ext != NULL); - OPENSSL_assert(ctx == NULL || ctx->verify_cb != NULL); + if (!ossl_assert(chain != NULL && sk_X509_num(chain) > 0) + || !ossl_assert(ctx != NULL || ext != NULL) + || !ossl_assert(ctx == NULL || ctx->verify_cb != NULL)) { + if (ctx != NULL) + ctx->error = X509_V_ERR_UNSPECIFIED; + return 0; + } + /* * Figure out where to start. If we don't have an extension to @@ -730,7 +745,6 @@ static int asid_validate_path_internal(X509_STORE_CTX *ctx, } else { i = 0; x = sk_X509_value(chain, i); - OPENSSL_assert(x != NULL); if ((ext = x->rfc3779_asid) == NULL) goto done; } @@ -763,7 +777,11 @@ static int asid_validate_path_internal(X509_STORE_CTX *ctx, */ for (i++; i < sk_X509_num(chain); i++) { x = sk_X509_value(chain, i); - OPENSSL_assert(x != NULL); + if (!ossl_assert(x != NULL)) { + if (ctx != NULL) + ctx->error = X509_V_ERR_UNSPECIFIED; + return 0; + } if (x->rfc3779_asid == NULL) { if (child_as != NULL || child_rdi != NULL) validation_err(X509_V_ERR_UNNESTED_RESOURCE); @@ -809,7 +827,11 @@ static int asid_validate_path_internal(X509_STORE_CTX *ctx, /* * Trust anchor can't inherit. */ - OPENSSL_assert(x != NULL); + if (!ossl_assert(x != NULL)) { + if (ctx != NULL) + ctx->error = X509_V_ERR_UNSPECIFIED; + return 0; + } if (x->rfc3779_asid != NULL) { if (x->rfc3779_asid->asnum != NULL && x->rfc3779_asid->asnum->type == ASIdentifierChoice_inherit) @@ -830,6 +852,12 @@ static int asid_validate_path_internal(X509_STORE_CTX *ctx, */ int X509v3_asid_validate_path(X509_STORE_CTX *ctx) { + if (ctx->chain == NULL + || sk_X509_num(ctx->chain) == 0 + || ctx->verify_cb == NULL) { + ctx->error = X509_V_ERR_UNSPECIFIED; + return 0; + } return asid_validate_path_internal(ctx, ctx->chain, NULL); } diff --git a/crypto/x509v3/v3_conf.c b/crypto/x509v3/v3_conf.c index 3cc5b14d..7acaebfa 100644 --- a/crypto/x509v3/v3_conf.c +++ b/crypto/x509v3/v3_conf.c @@ -10,7 +10,7 @@ /* extension creation utilities */ #include -#include +#include "internal/ctype.h" #include "internal/cryptlib.h" #include #include @@ -192,7 +192,7 @@ static int v3_check_critical(const char **value) if ((strlen(p) < 9) || strncmp(p, "critical,", 9)) return 0; p += 9; - while (isspace((unsigned char)*p)) + while (ossl_isspace(*p)) p++; *value = p; return 1; @@ -212,7 +212,7 @@ static int v3_check_generic(const char **value) } else return 0; - while (isspace((unsigned char)*p)) + while (ossl_isspace(*p)) p++; *value = p; return gen_type; diff --git a/crypto/x509v3/v3_cpols.c b/crypto/x509v3/v3_cpols.c index 22c56ba3..51fbb1f0 100644 --- a/crypto/x509v3/v3_cpols.c +++ b/crypto/x509v3/v3_cpols.c @@ -31,6 +31,8 @@ static POLICYINFO *policy_section(X509V3_CTX *ctx, static POLICYQUALINFO *notice_section(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *unot, int ia5org); static int nref_nos(STACK_OF(ASN1_INTEGER) *nnums, STACK_OF(CONF_VALUE) *nos); +static int displaytext_str2tag(const char *tagstr, unsigned int *tag_len); +static int displaytext_get_tag_len(const char *tagstr); const X509V3_EXT_METHOD v3_cpols = { NID_certificate_policies, 0, ASN1_ITEM_ref(CERTIFICATEPOLICIES), @@ -86,26 +88,30 @@ IMPLEMENT_ASN1_FUNCTIONS(NOTICEREF) static STACK_OF(POLICYINFO) *r2i_certpol(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *value) { - STACK_OF(POLICYINFO) *pols = NULL; + STACK_OF(POLICYINFO) *pols; char *pstr; POLICYINFO *pol; ASN1_OBJECT *pobj; - STACK_OF(CONF_VALUE) *vals; + STACK_OF(CONF_VALUE) *vals = X509V3_parse_list(value); CONF_VALUE *cnf; + const int num = sk_CONF_VALUE_num(vals); int i, ia5org; - pols = sk_POLICYINFO_new_null(); - if (pols == NULL) { - X509V3err(X509V3_F_R2I_CERTPOL, ERR_R_MALLOC_FAILURE); - return NULL; - } - vals = X509V3_parse_list(value); + if (vals == NULL) { X509V3err(X509V3_F_R2I_CERTPOL, ERR_R_X509V3_LIB); + return NULL; + } + + pols = sk_POLICYINFO_new_reserve(NULL, num); + if (pols == NULL) { + X509V3err(X509V3_F_R2I_CERTPOL, ERR_R_MALLOC_FAILURE); goto err; } + ia5org = 0; - for (i = 0; i < sk_CONF_VALUE_num(vals); i++) { + for (i = 0; i < num; i++) { cnf = sk_CONF_VALUE_value(vals, i); + if (cnf->value || !cnf->name) { X509V3err(X509V3_F_R2I_CERTPOL, X509V3_R_INVALID_POLICY_IDENTIFIER); @@ -239,16 +245,50 @@ static POLICYINFO *policy_section(X509V3_CTX *ctx, err: POLICYINFO_free(pol); return NULL; +} +static int displaytext_get_tag_len(const char *tagstr) +{ + char *colon = strchr(tagstr, ':'); + + return (colon == NULL) ? -1 : colon - tagstr; +} + +static int displaytext_str2tag(const char *tagstr, unsigned int *tag_len) +{ + int len; + + *tag_len = 0; + len = displaytext_get_tag_len(tagstr); + + if (len == -1) + return V_ASN1_VISIBLESTRING; + *tag_len = len; + if (len == sizeof("UTF8") - 1 && strncmp(tagstr, "UTF8", len) == 0) + return V_ASN1_UTF8STRING; + if (len == sizeof("UTF8String") - 1 && strncmp(tagstr, "UTF8String", len) == 0) + return V_ASN1_UTF8STRING; + if (len == sizeof("BMP") - 1 && strncmp(tagstr, "BMP", len) == 0) + return V_ASN1_BMPSTRING; + if (len == sizeof("BMPSTRING") - 1 && strncmp(tagstr, "BMPSTRING", len) == 0) + return V_ASN1_BMPSTRING; + if (len == sizeof("VISIBLE") - 1 && strncmp(tagstr, "VISIBLE", len) == 0) + return V_ASN1_VISIBLESTRING; + if (len == sizeof("VISIBLESTRING") - 1 && strncmp(tagstr, "VISIBLESTRING", len) == 0) + return V_ASN1_VISIBLESTRING; + *tag_len = 0; + return V_ASN1_VISIBLESTRING; } static POLICYQUALINFO *notice_section(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *unot, int ia5org) { - int i, ret; + int i, ret, len, tag; + unsigned int tag_len; CONF_VALUE *cnf; USERNOTICE *not; POLICYQUALINFO *qual; + char *value = NULL; if ((qual = POLICYQUALINFO_new()) == NULL) goto merr; @@ -261,11 +301,15 @@ static POLICYQUALINFO *notice_section(X509V3_CTX *ctx, qual->d.usernotice = not; for (i = 0; i < sk_CONF_VALUE_num(unot); i++) { cnf = sk_CONF_VALUE_value(unot, i); + value = cnf->value; if (strcmp(cnf->name, "explicitText") == 0) { - if ((not->exptext = ASN1_VISIBLESTRING_new()) == NULL) + tag = displaytext_str2tag(value, &tag_len); + if ((not->exptext = ASN1_STRING_type_new(tag)) == NULL) goto merr; - if (!ASN1_STRING_set(not->exptext, cnf->value, - strlen(cnf->value))) + if (tag_len != 0) + value += tag_len + 1; + len = strlen(value); + if (!ASN1_STRING_set(not->exptext, value, len)) goto merr; } else if (strcmp(cnf->name, "organization") == 0) { NOTICEREF *nref; diff --git a/crypto/x509v3/v3_crld.c b/crypto/x509v3/v3_crld.c index c4c77f18..6cba4240 100644 --- a/crypto/x509v3/v3_crld.c +++ b/crypto/x509v3/v3_crld.c @@ -205,8 +205,8 @@ static DIST_POINT *crldp_from_section(X509V3_CTX *ctx, { int i; CONF_VALUE *cnf; - DIST_POINT *point = NULL; - point = DIST_POINT_new(); + DIST_POINT *point = DIST_POINT_new(); + if (point == NULL) goto err; for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { @@ -237,16 +237,19 @@ static DIST_POINT *crldp_from_section(X509V3_CTX *ctx, static void *v2i_crld(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { - STACK_OF(DIST_POINT) *crld = NULL; + STACK_OF(DIST_POINT) *crld; GENERAL_NAMES *gens = NULL; GENERAL_NAME *gen = NULL; CONF_VALUE *cnf; + const int num = sk_CONF_VALUE_num(nval); int i; - if ((crld = sk_DIST_POINT_new_null()) == NULL) + crld = sk_DIST_POINT_new_reserve(NULL, num); + if (crld == NULL) goto merr; - for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { + for (i = 0; i < num; i++) { DIST_POINT *point; + cnf = sk_CONF_VALUE_value(nval, i); if (!cnf->value) { STACK_OF(CONF_VALUE) *dpsect; @@ -257,10 +260,7 @@ static void *v2i_crld(const X509V3_EXT_METHOD *method, X509V3_section_free(ctx, dpsect); if (!point) goto err; - if (!sk_DIST_POINT_push(crld, point)) { - DIST_POINT_free(point); - goto merr; - } + sk_DIST_POINT_push(crld, point); /* no failure as it was reserved */ } else { if ((gen = v2i_GENERAL_NAME(method, ctx, cnf)) == NULL) goto err; @@ -271,10 +271,7 @@ static void *v2i_crld(const X509V3_EXT_METHOD *method, gen = NULL; if ((point = DIST_POINT_new()) == NULL) goto merr; - if (!sk_DIST_POINT_push(crld, point)) { - DIST_POINT_free(point); - goto merr; - } + sk_DIST_POINT_push(crld, point); /* no failure as it was reserved */ if ((point->distpoint = DIST_POINT_NAME_new()) == NULL) goto merr; point->distpoint->name.fullname = gens; diff --git a/crypto/x509v3/v3_enum.c b/crypto/x509v3/v3_enum.c index f39cb5ac..3b0f1974 100644 --- a/crypto/x509v3/v3_enum.c +++ b/crypto/x509v3/v3_enum.c @@ -38,7 +38,7 @@ const X509V3_EXT_METHOD v3_crl_reason = { crl_reasons }; -char *i2s_ASN1_ENUMERATED_TABLE(X509V3_EXT_METHOD *method, +char *i2s_ASN1_ENUMERATED_TABLE(X509V3_EXT_METHOD *method, const ASN1_ENUMERATED *e) { ENUMERATED_NAMES *enam; diff --git a/crypto/x509v3/v3_extku.c b/crypto/x509v3/v3_extku.c index bae755e3..91b24376 100644 --- a/crypto/x509v3/v3_extku.c +++ b/crypto/x509v3/v3_extku.c @@ -74,14 +74,17 @@ static void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method, char *extval; ASN1_OBJECT *objtmp; CONF_VALUE *val; + const int num = sk_CONF_VALUE_num(nval); int i; - if ((extku = sk_ASN1_OBJECT_new_null()) == NULL) { + extku = sk_ASN1_OBJECT_new_reserve(NULL, num); + if (extku == NULL) { X509V3err(X509V3_F_V2I_EXTENDED_KEY_USAGE, ERR_R_MALLOC_FAILURE); + sk_ASN1_OBJECT_free(extku); return NULL; } - for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { + for (i = 0; i < num; i++) { val = sk_CONF_VALUE_value(nval, i); if (val->value) extval = val->value; @@ -94,7 +97,7 @@ static void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method, X509V3_conf_err(val); return NULL; } - sk_ASN1_OBJECT_push(extku, objtmp); + sk_ASN1_OBJECT_push(extku, objtmp); /* no failure as it was reserved */ } return extku; } diff --git a/crypto/x509v3/v3_info.c b/crypto/x509v3/v3_info.c index a0bca5fb..7af9e23a 100644 --- a/crypto/x509v3/v3_info.c +++ b/crypto/x509v3/v3_info.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-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 @@ -78,16 +78,13 @@ static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS( tret = tmp; vtmp = sk_CONF_VALUE_value(tret, i); i2t_ASN1_OBJECT(objtmp, sizeof(objtmp), desc->method); - nlen = strlen(objtmp) + strlen(vtmp->name) + 5; + nlen = strlen(objtmp) + 3 + strlen(vtmp->name) + 1; ntmp = OPENSSL_malloc(nlen); if (ntmp == NULL) goto err; - OPENSSL_strlcpy(ntmp, objtmp, nlen); - OPENSSL_strlcat(ntmp, " - ", nlen); - OPENSSL_strlcat(ntmp, vtmp->name, nlen); + BIO_snprintf(ntmp, nlen, "%s - %s", objtmp, vtmp->name); OPENSSL_free(vtmp->name); vtmp->name = ntmp; - } if (ret == NULL && tret == NULL) return sk_CONF_VALUE_new_null(); @@ -110,20 +107,21 @@ static AUTHORITY_INFO_ACCESS *v2i_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD CONF_VALUE *cnf, ctmp; ACCESS_DESCRIPTION *acc; int i, objlen; + const int num = sk_CONF_VALUE_num(nval); char *objtmp, *ptmp; - if ((ainfo = sk_ACCESS_DESCRIPTION_new_null()) == NULL) { + if ((ainfo = sk_ACCESS_DESCRIPTION_new_reserve(NULL, num)) == NULL) { X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS, ERR_R_MALLOC_FAILURE); return NULL; } - for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { + for (i = 0; i < num; i++) { cnf = sk_CONF_VALUE_value(nval, i); - if ((acc = ACCESS_DESCRIPTION_new()) == NULL - || !sk_ACCESS_DESCRIPTION_push(ainfo, acc)) { + if ((acc = ACCESS_DESCRIPTION_new()) == NULL) { X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS, ERR_R_MALLOC_FAILURE); goto err; } + sk_ACCESS_DESCRIPTION_push(ainfo, acc); /* Cannot fail due to reserve */ ptmp = strchr(cnf->name, ';'); if (!ptmp) { X509V3err(X509V3_F_V2I_AUTHORITY_INFO_ACCESS, diff --git a/crypto/x509v3/v3_lib.c b/crypto/x509v3/v3_lib.c index d7143086..f51aa962 100644 --- a/crypto/x509v3/v3_lib.c +++ b/crypto/x509v3/v3_lib.c @@ -47,73 +47,7 @@ DECLARE_OBJ_BSEARCH_CMP_FN(const X509V3_EXT_METHOD *, IMPLEMENT_OBJ_BSEARCH_CMP_FN(const X509V3_EXT_METHOD *, const X509V3_EXT_METHOD *, ext); -/* - * This table will be searched using OBJ_bsearch so it *must* kept in order - * of the ext_nid values. - */ - -static const X509V3_EXT_METHOD *standard_exts[] = { - &v3_nscert, - &v3_ns_ia5_list[0], - &v3_ns_ia5_list[1], - &v3_ns_ia5_list[2], - &v3_ns_ia5_list[3], - &v3_ns_ia5_list[4], - &v3_ns_ia5_list[5], - &v3_ns_ia5_list[6], - &v3_skey_id, - &v3_key_usage, - &v3_pkey_usage_period, - &v3_alt[0], - &v3_alt[1], - &v3_bcons, - &v3_crl_num, - &v3_cpols, - &v3_akey_id, - &v3_crld, - &v3_ext_ku, - &v3_delta_crl, - &v3_crl_reason, -#ifndef OPENSSL_NO_OCSP - &v3_crl_invdate, -#endif - &v3_sxnet, - &v3_info, -#ifndef OPENSSL_NO_RFC3779 - &v3_addr, - &v3_asid, -#endif -#ifndef OPENSSL_NO_OCSP - &v3_ocsp_nonce, - &v3_ocsp_crlid, - &v3_ocsp_accresp, - &v3_ocsp_nocheck, - &v3_ocsp_acutoff, - &v3_ocsp_serviceloc, -#endif - &v3_sinfo, - &v3_policy_constraints, -#ifndef OPENSSL_NO_OCSP - &v3_crl_hold, -#endif - &v3_pci, - &v3_name_constraints, - &v3_policy_mappings, - &v3_inhibit_anyp, - &v3_idp, - &v3_alt[2], - &v3_freshest_crl, -#ifndef OPENSSL_NO_CT - &v3_ct_scts[0], - &v3_ct_scts[1], - &v3_ct_scts[2], -#endif - &v3_tls_feature, -}; - -/* Number of standard extensions */ - -#define STANDARD_EXTENSION_COUNT OSSL_NELEM(standard_exts) +#include "standard_exts.h" const X509V3_EXT_METHOD *X509V3_EXT_get_nid(int nid) { diff --git a/crypto/x509v3/v3_ncons.c b/crypto/x509v3/v3_ncons.c index 2eec405a..1f1996b6 100644 --- a/crypto/x509v3/v3_ncons.c +++ b/crypto/x509v3/v3_ncons.c @@ -1,5 +1,5 @@ /* - * Copyright 2003-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2003-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 @@ -7,9 +7,9 @@ * https://www.openssl.org/source/license.html */ -#include #include "internal/cryptlib.h" #include "internal/numbers.h" +#include #include "internal/asn1_int.h" #include #include @@ -316,6 +316,7 @@ int NAME_CONSTRAINTS_check_CN(X509 *x, NAME_CONSTRAINTS *nc) for (i = -1;;) { X509_NAME_ENTRY *ne; ASN1_STRING *hn; + i = X509_NAME_get_index_by_NID(nm, NID_commonName, i); if (i == -1) break; diff --git a/crypto/x509v3/v3_pci.c b/crypto/x509v3/v3_pci.c index 2c05edb8..3d124fa6 100644 --- a/crypto/x509v3/v3_pci.c +++ b/crypto/x509v3/v3_pci.c @@ -7,7 +7,11 @@ * https://www.openssl.org/source/license.html */ -/* Copyright (c) 2004 Kungliga Tekniska Högskolan +/* + * This file is dual-licensed and is also available under the following + * terms: + * + * Copyright (c) 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * diff --git a/crypto/x509v3/v3_pcia.c b/crypto/x509v3/v3_pcia.c index e6f7a917..8d6af60e 100644 --- a/crypto/x509v3/v3_pcia.c +++ b/crypto/x509v3/v3_pcia.c @@ -7,7 +7,11 @@ * https://www.openssl.org/source/license.html */ -/* Copyright (c) 2004 Kungliga Tekniska Högskolan +/* + * This file is dual-licensed and is also available under the following + * terms: + * + * Copyright (c) 2004 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * diff --git a/crypto/x509v3/v3_pku.c b/crypto/x509v3/v3_pku.c index ed82bca8..5a7e7d97 100644 --- a/crypto/x509v3/v3_pku.c +++ b/crypto/x509v3/v3_pku.c @@ -17,10 +17,7 @@ static int i2r_PKEY_USAGE_PERIOD(X509V3_EXT_METHOD *method, PKEY_USAGE_PERIOD *usage, BIO *out, int indent); -/* - * static PKEY_USAGE_PERIOD *v2i_PKEY_USAGE_PERIOD(X509V3_EXT_METHOD *method, - * X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *values); - */ + const X509V3_EXT_METHOD v3_pkey_usage_period = { NID_private_key_usage_period, 0, ASN1_ITEM_ref(PKEY_USAGE_PERIOD), 0, 0, 0, 0, @@ -53,13 +50,3 @@ static int i2r_PKEY_USAGE_PERIOD(X509V3_EXT_METHOD *method, } return 1; } - -/*- -static PKEY_USAGE_PERIOD *v2i_PKEY_USAGE_PERIOD(method, ctx, values) -X509V3_EXT_METHOD *method; -X509V3_CTX *ctx; -STACK_OF(CONF_VALUE) *values; -{ -return NULL; -} -*/ diff --git a/crypto/x509v3/v3_pmaps.c b/crypto/x509v3/v3_pmaps.c index 73f4ec24..5b6a2af0 100644 --- a/crypto/x509v3/v3_pmaps.c +++ b/crypto/x509v3/v3_pmaps.c @@ -52,6 +52,7 @@ static STACK_OF(CONF_VALUE) *i2v_POLICY_MAPPINGS(const X509V3_EXT_METHOD int i; char obj_tmp1[80]; char obj_tmp2[80]; + for (i = 0; i < sk_POLICY_MAPPING_num(pmaps); i++) { pmap = sk_POLICY_MAPPING_value(pmaps, i); i2t_ASN1_OBJECT(obj_tmp1, 80, pmap->issuerDomainPolicy); @@ -64,18 +65,19 @@ static STACK_OF(CONF_VALUE) *i2v_POLICY_MAPPINGS(const X509V3_EXT_METHOD static void *v2i_POLICY_MAPPINGS(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { - POLICY_MAPPINGS *pmaps = NULL; POLICY_MAPPING *pmap = NULL; ASN1_OBJECT *obj1 = NULL, *obj2 = NULL; CONF_VALUE *val; + POLICY_MAPPINGS *pmaps; + const int num = sk_CONF_VALUE_num(nval); int i; - if ((pmaps = sk_POLICY_MAPPING_new_null()) == NULL) { + if ((pmaps = sk_POLICY_MAPPING_new_reserve(NULL, num)) == NULL) { X509V3err(X509V3_F_V2I_POLICY_MAPPINGS, ERR_R_MALLOC_FAILURE); return NULL; } - for (i = 0; i < sk_CONF_VALUE_num(nval); i++) { + for (i = 0; i < num; i++) { val = sk_CONF_VALUE_value(nval, i); if (!val->value || !val->name) { X509V3err(X509V3_F_V2I_POLICY_MAPPINGS, @@ -99,7 +101,7 @@ static void *v2i_POLICY_MAPPINGS(const X509V3_EXT_METHOD *method, pmap->issuerDomainPolicy = obj1; pmap->subjectDomainPolicy = obj2; obj1 = obj2 = NULL; - sk_POLICY_MAPPING_push(pmaps, pmap); + sk_POLICY_MAPPING_push(pmaps, pmap); /* no failure as it was reserved */ } return pmaps; err: diff --git a/crypto/x509v3/v3_purp.c b/crypto/x509v3/v3_purp.c index 6d2f354d..d344e2df 100644 --- a/crypto/x509v3/v3_purp.c +++ b/crypto/x509v3/v3_purp.c @@ -488,6 +488,7 @@ static void x509v3_cache_extensions(X509 *x) break; } } + x509_init_sig_info(x); x->ex_flags |= EXFLAG_SET; } diff --git a/crypto/x509v3/v3_skey.c b/crypto/x509v3/v3_skey.c index 39597dc4..749f51b2 100644 --- a/crypto/x509v3/v3_skey.c +++ b/crypto/x509v3/v3_skey.c @@ -24,7 +24,7 @@ const X509V3_EXT_METHOD v3_skey_id = { NULL }; -char *i2s_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method, +char *i2s_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method, const ASN1_OCTET_STRING *oct) { return OPENSSL_buf2hexstr(oct->data, oct->length); diff --git a/crypto/x509v3/v3_tlsf.c b/crypto/x509v3/v3_tlsf.c index fec67243..5f2d5d2c 100644 --- a/crypto/x509v3/v3_tlsf.c +++ b/crypto/x509v3/v3_tlsf.c @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-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 @@ -7,8 +7,9 @@ * https://www.openssl.org/source/license.html */ -#include +#include "e_os.h" #include "internal/cryptlib.h" +#include #include "internal/o_str.h" #include #include diff --git a/crypto/x509v3/v3_utl.c b/crypto/x509v3/v3_utl.c index 418ef06a..c9b40d2c 100644 --- a/crypto/x509v3/v3_utl.c +++ b/crypto/x509v3/v3_utl.c @@ -1,5 +1,5 @@ /* - * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1999-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 @@ -9,9 +9,10 @@ /* X509 v3 extension utilities */ -#include -#include +#include "e_os.h" #include "internal/cryptlib.h" +#include +#include "internal/ctype.h" #include #include #include @@ -377,12 +378,12 @@ static char *strip_spaces(char *name) char *p, *q; /* Skip over leading spaces */ p = name; - while (*p && isspace((unsigned char)*p)) + while (*p && ossl_isspace(*p)) p++; if (!*p) return NULL; q = p + strlen(p) - 1; - while ((q != p) && isspace((unsigned char)*q)) + while ((q != p) && ossl_isspace(*q)) q--; if (p != q) q[1] = 0; @@ -467,11 +468,11 @@ static STACK_OF(OPENSSL_STRING) *get_email(X509_NAME *name, { STACK_OF(OPENSSL_STRING) *ret = NULL; X509_NAME_ENTRY *ne; - ASN1_IA5STRING *email; + const ASN1_IA5STRING *email; GENERAL_NAME *gen; - int i; + int i = -1; + /* Now add any email address(es) to STACK */ - i = -1; /* First supplied X509_NAME */ while ((i = X509_NAME_get_index_by_NID(name, NID_pkcs9_emailAddress, i)) >= 0) { diff --git a/crypto/x509v3/v3conf.c b/crypto/x509v3/v3conf.c deleted file mode 100644 index 966ab90b..00000000 --- a/crypto/x509v3/v3conf.c +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 1999-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 - */ - -#include -#include "internal/cryptlib.h" -#include -#include -#include -#include - -/* Test application to add extensions from a config file */ - -int main(int argc, char **argv) -{ - LHASH *conf; - X509 *cert; - FILE *inf; - char *conf_file; - int i; - int count; - X509_EXTENSION *ext; - X509V3_add_standard_extensions(); - ERR_load_crypto_strings(); - if (!argv[1]) { - fprintf(stderr, "Usage: v3conf cert.pem [file.cnf]\n"); - exit(1); - } - conf_file = argv[2]; - if (!conf_file) - conf_file = "test.cnf"; - conf = CONF_load(NULL, "test.cnf", NULL); - if (!conf) { - fprintf(stderr, "Error opening Config file %s\n", conf_file); - ERR_print_errors_fp(stderr); - exit(1); - } - - inf = fopen(argv[1], "r"); - if (!inf) { - fprintf(stderr, "Can't open certificate file %s\n", argv[1]); - exit(1); - } - cert = PEM_read_X509(inf, NULL, NULL); - if (!cert) { - fprintf(stderr, "Error reading certificate file %s\n", argv[1]); - exit(1); - } - fclose(inf); - - sk_pop_free(cert->cert_info->extensions, X509_EXTENSION_free); - cert->cert_info->extensions = NULL; - - if (!X509V3_EXT_add_conf(conf, NULL, "test_section", cert)) { - fprintf(stderr, "Error adding extensions\n"); - ERR_print_errors_fp(stderr); - exit(1); - } - - count = X509_get_ext_count(cert); - printf("%d extensions\n", count); - for (i = 0; i < count; i++) { - ext = X509_get_ext(cert, i); - printf("%s", OBJ_nid2ln(OBJ_obj2nid(ext->object))); - if (ext->critical) - printf(",critical:\n"); - else - printf(":\n"); - X509V3_EXT_print_fp(stdout, ext, 0, 0); - printf("\n"); - - } - return 0; -} diff --git a/crypto/x509v3/v3err.c b/crypto/x509v3/v3err.c index d5987913..6f30ba3a 100644 --- a/crypto/x509v3/v3err.c +++ b/crypto/x509v3/v3err.c @@ -8,168 +8,231 @@ * https://www.openssl.org/source/license.html */ -#include #include -#include +#include -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK(ERR_LIB_X509V3,func,0) -# define ERR_REASON(reason) ERR_PACK(ERR_LIB_X509V3,0,reason) - -static ERR_STRING_DATA X509V3_str_functs[] = { - {ERR_FUNC(X509V3_F_A2I_GENERAL_NAME), "a2i_GENERAL_NAME"}, - {ERR_FUNC(X509V3_F_ADDR_VALIDATE_PATH_INTERNAL), +static const ERR_STRING_DATA X509V3_str_functs[] = { + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_A2I_GENERAL_NAME, 0), + "a2i_GENERAL_NAME"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_ADDR_VALIDATE_PATH_INTERNAL, 0), "addr_validate_path_internal"}, - {ERR_FUNC(X509V3_F_ASIDENTIFIERCHOICE_CANONIZE), + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_ASIDENTIFIERCHOICE_CANONIZE, 0), "ASIdentifierChoice_canonize"}, - {ERR_FUNC(X509V3_F_ASIDENTIFIERCHOICE_IS_CANONICAL), + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_ASIDENTIFIERCHOICE_IS_CANONICAL, 0), "ASIdentifierChoice_is_canonical"}, - {ERR_FUNC(X509V3_F_BIGNUM_TO_STRING), "bignum_to_string"}, - {ERR_FUNC(X509V3_F_COPY_EMAIL), "copy_email"}, - {ERR_FUNC(X509V3_F_COPY_ISSUER), "copy_issuer"}, - {ERR_FUNC(X509V3_F_DO_DIRNAME), "do_dirname"}, - {ERR_FUNC(X509V3_F_DO_EXT_I2D), "do_ext_i2d"}, - {ERR_FUNC(X509V3_F_DO_EXT_NCONF), "do_ext_nconf"}, - {ERR_FUNC(X509V3_F_GNAMES_FROM_SECTNAME), "gnames_from_sectname"}, - {ERR_FUNC(X509V3_F_I2S_ASN1_ENUMERATED), "i2s_ASN1_ENUMERATED"}, - {ERR_FUNC(X509V3_F_I2S_ASN1_IA5STRING), "i2s_ASN1_IA5STRING"}, - {ERR_FUNC(X509V3_F_I2S_ASN1_INTEGER), "i2s_ASN1_INTEGER"}, - {ERR_FUNC(X509V3_F_I2V_AUTHORITY_INFO_ACCESS), + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_BIGNUM_TO_STRING, 0), + "bignum_to_string"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_COPY_EMAIL, 0), "copy_email"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_COPY_ISSUER, 0), "copy_issuer"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_DO_DIRNAME, 0), "do_dirname"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_DO_EXT_I2D, 0), "do_ext_i2d"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_DO_EXT_NCONF, 0), "do_ext_nconf"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_GNAMES_FROM_SECTNAME, 0), + "gnames_from_sectname"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_I2S_ASN1_ENUMERATED, 0), + "i2s_ASN1_ENUMERATED"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_I2S_ASN1_IA5STRING, 0), + "i2s_ASN1_IA5STRING"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_I2S_ASN1_INTEGER, 0), + "i2s_ASN1_INTEGER"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_I2V_AUTHORITY_INFO_ACCESS, 0), "i2v_AUTHORITY_INFO_ACCESS"}, - {ERR_FUNC(X509V3_F_NOTICE_SECTION), "notice_section"}, - {ERR_FUNC(X509V3_F_NREF_NOS), "nref_nos"}, - {ERR_FUNC(X509V3_F_POLICY_SECTION), "policy_section"}, - {ERR_FUNC(X509V3_F_PROCESS_PCI_VALUE), "process_pci_value"}, - {ERR_FUNC(X509V3_F_R2I_CERTPOL), "r2i_certpol"}, - {ERR_FUNC(X509V3_F_R2I_PCI), "r2i_pci"}, - {ERR_FUNC(X509V3_F_S2I_ASN1_IA5STRING), "s2i_ASN1_IA5STRING"}, - {ERR_FUNC(X509V3_F_S2I_ASN1_INTEGER), "s2i_ASN1_INTEGER"}, - {ERR_FUNC(X509V3_F_S2I_ASN1_OCTET_STRING), "s2i_ASN1_OCTET_STRING"}, - {ERR_FUNC(X509V3_F_S2I_SKEY_ID), "s2i_skey_id"}, - {ERR_FUNC(X509V3_F_SET_DIST_POINT_NAME), "set_dist_point_name"}, - {ERR_FUNC(X509V3_F_SXNET_ADD_ID_ASC), "SXNET_add_id_asc"}, - {ERR_FUNC(X509V3_F_SXNET_ADD_ID_INTEGER), "SXNET_add_id_INTEGER"}, - {ERR_FUNC(X509V3_F_SXNET_ADD_ID_ULONG), "SXNET_add_id_ulong"}, - {ERR_FUNC(X509V3_F_SXNET_GET_ID_ASC), "SXNET_get_id_asc"}, - {ERR_FUNC(X509V3_F_SXNET_GET_ID_ULONG), "SXNET_get_id_ulong"}, - {ERR_FUNC(X509V3_F_V2I_ASIDENTIFIERS), "v2i_ASIdentifiers"}, - {ERR_FUNC(X509V3_F_V2I_ASN1_BIT_STRING), "v2i_ASN1_BIT_STRING"}, - {ERR_FUNC(X509V3_F_V2I_AUTHORITY_INFO_ACCESS), + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_NOTICE_SECTION, 0), "notice_section"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_NREF_NOS, 0), "nref_nos"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_POLICY_SECTION, 0), "policy_section"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_PROCESS_PCI_VALUE, 0), + "process_pci_value"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_R2I_CERTPOL, 0), "r2i_certpol"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_R2I_PCI, 0), "r2i_pci"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_S2I_ASN1_IA5STRING, 0), + "s2i_ASN1_IA5STRING"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_S2I_ASN1_INTEGER, 0), + "s2i_ASN1_INTEGER"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_S2I_ASN1_OCTET_STRING, 0), + "s2i_ASN1_OCTET_STRING"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_S2I_SKEY_ID, 0), "s2i_skey_id"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_SET_DIST_POINT_NAME, 0), + "set_dist_point_name"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_SXNET_ADD_ID_ASC, 0), + "SXNET_add_id_asc"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_SXNET_ADD_ID_INTEGER, 0), + "SXNET_add_id_INTEGER"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_SXNET_ADD_ID_ULONG, 0), + "SXNET_add_id_ulong"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_SXNET_GET_ID_ASC, 0), + "SXNET_get_id_asc"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_SXNET_GET_ID_ULONG, 0), + "SXNET_get_id_ulong"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_ASIDENTIFIERS, 0), + "v2i_ASIdentifiers"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_ASN1_BIT_STRING, 0), + "v2i_ASN1_BIT_STRING"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_AUTHORITY_INFO_ACCESS, 0), "v2i_AUTHORITY_INFO_ACCESS"}, - {ERR_FUNC(X509V3_F_V2I_AUTHORITY_KEYID), "v2i_AUTHORITY_KEYID"}, - {ERR_FUNC(X509V3_F_V2I_BASIC_CONSTRAINTS), "v2i_BASIC_CONSTRAINTS"}, - {ERR_FUNC(X509V3_F_V2I_CRLD), "v2i_crld"}, - {ERR_FUNC(X509V3_F_V2I_EXTENDED_KEY_USAGE), "v2i_EXTENDED_KEY_USAGE"}, - {ERR_FUNC(X509V3_F_V2I_GENERAL_NAMES), "v2i_GENERAL_NAMES"}, - {ERR_FUNC(X509V3_F_V2I_GENERAL_NAME_EX), "v2i_GENERAL_NAME_ex"}, - {ERR_FUNC(X509V3_F_V2I_IDP), "v2i_idp"}, - {ERR_FUNC(X509V3_F_V2I_IPADDRBLOCKS), "v2i_IPAddrBlocks"}, - {ERR_FUNC(X509V3_F_V2I_ISSUER_ALT), "v2i_issuer_alt"}, - {ERR_FUNC(X509V3_F_V2I_NAME_CONSTRAINTS), "v2i_NAME_CONSTRAINTS"}, - {ERR_FUNC(X509V3_F_V2I_POLICY_CONSTRAINTS), "v2i_POLICY_CONSTRAINTS"}, - {ERR_FUNC(X509V3_F_V2I_POLICY_MAPPINGS), "v2i_POLICY_MAPPINGS"}, - {ERR_FUNC(X509V3_F_V2I_SUBJECT_ALT), "v2i_subject_alt"}, - {ERR_FUNC(X509V3_F_V2I_TLS_FEATURE), "v2i_TLS_FEATURE"}, - {ERR_FUNC(X509V3_F_V3_GENERIC_EXTENSION), "v3_generic_extension"}, - {ERR_FUNC(X509V3_F_X509V3_ADD1_I2D), "X509V3_add1_i2d"}, - {ERR_FUNC(X509V3_F_X509V3_ADD_VALUE), "X509V3_add_value"}, - {ERR_FUNC(X509V3_F_X509V3_EXT_ADD), "X509V3_EXT_add"}, - {ERR_FUNC(X509V3_F_X509V3_EXT_ADD_ALIAS), "X509V3_EXT_add_alias"}, - {ERR_FUNC(X509V3_F_X509V3_EXT_I2D), "X509V3_EXT_i2d"}, - {ERR_FUNC(X509V3_F_X509V3_EXT_NCONF), "X509V3_EXT_nconf"}, - {ERR_FUNC(X509V3_F_X509V3_GET_SECTION), "X509V3_get_section"}, - {ERR_FUNC(X509V3_F_X509V3_GET_STRING), "X509V3_get_string"}, - {ERR_FUNC(X509V3_F_X509V3_GET_VALUE_BOOL), "X509V3_get_value_bool"}, - {ERR_FUNC(X509V3_F_X509V3_PARSE_LIST), "X509V3_parse_list"}, - {ERR_FUNC(X509V3_F_X509_PURPOSE_ADD), "X509_PURPOSE_add"}, - {ERR_FUNC(X509V3_F_X509_PURPOSE_SET), "X509_PURPOSE_set"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_AUTHORITY_KEYID, 0), + "v2i_AUTHORITY_KEYID"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_BASIC_CONSTRAINTS, 0), + "v2i_BASIC_CONSTRAINTS"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_CRLD, 0), "v2i_crld"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_EXTENDED_KEY_USAGE, 0), + "v2i_EXTENDED_KEY_USAGE"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_GENERAL_NAMES, 0), + "v2i_GENERAL_NAMES"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_GENERAL_NAME_EX, 0), + "v2i_GENERAL_NAME_ex"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_IDP, 0), "v2i_idp"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_IPADDRBLOCKS, 0), + "v2i_IPAddrBlocks"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_ISSUER_ALT, 0), "v2i_issuer_alt"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_NAME_CONSTRAINTS, 0), + "v2i_NAME_CONSTRAINTS"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_POLICY_CONSTRAINTS, 0), + "v2i_POLICY_CONSTRAINTS"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_POLICY_MAPPINGS, 0), + "v2i_POLICY_MAPPINGS"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_SUBJECT_ALT, 0), "v2i_subject_alt"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V2I_TLS_FEATURE, 0), "v2i_TLS_FEATURE"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_V3_GENERIC_EXTENSION, 0), + "v3_generic_extension"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_ADD1_I2D, 0), "X509V3_add1_i2d"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_ADD_VALUE, 0), + "X509V3_add_value"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_EXT_ADD, 0), "X509V3_EXT_add"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_EXT_ADD_ALIAS, 0), + "X509V3_EXT_add_alias"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_EXT_I2D, 0), "X509V3_EXT_i2d"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_EXT_NCONF, 0), + "X509V3_EXT_nconf"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_GET_SECTION, 0), + "X509V3_get_section"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_GET_STRING, 0), + "X509V3_get_string"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_GET_VALUE_BOOL, 0), + "X509V3_get_value_bool"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509V3_PARSE_LIST, 0), + "X509V3_parse_list"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509_PURPOSE_ADD, 0), + "X509_PURPOSE_add"}, + {ERR_PACK(ERR_LIB_X509V3, X509V3_F_X509_PURPOSE_SET, 0), + "X509_PURPOSE_set"}, {0, NULL} }; -static ERR_STRING_DATA X509V3_str_reasons[] = { - {ERR_REASON(X509V3_R_BAD_IP_ADDRESS), "bad ip address"}, - {ERR_REASON(X509V3_R_BAD_OBJECT), "bad object"}, - {ERR_REASON(X509V3_R_BN_DEC2BN_ERROR), "bn dec2bn error"}, - {ERR_REASON(X509V3_R_BN_TO_ASN1_INTEGER_ERROR), - "bn to asn1 integer error"}, - {ERR_REASON(X509V3_R_DIRNAME_ERROR), "dirname error"}, - {ERR_REASON(X509V3_R_DISTPOINT_ALREADY_SET), "distpoint already set"}, - {ERR_REASON(X509V3_R_DUPLICATE_ZONE_ID), "duplicate zone id"}, - {ERR_REASON(X509V3_R_ERROR_CONVERTING_ZONE), "error converting zone"}, - {ERR_REASON(X509V3_R_ERROR_CREATING_EXTENSION), - "error creating extension"}, - {ERR_REASON(X509V3_R_ERROR_IN_EXTENSION), "error in extension"}, - {ERR_REASON(X509V3_R_EXPECTED_A_SECTION_NAME), "expected a section name"}, - {ERR_REASON(X509V3_R_EXTENSION_EXISTS), "extension exists"}, - {ERR_REASON(X509V3_R_EXTENSION_NAME_ERROR), "extension name error"}, - {ERR_REASON(X509V3_R_EXTENSION_NOT_FOUND), "extension not found"}, - {ERR_REASON(X509V3_R_EXTENSION_SETTING_NOT_SUPPORTED), - "extension setting not supported"}, - {ERR_REASON(X509V3_R_EXTENSION_VALUE_ERROR), "extension value error"}, - {ERR_REASON(X509V3_R_ILLEGAL_EMPTY_EXTENSION), "illegal empty extension"}, - {ERR_REASON(X509V3_R_INCORRECT_POLICY_SYNTAX_TAG), - "incorrect policy syntax tag"}, - {ERR_REASON(X509V3_R_INVALID_ASNUMBER), "invalid asnumber"}, - {ERR_REASON(X509V3_R_INVALID_ASRANGE), "invalid asrange"}, - {ERR_REASON(X509V3_R_INVALID_BOOLEAN_STRING), "invalid boolean string"}, - {ERR_REASON(X509V3_R_INVALID_EXTENSION_STRING), - "invalid extension string"}, - {ERR_REASON(X509V3_R_INVALID_INHERITANCE), "invalid inheritance"}, - {ERR_REASON(X509V3_R_INVALID_IPADDRESS), "invalid ipaddress"}, - {ERR_REASON(X509V3_R_INVALID_MULTIPLE_RDNS), "invalid multiple rdns"}, - {ERR_REASON(X509V3_R_INVALID_NAME), "invalid name"}, - {ERR_REASON(X509V3_R_INVALID_NULL_ARGUMENT), "invalid null argument"}, - {ERR_REASON(X509V3_R_INVALID_NULL_NAME), "invalid null name"}, - {ERR_REASON(X509V3_R_INVALID_NULL_VALUE), "invalid null value"}, - {ERR_REASON(X509V3_R_INVALID_NUMBER), "invalid number"}, - {ERR_REASON(X509V3_R_INVALID_NUMBERS), "invalid numbers"}, - {ERR_REASON(X509V3_R_INVALID_OBJECT_IDENTIFIER), - "invalid object identifier"}, - {ERR_REASON(X509V3_R_INVALID_OPTION), "invalid option"}, - {ERR_REASON(X509V3_R_INVALID_POLICY_IDENTIFIER), - "invalid policy identifier"}, - {ERR_REASON(X509V3_R_INVALID_PROXY_POLICY_SETTING), - "invalid proxy policy setting"}, - {ERR_REASON(X509V3_R_INVALID_PURPOSE), "invalid purpose"}, - {ERR_REASON(X509V3_R_INVALID_SAFI), "invalid safi"}, - {ERR_REASON(X509V3_R_INVALID_SECTION), "invalid section"}, - {ERR_REASON(X509V3_R_INVALID_SYNTAX), "invalid syntax"}, - {ERR_REASON(X509V3_R_ISSUER_DECODE_ERROR), "issuer decode error"}, - {ERR_REASON(X509V3_R_MISSING_VALUE), "missing value"}, - {ERR_REASON(X509V3_R_NEED_ORGANIZATION_AND_NUMBERS), - "need organization and numbers"}, - {ERR_REASON(X509V3_R_NO_CONFIG_DATABASE), "no config database"}, - {ERR_REASON(X509V3_R_NO_ISSUER_CERTIFICATE), "no issuer certificate"}, - {ERR_REASON(X509V3_R_NO_ISSUER_DETAILS), "no issuer details"}, - {ERR_REASON(X509V3_R_NO_POLICY_IDENTIFIER), "no policy identifier"}, - {ERR_REASON(X509V3_R_NO_PROXY_CERT_POLICY_LANGUAGE_DEFINED), - "no proxy cert policy language defined"}, - {ERR_REASON(X509V3_R_NO_PUBLIC_KEY), "no public key"}, - {ERR_REASON(X509V3_R_NO_SUBJECT_DETAILS), "no subject details"}, - {ERR_REASON(X509V3_R_OPERATION_NOT_DEFINED), "operation not defined"}, - {ERR_REASON(X509V3_R_OTHERNAME_ERROR), "othername error"}, - {ERR_REASON(X509V3_R_POLICY_LANGUAGE_ALREADY_DEFINED), - "policy language already defined"}, - {ERR_REASON(X509V3_R_POLICY_PATH_LENGTH), "policy path length"}, - {ERR_REASON(X509V3_R_POLICY_PATH_LENGTH_ALREADY_DEFINED), - "policy path length already defined"}, - {ERR_REASON(X509V3_R_POLICY_WHEN_PROXY_LANGUAGE_REQUIRES_NO_POLICY), - "policy when proxy language requires no policy"}, - {ERR_REASON(X509V3_R_SECTION_NOT_FOUND), "section not found"}, - {ERR_REASON(X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS), - "unable to get issuer details"}, - {ERR_REASON(X509V3_R_UNABLE_TO_GET_ISSUER_KEYID), - "unable to get issuer keyid"}, - {ERR_REASON(X509V3_R_UNKNOWN_BIT_STRING_ARGUMENT), - "unknown bit string argument"}, - {ERR_REASON(X509V3_R_UNKNOWN_EXTENSION), "unknown extension"}, - {ERR_REASON(X509V3_R_UNKNOWN_EXTENSION_NAME), "unknown extension name"}, - {ERR_REASON(X509V3_R_UNKNOWN_OPTION), "unknown option"}, - {ERR_REASON(X509V3_R_UNSUPPORTED_OPTION), "unsupported option"}, - {ERR_REASON(X509V3_R_UNSUPPORTED_TYPE), "unsupported type"}, - {ERR_REASON(X509V3_R_USER_TOO_LONG), "user too long"}, +static const ERR_STRING_DATA X509V3_str_reasons[] = { + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_BAD_IP_ADDRESS), "bad ip address"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_BAD_OBJECT), "bad object"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_BN_DEC2BN_ERROR), "bn dec2bn error"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_BN_TO_ASN1_INTEGER_ERROR), + "bn to asn1 integer error"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_DIRNAME_ERROR), "dirname error"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_DISTPOINT_ALREADY_SET), + "distpoint already set"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_DUPLICATE_ZONE_ID), + "duplicate zone id"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_ERROR_CONVERTING_ZONE), + "error converting zone"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_ERROR_CREATING_EXTENSION), + "error creating extension"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_ERROR_IN_EXTENSION), + "error in extension"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXPECTED_A_SECTION_NAME), + "expected a section name"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXTENSION_EXISTS), + "extension exists"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXTENSION_NAME_ERROR), + "extension name error"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXTENSION_NOT_FOUND), + "extension not found"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXTENSION_SETTING_NOT_SUPPORTED), + "extension setting not supported"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXTENSION_VALUE_ERROR), + "extension value error"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_ILLEGAL_EMPTY_EXTENSION), + "illegal empty extension"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INCORRECT_POLICY_SYNTAX_TAG), + "incorrect policy syntax tag"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_ASNUMBER), + "invalid asnumber"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_ASRANGE), "invalid asrange"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_BOOLEAN_STRING), + "invalid boolean string"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_EXTENSION_STRING), + "invalid extension string"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_INHERITANCE), + "invalid inheritance"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_IPADDRESS), + "invalid ipaddress"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_MULTIPLE_RDNS), + "invalid multiple rdns"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NAME), "invalid name"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NULL_ARGUMENT), + "invalid null argument"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NULL_NAME), + "invalid null name"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NULL_VALUE), + "invalid null value"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NUMBER), "invalid number"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NUMBERS), "invalid numbers"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_OBJECT_IDENTIFIER), + "invalid object identifier"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_OPTION), "invalid option"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_POLICY_IDENTIFIER), + "invalid policy identifier"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_PROXY_POLICY_SETTING), + "invalid proxy policy setting"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_PURPOSE), "invalid purpose"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_SAFI), "invalid safi"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_SECTION), "invalid section"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_SYNTAX), "invalid syntax"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_ISSUER_DECODE_ERROR), + "issuer decode error"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_MISSING_VALUE), "missing value"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NEED_ORGANIZATION_AND_NUMBERS), + "need organization and numbers"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_CONFIG_DATABASE), + "no config database"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_ISSUER_CERTIFICATE), + "no issuer certificate"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_ISSUER_DETAILS), + "no issuer details"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_POLICY_IDENTIFIER), + "no policy identifier"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_PROXY_CERT_POLICY_LANGUAGE_DEFINED), + "no proxy cert policy language defined"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_PUBLIC_KEY), "no public key"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_SUBJECT_DETAILS), + "no subject details"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_OPERATION_NOT_DEFINED), + "operation not defined"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_OTHERNAME_ERROR), "othername error"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_POLICY_LANGUAGE_ALREADY_DEFINED), + "policy language already defined"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_POLICY_PATH_LENGTH), + "policy path length"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_POLICY_PATH_LENGTH_ALREADY_DEFINED), + "policy path length already defined"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_POLICY_WHEN_PROXY_LANGUAGE_REQUIRES_NO_POLICY), + "policy when proxy language requires no policy"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_SECTION_NOT_FOUND), + "section not found"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS), + "unable to get issuer details"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNABLE_TO_GET_ISSUER_KEYID), + "unable to get issuer keyid"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNKNOWN_BIT_STRING_ARGUMENT), + "unknown bit string argument"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNKNOWN_EXTENSION), + "unknown extension"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNKNOWN_EXTENSION_NAME), + "unknown extension name"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNKNOWN_OPTION), "unknown option"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNSUPPORTED_OPTION), + "unsupported option"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNSUPPORTED_TYPE), + "unsupported type"}, + {ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_USER_TOO_LONG), "user too long"}, {0, NULL} }; @@ -178,10 +241,9 @@ static ERR_STRING_DATA X509V3_str_reasons[] = { int ERR_load_X509V3_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(X509V3_str_functs[0].error) == NULL) { - ERR_load_strings(0, X509V3_str_functs); - ERR_load_strings(0, X509V3_str_reasons); + ERR_load_strings_const(X509V3_str_functs); + ERR_load_strings_const(X509V3_str_reasons); } #endif return 1; diff --git a/crypto/x509v3/v3prin.c b/crypto/x509v3/v3prin.c deleted file mode 100644 index 7431a4ea..00000000 --- a/crypto/x509v3/v3prin.c +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 1999-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 - */ - -#include -#include -#include -#include -#include - -int main(int argc, char **argv) -{ - X509 *cert; - FILE *inf; - int i, count; - X509_EXTENSION *ext; - - X509V3_add_standard_extensions(); - ERR_load_crypto_strings(); - if (!argv[1]) { - fprintf(stderr, "Usage v3prin cert.pem\n"); - exit(1); - } - if ((inf = fopen(argv[1], "r")) == NULL) { - fprintf(stderr, "Can't open %s\n", argv[1]); - exit(1); - } - if ((cert = PEM_read_X509(inf, NULL, NULL)) == NULL) { - fprintf(stderr, "Can't read certificate %s\n", argv[1]); - ERR_print_errors_fp(stderr); - exit(1); - } - fclose(inf); - count = X509_get_ext_count(cert); - printf("%d extensions\n", count); - for (i = 0; i < count; i++) { - ext = X509_get_ext(cert, i); - printf("%s\n", OBJ_nid2ln(OBJ_obj2nid(ext->object))); - if (!X509V3_EXT_print_fp(stdout, ext, 0, 0)) - ERR_print_errors_fp(stderr); - printf("\n"); - - } - return 0; -} diff --git a/crypto/x86_64cpuid.pl b/crypto/x86_64cpuid.pl index 1a6f728d..0a88c7a4 100644 --- a/crypto/x86_64cpuid.pl +++ b/crypto/x86_64cpuid.pl @@ -63,10 +63,12 @@ OPENSSL_rdtsc: .type OPENSSL_ia32_cpuid,\@function,1 .align 16 OPENSSL_ia32_cpuid: +.cfi_startproc mov %rbx,%r8 # save %rbx +.cfi_register %rbx,%r8 xor %eax,%eax - mov %eax,8(%rdi) # clear extended feature flags + mov %rax,8(%rdi) # clear extended feature flags cpuid mov %eax,%r11d # max value for standard query level @@ -137,6 +139,7 @@ OPENSSL_ia32_cpuid: .Lnocacheinfo: mov \$1,%eax cpuid + movd %eax,%xmm0 # put aside processor id and \$0xbfefffff,%edx # force reserved bits to 0 cmp \$0,%r9d jne .Lnotintel @@ -184,26 +187,45 @@ OPENSSL_ia32_cpuid: jc .Lnotknights and \$0xfff7ffff,%ebx # clear ADCX/ADOX flag .Lnotknights: + movd %xmm0,%eax # restore processor id + and \$0x0fff0ff0,%eax + cmp \$0x00050650,%eax # Skylake-X + jne .Lnotskylakex + and \$0xfffeffff,%ebx # ~(1<<16) + # suppress AVX512F flag on Skylake-X +.Lnotskylakex: mov %ebx,8(%rdi) # save extended feature flags + mov %ecx,12(%rdi) .Lno_extended_info: bt \$27,%r9d # check OSXSAVE bit jnc .Lclear_avx xor %ecx,%ecx # XCR0 .byte 0x0f,0x01,0xd0 # xgetbv + and \$0xe6,%eax # isolate XMM, YMM and ZMM state support + cmp \$0xe6,%eax + je .Ldone + andl \$0x3fdeffff,8(%rdi) # ~(1<<31|1<<30|1<<21|1<<16) + # clear AVX512F+BW+VL+FIMA, all of + # them are EVEX-encoded, which requires + # ZMM state support even if one uses + # only XMM and YMM :-( and \$6,%eax # isolate XMM and YMM state support cmp \$6,%eax je .Ldone .Lclear_avx: mov \$0xefffe7ff,%eax # ~(1<<28|1<<12|1<<11) and %eax,%r9d # clear AVX, FMA and AMD XOP bits - andl \$0xffffffdf,8(%rdi) # clear AVX2, ~(1<<5) + mov \$0x3fdeffdf,%eax # ~(1<<31|1<<30|1<<21|1<<16|1<<5) + and %eax,8(%rdi) # clear AVX2 and AVX512* bits .Ldone: shl \$32,%r9 mov %r10d,%eax mov %r8,%rbx # restore %rbx +.cfi_restore %rbx or %r9,%rax ret +.cfi_endproc .size OPENSSL_ia32_cpuid,.-OPENSSL_ia32_cpuid .globl OPENSSL_cleanse diff --git a/crypto/x86cpuid.pl b/crypto/x86cpuid.pl index 4622a9fa..08c129a2 100644 --- a/crypto/x86cpuid.pl +++ b/crypto/x86cpuid.pl @@ -14,7 +14,7 @@ $output = pop; open OUT,">$output"; *STDOUT=*OUT; -&asm_init($ARGV[0],"x86cpuid"); +&asm_init($ARGV[0]); for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } @@ -89,7 +89,7 @@ for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } &ja (&label("generic")); &and ("edx",0xefffffff); # clear hyper-threading bit &jmp (&label("generic")); - + &set_label("intel"); &cmp ("edi",4); &mov ("esi",-1); @@ -110,7 +110,7 @@ for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } &cmp ("ebp",0); &jne (&label("notintel")); &or ("edx",1<<30); # set reserved bit#30 on Intel CPUs - &and (&HB("eax"),15); # familiy ID + &and (&HB("eax"),15); # family ID &cmp (&HB("eax"),15); # P4? &jne (&label("notintel")); &or ("edx",1<<20); # set reserved bit#20 to engage RC4_CHAR @@ -290,45 +290,6 @@ for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } &ret (); &function_end_B("OPENSSL_atomic_add"); -# This function can become handy under Win32 in situations when -# we don't know which calling convention, __stdcall or __cdecl(*), -# indirect callee is using. In C it can be deployed as -# -#ifdef OPENSSL_CPUID_OBJ -# type OPENSSL_indirect_call(void *f,...); -# ... -# OPENSSL_indirect_call(func,[up to $max arguments]); -#endif -# -# (*) it's designed to work even for __fastcall if number of -# arguments is 1 or 2! -&function_begin_B("OPENSSL_indirect_call"); - { - my ($max,$i)=(7,); # $max has to be chosen as 4*n-1 - # in order to preserve eventual - # stack alignment - &push ("ebp"); - &mov ("ebp","esp"); - &sub ("esp",$max*4); - &mov ("ecx",&DWP(12,"ebp")); - &mov (&DWP(0,"esp"),"ecx"); - &mov ("edx",&DWP(16,"ebp")); - &mov (&DWP(4,"esp"),"edx"); - for($i=2;$i<$max;$i++) - { - # Some copies will be redundant/bogus... - &mov ("eax",&DWP(12+$i*4,"ebp")); - &mov (&DWP(0+$i*4,"esp"),"eax"); - } - &call_ptr (&DWP(8,"ebp"));# make the call... - &mov ("esp","ebp"); # ... and just restore the stack pointer - # without paying attention to what we called, - # (__cdecl *func) or (__stdcall *one). - &pop ("ebp"); - &ret (); - } -&function_end_B("OPENSSL_indirect_call"); - &function_begin_B("OPENSSL_cleanse"); &mov ("edx",&wparam(0)); &mov ("ecx",&wparam(1)); diff --git a/demos/bio/Makefile b/demos/bio/Makefile index 493e8a58..5a4e4a4a 100644 --- a/demos/bio/Makefile +++ b/demos/bio/Makefile @@ -27,4 +27,4 @@ server-cmod: server-cmod.o server-conf: server-conf.o client-arg client-conf saccept sconnect server-arg server-cmod server-conf: - $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $< + $(CC) $(CFLAGS) -o $@ $< $(LDFLAGS) diff --git a/demos/bio/saccept.c b/demos/bio/saccept.c index 66c5c617..de86ae63 100644 --- a/demos/bio/saccept.c +++ b/demos/bio/saccept.c @@ -1,5 +1,5 @@ /* - * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1998-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 @@ -19,12 +19,13 @@ #include #include +#include #include #include #define CERT_FILE "server.pem" -static int done = 0; +static volatile int done = 0; void interrupt(int sig) { @@ -51,7 +52,7 @@ int main(int argc, char *argv[]) BIO *ssl_bio, *tmp; SSL_CTX *ctx; char buf[512]; - int ret = 1, i; + int ret = EXIT_FAILURE, i; if (argc <= 1) port = "*:4433"; @@ -111,12 +112,10 @@ int main(int argc, char *argv[]) fflush(stdout); } - ret = 0; + ret = EXIT_SUCCESS; err: - if (ret) { + if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); - } BIO_free(in); - exit(ret); - return (!ret); + return ret; } diff --git a/demos/bio/sconnect.c b/demos/bio/sconnect.c index 664a1e03..db71f29a 100644 --- a/demos/bio/sconnect.c +++ b/demos/bio/sconnect.c @@ -1,5 +1,5 @@ /* - * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 1998-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 @@ -18,17 +18,14 @@ #include #include #include +#include #include #include #define HOSTPORT "localhost:4433" #define CAFILE "root.pem" -extern int errno; - -int main(argc, argv) -int argc; -char *argv[]; +int main(int argc, char *argv[]) { const char *hostport = HOSTPORT; const char *CAfile = CAFILE; @@ -39,7 +36,7 @@ char *argv[]; SSL_CTX *ssl_ctx = NULL; SSL *ssl; BIO *ssl_bio; - int i, len, off, ret = 1; + int i, len, off, ret = EXIT_FAILURE; if (argc > 1) hostport = argv[1]; @@ -115,17 +112,18 @@ char *argv[]; fwrite(buf, 1, i, stdout); } - ret = 1; + ret = EXIT_SUCCESS; goto done; err: if (ERR_peek_error() == 0) { /* system call error */ fprintf(stderr, "errno=%d ", errno); perror("error"); - } else + } else { ERR_print_errors_fp(stderr); + } done: BIO_free_all(out); SSL_CTX_free(ssl_ctx); - return (ret == 1); + return ret; } diff --git a/demos/bio/server-arg.c b/demos/bio/server-arg.c index 6056969f..d80d070f 100644 --- a/demos/bio/server-arg.c +++ b/demos/bio/server-arg.c @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2013-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 @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -27,7 +28,7 @@ int main(int argc, char *argv[]) SSL_CONF_CTX *cctx; char buf[512]; BIO *in = NULL; - int ret = 1, i; + int ret = EXIT_FAILURE, i; char **args = argv + 1; int nargs = argc - 1; @@ -134,12 +135,10 @@ int main(int argc, char *argv[]) fflush(stdout); } - ret = 0; + ret = EXIT_SUCCESS; err: - if (ret) { + if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); - } BIO_free(in); - exit(ret); - return (!ret); + return ret; } diff --git a/demos/bio/server-cmod.c b/demos/bio/server-cmod.c index 9cb24637..f1079ad3 100644 --- a/demos/bio/server-cmod.c +++ b/demos/bio/server-cmod.c @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2015-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 @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -25,7 +26,7 @@ int main(int argc, char *argv[]) BIO *in = NULL; BIO *ssl_bio, *tmp; SSL_CTX *ctx; - int ret = 1, i; + int ret = EXIT_FAILURE, i; ctx = SSL_CTX_new(TLS_server_method()); @@ -84,12 +85,10 @@ int main(int argc, char *argv[]) fflush(stdout); } - ret = 0; + ret = EXIT_SUCCESS; err: - if (ret) { + if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); - } BIO_free(in); - exit(ret); - return (!ret); + return ret; } diff --git a/demos/bio/server-conf.c b/demos/bio/server-conf.c index 41b13089..4d1655bf 100644 --- a/demos/bio/server-conf.c +++ b/demos/bio/server-conf.c @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. + * Copyright 2013-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 @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -32,7 +33,7 @@ int main(int argc, char *argv[]) CONF_VALUE *cnf; long errline = -1; char buf[512]; - int ret = 1, i; + int ret = EXIT_FAILURE, i; ctx = SSL_CTX_new(TLS_server_method()); @@ -129,12 +130,10 @@ int main(int argc, char *argv[]) fflush(stdout); } - ret = 0; + ret = EXIT_SUCCESS; err: - if (ret) { + if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); - } BIO_free(in); - exit(ret); - return (!ret); + return ret; } diff --git a/demos/engines/e_chil.txt b/demos/engines/e_chil.txt new file mode 100644 index 00000000..dc7076ba --- /dev/null +++ b/demos/engines/e_chil.txt @@ -0,0 +1,12 @@ +HWCRHK_F_BIND_HELPER 110 +HWCRHK_F_HWCRHK_CTRL 100 +HWCRHK_F_HWCRHK_FINISH 101 +HWCRHK_F_HWCRHK_GET_PASS 102 +HWCRHK_F_HWCRHK_INIT 103 +HWCRHK_F_HWCRHK_INSERT_CARD 104 +HWCRHK_F_HWCRHK_LOAD_PRIVKEY 105 +HWCRHK_F_HWCRHK_LOAD_PUBKEY 106 +HWCRHK_F_HWCRHK_MOD_EXP 107 +HWCRHK_F_HWCRHK_MUTEX_INIT 111 +HWCRHK_F_HWCRHK_RAND_BYTES 108 +HWCRHK_F_HWCRHK_RSA_MOD_EXP 109 diff --git a/demos/evp/Makefile b/demos/evp/Makefile index 72c6e81d..3a85b223 100644 --- a/demos/evp/Makefile +++ b/demos/evp/Makefile @@ -17,4 +17,4 @@ aesccm: aesccm.o aesgcm: aesgcm.o aesccm aesgcm: - $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $< + $(CC) $(CFLAGS) -o $@ $< $(LDFLAGS) diff --git a/demos/evp/aesgcm.c b/demos/evp/aesgcm.c index df59f469..46d9a563 100644 --- a/demos/evp/aesgcm.c +++ b/demos/evp/aesgcm.c @@ -102,7 +102,7 @@ void aes_gcm_decrypt(void) printf("Plaintext:\n"); BIO_dump_fp(stdout, outbuf, outlen); /* Set expected tag value. */ - EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(gcm_tag), + EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(gcm_tag), (void *)gcm_tag); /* Finalise: note get no output for GCM */ rv = EVP_DecryptFinal_ex(ctx, outbuf, &outlen); diff --git a/demos/pkcs12/README b/demos/pkcs12/README deleted file mode 100644 index c87434b0..00000000 --- a/demos/pkcs12/README +++ /dev/null @@ -1,3 +0,0 @@ -PKCS#12 demo applications - -Written by Steve Henson. diff --git a/demos/pkcs12/pkread.c b/demos/pkcs12/pkread.c index 3b87d7a4..3f7913b2 100644 --- a/demos/pkcs12/pkread.c +++ b/demos/pkcs12/pkread.c @@ -15,6 +15,36 @@ /* Simple PKCS#12 file reader */ +static char *find_friendly_name(PKCS12 *p12) +{ + STACK_OF(PKCS7) *safes = PKCS12_unpack_authsafes(p12); + int n, m; + char *name = NULL; + PKCS7 *safe; + STACK_OF(PKCS12_SAFEBAG) *bags; + PKCS12_SAFEBAG *bag; + + if ((safes = PKCS12_unpack_authsafes(p12)) == NULL) + return NULL; + + for (n = 0; n < sk_PKCS7_num(safes) && name == NULL; n++) { + safe = sk_PKCS7_value(safes, n); + if (OBJ_obj2nid(safe->type) != NID_pkcs7_data + || (bags = PKCS12_unpack_p7data(safe)) == NULL) + continue; + + for (m = 0; m < sk_PKCS12_SAFEBAG_num(bags) && name == NULL; m++) { + bag = sk_PKCS12_SAFEBAG_value(bags, m); + name = PKCS12_get_friendlyname(bag); + } + sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); + } + + sk_PKCS7_pop_free(safes, PKCS7_free); + + return name; +} + int main(int argc, char **argv) { FILE *fp; @@ -22,7 +52,9 @@ int main(int argc, char **argv) X509 *cert; STACK_OF(X509) *ca = NULL; PKCS12 *p12; + const char *name; int i; + if (argc != 4) { fprintf(stderr, "Usage: pkread p12file password opfile\n"); exit(1); @@ -45,11 +77,14 @@ int main(int argc, char **argv) ERR_print_errors_fp(stderr); exit(1); } + name = find_friendly_name(p12); PKCS12_free(p12); if ((fp = fopen(argv[3], "w")) == NULL) { fprintf(stderr, "Error opening file %s\n", argv[1]); exit(1); } + if (name) + fprintf(fp, "***Friendly Name***\n%s\n", name); if (pkey) { fprintf(fp, "***Private Key***\n"); PEM_write_PrivateKey(fp, pkey, NULL, NULL, 0, NULL, NULL); diff --git a/doc/HOWTO/certificates.txt b/doc/HOWTO/certificates.txt index 65f8fc82..c2efdca8 100644 --- a/doc/HOWTO/certificates.txt +++ b/doc/HOWTO/certificates.txt @@ -90,7 +90,7 @@ Your key most definitely is if you have followed the examples above. However, some (most?) certificate authorities will encode them with things like PKCS7 or PKCS12, or something else. Depending on your applications, this may be perfectly OK, it all depends on what they -know how to decode. If not, There are a number of OpenSSL tools to +know how to decode. If not, there are a number of OpenSSL tools to convert between some (most?) formats. So, depending on your application, you may have to convert your diff --git a/doc/HOWTO/proxy_certificates.txt b/doc/HOWTO/proxy_certificates.txt index 642bec92..18b3e034 100644 --- a/doc/HOWTO/proxy_certificates.txt +++ b/doc/HOWTO/proxy_certificates.txt @@ -18,7 +18,7 @@ rights to some other entity (a computer process, typically, or sometimes to the user itself). This allows the entity to perform operations on behalf of the owner of the EE certificate. -See http://www.ietf.org/rfc/rfc3820.txt for more information. +See https://www.ietf.org/rfc/rfc3820.txt for more information. 2. A warning about proxy certificates diff --git a/doc/README b/doc/README index cac4115f..964d8798 100644 --- a/doc/README +++ b/doc/README @@ -9,12 +9,19 @@ standards.txt HOWTO/ A few how-to documents; not necessarily up-to-date -apps/ + +man1/ The openssl command-line tools; start with openssl.pod -ssl/ - The SSL library; start with ssl.pod -crypto/ - The cryptographic library; start with crypto.pod + +man3/ + The SSL library and the crypto library + +man5/ + File formats + +man7/ + Overviews; start with crypto.pod and ssl.pod, for example + Algorithm specific EVP_PKEY documentation. Formatted versions of the manpages (apps,ssl,crypto) can be found at https://www.openssl.org/docs/manpages.html diff --git a/doc/apps/enc.pod b/doc/apps/enc.pod deleted file mode 100644 index 6338d6c8..00000000 --- a/doc/apps/enc.pod +++ /dev/null @@ -1,354 +0,0 @@ -=pod - -=head1 NAME - -openssl-enc, -enc - symmetric cipher routines - -=head1 SYNOPSIS - -B -[B<-help>] -[B<-ciphers>] -[B<-in filename>] -[B<-out filename>] -[B<-pass arg>] -[B<-e>] -[B<-d>] -[B<-a/-base64>] -[B<-A>] -[B<-k password>] -[B<-kfile filename>] -[B<-K key>] -[B<-iv IV>] -[B<-S salt>] -[B<-salt>] -[B<-nosalt>] -[B<-z>] -[B<-md digest>] -[B<-p>] -[B<-P>] -[B<-bufsize number>] -[B<-nopad>] -[B<-debug>] -[B<-none>] -[B<-engine id>] - -=head1 DESCRIPTION - -The symmetric cipher commands allow data to be encrypted or decrypted -using various block and stream ciphers using keys based on passwords -or explicitly provided. Base64 encoding or decoding can also be performed -either by itself or in addition to the encryption or decryption. - -=head1 OPTIONS - -=over 4 - -=item B<-help> - -Print out a usage message. - -=item B<-ciphers> - -List all supported ciphers. - -=item B<-in filename> - -the input filename, standard input by default. - -=item B<-out filename> - -the output filename, standard output by default. - -=item B<-pass arg> - -the password source. For more information about the format of B -see the B section in L. - -=item B<-e> - -encrypt the input data: this is the default. - -=item B<-d> - -decrypt the input data. - -=item B<-a> - -base64 process the data. This means that if encryption is taking place -the data is base64 encoded after encryption. If decryption is set then -the input data is base64 decoded before being decrypted. - -=item B<-base64> - -same as B<-a> - -=item B<-A> - -if the B<-a> option is set then base64 process the data on one line. - -=item B<-k password> - -the password to derive the key from. This is for compatibility with previous -versions of OpenSSL. Superseded by the B<-pass> argument. - -=item B<-kfile filename> - -read the password to derive the key from the first line of B. -This is for compatibility with previous versions of OpenSSL. Superseded by -the B<-pass> argument. - -=item B<-md digest> - -Use the specified digest to create the key from the passphrase. -The default algorithm is sha-256. - -=item B<-nosalt> - -don't use a salt in the key derivation routines. This option B be -used except for test purposes or compatibility with ancient versions of -OpenSSL. - -=item B<-salt> - -use salt (randomly generated or provide with B<-S> option) when -encrypting (this is the default). - -=item B<-S salt> - -the actual salt to use: this must be represented as a string of hex digits. - -=item B<-K key> - -the actual key to use: this must be represented as a string comprised only -of hex digits. If only the key is specified, the IV must additionally specified -using the B<-iv> option. When both a key and a password are specified, the -key given with the B<-K> option will be used and the IV generated from the -password will be taken. It probably does not make much sense to specify -both key and password. - -=item B<-iv IV> - -the actual IV to use: this must be represented as a string comprised only -of hex digits. When only the key is specified using the B<-K> option, the -IV must explicitly be defined. When a password is being specified using -one of the other options, the IV is generated from this password. - -=item B<-p> - -print out the key and IV used. - -=item B<-P> - -print out the key and IV used then immediately exit: don't do any encryption -or decryption. - -=item B<-bufsize number> - -set the buffer size for I/O - -=item B<-nopad> - -disable standard block padding - -=item B<-debug> - -debug the BIOs used for I/O. - -=item B<-z> - -Compress or decompress clear text using zlib before encryption or after -decryption. This option exists only if OpenSSL with compiled with zlib -or zlib-dynamic option. - -=item B<-none> - -Use NULL cipher (no encryption or decryption of input). - -=back - -=head1 NOTES - -The program can be called either as B or -B. But the first form doesn't work with -engine-provided ciphers, because this form is processed before the -configuration file is read and any ENGINEs loaded. - -Engines which provide entirely new encryption algorithms (such as ccgost -engine which provides gost89 algorithm) should be configured in the -configuration file. Engines, specified in the command line using -engine -options can only be used for hardware-assisted implementations of -ciphers, which are supported by OpenSSL core or other engine, specified -in the configuration file. - -When enc command lists supported ciphers, ciphers provided by engines, -specified in the configuration files are listed too. - -A password will be prompted for to derive the key and IV if necessary. - -The B<-salt> option should B be used if the key is being derived -from a password unless you want compatibility with previous versions of -OpenSSL. - -Without the B<-salt> option it is possible to perform efficient dictionary -attacks on the password and to attack stream cipher encrypted data. The reason -for this is that without the salt the same password always generates the same -encryption key. When the salt is being used the first eight bytes of the -encrypted data are reserved for the salt: it is generated at random when -encrypting a file and read from the encrypted file when it is decrypted. - -Some of the ciphers do not have large keys and others have security -implications if not used correctly. A beginner is advised to just use -a strong block cipher in CBC mode such as bf or des3. - -All the block ciphers normally use PKCS#5 padding also known as standard block -padding: this allows a rudimentary integrity or password check to be -performed. However since the chance of random data passing the test is -better than 1 in 256 it isn't a very good test. - -If padding is disabled then the input data must be a multiple of the cipher -block length. - -All RC2 ciphers have the same key and effective key length. - -Blowfish and RC5 algorithms use a 128 bit key. - -=head1 SUPPORTED CIPHERS - -Note that some of these ciphers can be disabled at compile time -and some are available only if an appropriate engine is configured -in the configuration file. The output of the B command run with -unsupported options (for example B) includes a -list of ciphers, supported by your version of OpenSSL, including -ones provided by configured engines. - -The B program does not support authenticated encryption modes -like CCM and GCM. The utility does not store or retrieve the -authentication tag. - - - base64 Base 64 - - bf-cbc Blowfish in CBC mode - bf Alias for bf-cbc - bf-cfb Blowfish in CFB mode - bf-ecb Blowfish in ECB mode - bf-ofb Blowfish in OFB mode - - cast-cbc CAST in CBC mode - cast Alias for cast-cbc - cast5-cbc CAST5 in CBC mode - cast5-cfb CAST5 in CFB mode - cast5-ecb CAST5 in ECB mode - cast5-ofb CAST5 in OFB mode - - des-cbc DES in CBC mode - des Alias for des-cbc - des-cfb DES in CBC mode - des-ofb DES in OFB mode - des-ecb DES in ECB mode - - des-ede-cbc Two key triple DES EDE in CBC mode - des-ede Two key triple DES EDE in ECB mode - des-ede-cfb Two key triple DES EDE in CFB mode - des-ede-ofb Two key triple DES EDE in OFB mode - - des-ede3-cbc Three key triple DES EDE in CBC mode - des-ede3 Three key triple DES EDE in ECB mode - des3 Alias for des-ede3-cbc - des-ede3-cfb Three key triple DES EDE CFB mode - des-ede3-ofb Three key triple DES EDE in OFB mode - - desx DESX algorithm. - - gost89 GOST 28147-89 in CFB mode (provided by ccgost engine) - gost89-cnt `GOST 28147-89 in CNT mode (provided by ccgost engine) - - idea-cbc IDEA algorithm in CBC mode - idea same as idea-cbc - idea-cfb IDEA in CFB mode - idea-ecb IDEA in ECB mode - idea-ofb IDEA in OFB mode - - rc2-cbc 128 bit RC2 in CBC mode - rc2 Alias for rc2-cbc - rc2-cfb 128 bit RC2 in CFB mode - rc2-ecb 128 bit RC2 in ECB mode - rc2-ofb 128 bit RC2 in OFB mode - rc2-64-cbc 64 bit RC2 in CBC mode - rc2-40-cbc 40 bit RC2 in CBC mode - - rc4 128 bit RC4 - rc4-64 64 bit RC4 - rc4-40 40 bit RC4 - - rc5-cbc RC5 cipher in CBC mode - rc5 Alias for rc5-cbc - rc5-cfb RC5 cipher in CFB mode - rc5-ecb RC5 cipher in ECB mode - rc5-ofb RC5 cipher in OFB mode - - aes-[128|192|256]-cbc 128/192/256 bit AES in CBC mode - aes[128|192|256] Alias for aes-[128|192|256]-cbc - aes-[128|192|256]-cfb 128/192/256 bit AES in 128 bit CFB mode - aes-[128|192|256]-cfb1 128/192/256 bit AES in 1 bit CFB mode - aes-[128|192|256]-cfb8 128/192/256 bit AES in 8 bit CFB mode - aes-[128|192|256]-ecb 128/192/256 bit AES in ECB mode - aes-[128|192|256]-ofb 128/192/256 bit AES in OFB mode - -=head1 EXAMPLES - -Just base64 encode a binary file: - - openssl base64 -in file.bin -out file.b64 - -Decode the same file - - openssl base64 -d -in file.b64 -out file.bin - -Encrypt a file using triple DES in CBC mode using a prompted password: - - openssl des3 -salt -in file.txt -out file.des3 - -Decrypt a file using a supplied password: - - openssl des3 -d -salt -in file.des3 -out file.txt -k mypassword - -Encrypt a file then base64 encode it (so it can be sent via mail for example) -using Blowfish in CBC mode: - - openssl bf -a -salt -in file.txt -out file.bf - -Base64 decode a file then decrypt it: - - openssl bf -d -salt -a -in file.bf -out file.txt - -Decrypt some data using a supplied 40 bit RC4 key: - - openssl rc4-40 -in file.rc4 -out file.txt -K 0102030405 - -=head1 BUGS - -The B<-A> option when used with large files doesn't work properly. - -There should be an option to allow an iteration count to be included. - -The B program only supports a fixed number of algorithms with -certain parameters. So if, for example, you want to use RC2 with a -76 bit key or RC4 with an 84 bit key you can't use this program. - -=head1 HISTORY - -The default digest was changed from MD5 to SHA256 in Openssl 1.1. - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/apps/genrsa.pod b/doc/apps/genrsa.pod deleted file mode 100644 index 8be06834..00000000 --- a/doc/apps/genrsa.pod +++ /dev/null @@ -1,119 +0,0 @@ -=pod - -=head1 NAME - -openssl-genrsa, -genrsa - generate an RSA private key - -=head1 SYNOPSIS - -B B -[B<-help>] -[B<-out filename>] -[B<-passout arg>] -[B<-aes128>] -[B<-aes192>] -[B<-aes256>] -[B<-aria128>] -[B<-aria192>] -[B<-aria256>] -[B<-camellia128>] -[B<-camellia192>] -[B<-camellia256>] -[B<-des>] -[B<-des3>] -[B<-idea>] -[B<-f4>] -[B<-3>] -[B<-rand file(s)>] -[B<-engine id>] -[B] - -=head1 DESCRIPTION - -The B command generates an RSA private key. - -=head1 OPTIONS - -=over 4 - -=item B<-help> - -Print out a usage message. - -=item B<-out filename> - -Output the key to the specified file. If this argument is not specified then -standard output is used. - -=item B<-passout arg> - -the output file password source. For more information about the format of B -see the B section in L. - -=item B<-aes128|-aes192|-aes256|-aria128|-aria192|-aria256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea> - -These options encrypt the private key with specified -cipher before outputting it. If none of these options is -specified no encryption is used. If encryption is used a pass phrase is prompted -for if it is not supplied via the B<-passout> argument. - -=item B<-F4|-3> - -the public exponent to use, either 65537 or 3. The default is 65537. - -=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). -Multiple files can be specified separated by an 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 string) will cause B -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 - -the size of the private key to generate in bits. This must be the last option -specified. The default is 2048. - -=back - -=head1 NOTES - -RSA private key generation essentially involves the generation of two prime -numbers. When generating a private key various symbols will be output to -indicate the progress of the generation. A B<.> represents each number which -has passed an initial sieve test, B<+> means a number has passed a single -round of the Miller-Rabin primality test. A newline means that the number has -passed all the prime tests (the actual number depends on the key size). - -Because key generation is a random process the time taken to generate a key -may vary somewhat. - -=head1 BUGS - -A quirk of the prime generation algorithm is that it cannot generate small -primes. Therefore the number of bits should not be less that 64. For typical -private keys this will not matter because for security reasons they will -be much larger (typically 1024 bits). - -=head1 SEE ALSO - -L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/apps/passwd.pod b/doc/apps/passwd.pod deleted file mode 100644 index 46632014..00000000 --- a/doc/apps/passwd.pod +++ /dev/null @@ -1,97 +0,0 @@ -=pod - -=head1 NAME - -openssl-passwd, -passwd - compute password hashes - -=head1 SYNOPSIS - -B -[B<-help>] -[B<-crypt>] -[B<-1>] -[B<-apr1>] -[B<-salt> I] -[B<-in> I] -[B<-stdin>] -[B<-noverify>] -[B<-quiet>] -[B<-table>] -{I} - -=head1 DESCRIPTION - -The B command computes the hash of a password typed at -run-time or the hash of each password in a list. The password list is -taken from the named file for option B<-in file>, from stdin for -option B<-stdin>, or from the command line, or from the terminal otherwise. -The Unix standard algorithm B and the MD5-based BSD password -algorithm B<1> and its Apache variant B are available. - -=head1 OPTIONS - -=over 4 - -=item B<-help> - -Print out a usage message. - -=item B<-crypt> - -Use the B algorithm (default). - -=item B<-1> - -Use the MD5 based BSD password algorithm B<1>. - -=item B<-apr1> - -Use the B algorithm (Apache variant of the BSD algorithm). - -=item B<-salt> I - -Use the specified salt. -When reading a password from the terminal, this implies B<-noverify>. - -=item B<-in> I - -Read passwords from I. - -=item B<-stdin> - -Read passwords from B. - -=item B<-noverify> - -Don't verify when reading a password from the terminal. - -=item B<-quiet> - -Don't output warnings when passwords given at the command line are truncated. - -=item B<-table> - -In the output list, prepend the cleartext password and a TAB character -to each password hash. - -=back - -=head1 EXAMPLES - -B prints B. - -B prints B<$1$xxxxxxxx$UYCIxa628.9qXjpQCjM4a.>. - -B prints B<$apr1$xxxxxxxx$dxHfLAsjHkDRmG83UXe8K0>. - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/apps/pkeyutl.pod b/doc/apps/pkeyutl.pod deleted file mode 100644 index e72486de..00000000 --- a/doc/apps/pkeyutl.pod +++ /dev/null @@ -1,293 +0,0 @@ -=pod - -=head1 NAME - -openssl-pkeyutl, -pkeyutl - public key algorithm utility - -=head1 SYNOPSIS - -B B -[B<-help>] -[B<-in file>] -[B<-out file>] -[B<-sigfile file>] -[B<-inkey file>] -[B<-keyform PEM|DER|ENGINE>] -[B<-passin arg>] -[B<-peerkey file>] -[B<-peerform PEM|DER|ENGINE>] -[B<-pubin>] -[B<-certin>] -[B<-rev>] -[B<-sign>] -[B<-verify>] -[B<-verifyrecover>] -[B<-encrypt>] -[B<-decrypt>] -[B<-derive>] -[B<-kdf algorithm>] -[B<-kdflen length>] -[B<-pkeyopt opt:value>] -[B<-hexdump>] -[B<-asn1parse>] -[B<-engine id>] -[B<-engine_impl>] - -=head1 DESCRIPTION - -The B command can be used to perform public key operations using -any supported algorithm. - -=head1 OPTIONS - -=over 4 - -=item B<-help> - -Print out a usage message. - -=item B<-in filename> - -This specifies the input filename to read data from or standard input -if this option is not specified. - -=item B<-out filename> - -specifies the output filename to write to or standard output by -default. - -=item B<-sigfile file> - -Signature file, required for B operations only - -=item B<-inkey file> - -the input key file, by default it should be a private key. - -=item B<-keyform PEM|DER|ENGINE> - -the key format PEM, DER or ENGINE. Default is PEM. - -=item B<-passin arg> - -the input key password source. For more information about the format of B -see the B section in L. - - -=item B<-peerkey file> - -the peer key file, used by key derivation (agreement) operations. - -=item B<-peerform PEM|DER|ENGINE> - -the peer key format PEM, DER or ENGINE. Default is PEM. - -=item B<-pubin> - -the input file is a public key. - -=item B<-certin> - -the input is a certificate containing a public key. - -=item B<-rev> - -reverse the order of the input buffer. This is useful for some libraries -(such as CryptoAPI) which represent the buffer in little endian format. - -=item B<-sign> - -sign the input data and output the signed result. This requires -a private key. - -=item B<-verify> - -verify the input data against the signature file and indicate if the -verification succeeded or failed. - -=item B<-verifyrecover> - -verify the input data and output the recovered data. - -=item B<-encrypt> - -encrypt the input data using a public key. - -=item B<-decrypt> - -decrypt the input data using a private key. - -=item B<-derive> - -derive a shared secret using the peer key. - -=item B<-kdf algorithm> - -Use key derivation function B. The supported algorithms are -at present B and B. -Note: additional parameters and the KDF output length will normally have to be -set for this to work. -See L and L -for the supported string parameters of each algorithm. - -=item B<-kdflen length> - -Set the output length for KDF. - -=item B<-pkeyopt opt:value> - -Public key options specified as opt:value. See NOTES below for more details. - -=item B<-hexdump> - -hex dump the output data. - -=item B<-asn1parse> - -asn1parse the output data, this is useful when combined with the -B<-verifyrecover> option when an ASN1 structure is signed. - -=item B<-engine id> - -specifying an engine (by its unique B string) will cause B -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<-engine_impl> - -When used with the B<-engine> option, it specifies to also use -engine B for crypto operations. - -=back - -=head1 NOTES - -The operations and options supported vary according to the key algorithm -and its implementation. The OpenSSL operations and options are indicated below. - -Unless otherwise mentioned all algorithms support the B option -which specifies the digest in use for sign, verify and verifyrecover operations. -The value B should represent a digest name as used in the -EVP_get_digestbyname() function for example B. -This value is used only for sanity-checking the lengths of data passed in to -the B and for creating the structures that make up the signature -(e.g. B in RSASSA PKCS#1 v1.5 signatures). -In case of RSA, ECDSA and DSA signatures, this utility -will not perform hashing on input data but rather use the data directly as -input of signature algorithm. Depending on key type, signature type and mode -of padding, the maximum acceptable lengths of input data differ. In general, -with RSA the signed data can't be longer than the key modulus, in case of ECDSA -and DSA the data shouldn't be longer than field size, otherwise it will be -silently truncated to field size. - -In other words, if the value of digest is B the input should be 20 bytes -long binary encoding of SHA-1 hash function output. - -=head1 RSA ALGORITHM - -The RSA algorithm generally supports the encrypt, decrypt, sign, -verify and verifyrecover operations. However, some padding modes -support only a subset of these operations. The following additional -B values are supported: - -=over 4 - -=item B - -This sets the RSA padding mode. Acceptable values for B are B for -PKCS#1 padding, B for SSLv23 padding, B for no padding, B -for B mode, B for X9.31 mode and B for PSS. - -In PKCS#1 padding if the message digest is not set then the supplied data is -signed or verified directly instead of using a B structure. If a -digest is set then the a B structure is used and its the length -must correspond to the digest type. - -For B mode only encryption and decryption is supported. - -For B if the digest type is set it is used to format the block data -otherwise the first byte is used to specify the X9.31 digest ID. Sign, -verify and verifyrecover are can be performed in this mode. - -For B mode only sign and verify are supported and the digest type must be -specified. - -=item B - -For B mode only this option specifies the salt length. Two special values -are supported: -1 sets the salt length to the digest length. When signing -2 -sets the salt length to the maximum permissible value. When verifying -2 causes -the salt length to be automatically determined based on the B block -structure. - -=back - -=head1 DSA ALGORITHM - -The DSA algorithm supports signing and verification operations only. Currently -there are no additional options other than B. Only the SHA1 -digest can be used and this digest is assumed by default. - -=head1 DH ALGORITHM - -The DH algorithm only supports the derivation operation and no additional -options. - -=head1 EC ALGORITHM - -The EC algorithm supports sign, verify and derive operations. The sign and -verify operations use ECDSA and derive uses ECDH. Currently there are no -additional options other than B. Only the SHA1 digest can be used and -this digest is assumed by default. - -=head1 X25519 ALGORITHM - -The X25519 algorithm supports key derivation only. Currently there are no -additional options. - -=head1 EXAMPLES - -Sign some data using a private key: - - openssl pkeyutl -sign -in file -inkey key.pem -out sig - -Recover the signed data (e.g. if an RSA key is used): - - openssl pkeyutl -verifyrecover -in sig -inkey key.pem - -Verify the signature (e.g. a DSA key): - - openssl pkeyutl -verify -in file -sigfile sig -inkey key.pem - -Sign data using a message digest value (this is currently only valid for RSA): - - openssl pkeyutl -sign -in file -inkey key.pem -out sig -pkeyopt digest:sha256 - -Derive a shared secret value: - - openssl pkeyutl -derive -inkey key.pem -peerkey pubkey.pem -out secret - -Hexdump 48 bytes of TLS1 PRF using digest B and shared secret and -seed consisting of the single byte 0xFF: - - openssl pkeyutl -kdf TLS1-PRF -kdflen 48 -pkeyopt md:SHA256 \ - -pkeyopt hexsecret:ff -pkeyopt hexseed:ff -hexdump - -=head1 SEE ALSO - -L, L, L -L, L, L, -L, L - -=head1 COPYRIGHT - -Copyright 2006-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 -L. - -=cut diff --git a/doc/apps/s_client.pod b/doc/apps/s_client.pod deleted file mode 100644 index 01a6c5f7..00000000 --- a/doc/apps/s_client.pod +++ /dev/null @@ -1,619 +0,0 @@ -=pod - -=head1 NAME - -openssl-s_client, -s_client - SSL/TLS client program - -=head1 SYNOPSIS - -B B -[B<-help>] -[B<-connect host:port>] -[B<-proxy host:port>] -[B<-unix path>] -[B<-4>] -[B<-6>] -[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-CAfile>] -[B<-no-CApath>] -[B<-dane_tlsa_domain domain>] -[B<-dane_tlsa_rrdata rrdata>] -[B<-dane_ee_no_namechecks>] -[B<-attime timestamp>] -[B<-check_ss_sig>] -[B<-crl_check>] -[B<-crl_check_all>] -[B<-explicit_policy>] -[B<-extended_crl>] -[B<-ignore_critical>] -[B<-inhibit_any>] -[B<-inhibit_map>] -[B<-no_check_time>] -[B<-partial_chain>] -[B<-policy arg>] -[B<-policy_check>] -[B<-policy_print>] -[B<-purpose purpose>] -[B<-suiteB_128>] -[B<-suiteB_128_only>] -[B<-suiteB_192>] -[B<-trusted_first>] -[B<-no_alt_chains>] -[B<-use_deltas>] -[B<-auth_level num>] -[B<-verify_depth num>] -[B<-verify_email email>] -[B<-verify_hostname hostname>] -[B<-verify_ip ip>] -[B<-verify_name name>] -[B<-x509_strict>] -[B<-reconnect>] -[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<-ssl3>] -[B<-tls1>] -[B<-tls1_1>] -[B<-tls1_2>] -[B<-no_ssl3>] -[B<-no_tls1>] -[B<-no_tls1_1>] -[B<-no_tls1_2>] -[B<-dtls>] -[B<-dtls1>] -[B<-dtls1_2>] -[B<-fallback_scsv>] -[B<-async>] -[B<-split_send_frag>] -[B<-max_pipelines>] -[B<-read_buf>] -[B<-bugs>] -[B<-comp>] -[B<-no_comp>] -[B<-sigalgs sigalglist>] -[B<-curves curvelist>] -[B<-cipher cipherlist>] -[B<-serverpref>] -[B<-starttls protocol>] -[B<-xmpphost hostname>] -[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>] -[B<-ct|noct>] -[B<-ctlogfile>] - -=head1 DESCRIPTION - -The B command implements a generic SSL/TLS client which connects -to a remote host using SSL/TLS. It is a I useful diagnostic tool for -SSL servers. - -=head1 OPTIONS - -In addition to the options below the B utility also supports the -common and client only options documented in the -in the "Supported Command Line Commands" section of the L -manual page. - -=over 4 - -=item B<-help> - -Print out a usage message. - -=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<-proxy host:port> - -When used with the B<-connect> flag, the program uses the host and port -specified with this flag and issues an HTTP CONNECT command to connect -to the desired server. - -=item B<-unix path> - -Connect over the specified Unix-domain socket. - -=item B<-4> - -Use IPv4 only. - -=item B<-6> - -Use IPv6 only. - -=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 -see the B section in L. - -=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 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<-no-CAfile> - -Do not load the trusted CA certificates from the default file location - -=item B<-no-CApath> - -Do not load the trusted CA certificates from the default directory location - -=item B<-dane_tlsa_domain domain> - -Enable RFC6698/RFC7671 DANE TLSA authentication and specify the -TLSA base domain which becomes the default SNI hint and the primary -reference identifier for hostname checks. This must be used in -combination with at least one instance of the B<-dane_tlsa_rrdata> -option below. - -When DANE authentication succeeds, the diagnostic output will include -the lowest (closest to 0) depth at which a TLSA record authenticated -a chain certificate. When that TLSA record is a "2 1 0" trust -anchor public key that signed (rather than matched) the top-most -certificate of the chain, the result is reported as "TA public key -verified". Otherwise, either the TLSA record "matched TA certificate" -at a positive depth or else "matched EE certificate" at depth 0. - -=item B<-dane_tlsa_rrdata rrdata> - -Use one or more times to specify the RRDATA fields of the DANE TLSA -RRset associated with the target service. The B value is -specied in "presentation form", that is four whitespace separated -fields that specify the usage, selector, matching type and associated -data, with the last of these encoded in hexadecimal. Optional -whitespace is ignored in the associated data field. For example: - - $ openssl s_client -brief -starttls smtp \ - -connect smtp.example.com:25 \ - -dane_tlsa_domain smtp.example.com \ - -dane_tlsa_rrdata "2 1 1 - B111DD8A1C2091A89BD4FD60C57F0716CCE50FEEFF8137CDBEE0326E 02CF362B" \ - -dane_tlsa_rrdata "2 1 1 - 60B87575447DCBA2A36B7D11AC09FB24A9DB406FEE12D2CC90180517 616E8A18" - ... - Verification: OK - Verified peername: smtp.example.com - DANE TLSA 2 1 1 ...ee12d2cc90180517616e8a18 matched TA certificate at depth 1 - ... - -=item B<-dane_ee_no_namechecks> - -This disables server name checks when authenticating via DANE-EE(3) TLSA -records. -For some applications, primarily web browsers, it is not safe to disable name -checks due to "unknown key share" attacks, in which a malicious server can -convince a client that a connection to a victim server is instead a secure -connection to the malicious server. -The malicious server may then be able to violate cross-origin scripting -restrictions. -Thus, despite the text of RFC7671, name checks are by default enabled for -DANE-EE(3) TLSA records, and can be disabled in applications where it is safe -to do so. -In particular, SMTP and XMPP clients should set this option as SRV and MX -records already make it possible for a remote domain to redirect client -connections to any server of its choice, and in any case SMTP and XMPP clients -do not execute scripts downloaded from remote servers. - -=item B<-attime>, B<-check_ss_sig>, B<-crl_check>, B<-crl_check_all>, -B<-explicit_policy>, B<-extended_crl>, B<-ignore_critical>, B<-inhibit_any>, -B<-inhibit_map>, B<-no_alt_chains>, B<-no_check_time>, B<-partial_chain>, B<-policy>, -B<-policy_check>, B<-policy_print>, B<-purpose>, B<-suiteB_128>, -B<-suiteB_128_only>, B<-suiteB_192>, B<-trusted_first>, B<-use_deltas>, -B<-auth_level>, B<-verify_depth>, B<-verify_email>, B<-verify_hostname>, -B<-verify_ip>, B<-verify_name>, B<-x509_strict> - -Set various certificate chain validation options. See the -L 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<-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<-trace> - -show verbose trace output of protocol messages. OpenSSL needs to be compiled -with B for this option to work. - -=item B<-msgfile> - -file to send output of B<-msg> or B<-trace> to, default standard output. - -=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 when using a PSK cipher suite. -The default value is "Client_identity" (without the quotes). - -=item B<-psk key> - -Use the PSK key B 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<-ssl3>, B<-tls1>, B<-tls1_1>, B<-tls1_2>, 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 B will negotiate the highest mutually supported protocol -version. -When a specific TLS version is required, only that version will be offered to -and accepted from the server. - -=item B<-dtls>, B<-dtls1>, B<-dtls1_2> - -These options make B use DTLS protocols instead of TLS. -With B<-dtls>, B will negotiate any supported DTLS protocol version, -whilst B<-dtls1> and B<-dtls1_2> will only support DTLS1.0 and DTLS1.2 -respectively. - -=item B<-fallback_scsv> - -Send TLS_FALLBACK_SCSV in the ClientHello. - -=item B<-async> - -switch on asynchronous mode. Cryptographic operations will be performed -asynchronously. This will only have an effect if an asynchronous capable engine -is also used via the B<-engine> option. For test purposes the dummy async engine -(dasync) can be used (if available). - -=item B<-split_send_frag int> - -The size used to split data for encrypt pipelines. If more data is written in -one go than this value then it will be split into multiple pipelines, up to the -maximum number of pipelines defined by max_pipelines. This only has an effect if -a suitable ciphersuite has been negotiated, an engine that supports pipelining -has been loaded, and max_pipelines is greater than 1. See -L for further information. - -=item B<-max_pipelines int> - -The maximum number of encrypt/decrypt pipelines to be used. This will only have -an effect if an engine has been loaded that supports pipelining (e.g. the dasync -engine) and a suitable ciphersuite has been negotiated. The default value is 1. -See L for further information. - -=item B<-read_buf int> - -The default read buffer size to be used for connections. This will only have an -effect if the buffer size is larger than the size that would otherwise be used -and pipelining is in use (see L for -further information). - -=item B<-bugs> - -there are several known bug in SSL and TLS implementations. Adding this -option enables various workarounds. - -=item B<-comp> - -Enables support for SSL/TLS compression. -This option was introduced in OpenSSL 1.1.0. -TLS compression is not recommended and is off by default as of -OpenSSL 1.1.0. - -=item B<-no_comp> - -Disables support for SSL/TLS compression. -TLS compression is not recommended and is off by default as of -OpenSSL 1.1.0. - -=item B<-brief> - -only provide a brief summary of connection parameters instead of the -normal verbose output. - -=item B<-sigalgs 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 - -=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 -command for more information. - -=item B<-starttls protocol> - -send the protocol-specific message(s) to switch to TLS for communication. -B is a keyword for the intended protocol. Currently, the only -supported keywords are "smtp", "pop3", "imap", "ftp", "xmpp", "xmpp-server", -and "irc." - -=item B<-xmpphost hostname> - -This option, when used with "-starttls xmpp" or "-starttls xmpp-server", -specifies the host for the "to" attribute of the stream element. -If this option is not specified, then the host specified with "-connect" -will be used. - -=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 - -=item B<-sess_in sess.pem> - -load SSL session from B. The client will attempt to resume a -connection from this session. - -=item B<-engine id> - -specifying an engine (by its unique B string) will cause B -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). -Multiple files can be specified separated by an 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 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 -receiving ServerHello with a list of server supported protocols. - -=item B<-ct|noct> - -Use one of these two options to control whether Certificate Transparency (CT) -is enabled (B<-ct>) or disabled (B<-noct>). -If CT is enabled, signed certificate timestamps (SCTs) will be requested from -the server and reported at handshake completion. - -Enabling CT also enables OCSP stapling, as this is one possible delivery method -for SCTs. - -=item B<-ctlogfile> - -A file containing a list of known Certificate Transparency logs. See -L for the expected file format. - -=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, and if the line begins with a B or if end of file is reached, the -connection will be closed down. - -=head1 NOTES - -B can be used to debug SSL servers. To connect to an SSL HTTP -server the command: - - openssl s_client -connect servername:443 - -would typically be used (https uses port 443). If the connection succeeds -then an HTTP command can be given such as "GET /" to retrieve a web page. - -If the handshake fails then there are several possible causes, if it is -nothing obvious like no client certificate then the B<-bugs>, -B<-ssl3>, B<-tls1>, B<-no_ssl3>, B<-no_tls1> options can be tried -in case it is a buggy server. In particular you should play with these -options B 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 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. - -The B 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 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 B 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, -L, L, L - -=head1 HISTORY - -The -no_alt_chains options was first added to OpenSSL 1.1.0. - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/apps/s_server.pod b/doc/apps/s_server.pod deleted file mode 100644 index e8ec91b4..00000000 --- a/doc/apps/s_server.pod +++ /dev/null @@ -1,616 +0,0 @@ -=pod - -=head1 NAME - -openssl-s_server, -s_server - SSL/TLS server program - -=head1 SYNOPSIS - -B B -[B<-help>] -[B<-port port>] -[B<-accept val>] -[B<-naccept count>] -[B<-unix val>] -[B<-unlink>] -[B<-4>] -[B<-6>] -[B<-context id>] -[B<-verify depth>] -[B<-Verify depth>] -[B<-crl_check>] -[B<-crl_check_all>] -[B<-cert filename>] -[B<-certform DER|PEM>] -[B<-key keyfile>] -[B<-keyform DER|PEM>] -[B<-pass arg>] -[B<-dcert filename>] -[B<-dcertform DER|PEM>] -[B<-dkey keyfile>] -[B<-dkeyform DER|PEM>] -[B<-dpass arg>] -[B<-dhparam filename>] -[B<-nbio>] -[B<-nbio_test>] -[B<-crlf>] -[B<-debug>] -[B<-msg>] -[B<-state>] -[B<-CApath directory>] -[B<-CAfile filename>] -[B<-no-CAfile>] -[B<-no-CApath>] -[B<-attime timestamp>] -[B<-check_ss_sig>] -[B<-explicit_policy>] -[B<-extended_crl>] -[B<-ignore_critical>] -[B<-inhibit_any>] -[B<-inhibit_map>] -[B<-no_check_time>] -[B<-partial_chain>] -[B<-policy arg>] -[B<-policy_check>] -[B<-policy_print>] -[B<-purpose purpose>] -[B<-suiteB_128>] -[B<-suiteB_128_only>] -[B<-suiteB_192>] -[B<-trusted_first>] -[B<-no_alt_chains>] -[B<-use_deltas>] -[B<-auth_level num>] -[B<-verify_depth num>] -[B<-verify_return_error>] -[B<-verify_email email>] -[B<-verify_hostname hostname>] -[B<-verify_ip ip>] -[B<-verify_name name>] -[B<-x509_strict>] -[B<-nocert>] -[B<-client_sigalgs sigalglist>] -[B<-named_curve curve>] -[B<-cipher cipherlist>] -[B<-serverpref>] -[B<-quiet>] -[B<-ssl3>] -[B<-tls1>] -[B<-tls1_1>] -[B<-tls1_2>] -[B<-dtls>] -[B<-dtls1>] -[B<-dtls1_2>] -[B<-listen>] -[B<-async>] -[B<-split_send_frag>] -[B<-max_pipelines>] -[B<-read_buf>] -[B<-no_ssl3>] -[B<-no_tls1>] -[B<-no_tls1_1>] -[B<-no_tls1_2>] -[B<-no_dhe>] -[B<-bugs>] -[B<-comp>] -[B<-no_comp>] -[B<-brief>] -[B<-www>] -[B<-WWW>] -[B<-HTTP>] -[B<-engine id>] -[B<-tlsextdebug>] -[B<-no_ticket>] -[B<-id_prefix arg>] -[B<-rand file(s)>] -[B<-serverinfo file>] -[B<-no_resumption_on_reneg>] -[B<-status>] -[B<-status_verbose>] -[B<-status_timeout nsec>] -[B<-status_url url>] -[B<-alpn protocols>] -[B<-nextprotoneg protocols>] - -=head1 DESCRIPTION - -The B command implements a generic SSL/TLS server which listens -for connections on a given port using SSL/TLS. - -=head1 OPTIONS - -In addition to the options below the B utility also supports the -common and server only options documented in the -in the "Supported Command Line Commands" section of the L -manual page. - -=over 4 - -=item B<-help> - -Print out a usage message. - -=item B<-port port> - -The TCP port to listen on for connections. If not specified 4433 is used. - -=item B<-accept val> - -The optional TCP host and port to listen on for connections. If not specified, *:4433 is used. - -=item B<-naccept count> - -The server will exit after receiving B connections, default unlimited. - -=item B<-unix val> - -Unix domain socket to accept on. - -=item B<-unlink> - -For -unix, unlink existing socket first. - -=item B<-4> - -Use IPv4 only. - -=item B<-6> - -Use IPv6 only. - -=item B<-context id> - -Sets the SSL context id. It can be given any string value. If this option -is not present a default value will be used. - -=item B<-cert certname> - -The certificate to use, most servers cipher suites require the use of a -certificate and some require a certificate with a certain public key type: -for example the DSS cipher suites require a certificate containing a DSS -(DSA) key. If not specified then the filename "server.pem" will be used. - -=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 -see the B section in L. - -=item B<-dcert filename>, B<-dkey keyname> - -Specify an additional certificate and private key, these behave in the -same manner as the B<-cert> and B<-key> options except there is no default -if they are not specified (no additional certificate and key is used). As -noted above some cipher suites require a certificate containing a key of -a certain type. Some cipher suites need a certificate carrying an RSA key -and some a DSS (DSA) key. By using RSA and DSS certificates and keys -a server can support clients which only support RSA or DSS cipher suites -by using an appropriate certificate. - -=item B<-dcertform format>, B<-dkeyform format>, B<-dpass arg> - -Additional certificate and private key format and passphrase respectively. - -=item B<-nocert> - -If this option is set then no certificate is used. This restricts the -cipher suites available to the anonymous ones (currently just anonymous -DH). - -=item B<-dhparam filename> - -The DH parameter file to use. The ephemeral DH cipher suites generate keys -using a set of DH parameters. If not specified then an attempt is made to -load the parameters from the server certificate file. -If this fails then a static set of parameters hard coded into the B -program will be used. - -=item B<-no_dhe> - -If this option is set then no DH parameters will be loaded effectively -disabling the ephemeral DH cipher suites. - -=item B<-crl_check>, B<-crl_check_all> - -Check the peer certificate has not been revoked by its CA. -The CRL(s) are appended to the certificate file. With the B<-crl_check_all> -option all CRLs of all CAs in the chain are checked. - -=item B<-CApath directory> - -The directory to use for client certificate verification. This directory -must be in "hash format", see B for more information. These are -also used when building the server certificate chain. - -=item B<-CAfile file> - -A file containing trusted certificates to use during client authentication -and to use when attempting to build the server certificate chain. The list -is also used in the list of acceptable client CAs passed to the client when -a certificate is requested. - -=item B<-no-CAfile> - -Do not load the trusted CA certificates from the default file location - -=item B<-no-CApath> - -Do not load the trusted CA certificates from the default directory location - -=item B<-verify depth>, B<-Verify depth> - -The verify depth to use. This specifies the maximum length of the -client certificate chain and makes the server request a certificate from -the client. With the B<-verify> option a certificate is requested but the -client does not have to send one, with the B<-Verify> option the client -must supply a certificate or an error occurs. - -If the ciphersuite cannot request a client certificate (for example an -anonymous ciphersuite or PSK) this option has no effect. - -=item B<-attime>, B<-check_ss_sig>, B<-crl_check>, B<-crl_check_all>, -B<-explicit_policy>, B<-extended_crl>, B<-ignore_critical>, B<-inhibit_any>, -B<-inhibit_map>, B<-no_alt_chains>, B<-no_check_time>, B<-partial_chain>, B<-policy>, -B<-policy_check>, B<-policy_print>, B<-purpose>, B<-suiteB_128>, -B<-suiteB_128_only>, B<-suiteB_192>, B<-trusted_first>, B<-use_deltas>, -B<-auth_level>, B<-verify_depth>, B<-verify_email>, B<-verify_hostname>, -B<-verify_ip>, B<-verify_name>, B<-x509_strict> - -Set different peer certificate verification options. -See the L manual page for details. - -=item B<-verify_return_error> - -Verification errors normally just print a message but allow the -connection to continue, for debugging purposes. -If this option is used, then verification errors close the connection. - -=item B<-state> - -Prints 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<-trace> - -Show verbose trace output of protocol messages. OpenSSL needs to be compiled -with B for this option to work. - -=item B<-msgfile> - -File to send output of B<-msg> or B<-trace> to, default standard output. - -=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. - -=item B<-quiet> - -Inhibit printing of session and certificate information. - -=item B<-psk_hint hint> - -Use the PSK identity hint B when using a PSK cipher suite. - -=item B<-psk key> - -Use the PSK key B 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 B will negotiate the highest mutually supported protocol -version. -When a specific TLS version is required, only that version will be accepted -from the client. - -=item B<-dtls>, B<-dtls1>, B<-dtls1_2> - -These options make B use DTLS protocols instead of TLS. -With B<-dtls>, B will negotiate any supported DTLS protocol version, -whilst B<-dtls1> and B<-dtls1_2> will only support DTLSv1.0 and DTLSv1.2 -respectively. - -=item B<-listen> - -This option can only be used in conjunction with one of the DTLS options above. -With this option B will listen on a UDP port for incoming connections. -Any ClientHellos that arrive will be checked to see if they have a cookie in -them or not. -Any without a cookie will be responded to with a HelloVerifyRequest. -If a ClientHello with a cookie is received then B will connect to -that peer and complete the handshake. - -=item B<-async> - -Switch on asynchronous mode. Cryptographic operations will be performed -asynchronously. This will only have an effect if an asynchronous capable engine -is also used via the B<-engine> option. For test purposes the dummy async engine -(dasync) can be used (if available). - -=item B<-split_send_frag int> - -The size used to split data for encrypt pipelines. If more data is written in -one go than this value then it will be split into multiple pipelines, up to the -maximum number of pipelines defined by max_pipelines. This only has an effect if -a suitable ciphersuite has been negotiated, an engine that supports pipelining -has been loaded, and max_pipelines is greater than 1. See -L for further information. - -=item B<-max_pipelines int> - -The maximum number of encrypt/decrypt pipelines to be used. This will only have -an effect if an engine has been loaded that supports pipelining (e.g. the dasync -engine) and a suitable ciphersuite has been negotiated. The default value is 1. -See L for further information. - -=item B<-read_buf int> - -The default read buffer size to be used for connections. This will only have an -effect if the buffer size is larger than the size that would otherwise be used -and pipelining is in use (see L for -further information). - -=item B<-bugs> - -There are several known bug in SSL and TLS implementations. Adding this -option enables various workarounds. - -=item B<-comp> - -Enable negotiation of TLS compression. -This option was introduced in OpenSSL 1.1.0. -TLS compression is not recommended and is off by default as of -OpenSSL 1.1.0. - -=item B<-no_comp> - -Disable negotiation of TLS compression. -TLS compression is not recommended and is off by default as of -OpenSSL 1.1.0. - -=item B<-brief> - -Provide a brief summary of connection parameters instead of the normal verbose -output. - -=item B<-client_sigalgs sigalglist> - -Signature algorithms to support for client certificate authentication -(colon-separated list) - -=item B<-named_curve curve> - -Specifies the elliptic curve to use. NOTE: this is single curve, not a list. -For a list of all possible curves, use: - - $ openssl ecparam -list_curves - -=item B<-cipher cipherlist> - -This allows the cipher list used by the server to be modified. When -the client sends a list of supported ciphers the first client cipher -also included in the server list is used. Because the client specifies -the preference order, the order of the server cipherlist irrelevant. See -the B command for more information. - -=item B<-serverpref> - -Use the server's cipher preferences, rather than the client's preferences. - -=item B<-tlsextdebug> - -Print a hex dump of any TLS extensions received from the server. - -=item B<-no_ticket> - -Disable RFC4507bis session ticket support. - -=item B<-www> - -Sends a status message back to the client when it connects. This includes -information about the ciphers used and various session parameters. -The output is in HTML format so this option will normally be used with a -web browser. - -=item B<-WWW> - -Emulates a simple web server. Pages will be resolved relative to the -current directory, for example if the URL https://myhost/page.html is -requested the file ./page.html will be loaded. - -=item B<-HTTP> - -Emulates a simple web server. Pages will be resolved relative to the -current directory, for example if the URL https://myhost/page.html is -requested the file ./page.html will be loaded. The files loaded are -assumed to contain a complete and correct HTTP response (lines that -are part of the HTTP response line and headers must end with CRLF). - -=item B<-rev> - -Simple test server which just reverses the text received from the client -and sends it back to the server. Also sets B<-brief>. - -=item B<-engine id> - -Specifying an engine (by its unique B string) will cause B -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<-id_prefix arg> - -Generate SSL/TLS session IDs prefixed by B. This is mostly useful -for testing any SSL/TLS code (eg. proxies) that wish to deal with multiple -servers, when each of which might be generating a unique range of session -IDs (eg. with a certain prefix). - -=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). -Multiple files can be specified separated by an OS-dependent character. -The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for -all others. - -=item B<-serverinfo file> - -A file containing one or more blocks of PEM data. Each PEM block -must encode a TLS ServerHello extension (2 bytes type, 2 bytes length, -followed by "length" bytes of extension data). If the client sends -an empty TLS ClientHello extension matching the type, the corresponding -ServerHello extension will be returned. - -=item B<-no_resumption_on_reneg> - -Set the B option. - -=item B<-status> - -Enables certificate status request support (aka OCSP stapling). - -=item B<-status_verbose> - -Enables certificate status request support (aka OCSP stapling) and gives -a verbose printout of the OCSP response. - -=item B<-status_timeout nsec> - -Sets the timeout for OCSP response to B seconds. - -=item B<-status_url url> - -Sets a fallback responder URL to use if no responder URL is present in the -server certificate. Without this option an error is returned if the server -certificate does not contain a responder address. - -=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 list is a -comma-separated list of supported protocol names. -The list should contain most wanted protocols first. -Protocol names are printable ASCII strings, for example "http/1.1" or -"spdy/3". - -=back - -=head1 CONNECTED COMMANDS - -If a connection request is established with an SSL client and neither the -B<-www> nor the B<-WWW> option has been used then normally any data received -from the client is displayed and any key presses will be sent to the client. - -Certain single letter commands are also recognized which perform special -operations: these are listed below. - -=over 4 - -=item B - -end the current SSL connection but still accept new connections. - -=item B - -end the current SSL connection and exit. - -=item B - -renegotiate the SSL session. - -=item B - -renegotiate the SSL session and request a client certificate. - -=item B

- -send some plain text down the underlying TCP connection: this should -cause the client to disconnect due to a protocol violation. - -=item B - -print out some session cache status information. - -=back - -=head1 NOTES - -B can be used to debug SSL clients. To accept connections from -a web browser the command: - - openssl s_server -accept 443 -www - -can be used for example. - -Although specifying an empty list of CAs when requesting a client certificate -is strictly speaking a protocol violation, some SSL clients interpret this to -mean any CA is acceptable. This is useful for debugging purposes. - -The session parameters can printed out using the B program. - -=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 B is rather hard to -read and not a model of how things should be done. -A typical SSL server program would be much simpler. - -The output of common ciphers is wrong: it just gives the list of ciphers that -OpenSSL recognizes and the client supports. - -There should be a way for the B program to print out details of any -unknown cipher suites a client says it supports. - -=head1 SEE ALSO - -L, -L, L, L - -=head1 HISTORY - -The -no_alt_chains options was first added to OpenSSL 1.1.0. - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/apps/sess_id.pod b/doc/apps/sess_id.pod deleted file mode 100644 index 7766c71e..00000000 --- a/doc/apps/sess_id.pod +++ /dev/null @@ -1,164 +0,0 @@ -=pod - -=head1 NAME - -openssl-sess_id, -sess_id - SSL/TLS session handling utility - -=head1 SYNOPSIS - -B B -[B<-help>] -[B<-inform PEM|DER>] -[B<-outform PEM|DER|NSS>] -[B<-in filename>] -[B<-out filename>] -[B<-text>] -[B<-noout>] -[B<-context ID>] - -=head1 DESCRIPTION - -The B process the encoded version of the SSL session structure -and optionally prints out SSL session details (for example the SSL session -master key) in human readable format. Since this is a diagnostic tool that -needs some knowledge of the SSL protocol to use properly, most users will -not need to use it. - -=head1 OPTIONS - -=over 4 - -=item B<-help> - -Print out a usage message. - -=item B<-inform DER|PEM> - -This specifies the input format. The B option uses an ASN1 DER encoded -format containing session details. The precise format can vary from one version -to the next. The B form is the default format: it consists of the B -format base64 encoded with additional header and footer lines. - -=item B<-outform DER|PEM|NSS> - -This specifies the output format. The B and B options have the same meaning -as the B<-inform> option. The B option outputs the session id and the master key -in NSS keylog format. - -=item B<-in filename> - -This specifies the input filename to read session information from or standard -input by default. - -=item B<-out filename> - -This specifies the output filename to write session information to or standard -output if this option is not specified. - -=item B<-text> - -prints out the various public or private key components in -plain text in addition to the encoded version. - -=item B<-cert> - -if a certificate is present in the session it will be output using this option, -if the B<-text> option is also present then it will be printed out in text form. - -=item B<-noout> - -this option prevents output of the encoded version of the session. - -=item B<-context ID> - -this option can set the session id so the output session information uses the -supplied ID. The ID can be any string of characters. This option won't normally -be used. - -=back - -=head1 OUTPUT - -Typical output: - - SSL-Session: - Protocol : TLSv1 - Cipher : 0016 - Session-ID: 871E62626C554CE95488823752CBD5F3673A3EF3DCE9C67BD916C809914B40ED - Session-ID-ctx: 01000000 - Master-Key: A7CEFC571974BE02CAC305269DC59F76EA9F0B180CB6642697A68251F2D2BB57E51DBBB4C7885573192AE9AEE220FACD - Key-Arg : None - Start Time: 948459261 - Timeout : 300 (sec) - Verify return code 0 (ok) - -Theses are described below in more detail. - -=over 4 - -=item B - -this is the protocol in use TLSv1.2, TLSv1.1, TLSv1 or SSLv3. - -=item B - -the cipher used this is the actual raw SSL or TLS cipher code, see the SSL -or TLS specifications for more information. - -=item B - -the SSL session ID in hex format. - -=item B - -the session ID context in hex format. - -=item B - -this is the SSL session master key. - -=item B - -this is the session start time represented as an integer in standard Unix format. - -=item B - -the timeout in seconds. - -=item B - -this is the return code when an SSL client certificate is verified. - -=back - -=head1 NOTES - -The PEM encoded session format uses the header and footer lines: - - -----BEGIN SSL SESSION PARAMETERS----- - -----END SSL SESSION PARAMETERS----- - -Since the SSL session output contains the master key it is possible to read the contents -of an encrypted session using this information. Therefore appropriate security precautions -should be taken if the information is being output by a "real" application. This is -however strongly discouraged and should only be used for debugging purposes. - -=head1 BUGS - -The cipher and start time should be printed out in human readable form. - -=head1 SEE ALSO - -L, L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/apps/speed.pod b/doc/apps/speed.pod deleted file mode 100644 index 4379319d..00000000 --- a/doc/apps/speed.pod +++ /dev/null @@ -1,68 +0,0 @@ -=pod - -=head1 NAME - -openssl-speed, -speed - test library performance - -=head1 SYNOPSIS - -B -[B<-help>] -[B<-engine id>] -[B<-elapsed>] -[B<-evp algo>] -[B<-decrypt>] -[B] - -=head1 DESCRIPTION - -This command is used to test the performance of cryptographic algorithms. -To see the list of supported algorithms, use the I -or I command. - -=head1 OPTIONS - -=over 4 - -=item B<-help> - -Print out a usage message. - -=item B<-engine id> - -specifying an engine (by its unique B string) will cause B -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<-elapsed> - -Measure time in real time instead of CPU time. It can be useful when testing -speed of hardware engines. - -=item B<-evp algo> - -Use the specified cipher or message digest algorithm via the EVP interface. - -=item B<-decrypt> - -Time the decryption instead of encryption. Affects only the EVP testing. - -=item B<[zero or more test algorithms]> - -If any options are given, B tests those algorithms, otherwise all of -the above are tested. - -=back - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/apps/version.pod b/doc/apps/version.pod deleted file mode 100644 index 305a1b74..00000000 --- a/doc/apps/version.pod +++ /dev/null @@ -1,81 +0,0 @@ -=pod - -=head1 NAME - -openssl-version, -version - print OpenSSL version information - -=head1 SYNOPSIS - -B -[B<-help>] -[B<-a>] -[B<-v>] -[B<-b>] -[B<-o>] -[B<-f>] -[B<-p>] -[B<-d>] -[B<-e>] - -=head1 DESCRIPTION - -This command is used to print out version information about OpenSSL. - -=head1 OPTIONS - -=over 4 - -=item B<-help> - -Print out a usage message. - -=item B<-a> - -all information, this is the same as setting all the other flags. - -=item B<-v> - -the current OpenSSL version. - -=item B<-b> - -the date the current version of OpenSSL was built. - -=item B<-o> - -option information: various options set when the library was built. - -=item B<-f> - -compilation flags. - -=item B<-p> - -platform setting. - -=item B<-d> - -OPENSSLDIR setting. - -=item B<-e> - -ENGINESDIR setting. - -=back - -=head1 NOTES - -The output of B would typically be used when sending -in a bug report. - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/apps/x509.pod b/doc/apps/x509.pod deleted file mode 100644 index f2dcef2e..00000000 --- a/doc/apps/x509.pod +++ /dev/null @@ -1,898 +0,0 @@ -=pod - -=head1 NAME - -openssl-x509, -x509 - Certificate display and signing utility - -=head1 SYNOPSIS - -B B -[B<-help>] -[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<-[digest]>] -[B<-clrext>] -[B<-extfile filename>] -[B<-extensions section>] -[B<-engine id>] - -=head1 DESCRIPTION - -The B 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<-help> - -Print out a usage message. - -=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<-[digest]> - -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. -Any digest supported by the OpenSSL B command can be used. -If not specified then SHA1 is used with B<-fingerprint> or -the default digest for the signing algorithm is used, typically SHA256. - -=item B<-engine id> - -specifying an engine (by its unique B string) will cause B -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 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

and B are likely enough to -be valid. -This is a lightweight check, if a more thorough check is needed, use -DH_check(). -The value of B<*codes> is updated with any problems found. -If B<*codes> is zero then no problems were found, otherwise the -following bits may be set: - -=over 4 - -=item DH_CHECK_P_NOT_PRIME - -The parameter B

has been determined to not being an odd prime. -Note that the lack of this bit doesn't guarantee that B

is a -prime. - -=item DH_NOT_SUITABLE_GENERATOR - -The generator B is not suitable. -Note that the lack of this bit doesn't guarantee that B is -suitable, unless B

is known to be a strong prime. - -=back - -DH_check() confirms that the Diffie-Hellman parameters B are valid. The -value of B<*codes> is updated with any problems found. If B<*codes> is zero then -no problems were found, otherwise the following bits may be set: - -=over 4 - -=item DH_CHECK_P_NOT_PRIME - -The parameter B

is not prime. - -=item DH_CHECK_P_NOT_SAFE_PRIME - -The parameter B

is not a safe prime and no B value is present. - -=item DH_UNABLE_TO_CHECK_GENERATOR - -The generator B cannot be checked for suitability. - -=item DH_NOT_SUITABLE_GENERATOR - -The generator B is not suitable. - -=item DH_CHECK_Q_NOT_PRIME - -The parameter B is not prime. - -=item DH_CHECK_INVALID_Q_VALUE - -The parameter B is invalid. - -=item DH_CHECK_INVALID_J_VALUE - -The parameter B is invalid. - -=back - -=head1 RETURN VALUES - -DH_generate_parameters_ex(), DH_check() and DH_check_params() return 1 -if the check could be performed, 0 otherwise. - -DH_generate_parameters() (deprecated) returns a pointer to the DH structure, or -NULL if the parameter generation fails. - -The error codes can be obtained by L. - -=head1 NOTES - -DH_generate_parameters_ex() and DH_generate_parameters() may run for several -hours before finding a suitable prime. - -The parameters generated by DH_generate_parameters_ex() and DH_generate_parameters() -are not to be used in signature schemes. - -=head1 SEE ALSO - -L, L, L, -L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/DH_size.pod b/doc/crypto/DH_size.pod deleted file mode 100644 index 8c1d151f..00000000 --- a/doc/crypto/DH_size.pod +++ /dev/null @@ -1,47 +0,0 @@ -=pod - -=head1 NAME - -DH_size, DH_bits - get Diffie-Hellman prime size - -=head1 SYNOPSIS - -#include - -int DH_size(const DH *dh); - -int DH_bits(const DH *dh); - -=head1 DESCRIPTION - -DH_size() returns the Diffie-Hellman prime size in bytes. It can be used -to determine how much memory must be allocated for the shared secret -computed by DH_compute_key(). - -DH_bits() returns the number of significant bits. - -B and Bp> must not be B. - -=head1 RETURN VALUE - -The size. - -=head1 SEE ALSO - -L, L, -L - -=head1 HISTORY - -DH_bits() was added in OpenSSL 1.1.0. - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/DSA_meth_new.pod b/doc/crypto/DSA_meth_new.pod deleted file mode 100644 index 948ab29b..00000000 --- a/doc/crypto/DSA_meth_new.pod +++ /dev/null @@ -1,193 +0,0 @@ -=pod - -=head1 NAME - -DSA_meth_new, DSA_meth_free, DSA_meth_dup, DSA_meth_get0_name, -DSA_meth_set1_name, DSA_meth_get_flags, DSA_meth_set_flags, -DSA_meth_get0_app_data, DSA_meth_set0_app_data, DSA_meth_get_sign, -DSA_meth_set_sign, DSA_meth_get_sign_setup, DSA_meth_set_sign_setup, -DSA_meth_get_verify, DSA_meth_set_verify, DSA_meth_get_mod_exp, -DSA_meth_set_mod_exp, DSA_meth_get_bn_mod_exp, DSA_meth_set_bn_mod_exp, -DSA_meth_get_init, DSA_meth_set_init, DSA_meth_get_finish, DSA_meth_set_finish, -DSA_meth_get_paramgen, DSA_meth_set_paramgen, DSA_meth_get_keygen, -DSA_meth_set_keygen - Routines to build up DSA methods - -=head1 SYNOPSIS - - #include - - DSA_METHOD *DSA_meth_new(const char *name, int flags); - void DSA_meth_free(DSA_METHOD *dsam); - DSA_METHOD *DSA_meth_dup(const DSA_METHOD *meth); - const char *DSA_meth_get0_name(const DSA_METHOD *dsam); - int DSA_meth_set1_name(DSA_METHOD *dsam, const char *name); - int DSA_meth_get_flags(DSA_METHOD *dsam); - int DSA_meth_set_flags(DSA_METHOD *dsam, int flags); - void *DSA_meth_get0_app_data(const DSA_METHOD *dsam); - int DSA_meth_set0_app_data(DSA_METHOD *dsam, void *app_data); - DSA_SIG *(*DSA_meth_get_sign(const DSA_METHOD *dsam)) - (const unsigned char *, int, DSA *); - int DSA_meth_set_sign(DSA_METHOD *dsam, - DSA_SIG *(*sign) (const unsigned char *, int, DSA *)); - int (*DSA_meth_get_sign_setup(const DSA_METHOD *dsam)) - (DSA *, BN_CTX *, BIGNUM **, BIGNUM **); - int DSA_meth_set_sign_setup(DSA_METHOD *dsam, - int (*sign_setup) (DSA *, BN_CTX *, BIGNUM **, BIGNUM **)); - int (*DSA_meth_get_verify(const DSA_METHOD *dsam)) - (const unsigned char *, int , DSA_SIG *, DSA *); - int DSA_meth_set_verify(DSA_METHOD *dsam, - int (*verify) (const unsigned char *, int, DSA_SIG *, DSA *)); - int (*DSA_meth_get_mod_exp(const DSA_METHOD *dsam)) - (DSA *dsa, BIGNUM *rr, BIGNUM *a1, BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, - BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont); - int DSA_meth_set_mod_exp(DSA_METHOD *dsam, - int (*mod_exp) (DSA *dsa, BIGNUM *rr, BIGNUM *a1, BIGNUM *p1, BIGNUM *a2, - BIGNUM *p2, BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *mont)); - int (*DSA_meth_get_bn_mod_exp(const DSA_METHOD *dsam)) - (DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p, const BIGNUM *m, - BN_CTX *ctx, BN_MONT_CTX *mont); - int DSA_meth_set_bn_mod_exp(DSA_METHOD *dsam, - int (*bn_mod_exp) (DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p, - const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *mont)); - int (*DSA_meth_get_init(const DSA_METHOD *dsam))(DSA *); - int DSA_meth_set_init(DSA_METHOD *dsam, int (*init)(DSA *)); - int (*DSA_meth_get_finish(const DSA_METHOD *dsam)) (DSA *); - int DSA_meth_set_finish(DSA_METHOD *dsam, int (*finish) (DSA *)); - int (*DSA_meth_get_paramgen(const DSA_METHOD *dsam)) - (DSA *, int, const unsigned char *, int, int *, unsigned long *, - BN_GENCB *); - int DSA_meth_set_paramgen(DSA_METHOD *dsam, - int (*paramgen) (DSA *, int, const unsigned char *, int, int *, - unsigned long *, BN_GENCB *)); - int (*DSA_meth_get_keygen(const DSA_METHOD *dsam)) (DSA *); - int DSA_meth_set_keygen(DSA_METHOD *dsam, int (*keygen) (DSA *)); - -=head1 DESCRIPTION - -The B type is a structure used for the provision of custom DSA -implementations. It provides a set of of functions used by OpenSSL for the -implementation of the various DSA capabilities. See the L page for more -information. - -DSA_meth_new() creates a new B structure. It should be given a -unique B and a set of B. The B should be a NULL terminated -string, which will be duplicated and stored in the B object. It is -the callers responsibility to free the original string. The flags will be used -during the construction of a new B object based on this B. Any -new B object will have those flags set by default. - -DSA_meth_dup() creates a duplicate copy of the B object passed as a -parameter. This might be useful for creating a new B based on an -existing one, but with some differences. - -DSA_meth_free() destroys a B structure and frees up any memory -associated with it. - -DSA_meth_get0_name() will return a pointer to the name of this DSA_METHOD. This -is a pointer to the internal name string and so should not be freed by the -caller. DSA_meth_set1_name() sets the name of the DSA_METHOD to B. The -string is duplicated and the copy is stored in the DSA_METHOD structure, so the -caller remains responsible for freeing the memory associated with the name. - -DSA_meth_get_flags() returns the current value of the flags associated with this -DSA_METHOD. DSA_meth_set_flags() provides the ability to set these flags. - -The functions DSA_meth_get0_app_data() and DSA_meth_set0_app_data() provide the -ability to associate implementation specific data with the DSA_METHOD. It is -the application's responsibility to free this data before the DSA_METHOD is -freed via a call to DSA_meth_free(). - -DSA_meth_get_sign() and DSA_meth_set_sign() get and set the function used for -creating a DSA signature respectively. This function will be -called in response to the application calling DSA_do_sign() (or DSA_sign()). The -parameters for the function have the same meaning as for DSA_do_sign(). - -DSA_meth_get_sign_setup() and DSA_meth_set_sign_setup() get and set the function -used for precalculating the DSA signature values B and B. This function -will be called in response to the application calling DSA_sign_setup(). The -parameters for the function have the same meaning as for DSA_sign_setup(). - -DSA_meth_get_verify() and DSA_meth_set_verify() get and set the function used -for verifying a DSA signature respectively. This function will be called in -response to the application calling DSA_do_verify() (or DSA_verify()). The -parameters for the function have the same meaning as for DSA_do_verify(). - -DSA_meth_get_mod_exp() and DSA_meth_set_mod_exp() get and set the function used -for computing the following value: - - rr = a1^p1 * a2^p2 mod m - -This function will be called by the default OpenSSL method during verification -of a DSA signature. The result is stored in the B parameter. This function -may be NULL. - -DSA_meth_get_bn_mod_exp() and DSA_meth_set_bn_mod_exp() get and set the function -used for computing the following value: - - r = a ^ p mod m - -This function will be called by the default OpenSSL function for -DSA_sign_setup(). The result is stored in the B parameter. This function -may be NULL. - -DSA_meth_get_init() and DSA_meth_set_init() get and set the function used -for creating a new DSA instance respectively. This function will be -called in response to the application calling DSA_new() (if the current default -DSA_METHOD is this one) or DSA_new_method(). The DSA_new() and DSA_new_method() -functions will allocate the memory for the new DSA object, and a pointer to this -newly allocated structure will be passed as a parameter to the function. This -function may be NULL. - -DSA_meth_get_finish() and DSA_meth_set_finish() get and set the function used -for destroying an instance of a DSA object respectively. This function will be -called in response to the application calling DSA_free(). A pointer to the DSA -to be destroyed is passed as a parameter. The destroy function should be used -for DSA implementation specific clean up. The memory for the DSA itself should -not be freed by this function. This function may be NULL. - -DSA_meth_get_paramgen() and DSA_meth_set_paramgen() get and set the function -used for generating DSA parameters respectively. This function will be called in -response to the application calling DSA_generate_parameters_ex() (or -DSA_generate_parameters()). The parameters for the function have the same -meaning as for DSA_generate_parameters_ex(). - -DSA_meth_get_keygen() and DSA_meth_set_keygen() get and set the function -used for generating a new DSA key pair respectively. This function will be -called in response to the application calling DSA_generate_key(). The parameter -for the function has the same meaning as for DSA_generate_key(). - -=head1 RETURN VALUES - -DSA_meth_new() and DSA_meth_dup() return the newly allocated DSA_METHOD object -or NULL on failure. - -DSA_meth_get0_name() and DSA_meth_get_flags() return the name and flags -associated with the DSA_METHOD respectively. - -All other DSA_meth_get_*() functions return the appropriate function pointer -that has been set in the DSA_METHOD, or NULL if no such pointer has yet been -set. - -DSA_meth_set1_name() and all DSA_meth_set_*() functions return 1 on success or -0 on failure. - -=head1 SEE ALSO - -L, L, L, L, -L, L, L, L, -L, L, L - -=head1 HISTORY - -The functions described here were added in OpenSSL 1.1.0. - -=head1 COPYRIGHT - -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 -L. - -=cut diff --git a/doc/crypto/DSA_size.pod b/doc/crypto/DSA_size.pod deleted file mode 100644 index 16e6f3a9..00000000 --- a/doc/crypto/DSA_size.pod +++ /dev/null @@ -1,44 +0,0 @@ -=pod - -=head1 NAME - -DSA_size, DSA_bits - get DSA signature size or key bits - -=head1 SYNOPSIS - - #include - - int DSA_size(const DSA *dsa); - int DSA_bits(const DSA *dsa); - -=head1 DESCRIPTION - -DSA_size() returns the maximum size of an ASN.1 encoded DSA signature -for key B in bytes. It can be used to determine how much memory must -be allocated for a DSA signature. - -Bq> must not be B. - -DSA_bits() returns the number of bits in key B: this is the number -of bits in the B

parameter. - -=head1 RETURN VALUE - -DSA_size() returns the size in bytes. - -DSA_bits() returns the number of bits in the key. - -=head1 SEE ALSO - -L, L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/ERR_remove_state.pod b/doc/crypto/ERR_remove_state.pod deleted file mode 100644 index 617b4b70..00000000 --- a/doc/crypto/ERR_remove_state.pod +++ /dev/null @@ -1,53 +0,0 @@ -=pod - -=head1 NAME - -ERR_remove_thread_state, ERR_remove_state - DEPRECATED - -=head1 SYNOPSIS - -Deprecated: - - #if OPENSSL_API_COMPAT < 0x10000000L - void ERR_remove_state(unsigned long pid); - #endif - - #if OPENSSL_API_COMPAT < 0x10100000L - void ERR_remove_thread_state(void *); - #endif - -=head1 DESCRIPTION - -The functions described here were used to free the error queue -associated with the current or specified thread. - -They are now deprecated and do nothing, as the OpenSSL libraries now -normally do all thread initialisation and deinitialisation -automatically (see L). - -=head1 RETURN VALUE - -The functions described here return no value. - -=head1 SEE ALSO - -LL - -=head1 HISTORY - -ERR_remove_state() was deprecated in OpenSSL 1.0.0 when -ERR_remove_thread_state() was introduced. - -ERR_remove_thread_state() was deprecated in OpenSSL 1.1.0 when the -thread handling functionality was entirely rewritten. - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/EVP_DigestInit.pod b/doc/crypto/EVP_DigestInit.pod deleted file mode 100644 index bb7ef7a2..00000000 --- a/doc/crypto/EVP_DigestInit.pod +++ /dev/null @@ -1,259 +0,0 @@ -=pod - -=head1 NAME - -EVP_MD_CTX_new, EVP_MD_CTX_reset, EVP_MD_CTX_free, EVP_MD_CTX_copy_ex, -EVP_DigestInit_ex, EVP_DigestUpdate, EVP_DigestFinal_ex, -EVP_DigestInit, EVP_DigestFinal, EVP_MD_CTX_copy, EVP_MD_type, -EVP_MD_pkey_type, EVP_MD_size, EVP_MD_block_size, EVP_MD_CTX_md, EVP_MD_CTX_size, -EVP_MD_CTX_block_size, EVP_MD_CTX_type, EVP_md_null, EVP_md2, EVP_md5, EVP_sha1, -EVP_sha224, EVP_sha256, EVP_sha384, EVP_sha512, EVP_mdc2, -EVP_ripemd160, EVP_blake2b512, EVP_blake2s256, EVP_get_digestbyname, -EVP_get_digestbynid, EVP_get_digestbyobj - EVP digest routines - -=head1 SYNOPSIS - - #include - - EVP_MD_CTX *EVP_MD_CTX_new(void); - int EVP_MD_CTX_reset(EVP_MD_CTX *ctx); - void EVP_MD_CTX_free(EVP_MD_CTX *ctx); - - int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl); - int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt); - int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, - unsigned int *s); - - int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in); - - int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type); - int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, - unsigned int *s); - - int EVP_MD_CTX_copy(EVP_MD_CTX *out, EVP_MD_CTX *in); - - int EVP_MD_type(const EVP_MD *md); - int EVP_MD_pkey_type(const EVP_MD *md); - int EVP_MD_size(const EVP_MD *md); - int EVP_MD_block_size(const EVP_MD *md); - - const EVP_MD *EVP_MD_CTX_md(const EVP_MD_CTX *ctx); - int EVP_MD_CTX_size(const EVP_MD *ctx); - int EVP_MD_CTX_block_size(const EVP_MD *ctx); - int EVP_MD_CTX_type(const EVP_MD *ctx); - - const EVP_MD *EVP_md_null(void); - const EVP_MD *EVP_md2(void); - const EVP_MD *EVP_md5(void); - const EVP_MD *EVP_sha1(void); - const EVP_MD *EVP_mdc2(void); - const EVP_MD *EVP_ripemd160(void); - const EVP_MD *EVP_blake2b512(void); - const EVP_MD *EVP_blake2s256(void); - - const EVP_MD *EVP_sha224(void); - const EVP_MD *EVP_sha256(void); - const EVP_MD *EVP_sha384(void); - const EVP_MD *EVP_sha512(void); - - const EVP_MD *EVP_get_digestbyname(const char *name); - const EVP_MD *EVP_get_digestbynid(int type); - const EVP_MD *EVP_get_digestbyobj(const ASN1_OBJECT *o); - -=head1 DESCRIPTION - -The EVP digest routines are a high level interface to message digests, -and should be used instead of the cipher-specific functions. - -EVP_MD_CTX_new() allocates, initializes and returns a digest context. - -EVP_MD_CTX_reset() resets the digest context B. This can be used -to reuse an already existing context. - -EVP_MD_CTX_free() cleans up digest context B and frees up the -space allocated to it. - -EVP_DigestInit_ex() sets up digest context B to use a digest -B from ENGINE B. B must be initialized before calling this -function. B will typically be supplied by a function such as EVP_sha1(). -If B is NULL then the default implementation of digest B is used. - -EVP_DigestUpdate() hashes B bytes of data at B into the -digest context B. This function can be called several times on the -same B to hash additional data. - -EVP_DigestFinal_ex() retrieves the digest value from B and places -it in B. If the B parameter is not NULL then the number of -bytes of data written (i.e. the length of the digest) will be written -to the integer at B, at most B bytes will be written. -After calling EVP_DigestFinal_ex() no additional calls to EVP_DigestUpdate() -can be made, but EVP_DigestInit_ex() can be called to initialize a new -digest operation. - -EVP_MD_CTX_copy_ex() can be used to copy the message digest state from -B to B. This is useful if large amounts of data are to be -hashed which only differ in the last few bytes. B must be initialized -before calling this function. - -EVP_DigestInit() behaves in the same way as EVP_DigestInit_ex() except -the passed context B does not have to be initialized, and it always -uses the default digest implementation. - -EVP_DigestFinal() is similar to EVP_DigestFinal_ex() except the digest -context B is automatically cleaned up. - -EVP_MD_CTX_copy() is similar to EVP_MD_CTX_copy_ex() except the destination -B does not have to be initialized. - -EVP_MD_size() and EVP_MD_CTX_size() return the size of the message digest -when passed an B or an B structure, i.e. the size of the -hash. - -EVP_MD_block_size() and EVP_MD_CTX_block_size() return the block size of the -message digest when passed an B or an B structure. - -EVP_MD_type() and EVP_MD_CTX_type() return the NID of the OBJECT IDENTIFIER -representing the given message digest when passed an B structure. -For example EVP_MD_type(EVP_sha1()) returns B. This function is -normally used when setting ASN1 OIDs. - -EVP_MD_CTX_md() returns the B structure corresponding to the passed -B. - -EVP_MD_pkey_type() returns the NID of the public key signing algorithm associated -with this digest. For example EVP_sha1() is associated with RSA so this will -return B. Since digests and signature algorithms -are no longer linked this function is only retained for compatibility -reasons. - -EVP_md2(), EVP_md5(), EVP_sha1(), EVP_sha224(), EVP_sha256(), -EVP_sha384(), EVP_sha512(), EVP_mdc2(), EVP_ripemd160(), EVP_blake2b512(), and -EVP_blake2s256() return B structures for the MD2, MD5, SHA1, SHA224, -SHA256, SHA384, SHA512, MDC2, RIPEMD160, BLAKE2b-512, and BLAKE2s-256 digest -algorithms respectively. - -EVP_md_null() is a "null" message digest that does nothing: i.e. the hash it -returns is of zero length. - -EVP_get_digestbyname(), EVP_get_digestbynid() and EVP_get_digestbyobj() -return an B structure when passed a digest name, a digest NID or -an ASN1_OBJECT structure respectively. - -=head1 RETURN VALUES - -EVP_DigestInit_ex(), EVP_DigestUpdate() and EVP_DigestFinal_ex() return 1 for -success and 0 for failure. - -EVP_MD_CTX_copy_ex() returns 1 if successful or 0 for failure. - -EVP_MD_type(), EVP_MD_pkey_type() and EVP_MD_type() return the NID of the -corresponding OBJECT IDENTIFIER or NID_undef if none exists. - -EVP_MD_size(), EVP_MD_block_size(), EVP_MD_CTX_size() and -EVP_MD_CTX_block_size() return the digest or block size in bytes. - -EVP_md_null(), EVP_md2(), EVP_md5(), EVP_sha1(), -EVP_mdc2(), EVP_ripemd160(), EVP_blake2b512(), and EVP_blake2s256() return -pointers to the corresponding EVP_MD structures. - -EVP_get_digestbyname(), EVP_get_digestbynid() and EVP_get_digestbyobj() -return either an B structure or NULL if an error occurs. - -=head1 NOTES - -The B interface to message digests should almost always be used in -preference to the low level interfaces. This is because the code then becomes -transparent to the digest used and much more flexible. - -New applications should use the SHA2 digest algorithms such as SHA256. -The other digest algorithms are still in common use. - -For most applications the B parameter to EVP_DigestInit_ex() will be -set to NULL to use the default digest implementation. - -The functions EVP_DigestInit(), EVP_DigestFinal() and EVP_MD_CTX_copy() are -obsolete but are retained to maintain compatibility with existing code. New -applications should use EVP_DigestInit_ex(), EVP_DigestFinal_ex() and -EVP_MD_CTX_copy_ex() because they can efficiently reuse a digest context -instead of initializing and cleaning it up on each call and allow non default -implementations of digests to be specified. - -If digest contexts are not cleaned up after use -memory leaks will occur. - -EVP_MD_CTX_size(), EVP_MD_CTX_block_size(), EVP_MD_CTX_type(), -EVP_get_digestbynid() and EVP_get_digestbyobj() are defined as -macros. - - -=head1 EXAMPLE - -This example digests the data "Test Message\n" and "Hello World\n", using the -digest name passed on the command line. - - #include - #include - - main(int argc, char *argv[]) - { - EVP_MD_CTX *mdctx; - const EVP_MD *md; - char mess1[] = "Test Message\n"; - char mess2[] = "Hello World\n"; - unsigned char md_value[EVP_MAX_MD_SIZE]; - int md_len, i; - - if(!argv[1]) { - printf("Usage: mdtest digestname\n"); - exit(1); - } - - md = EVP_get_digestbyname(argv[1]); - - if(!md) { - printf("Unknown message digest %s\n", argv[1]); - exit(1); - } - - mdctx = EVP_MD_CTX_new(); - EVP_DigestInit_ex(mdctx, md, NULL); - EVP_DigestUpdate(mdctx, mess1, strlen(mess1)); - EVP_DigestUpdate(mdctx, mess2, strlen(mess2)); - EVP_DigestFinal_ex(mdctx, md_value, &md_len); - EVP_MD_CTX_free(mdctx); - - printf("Digest is: "); - for (i = 0; i < md_len; i++) - printf("%02x", md_value[i]); - printf("\n"); - - exit(0); - } - -=head1 SEE ALSO - -L, -L - -=head1 HISTORY - -B became opaque in OpenSSL 1.1. Consequently, stack -allocated Bs are no longer supported. - -EVP_MD_CTX_create() and EVP_MD_CTX_destroy() were renamed to -EVP_MD_CTX_new() and EVP_MD_CTX_free() in OpenSSL 1.1. - -The link between digests and signing algorithms was fixed in OpenSSL 1.0 and -later, so now EVP_sha1() can be used with RSA and DSA. The legacy EVP_dss1() -was removed in OpenSSL 1.1.0 - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/EVP_DigestVerifyInit.pod b/doc/crypto/EVP_DigestVerifyInit.pod deleted file mode 100644 index ce59422d..00000000 --- a/doc/crypto/EVP_DigestVerifyInit.pod +++ /dev/null @@ -1,91 +0,0 @@ -=pod - -=head1 NAME - -EVP_DigestVerifyInit, EVP_DigestVerifyUpdate, EVP_DigestVerifyFinal - EVP signature verification functions - -=head1 SYNOPSIS - - #include - - int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, - const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey); - int EVP_DigestVerifyUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt); - int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig, size_t siglen); - -=head1 DESCRIPTION - -The EVP signature routines are a high level interface to digital signatures. - -EVP_DigestVerifyInit() sets up verification context B to use digest -B from ENGINE B and public key B. B must be created -with EVP_MD_CTX_new() before calling this function. If B is not NULL the -EVP_PKEY_CTX of the verification operation will be written to B<*pctx>: this -can be used to set alternative verification options. - -EVP_DigestVerifyUpdate() hashes B bytes of data at B into the -verification context B. This function can be called several times on the -same B to include additional data. This function is currently implemented -using a macro. - -EVP_DigestVerifyFinal() verifies the data in B against the signature in -B of length B. - -=head1 RETURN VALUES - -EVP_DigestVerifyInit() and EVP_DigestVerifyUpdate() return 1 for success and 0 -for failure. - -EVP_DigestVerifyFinal() returns 1 for success; any other value indicates -failure. A return value of zero indicates that the signature did not verify -successfully (that is, tbs did not match the original data or the signature had -an invalid form), while other values indicate a more serious error (and -sometimes also indicate an invalid signature form). - -The error codes can be obtained from L. - -=head1 NOTES - -The B interface to digital signatures should almost always be used in -preference to the low level interfaces. This is because the code then becomes -transparent to the algorithm used and much more flexible. - -In previous versions of OpenSSL there was a link between message digest types -and public key algorithms. This meant that "clone" digests such as EVP_dss1() -needed to be used to sign using SHA1 and DSA. This is no longer necessary and -the use of clone digest is now discouraged. - -For some key types and parameters the random number generator must be seeded -or the operation will fail. - -The call to EVP_DigestVerifyFinal() internally finalizes a copy of the digest -context. This means that EVP_VerifyUpdate() and EVP_VerifyFinal() can -be called later to digest and verify additional data. - -Since only a copy of the digest context is ever finalized the context must -be cleaned up after use by calling EVP_MD_CTX_cleanup() or a memory leak -will occur. - -=head1 SEE ALSO - -L, -L, -L, L, L, -L, L, L, -L, L - -=head1 HISTORY - -EVP_DigestVerifyInit(), EVP_DigestVerifyUpdate() and EVP_DigestVerifyFinal() -were first added to OpenSSL 1.0.0. - -=head1 COPYRIGHT - -Copyright 2006-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 -L. - -=cut diff --git a/doc/crypto/EVP_EncryptInit.pod b/doc/crypto/EVP_EncryptInit.pod deleted file mode 100644 index d1af772f..00000000 --- a/doc/crypto/EVP_EncryptInit.pod +++ /dev/null @@ -1,661 +0,0 @@ -=pod - -=head1 NAME - -EVP_CIPHER_CTX_new, EVP_CIPHER_CTX_reset, EVP_CIPHER_CTX_free, -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_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_cbc, EVP_aes_128_ecb, EVP_aes_128_cfb, EVP_aes_128_ofb, -EVP_aes_192_cbc, EVP_aes_192_ecb, EVP_aes_192_cfb, EVP_aes_192_ofb, -EVP_aes_256_cbc, EVP_aes_256_ecb, EVP_aes_256_cfb, EVP_aes_256_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_chacha20, EVP_chacha20_poly1305 - EVP cipher routines - -=head1 SYNOPSIS - -=for comment generic - - #include - - EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void); - int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *ctx); - void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx); - - int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, - ENGINE *impl, const unsigned char *key, const unsigned char *iv); - int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *outl, const unsigned char *in, int inl); - int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *outl); - - int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, - ENGINE *impl, const unsigned char *key, const unsigned char *iv); - int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *outl, const unsigned char *in, int inl); - int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, - int *outl); - - int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, - ENGINE *impl, const unsigned char *key, const unsigned char *iv, int enc); - int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *outl, const unsigned char *in, int inl); - int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, - int *outl); - - int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, - const unsigned char *key, const unsigned char *iv); - int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *outl); - - int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, - const unsigned char *key, const unsigned char *iv); - int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, - int *outl); - - int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, - const unsigned char *key, const unsigned char *iv, int enc); - int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, - int *outl); - - int EVP_CIPHER_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); - - const EVP_CIPHER *EVP_get_cipherbyname(const char *name); - const EVP_CIPHER *EVP_get_cipherbynid(int nid); - const EVP_CIPHER *EVP_get_cipherbyobj(const ASN1_OBJECT *a); - - int EVP_CIPHER_nid(const EVP_CIPHER *e); - int EVP_CIPHER_block_size(const EVP_CIPHER *e); - int EVP_CIPHER_key_length(const EVP_CIPHER *e) - int EVP_CIPHER_key_length(const EVP_CIPHER *e); - int EVP_CIPHER_iv_length(const EVP_CIPHER *e); - unsigned long EVP_CIPHER_flags(const EVP_CIPHER *e); - unsigned long EVP_CIPHER_mode(const EVP_CIPHER *e); - int EVP_CIPHER_type(const EVP_CIPHER *ctx); - - const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx); - int EVP_CIPHER_CTX_nid(const EVP_CIPHER_CTX *ctx); - int EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx); - int EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx); - int EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx); - void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx); - void EVP_CIPHER_CTX_set_app_data(const EVP_CIPHER_CTX *ctx, void *data); - int EVP_CIPHER_CTX_type(const EVP_CIPHER_CTX *ctx); - int EVP_CIPHER_CTX_mode(const EVP_CIPHER_CTX *ctx); - - int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type); - int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type); - -=head1 DESCRIPTION - -The EVP cipher routines are a high level interface to certain -symmetric ciphers. - -EVP_CIPHER_CTX_new() creates a cipher context. - -EVP_CIPHER_CTX_free() clears all information from a cipher context -and free up any allocated memory associate with it, including B -itself. This function should be called after all operations using a -cipher are complete so sensitive information does not remain in -memory. - -EVP_EncryptInit_ex() sets up cipher context B for encryption -with cipher B from ENGINE B. B must be created -before calling this function. B is normally supplied -by a function such as EVP_aes_256_cbc(). If B is NULL then the -default implementation is used. B is the symmetric key to use -and B 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 in an initial call and supply -the remaining parameters in subsequent calls, all of which have B -set to NULL. This is done when the default cipher parameters are not -appropriate. - -EVP_EncryptUpdate() encrypts B bytes from the buffer B and -writes the encrypted version to B. 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 should contain sufficient -room. The actual number of bytes written is placed in B. It also -checks if B and B are partially overlapping, and if they are -0 is returned to indicate failure. - -If padding is enabled (the default) then EVP_EncryptFinal_ex() encrypts -the "final" data, that is any data that remains in a partial block. -It uses standard block padding (aka PKCS padding) as described in -the NOTES section, below. The encrypted -final data is written to B which should have sufficient space for -one cipher block. The number of bytes written is placed in B. 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 -passed to EVP_DecryptUpdate() should have sufficient room for -(B + cipher_block_size) bytes unless the cipher block size is 1 in -which case B 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 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_reset() clears all information from a cipher context -and free up any allocated memory associate with it, except the B -itself. This function should be called anytime B is to be reused -for another EVP_CipherInit() / EVP_CipherUpdate() / EVP_CipherFinal() -series of calls. - -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 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, 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 or B 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. This -function should be called after the context is set up for encryption -or decryption with EVP_EncryptInit_ex(), EVP_DecryptInit_ex() or -EVP_CipherInit_ex(). By default encryption operations are padded using -standard block padding and the padding is checked and removed when -decrypting. If the B 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 or B -structure. The constant B 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 or B. -It will return zero if the cipher does not use an IV. The constant -B 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 or B -structure. The constant B 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. - -EVP_CIPHER_CTX_cipher() returns the B structure when passed -an B 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_CIPHER_CTX_new() returns a pointer to a newly created -B for success and B for failure. - -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_reset() returns 1 for success and 0 for failure. - -EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj() -return an B 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 structure. - -EVP_CIPHER_param_to_asn1() and EVP_CIPHER_asn1_to_param() return greater -than zero for success and zero or a negative number. - -=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_aes_128_cbc(), EVP_aes_128_ecb(), EVP_aes_128_cfb(), EVP_aes_128_ofb() - -AES with a 128-bit key in CBC, ECB, CFB and OFB modes respectively. - -=item EVP_aes_192_cbc(), EVP_aes_192_ecb(), EVP_aes_192_cfb(), EVP_aes_192_ofb() - -AES with a 192-bit key in CBC, ECB, CFB and OFB modes respectively. - -=item EVP_aes_256_cbc(), EVP_aes_256_ecb(), EVP_aes_256_cfb(), EVP_aes_256_ofb() - -AES with a 256-bit key in CBC, ECB, CFB and OFB modes respectively. - -=item EVP_des_cbc(), EVP_des_ecb(), EVP_des_cfb(), EVP_des_ofb() - -DES in CBC, ECB, CFB and OFB modes respectively. - -=item EVP_des_ede_cbc(), EVP_des_ede(), EVP_des_ede_ofb(), EVP_des_ede_cfb() - -Two key triple DES in CBC, ECB, CFB and OFB modes respectively. - -=item EVP_des_ede3_cbc(), EVP_des_ede3(), EVP_des_ede3_ofb(), EVP_des_ede3_cfb() - -Three key triple DES in CBC, ECB, CFB and OFB modes respectively. - -=item EVP_desx_cbc() - -DESX algorithm in CBC mode. - -=item EVP_rc4() - -RC4 stream cipher. This is a variable key length cipher with default key length 128 bits. - -=item EVP_rc4_40() - -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(), EVP_idea_cfb(), EVP_idea_ofb() - -IDEA encryption algorithm in CBC, ECB, CFB and OFB modes respectively. - -=item EVP_rc2_cbc(), EVP_rc2_ecb(), EVP_rc2_cfb(), EVP_rc2_ofb() - -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(), EVP_rc2_64_cbc() - -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(), EVP_bf_ecb(), EVP_bf_cfb(), EVP_bf_ofb() - -Blowfish encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key -length cipher. - -=item EVP_cast5_cbc(), EVP_cast5_ecb(), EVP_cast5_cfb(), EVP_cast5_ofb() - -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(), EVP_rc5_32_12_16_ecb(), EVP_rc5_32_12_16_cfb(), EVP_rc5_32_12_16_ofb() - -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(), EVP_aes_192_gcm(), EVP_aes_256_gcm() - -AES Galois Counter Mode (GCM) for 128, 192 and 256 bit keys respectively. -These ciphers require additional control operations to function correctly: see -the L section below for details. - -=item EVP_aes_128_ocb(void), EVP_aes_192_ocb(void), EVP_aes_256_ocb(void) - -Offset Codebook Mode (OCB) for 128, 192 and 256 bit keys respectively. -These ciphers require additional control operations to function correctly: see -the L section below for details. - -=item EVP_aes_128_ccm(), EVP_aes_192_ccm(), EVP_aes_256_ccm() - -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. - -=item EVP_chacha20() - -The ChaCha20 stream cipher. The key length is 256 bits, the IV is 96 bits long. - -=item EVP_chacha20_poly1305() - -Authenticated encryption with ChaCha20-Poly1305. Like EVP_chacha20() the key is -256 bits and the IV is 96 bits. This supports additional authenticated -data (AAD) and produces a 128 bit authentication tag. See the -L section for more information. - -=back - -=head1 GCM and OCB Modes - -For GCM and OCB mode ciphers the behaviour of the EVP interface is subtly -altered and several additional ctrl operations are supported. - -To specify any additional authenticated data (AAD) a call to EVP_CipherUpdate(), -EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made with the output -parameter B set to B. - -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 -be used as it is corrupted. - -The following ctrls are supported in both GCM and OCB modes: - - EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL); - -Sets the IV length: this call can only be made before specifying an IV. If -not called a default IV length is used. For GCM AES and OCB AES the default is -12 (i.e. 96 bits). For OCB mode the maximum is 15. - - EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag); - -Writes B bytes of the tag value to the buffer indicated by B. -This call can only be made when encrypting data and B all data has been -processed (e.g. after an EVP_EncryptFinal() call). For OCB mode the taglen must -either be 16 or the value previously set via EVP_CTRL_OCB_SET_TAGLEN. - - EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag); - -Sets the expected tag to B bytes from B. This call is only legal -when decrypting data. For OCB mode the taglen must either be 16 or the value -previously set via EVP_CTRL_AEAD_SET_TAG. - -In OCB mode calling this with B set to NULL sets the tag length. The tag -length can only be set before specifying an IV. If not called a default tag -length is used. For OCB AES the default is 16 (i.e. 128 bits). This is also the -maximum tag length for OCB. - -=head1 CCM Mode - -The behaviour of CCM mode ciphers is similar to GCM mode but with a few -additional requirements and different ctrl values. - -Like GCM and OCB modes any additional authenticated data (AAD) is passed by calling -EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() with the output -parameter B set to B. Additionally the total plaintext or ciphertext -length B be passed to EVP_CipherUpdate(), EVP_EncryptUpdate() or -EVP_DecryptUpdate() with the output and input parameters (B and B) -set to B and the length passed in the B parameter. - -The following ctrls are supported in CCM mode: - - EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag); - -This call is made to set the expected B tag value when decrypting or -the length of the tag (with the B parameter set to NULL) when encrypting. -The tag length is often referred to as B. 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 value. If not set a default is used (8 for AES). - - EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL); - -Sets the CCM nonce (IV) length: this call can only be made before specifying -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 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 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 padding bytes of value B 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 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. - -EVP_get_cipherbynid(), and EVP_get_cipherbyobj() are implemented as macros. - -=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; - - ctx = EVP_CIPHER_CTX_new(); - 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_free(ctx); - /* Need binary mode for fopen because encrypted data is - * binary data. Also cannot use strlen() on it because - * it won't 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 -utility with the command line (shown on two lines for clarity): - - openssl idea -d - -=head1 HISTORY - -Support for OCB mode was added in OpenSSL 1.1.0 - -B was made opaque in OpenSSL 1.1.0. As a result, -EVP_CIPHER_CTX_reset() appeared and EVP_CIPHER_CTX_cleanup() -disappeared. EVP_CIPHER_CTX_init() remains as an alias for -EVP_CIPHER_CTX_reset(). - -=head1 COPYRIGHT - -Copyright 2000-2018 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 -L. - -=cut diff --git a/doc/crypto/EVP_PKEY_CTX_set_hkdf_md.pod b/doc/crypto/EVP_PKEY_CTX_set_hkdf_md.pod deleted file mode 100644 index 61e0eec5..00000000 --- a/doc/crypto/EVP_PKEY_CTX_set_hkdf_md.pod +++ /dev/null @@ -1,128 +0,0 @@ -=pod - -=head1 NAME - -EVP_PKEY_CTX_set_hkdf_md, EVP_PKEY_CTX_set1_hkdf_salt, -EVP_PKEY_CTX_set1_hkdf_key, EVP_PKEY_CTX_add1_hkdf_info - -HMAC-based Extract-and-Expand key derivation algorithm - -=head1 SYNOPSIS - - #include - - int EVP_PKEY_CTX_set_hkdf_md(EVP_PKEY_CTX *pctx, const EVP_MD *md); - - int EVP_PKEY_CTX_set1_hkdf_salt(EVP_PKEY_CTX *pctx, unsigned char *salt, - int saltlen); - - int EVP_PKEY_CTX_set1_hkdf_key(EVP_PKEY_CTX *pctx, unsigned char *key, - int keylen); - - int EVP_PKEY_CTX_add1_hkdf_info(EVP_PKEY_CTX *pctx, unsigned char *info, - int infolen); - -=head1 DESCRIPTION - -The EVP_PKEY_HKDF algorithm implements the HKDF key derivation function. -HKDF follows the "extract-then-expand" paradigm, where the KDF logically -consists of two modules. The first stage takes the input keying material -and "extracts" from it a fixed-length pseudorandom key K. The second stage -"expands" the key K into several additional pseudorandom keys (the output -of the KDF). - -EVP_PKEY_set_hkdf_md() sets the message digest associated with the HKDF. - -EVP_PKEY_CTX_set1_hkdf_salt() sets the salt to B bytes of the -buffer B. Any existing value is replaced. - -EVP_PKEY_CTX_set_hkdf_key() sets the key to B bytes of the buffer -B. Any existing value is replaced. - -EVP_PKEY_CTX_add1_hkdf_info() sets the info value to B bytes of the -buffer B. If a value is already set, it is appended to the existing -value. - -=head1 STRING CTRLS - -HKDF also supports string based control operations via -L. -The B parameter "md" uses the supplied B as the name of the digest -algorithm to use. -The B parameters "salt", "key" and "info" use the supplied B -parameter as a B, B or B value. -The names "hexsalt", "hexkey" and "hexinfo" are similar except they take a hex -string which is converted to binary. - -=head1 NOTES - -All these functions are implemented as macros. - -A context for HKDF can be obtained by calling: - - EVP_PKEY_CTX *pctx = EVP_PKEY_new_id(EVP_PKEY_HKDF, NULL); - -The digest, key, salt and info values must be set before a key is derived or -an error occurs. - -The total length of the info buffer cannot exceed 1024 bytes in length: this -should be more than enough for any normal use of HKDF. - -The output length of the KDF is specified via the length parameter to the -L function. -Since the HKDF output length is variable, passing a B buffer as a means -to obtain the requisite length is not meaningful with HKDF. -Instead, the caller must allocate a buffer of the desired length, and pass that -buffer to L along with (a pointer initialized to) the -desired length. - -Optimised versions of HKDF can be implemented in an ENGINE. - -=head1 RETURN VALUES - -All these functions return 1 for success and 0 or a negative value for failure. -In particular a return value of -2 indicates the operation is not supported by -the public key algorithm. - -=head1 EXAMPLE - -This example derives 10 bytes using SHA-256 with the secret key "secret", -salt value "salt" and info value "label": - - EVP_PKEY_CTX *pctx; - unsigned char out[10]; - size_t outlen = sizeof(out); - pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL); - - if (EVP_PKEY_derive_init(pctx) <= 0) - /* Error */ - if (EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()) <= 0) - /* Error */ - if (EVP_PKEY_CTX_set1_salt(pctx, "salt", 4) <= 0) - /* Error */ - if (EVP_PKEY_CTX_set1_key(pctx, "secret", 6) <= 0) - /* Error */ - if (EVP_PKEY_CTX_add1_hkdf_info(pctx, "label", 6) <= 0) - /* Error */ - if (EVP_PKEY_derive(pctx, out, &outlen) <= 0) - /* Error */ - -=head1 CONFORMING TO - -RFC 5869 - -=head1 SEE ALSO - -L, -L, -L - -=head1 COPYRIGHT - -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 -L. - -=cut diff --git a/doc/crypto/EVP_PKEY_keygen.pod b/doc/crypto/EVP_PKEY_keygen.pod deleted file mode 100644 index b1e708fc..00000000 --- a/doc/crypto/EVP_PKEY_keygen.pod +++ /dev/null @@ -1,175 +0,0 @@ -=pod - -=head1 NAME - -EVP_PKEY_keygen_init, EVP_PKEY_keygen, EVP_PKEY_paramgen_init, -EVP_PKEY_paramgen, EVP_PKEY_CTX_set_cb, EVP_PKEY_CTX_get_cb, -EVP_PKEY_CTX_get_keygen_info, EVP_PKEY_CTX_set_app_data, -EVP_PKEY_CTX_get_app_data, -EVP_PKEY_gen_cb -- key and parameter generation functions - -=head1 SYNOPSIS - - #include - - int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx); - int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey); - int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx); - int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey); - - typedef int EVP_PKEY_gen_cb(EVP_PKEY_CTX *ctx); - - void EVP_PKEY_CTX_set_cb(EVP_PKEY_CTX *ctx, EVP_PKEY_gen_cb *cb); - EVP_PKEY_gen_cb *EVP_PKEY_CTX_get_cb(EVP_PKEY_CTX *ctx); - - int EVP_PKEY_CTX_get_keygen_info(EVP_PKEY_CTX *ctx, int idx); - - void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX *ctx, void *data); - void *EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX *ctx); - -=head1 DESCRIPTION - -The EVP_PKEY_keygen_init() function initializes a public key algorithm -context using key B for a key generation operation. - -The EVP_PKEY_keygen() function performs a key generation operation, the -generated key is written to B. - -The functions EVP_PKEY_paramgen_init() and EVP_PKEY_paramgen() are similar -except parameters are generated. - -The function EVP_PKEY_set_cb() sets the key or parameter generation callback -to B. The function EVP_PKEY_CTX_get_cb() returns the key or parameter -generation callback. - -The function EVP_PKEY_CTX_get_keygen_info() returns parameters associated -with the generation operation. If B is -1 the total number of -parameters available is returned. Any non negative value returns the value of -that parameter. EVP_PKEY_CTX_gen_keygen_info() with a non-negative value for -B should only be called within the generation callback. - -If the callback returns 0 then the key generation operation is aborted and an -error occurs. This might occur during a time consuming operation where -a user clicks on a "cancel" button. - -The functions EVP_PKEY_CTX_set_app_data() and EVP_PKEY_CTX_get_app_data() set -and retrieve an opaque pointer. This can be used to set some application -defined value which can be retrieved in the callback: for example a handle -which is used to update a "progress dialog". - -=head1 NOTES - -After the call to EVP_PKEY_keygen_init() or EVP_PKEY_paramgen_init() algorithm -specific control operations can be performed to set any appropriate parameters -for the operation. - -The functions EVP_PKEY_keygen() and EVP_PKEY_paramgen() can be called more than -once on the same context if several operations are performed using the same -parameters. - -The meaning of the parameters passed to the callback will depend on the -algorithm and the specific implementation of the algorithm. Some might not -give any useful information at all during key or parameter generation. Others -might not even call the callback. - -The operation performed by key or parameter generation depends on the algorithm -used. In some cases (e.g. EC with a supplied named curve) the "generation" -option merely sets the appropriate fields in an EVP_PKEY structure. - -In OpenSSL an EVP_PKEY structure containing a private key also contains the -public key components and parameters (if any). An OpenSSL private key is -equivalent to what some libraries call a "key pair". A private key can be used -in functions which require the use of a public key or parameters. - -=head1 RETURN VALUES - -EVP_PKEY_keygen_init(), EVP_PKEY_paramgen_init(), EVP_PKEY_keygen() and -EVP_PKEY_paramgen() return 1 for success and 0 or a negative value for failure. -In particular a return value of -2 indicates the operation is not supported by -the public key algorithm. - -=head1 EXAMPLES - -Generate a 2048 bit RSA key: - - #include - #include - - EVP_PKEY_CTX *ctx; - EVP_PKEY *pkey = NULL; - ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL); - if (!ctx) - /* Error occurred */ - if (EVP_PKEY_keygen_init(ctx) <= 0) - /* Error */ - if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048) <= 0) - /* Error */ - - /* Generate key */ - if (EVP_PKEY_keygen(ctx, &pkey) <= 0) - /* Error */ - -Generate a key from a set of parameters: - - #include - #include - - EVP_PKEY_CTX *ctx; - EVP_PKEY *pkey = NULL, *param; - /* Assumed param is set up already */ - ctx = EVP_PKEY_CTX_new(param); - if (!ctx) - /* Error occurred */ - if (EVP_PKEY_keygen_init(ctx) <= 0) - /* Error */ - - /* Generate key */ - if (EVP_PKEY_keygen(ctx, &pkey) <= 0) - /* Error */ - -Example of generation callback for OpenSSL public key implementations: - - /* Application data is a BIO to output status to */ - - EVP_PKEY_CTX_set_app_data(ctx, status_bio); - - static int genpkey_cb(EVP_PKEY_CTX *ctx) - { - char c = '*'; - BIO *b = EVP_PKEY_CTX_get_app_data(ctx); - int p; - p = EVP_PKEY_CTX_get_keygen_info(ctx, 0); - if (p == 0) c = '.'; - if (p == 1) c = '+'; - if (p == 2) c = '*'; - if (p == 3) c = '\n'; - BIO_write(b, &c, 1); - (void)BIO_flush(b); - return 1; - } - -=head1 SEE ALSO - -L, -L, -L, -L, -L, -L, -L - -=head1 HISTORY - -These functions were first added to OpenSSL 1.0.0. - -=head1 COPYRIGHT - -Copyright 2006-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 -L. - -=cut diff --git a/doc/crypto/OCSP_response_status.pod b/doc/crypto/OCSP_response_status.pod deleted file mode 100644 index 180ab8d3..00000000 --- a/doc/crypto/OCSP_response_status.pod +++ /dev/null @@ -1,100 +0,0 @@ -=pod - -=head1 NAME - -OCSP_response_status, OCSP_response_get1_basic, OCSP_response_create, -OCSP_RESPONSE_free, OCSP_RESPID_set_by_name, -OCSP_RESPID_set_by_key, OCSP_RESPID_match - OCSP response functions - -=head1 SYNOPSIS - - #include - - int OCSP_response_status(OCSP_RESPONSE *resp); - OCSP_BASICRESP *OCSP_response_get1_basic(OCSP_RESPONSE *resp); - OCSP_RESPONSE *OCSP_response_create(int status, OCSP_BASICRESP *bs); - void OCSP_RESPONSE_free(OCSP_RESPONSE *resp); - - int OCSP_RESPID_set_by_name(OCSP_RESPID *respid, X509 *cert); - int OCSP_RESPID_set_by_key(OCSP_RESPID *respid, X509 *cert); - int OCSP_RESPID_match(OCSP_RESPID *respid, X509 *cert); - -=head1 DESCRIPTION - -OCSP_response_status() returns the OCSP response status of B. It returns -one of the values: B, -B, -B, B -B, or B. - -OCSP_response_get1_basic() decodes and returns the B structure -contained in B. - -OCSP_response_create() creates and returns an B structure for -B and optionally including basic response B. - -OCSP_RESPONSE_free() frees up OCSP response B. - -OCSP_RESPID_set_by_name() sets the name of the OCSP_RESPID to be the same as the -subject name in the supplied X509 certificate B for the OCSP responder. - -OCSP_RESPID_set_by_key() sets the key of the OCSP_RESPID to be the same as the -key in the supplied X509 certificate B for the OCSP responder. The key is -stored as a SHA1 hash. - -Note that an OCSP_RESPID can only have one of the name, or the key set. Calling -OCSP_RESPID_set_by_name() or OCSP_RESPID_set_by_key() will clear any existing -setting. - -OCSP_RESPID_match() tests whether the OCSP_RESPID given in B matches -with the X509 certificate B. - -=head1 RETURN VALUES - -OCSP_RESPONSE_status() returns a status value. - -OCSP_response_get1_basic() returns an B structure pointer or -B if an error occurred. - -OCSP_response_create() returns an B structure pointer or B -if an error occurred. - -OCSP_RESPONSE_free() does not return a value. - -OCSP_RESPID_set_by_name() and OCSP_RESPID_set_by_key() return 1 on success or 0 -on failure. - -OCSP_RESPID_match() returns 1 if the OCSP_RESPID and the X509 certificate match -or 0 otherwise. - -=head1 NOTES - -OCSP_response_get1_basic() is only called if the status of a response is -B. - -=head1 SEE ALSO - -L -L -L -L -L -L -L -L - -=head1 HISTORY - -The OCSP_RESPID_set_by_name(), OCSP_RESPID_set_by_key() and OCSP_RESPID_match() -functions were added in OpenSSL 1.1.0a. - -=head1 COPYRIGHT - -Copyright 2015-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 -L. - -=cut diff --git a/doc/crypto/OpenSSL_add_all_algorithms.pod b/doc/crypto/OpenSSL_add_all_algorithms.pod deleted file mode 100644 index aaa28dd6..00000000 --- a/doc/crypto/OpenSSL_add_all_algorithms.pod +++ /dev/null @@ -1,90 +0,0 @@ -=pod - -=head1 NAME - -OpenSSL_add_all_algorithms, OpenSSL_add_all_ciphers, OpenSSL_add_all_digests, EVP_cleanup - -add algorithms to internal table - -=head1 SYNOPSIS - - #include - -Deprecated: - - # if OPENSSL_API_COMPAT < 0x10100000L - void OpenSSL_add_all_algorithms(void); - void OpenSSL_add_all_ciphers(void); - void OpenSSL_add_all_digests(void); - - void EVP_cleanup(void) -# endif - -=head1 DESCRIPTION - -OpenSSL keeps an internal table of digest algorithms and ciphers. It uses -this table to lookup ciphers via functions such as EVP_get_cipher_byname(). In -OpenSSL versions prior to 1.1.0 these functions initialised and de-initialised -this table. From OpenSSL 1.1.0 they are deprecated. No explicit initialisation -or de-initialisation is required. See L for further -information. - -OpenSSL_add_all_digests() adds all digest algorithms to the table. - -OpenSSL_add_all_algorithms() adds all algorithms to the table (digests and -ciphers). - -OpenSSL_add_all_ciphers() adds all encryption algorithms to the table including -password based encryption algorithms. - -In versions prior to 1.1.0 EVP_cleanup() removed all ciphers and digests from -the table. It no longer has any effect in OpenSSL 1.1.0. - -=head1 RETURN VALUES - -None of the functions return a value. - -=head1 NOTES - -A typical application will call OpenSSL_add_all_algorithms() initially and -EVP_cleanup() before exiting. - -An application does not need to add algorithms to use them explicitly, for example -by EVP_sha1(). It just needs to add them if it (or any of the functions it calls) -needs to lookup algorithms. - -The cipher and digest lookup functions are used in many parts of the library. If -the table is not initialized several functions will misbehave and complain they -cannot find algorithms. This includes the PEM, PKCS#12, SSL and S/MIME libraries. -This is a common query in the OpenSSL mailing lists. - -Calling OpenSSL_add_all_algorithms() links in all algorithms: as a result a -statically linked executable can be quite large. If this is important it is possible -to just add the required ciphers and digests. - -=head1 BUGS - -Although the functions do not return error codes it is possible for them to fail. -This will only happen as a result of a memory allocation failure so this is not -too much of a problem in practice. - -=head1 SEE ALSO - -L, L, -L - -=head1 HISTORY - -The OpenSSL_add_all_algorithms(), OpenSSL_add_all_ciphers(), -OpenSSL_add_all_digests(), and EVP_cleanup(), functions -were deprecated in OpenSSL 1.1.0 by OPENSSL_init_crypto(). - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/PKCS12_newpass.pod b/doc/crypto/PKCS12_newpass.pod deleted file mode 100644 index 6b22fd72..00000000 --- a/doc/crypto/PKCS12_newpass.pod +++ /dev/null @@ -1,115 +0,0 @@ -=pod - -=head1 NAME - -PKCS12_newpass - change the password of a PKCS12 structure - -=head1 SYNOPSIS - - #include - - int PKCS12_newpass(PKCS12 *p12, const char *oldpass, const char *newpass); - -=head1 DESCRIPTION - -PKCS12_newpass() changes the password of a PKCS12 structure. - -B is a pointer to a PKCS12 structure. B is the existing password -and B is the new password. - -=head1 NOTES - -Each of B and B is independently interpreted as a string in -the UTF-8 encoding. If it is not valid UTF-8, it is assumed to be ISO8859-1 -instead. - -In particular, this means that passwords in the locale character set -(or code page on Windows) must potentially be converted to UTF-8 before -use. This may include passwords from local text files, or input from -the terminal or command line. Refer to the documentation of -L, for example. - -=head1 RETURN VALUES - -PKCS12_newpass() returns 1 on success or 0 on failure. Applications can -retrieve the most recent error from PKCS12_newpass() with ERR_get_error(). - -=head1 EXAMPLE - -This example loads a PKCS#12 file, changes its password and writes out -the result to a new file. - - #include - #include - #include - #include - #include - - int main(int argc, char **argv) - { - FILE *fp; - PKCS12 *p12; - if (argc != 5) { - fprintf(stderr, "Usage: pkread p12file password newpass opfile\n"); - return 1; - } - if ((fp = fopen(argv[1], "rb")) == NULL) { - fprintf(stderr, "Error opening file %s\n", argv[1]); - return 1; - } - p12 = d2i_PKCS12_fp(fp, NULL); - fclose(fp); - if (p12 == NULL) { - fprintf(stderr, "Error reading PKCS#12 file\n"); - ERR_print_errors_fp(stderr); - return 1; - } - if (PKCS12_newpass(p12, argv[2], argv[3]) == 0) { - fprintf(stderr, "Error changing password\n"); - ERR_print_errors_fp(stderr); - PKCS12_free(p12); - return 1; - } - if ((fp = fopen(argv[4], "wb")) == NULL) { - fprintf(stderr, "Error opening file %s\n", argv[4]); - PKCS12_free(p12); - return 1; - } - i2d_PKCS12_fp(fp, p12); - PKCS12_free(p12); - fclose(fp); - return 0; - } - - -=head1 NOTES - -If the PKCS#12 structure does not have a password, then you must use the empty -string "" for B. Using NULL for B will result in a -PKCS12_newpass() failure. - -If the wrong password is used for B then the function will fail, -with a MAC verification error. In rare cases the PKCS12 structure does not -contain a MAC: in this case it will usually fail with a decryption padding -error. - -=head1 BUGS - -The password format is a NULL terminated ASCII string which is converted to -Unicode form internally. As a result some passwords cannot be supplied to -this function. - -=head1 SEE ALSO - -L, L - -=head1 COPYRIGHT - -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 -L. - -=cut diff --git a/doc/crypto/RAND_add.pod b/doc/crypto/RAND_add.pod deleted file mode 100644 index 46de165a..00000000 --- a/doc/crypto/RAND_add.pod +++ /dev/null @@ -1,79 +0,0 @@ -=pod - -=head1 NAME - -RAND_add, RAND_seed, RAND_status, RAND_event, RAND_screen - add -entropy to the PRNG - -=head1 SYNOPSIS - - #include - - void RAND_seed(const void *buf, int num); - - void RAND_add(const void *buf, int num, double entropy); - - int RAND_status(void); - - #if OPENSSL_API_COMPAT < 0x10100000L - int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam); - void RAND_screen(void); - #endif - -=head1 DESCRIPTION - -RAND_add() mixes the B bytes at B into the PRNG state. Thus, -if the data at B are unpredictable to an adversary, this -increases the uncertainty about the state and makes the PRNG output -less predictable. Suitable input comes from user interaction (random -key presses, mouse movements) and certain hardware events. The -B argument is (the lower bound of) an estimate of how much -randomness is contained in B, measured in bytes. Details about -sources of randomness and how to estimate their entropy can be found -in the literature, e.g. RFC 1750. - -RAND_add() may be called with sensitive data such as user entered -passwords. The seed values cannot be recovered from the PRNG output. - -OpenSSL makes sure that the PRNG state is unique for each thread. On -systems that provide C, the randomness device is used -to seed the PRNG transparently. However, on all other systems, the -application is responsible for seeding the PRNG by calling RAND_add(), -L -or L. - -RAND_seed() is equivalent to RAND_add() when B. - -RAND_event() and RAND_screen() are deprecated and should not be called. - -=head1 RETURN VALUES - -RAND_status() returns 1 if the PRNG has been seeded -with enough data, 0 otherwise. - -RAND_event() calls RAND_poll() and returns RAND_status(). - -RAND_screen calls RAND_poll(). - -The other functions do not return values. - -=head1 HISTORY - -RAND_event() and RAND_screen() are deprecated since OpenSSL -1.1.0. Use the functions described above instead. - -=head1 SEE ALSO - -L, L, -L, L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/RAND_bytes.pod b/doc/crypto/RAND_bytes.pod deleted file mode 100644 index 684215ce..00000000 --- a/doc/crypto/RAND_bytes.pod +++ /dev/null @@ -1,58 +0,0 @@ -=pod - -=head1 NAME - -RAND_bytes, RAND_pseudo_bytes - generate random data - -=head1 SYNOPSIS - - #include - - int RAND_bytes(unsigned char *buf, int num); - -Deprecated: - - #if OPENSSL_API_COMPAT < 0x10100000L - int RAND_pseudo_bytes(unsigned char *buf, int num); - #endif - -=head1 DESCRIPTION - -RAND_bytes() puts B cryptographically strong pseudo-random bytes -into B. An error occurs if the PRNG has not been seeded with -enough randomness to ensure an unpredictable byte sequence. - -RAND_pseudo_bytes() has been deprecated. Users should use RAND_bytes() instead. -RAND_pseudo_bytes() puts B pseudo-random bytes into B. -Pseudo-random byte sequences generated by RAND_pseudo_bytes() will be -unique if they are of sufficient length, but are not necessarily -unpredictable. They can be used for non-cryptographic purposes and for -certain purposes in cryptographic protocols, but usually not for key -generation etc. - -The contents of B is mixed into the entropy pool before retrieving -the new pseudo-random bytes unless disabled at compile time (see FAQ). - -=head1 RETURN VALUES - -RAND_bytes() returns 1 on success, 0 otherwise. The error code can be -obtained by L. RAND_pseudo_bytes() returns 1 if the -bytes generated are cryptographically strong, 0 otherwise. Both -functions return -1 if they are not supported by the current RAND -method. - -=head1 SEE ALSO - -L, L, -L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/RAND_cleanup.pod b/doc/crypto/RAND_cleanup.pod deleted file mode 100644 index 2640c7d2..00000000 --- a/doc/crypto/RAND_cleanup.pod +++ /dev/null @@ -1,42 +0,0 @@ -=pod - -=head1 NAME - -RAND_cleanup - erase the PRNG state - -=head1 SYNOPSIS - - #include - - #if OPENSSL_API_COMPAT < 0x10100000L - void RAND_cleanup(void) - #endif - -=head1 DESCRIPTION - -Prior to OpenSSL 1.1.0 RAND_cleanup() erases the memory used by the PRNG. This -function is deprecated and as of version 1.1.0 does nothing. No explicit -initialisation or de-initialisation is necessary. See L. - -=head1 RETURN VALUE - -RAND_cleanup() returns no value. - -=head1 SEE ALSO - -L - -=head1 HISTORY - -RAND_cleanup() was deprecated in OpenSSL 1.1.0. - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/RAND_egd.pod b/doc/crypto/RAND_egd.pod deleted file mode 100644 index fcc57c06..00000000 --- a/doc/crypto/RAND_egd.pod +++ /dev/null @@ -1,87 +0,0 @@ -=pod - -=head1 NAME - -RAND_egd, RAND_egd_bytes, RAND_query_egd_bytes - query entropy gathering daemon - -=head1 SYNOPSIS - - #include - - int RAND_egd(const char *path); - int RAND_egd_bytes(const char *path, int bytes); - - int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes); - -=head1 DESCRIPTION - -RAND_egd() queries the entropy gathering daemon EGD on socket B. -It queries 255 bytes and uses L to seed the -OpenSSL built-in PRNG. RAND_egd(path) is a wrapper for -RAND_egd_bytes(path, 255); - -RAND_egd_bytes() queries the entropy gathering daemon EGD on socket B. -It queries B bytes and uses L to seed the -OpenSSL built-in PRNG. -This function is more flexible than RAND_egd(). -When only one secret key must -be generated, it is not necessary to request the full amount 255 bytes from -the EGD socket. This can be advantageous, since the amount of entropy -that can be retrieved from EGD over time is limited. - -RAND_query_egd_bytes() performs the actual query of the EGD daemon on socket -B. If B is given, B bytes are queried and written into -B. If B is NULL, B bytes are queried and used to seed the -OpenSSL built-in PRNG using L. - -=head1 NOTES - -On systems without /dev/*random devices providing entropy from the kernel, -the EGD entropy gathering daemon can be used to collect entropy. It provides -a socket interface through which entropy can be gathered in chunks up to -255 bytes. Several chunks can be queried during one connection. - -EGD is available from http://www.lothar.com/tech/crypto/ (C to install). It is run as B -I, where I is an absolute path designating a socket. When -RAND_egd() is called with that path as an argument, it tries to read -random bytes that EGD has collected. RAND_egd() retrieves entropy from the -daemon using the daemon's "non-blocking read" command which shall -be answered immediately by the daemon without waiting for additional -entropy to be collected. The write and read socket operations in the -communication are blocking. - -Alternatively, the EGD-interface compatible daemon PRNGD can be used. It is -available from -http://prngd.sourceforge.net/ . -PRNGD does employ an internal PRNG itself and can therefore never run -out of entropy. - -OpenSSL automatically queries EGD when entropy is requested via RAND_bytes() -or the status is checked via RAND_status() for the first time, if the socket -is located at /var/run/egd-pool, /dev/egd-pool or /etc/egd-pool. - -=head1 RETURN VALUE - -RAND_egd() and RAND_egd_bytes() return the number of bytes read from the -daemon on success, and -1 if the connection failed or the daemon did not -return enough data to fully seed the PRNG. - -RAND_query_egd_bytes() returns the number of bytes read from the daemon on -success, and -1 if the connection failed. The PRNG state is not considered. - -=head1 SEE ALSO - -L, L, -L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/RAND_load_file.pod b/doc/crypto/RAND_load_file.pod deleted file mode 100644 index 1053a925..00000000 --- a/doc/crypto/RAND_load_file.pod +++ /dev/null @@ -1,79 +0,0 @@ -=pod - -=head1 NAME - -RAND_load_file, RAND_write_file, RAND_file_name - PRNG seed file - -=head1 SYNOPSIS - - #include - - const char *RAND_file_name(char *buf, size_t num); - - int RAND_load_file(const char *filename, long max_bytes); - - int RAND_write_file(const char *filename); - -=head1 DESCRIPTION - -RAND_file_name() generates a default path for the random seed -file. B points to a buffer of size B in which to store the -filename. - -On all systems, if the environment variable B is set, its -value will be used as the seed file name. - -Otherwise, the file is called ".rnd", found in platform dependent locations: - -=over 4 - -=item On Windows (in order of preference) - -%HOME%, %USERPROFILE%, %SYSTEMROOT%, C:\ - -=item On VMS - -SYS$LOGIN: - -=item On all other systems - -$HOME - -=back - -If C<$HOME> (on non-Windows and non-VMS system) is not set either, or -B is too small for the path name, an error occurs. - -RAND_load_file() reads a number of bytes from file B and -adds them to the PRNG. If B is non-negative, -up to B are read; -if B is -1, the complete file is read. - -RAND_write_file() writes a number of random bytes (currently 1024) to -file B which can be used to initialize the PRNG by calling -RAND_load_file() in a later session. - -=head1 RETURN VALUES - -RAND_load_file() returns the number of bytes read or -1 on error. - -RAND_write_file() returns the number of bytes written, and -1 if the -bytes written were generated without appropriate seed. - -RAND_file_name() returns a pointer to B on success, and NULL on -error. - -=head1 SEE ALSO - -L, L, L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/RAND_set_rand_method.pod b/doc/crypto/RAND_set_rand_method.pod deleted file mode 100644 index 02fe90ca..00000000 --- a/doc/crypto/RAND_set_rand_method.pod +++ /dev/null @@ -1,81 +0,0 @@ -=pod - -=head1 NAME - -RAND_set_rand_method, RAND_get_rand_method, RAND_OpenSSL - select RAND method - -=head1 SYNOPSIS - - #include - - void RAND_set_rand_method(const RAND_METHOD *meth); - - const RAND_METHOD *RAND_get_rand_method(void); - - RAND_METHOD *RAND_OpenSSL(void); - -=head1 DESCRIPTION - -A B specifies the functions that OpenSSL uses for random number -generation. By modifying the method, alternative implementations such as -hardware RNGs may be used. IMPORTANT: See the NOTES section for important -information about how these RAND API functions are affected by the use of -B API calls. - -Initially, the default RAND_METHOD is the OpenSSL internal implementation, as -returned by RAND_OpenSSL(). - -RAND_set_default_method() makes B the method for PRNG use. B: This is -true only whilst no ENGINE has been set as a default for RAND, so this function -is no longer recommended. - -RAND_get_default_method() returns a pointer to the current RAND_METHOD. -However, the meaningfulness of this result is dependent on whether the ENGINE -API is being used, so this function is no longer recommended. - -=head1 THE RAND_METHOD STRUCTURE - - typedef struct rand_meth_st - { - void (*seed)(const void *buf, int num); - int (*bytes)(unsigned char *buf, int num); - void (*cleanup)(void); - void (*add)(const void *buf, int num, int entropy); - int (*pseudorand)(unsigned char *buf, int num); - int (*status)(void); - } RAND_METHOD; - -The components point to method implementations used by (or called by), in order, -RAND_seed(), RAND_bytes(), internal RAND cleanup, RAND_add(), RAND_pseudo_rand() -and RAND_status(). -Each component may be NULL if the function is not implemented. - -=head1 RETURN VALUES - -RAND_set_rand_method() returns no value. RAND_get_rand_method() and -RAND_OpenSSL() return pointers to the respective methods. - -=head1 NOTES - -RAND_METHOD implementations are grouped together with other -algorithmic APIs (eg. RSA_METHOD, EVP_CIPHER, etc) in B modules. If a -default ENGINE is specified for RAND functionality using an ENGINE API function, -that will override any RAND defaults set using the RAND API (ie. -RAND_set_rand_method()). For this reason, the ENGINE API is the recommended way -to control default implementations for use in RAND and other cryptographic -algorithms. - -=head1 SEE ALSO - -L, L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/RSA_generate_key.pod b/doc/crypto/RSA_generate_key.pod deleted file mode 100644 index e51c0b14..00000000 --- a/doc/crypto/RSA_generate_key.pod +++ /dev/null @@ -1,88 +0,0 @@ -=pod - -=head1 NAME - -RSA_generate_key_ex, RSA_generate_key - generate RSA key pair - -=head1 SYNOPSIS - - #include - - int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); - -Deprecated: - - #if OPENSSL_API_COMPAT < 0x00908000L - RSA *RSA_generate_key(int num, unsigned long e, - void (*callback)(int, int, void *), void *cb_arg); - #endif - -=head1 DESCRIPTION - -RSA_generate_key_ex() generates a key pair and stores it in the B -structure provided in B. The pseudo-random number generator must -be seeded prior to calling RSA_generate_key_ex(). - -The modulus size will be of length B, and the public exponent will be -B. Key sizes with B E 1024 should be considered insecure. -The exponent is an odd number, typically 3, 17 or 65537. - -A callback function may be used to provide feedback about the -progress of the key generation. If B is not B, it -will be called as follows using the BN_GENCB_call() function -described on the L page. - -=over 2 - -=item * - -While a random prime number is generated, it is called as -described in L. - -=item * - -When the n-th randomly generated prime is rejected as not -suitable for the key, B is called. - -=item * - -When a random p has been found with p-1 relatively prime to B, -it is called as B. - -=back - -The process is then repeated for prime q with B. - -RSA_generate_key() is deprecated (new applications should use -RSA_generate_key_ex() instead). RSA_generate_key() works in the same way as -RSA_generate_key_ex() except it uses "old style" call backs. See -L for further details. - -=head1 RETURN VALUE - -RSA_generate_key_ex() returns 1 on success or 0 on error. -RSA_generate_key() returns the key on success or B on error. - -The error codes can be obtained by L. - -=head1 BUGS - -B is used with two different meanings. - -RSA_generate_key() goes into an infinite loop for illegal input values. - -=head1 SEE ALSO - -L, L, -L, L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/RSA_get0_key.pod b/doc/crypto/RSA_get0_key.pod deleted file mode 100644 index 579a2df0..00000000 --- a/doc/crypto/RSA_get0_key.pod +++ /dev/null @@ -1,112 +0,0 @@ -=pod - -=head1 NAME - -RSA_set0_key, RSA_set0_factors, RSA_set0_crt_params, RSA_get0_key, -RSA_get0_factors, RSA_get0_crt_params, RSA_clear_flags, -RSA_test_flags, RSA_set_flags, RSA_get0_engine - Routines for getting -and setting data in an RSA object - -=head1 SYNOPSIS - - #include - - int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d); - int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q); - int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp); - void RSA_get0_key(const RSA *r, - const BIGNUM **n, const BIGNUM **e, const BIGNUM **d); - void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q); - void RSA_get0_crt_params(const RSA *r, - const BIGNUM **dmp1, const BIGNUM **dmq1, - const BIGNUM **iqmp); - void RSA_clear_flags(RSA *r, int flags); - int RSA_test_flags(const RSA *r, int flags); - void RSA_set_flags(RSA *r, int flags); - ENGINE *RSA_get0_engine(RSA *r); - -=head1 DESCRIPTION - -An RSA object contains the components for the public and private key, -B, B, B, B

, B, B, B and B. B is -the modulus common to both public and private key, B is the public -exponent and B is the private exponent. B

, B, B, -B and B are the factors for the second representation of a -private key (see PKCS#1 section 3 Key Types), where B

and B are -the first and second factor of B and B, B and B -are the exponents and coefficient for CRT calculations. - -The B, B and B parameters can be obtained by calling -RSA_get0_key(). If they have not been set yet, then B<*n>, B<*e> and -B<*d> will be set to NULL. Otherwise, they are set to pointers to -their respective values. These point directly to the internal -representations of the values and therefore should not be freed -by the caller. - -The B, B and B parameter values can be set by calling -RSA_set0_key() and passing the new values for B, B and B as -parameters to the function. The values B and B must be non-NULL -the first time this function is called on a given RSA object. The -value B may be NULL. On subsequent calls any of these values may be -NULL which means the corresponding RSA field is left untouched. -Calling this function transfers the memory management of the values to -the RSA object, and therefore the values that have been passed in -should not be freed by the caller after this function has been called. - -In a similar fashion, the B

and B parameters can be obtained and -set with RSA_get0_factors() and RSA_set0_factors(), and the B, -B and B parameters can be obtained and set with -RSA_get0_crt_params() and RSA_set0_crt_params(). - -For RSA_get0_key(), RSA_get0_factors(), and RSA_get0_crt_params(), -NULL value BIGNUM ** output parameters are permitted. The functions -ignore NULL parameters but return values for other, non-NULL, parameters. - -RSA_set_flags() sets the flags in the B parameter on the RSA -object. Multiple flags can be passed in one go (bitwise ORed together). -Any flags that are already set are left set. RSA_test_flags() tests to -see whether the flags passed in the B parameter are currently -set in the RSA object. Multiple flags can be tested in one go. All -flags that are currently set are returned, or zero if none of the -flags are set. RSA_clear_flags() clears the specified flags within the -RSA object. - -RSA_get0_engine() returns a handle to the ENGINE that has been set for -this RSA object, or NULL if no such ENGINE has been set. - -=head1 NOTES - -Values retrieved with RSA_get0_key() are owned by the RSA object used -in the call and may therefore I be passed to RSA_set0_key(). If -needed, duplicate the received value using BN_dup() and pass the -duplicate. The same applies to RSA_get0_factors() and RSA_set0_factors() -as well as RSA_get0_crt_params() and RSA_set0_crt_params(). - -=head1 RETURN VALUES - -RSA_set0_key(), RSA_set0_factors and RSA_set0_crt_params() return 1 on -success or 0 on failure. - -RSA_test_flags() returns the current state of the flags in the RSA object. - -RSA_get0_engine() returns the ENGINE set for the RSA object or NULL if no -ENGINE has been set. - -=head1 SEE ALSO - -L, L, L - -=head1 HISTORY - -The functions described here were added in OpenSSL 1.1.0. - -=head1 COPYRIGHT - -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 -L. - -=cut diff --git a/doc/crypto/RSA_meth_new.pod b/doc/crypto/RSA_meth_new.pod deleted file mode 100644 index 9970aa6b..00000000 --- a/doc/crypto/RSA_meth_new.pod +++ /dev/null @@ -1,235 +0,0 @@ -=pod - -=head1 NAME - -RSA_meth_get0_app_data, RSA_meth_set0_app_data, -RSA_meth_new, RSA_meth_free, RSA_meth_dup, RSA_meth_get0_name, -RSA_meth_set1_name, RSA_meth_get_flags, RSA_meth_set_flags, -RSA_meth_get_pub_enc, -RSA_meth_set_pub_enc, RSA_meth_get_pub_dec, RSA_meth_set_pub_dec, -RSA_meth_get_priv_enc, RSA_meth_set_priv_enc, RSA_meth_get_priv_dec, -RSA_meth_set_priv_dec, RSA_meth_get_mod_exp, RSA_meth_set_mod_exp, -RSA_meth_get_bn_mod_exp, RSA_meth_set_bn_mod_exp, RSA_meth_get_init, -RSA_meth_set_init, RSA_meth_get_finish, RSA_meth_set_finish, -RSA_meth_get_sign, RSA_meth_set_sign, RSA_meth_get_verify, -RSA_meth_set_verify, RSA_meth_get_keygen, RSA_meth_set_keygen -- Routines to build up RSA methods - -=head1 SYNOPSIS - - #include - - RSA_METHOD *RSA_meth_new(const char *name, int flags); - void RSA_meth_free(RSA_METHOD *meth); - RSA_METHOD *RSA_meth_dup(const RSA_METHOD *meth); - const char *RSA_meth_get0_name(const RSA_METHOD *meth); - int RSA_meth_set1_name(RSA_METHOD *meth, const char *name); - int RSA_meth_get_flags(RSA_METHOD *meth); - int RSA_meth_set_flags(RSA_METHOD *meth, int flags); - void *RSA_meth_get0_app_data(const RSA_METHOD *meth); - int RSA_meth_set0_app_data(RSA_METHOD *meth, void *app_data); - int (*RSA_meth_get_pub_enc(const RSA_METHOD *meth)) - (int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); - int RSA_meth_set_pub_enc(RSA_METHOD *rsa, - int (*pub_enc) (int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, - int padding)); - int (*RSA_meth_get_pub_dec(const RSA_METHOD *meth)) - (int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); - int RSA_meth_set_pub_dec(RSA_METHOD *rsa, - int (*pub_dec) (int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, - int padding)); - int (*RSA_meth_get_priv_enc(const RSA_METHOD *meth)) - (int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); - int RSA_meth_set_priv_enc(RSA_METHOD *rsa, - int (*priv_enc) (int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, - int padding)); - int (*RSA_meth_get_priv_dec(const RSA_METHOD *meth)) - (int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); - int RSA_meth_set_priv_dec(RSA_METHOD *rsa, - int (*priv_dec) (int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, - int padding)); - /* Can be null */ - int (*RSA_meth_get_mod_exp(const RSA_METHOD *meth)) - (BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); - int RSA_meth_set_mod_exp(RSA_METHOD *rsa, - int (*mod_exp) (BIGNUM *r0, const BIGNUM *I, RSA *rsa, - BN_CTX *ctx)); - /* Can be null */ - int (*RSA_meth_get_bn_mod_exp(const RSA_METHOD *meth)) - (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, - const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); - int RSA_meth_set_bn_mod_exp(RSA_METHOD *rsa, - int (*bn_mod_exp) (BIGNUM *r, - const BIGNUM *a, - const BIGNUM *p, - const BIGNUM *m, - BN_CTX *ctx, - BN_MONT_CTX *m_ctx)); - /* called at new */ - int (*RSA_meth_get_init(const RSA_METHOD *meth)) (RSA *rsa); - int RSA_meth_set_init(RSA_METHOD *rsa, int (*init) (RSA *rsa)); - /* called at free */ - int (*RSA_meth_get_finish(const RSA_METHOD *meth)) (RSA *rsa); - int RSA_meth_set_finish(RSA_METHOD *rsa, int (*finish) (RSA *rsa)); - int (*RSA_meth_get_sign(const RSA_METHOD *meth)) - (int type, - const unsigned char *m, unsigned int m_length, - unsigned char *sigret, unsigned int *siglen, - const RSA *rsa); - int RSA_meth_set_sign(RSA_METHOD *rsa, - int (*sign) (int type, const unsigned char *m, - unsigned int m_length, - unsigned char *sigret, unsigned int *siglen, - const RSA *rsa)); - int (*RSA_meth_get_verify(const RSA_METHOD *meth)) - (int dtype, const unsigned char *m, - unsigned int m_length, const unsigned char *sigbuf, - unsigned int siglen, const RSA *rsa); - int RSA_meth_set_verify(RSA_METHOD *rsa, - int (*verify) (int dtype, const unsigned char *m, - unsigned int m_length, - const unsigned char *sigbuf, - unsigned int siglen, const RSA *rsa)); - int (*RSA_meth_get_keygen(const RSA_METHOD *meth)) - (RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); - int RSA_meth_set_keygen(RSA_METHOD *rsa, - int (*keygen) (RSA *rsa, int bits, BIGNUM *e, - BN_GENCB *cb)); - -=head1 DESCRIPTION - -The B type is a structure used for the provision of custom -RSA implementations. It provides a set of of functions used by OpenSSL -for the implementation of the various RSA capabilities. See the L -page for more information. - -RSA_meth_new() creates a new B structure. It should be -given a unique B and a set of B. The B should be a -NULL terminated string, which will be duplicated and stored in the -B object. It is the callers responsibility to free the -original string. The flags will be used during the construction of a -new B object based on this B. Any new B object -will have those flags set by default. - -RSA_meth_dup() creates a duplicate copy of the B object -passed as a parameter. This might be useful for creating a new -B based on an existing one, but with some differences. - -RSA_meth_free() destroys an B structure and frees up any -memory associated with it. - -RSA_meth_get0_name() will return a pointer to the name of this -RSA_METHOD. This is a pointer to the internal name string and so -should not be freed by the caller. RSA_meth_set1_name() sets the name -of the RSA_METHOD to B. The string is duplicated and the copy is -stored in the RSA_METHOD structure, so the caller remains responsible -for freeing the memory associated with the name. - -RSA_meth_get_flags() returns the current value of the flags associated -with this RSA_METHOD. RSA_meth_set_flags() provides the ability to set -these flags. - -The functions RSA_meth_get0_app_data() and RSA_meth_set0_app_data() -provide the ability to associate implementation specific data with the -RSA_METHOD. It is the application's responsibility to free this data -before the RSA_METHOD is freed via a call to RSA_meth_free(). - -RSA_meth_get_sign() and RSA_meth_set_sign() get and set the function -used for creating an RSA signature respectively. This function will be -called in response to the application calling RSA_sign(). The -parameters for the function have the same meaning as for RSA_sign(). - -RSA_meth_get_verify() and RSA_meth_set_verify() get and set the -function used for verifying an RSA signature respectively. This -function will be called in response to the application calling -RSA_verify(). The parameters for the function have the same meaning as -for RSA_verify(). - -RSA_meth_get_mod_exp() and RSA_meth_set_mod_exp() get and set the -function used for CRT computations. - -RSA_meth_get_bn_mod_exp() and RSA_meth_set_bn_mod_exp() get and set -the function used for CRT computations, specifically the following -value: - - r = a ^ p mod m - -Both the mod_exp() and bn_mod_exp() functions are called by the -default OpenSSL method during encryption, decryption, signing and -verification. - -RSA_meth_get_init() and RSA_meth_set_init() get and set the function -used for creating a new RSA instance respectively. This function will -be called in response to the application calling RSA_new() (if the -current default RSA_METHOD is this one) or RSA_new_method(). The -RSA_new() and RSA_new_method() functions will allocate the memory for -the new RSA object, and a pointer to this newly allocated structure -will be passed as a parameter to the function. This function may be -NULL. - -RSA_meth_get_finish() and RSA_meth_set_finish() get and set the -function used for destroying an instance of an RSA object respectively. -This function will be called in response to the application calling -RSA_free(). A pointer to the RSA to be destroyed is passed as a -parameter. The destroy function should be used for RSA implementation -specific clean up. The memory for the RSA itself should not be freed -by this function. This function may be NULL. - -RSA_meth_get_keygen() and RSA_meth_set_keygen() get and set the -function used for generating a new RSA key pair respectively. This -function will be called in response to the application calling -RSA_generate_key(). The parameter for the function has the same -meaning as for RSA_generate_key(). - -RSA_meth_get_pub_enc(), RSA_meth_set_pub_enc(), -RSA_meth_get_pub_dec(), RSA_meth_set_pub_dec(), -RSA_meth_get_priv_enc(), RSA_meth_set_priv_enc(), -RSA_meth_get_priv_dec(), RSA_meth_set_priv_dec() get and set the -functions used for public and private key encryption and decryption. -These functions will be called in response to the application calling -RSA_public_encrypt(), RSA_private_decrypt(), RSA_private_encrypt() and -RSA_public_decrypt() and take the same parameters as those. - - -=head1 RETURN VALUES - -RSA_meth_new() and RSA_meth_dup() return the newly allocated -RSA_METHOD object or NULL on failure. - -RSA_meth_get0_name() and RSA_meth_get_flags() return the name and -flags associated with the RSA_METHOD respectively. - -All other RSA_meth_get_*() functions return the appropriate function -pointer that has been set in the RSA_METHOD, or NULL if no such -pointer has yet been set. - -RSA_meth_set1_name and all RSA_meth_set_*() functions return 1 on -success or 0 on failure. - -=head1 SEE ALSO - -L, L, L, -L, L, L - -=head1 HISTORY - -The functions described here were added in OpenSSL 1.1.0. - -=head1 COPYRIGHT - -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 -L. - -=cut diff --git a/doc/crypto/RSA_size.pod b/doc/crypto/RSA_size.pod deleted file mode 100644 index eb6e4813..00000000 --- a/doc/crypto/RSA_size.pod +++ /dev/null @@ -1,46 +0,0 @@ -=pod - -=head1 NAME - -RSA_size, RSA_bits - get RSA modulus size - -=head1 SYNOPSIS - -#include - -int RSA_size(const RSA *rsa); - -int RSA_bits(const RSA *rsa); - -=head1 DESCRIPTION - -RSA_size() returns the RSA modulus size in bytes. It can be used to -determine how much memory must be allocated for an RSA encrypted -value. - -RSA_bits() returns the number of significant bits. - -B and Bn> must not be B. - -=head1 RETURN VALUE - -The size. - -=head1 SEE ALSO - -L - -=head1 HISTORY - -RSA_bits() was added in OpenSSL 1.1.0. - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/UI_new.pod b/doc/crypto/UI_new.pod deleted file mode 100644 index 5b98cf8d..00000000 --- a/doc/crypto/UI_new.pod +++ /dev/null @@ -1,203 +0,0 @@ -=pod - -=head1 NAME - -UI, -UI_new, UI_new_method, UI_free, UI_add_input_string, UI_dup_input_string, -UI_add_verify_string, UI_dup_verify_string, UI_add_input_boolean, -UI_dup_input_boolean, UI_add_info_string, UI_dup_info_string, -UI_add_error_string, UI_dup_error_string, UI_construct_prompt, -UI_add_user_data, UI_get0_user_data, UI_get0_result, UI_process, -UI_ctrl, UI_set_default_method, UI_get_default_method, UI_get_method, -UI_set_method, UI_OpenSSL, UI_null - user interface - -=head1 SYNOPSIS - - #include - - typedef struct ui_st UI; - - UI *UI_new(void); - UI *UI_new_method(const UI_METHOD *method); - void UI_free(UI *ui); - - int UI_add_input_string(UI *ui, const char *prompt, int flags, - char *result_buf, int minsize, int maxsize); - int UI_dup_input_string(UI *ui, const char *prompt, int flags, - char *result_buf, int minsize, int maxsize); - int UI_add_verify_string(UI *ui, const char *prompt, int flags, - char *result_buf, int minsize, int maxsize, const char *test_buf); - int UI_dup_verify_string(UI *ui, const char *prompt, int flags, - char *result_buf, int minsize, int maxsize, const char *test_buf); - int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc, - const char *ok_chars, const char *cancel_chars, - int flags, char *result_buf); - int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc, - const char *ok_chars, const char *cancel_chars, - int flags, char *result_buf); - int UI_add_info_string(UI *ui, const char *text); - int UI_dup_info_string(UI *ui, const char *text); - int UI_add_error_string(UI *ui, const char *text); - int UI_dup_error_string(UI *ui, const char *text); - - char *UI_construct_prompt(UI *ui_method, - const char *object_desc, const char *object_name); - - void *UI_add_user_data(UI *ui, void *user_data); - void *UI_get0_user_data(UI *ui); - - const char *UI_get0_result(UI *ui, int i); - - int UI_process(UI *ui); - - int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f)()); - - void UI_set_default_method(const UI_METHOD *meth); - const UI_METHOD *UI_get_default_method(void); - const UI_METHOD *UI_get_method(UI *ui); - const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth); - - UI_METHOD *UI_OpenSSL(void); - const UI_METHOD *UI_null(void); - -=head1 DESCRIPTION - -UI stands for User Interface, and is general purpose set of routines to -prompt the user for text-based information. Through user-written methods -(see L), prompting can be done in any way -imaginable, be it plain text prompting, through dialog boxes or from a -cell phone. - -All the functions work through a context of the type UI. This context -contains all the information needed to prompt correctly as well as a -reference to a UI_METHOD, which is an ordered vector of functions that -carry out the actual prompting. - -The first thing to do is to create a UI with UI_new() or UI_new_method(), -then add information to it with the UI_add or UI_dup functions. Also, -user-defined random data can be passed down to the underlying method -through calls to UI_add_user_data. The default UI method doesn't care -about these data, but other methods might. Finally, use UI_process() -to actually perform the prompting and UI_get0_result() to find the result -to the prompt. - -A UI can contain more than one prompt, which are performed in the given -sequence. Each prompt gets an index number which is returned by the -UI_add and UI_dup functions, and has to be used to get the corresponding -result with UI_get0_result(). - -The functions are as follows: - -UI_new() creates a new UI using the default UI method. When done with -this UI, it should be freed using UI_free(). - -UI_new_method() creates a new UI using the given UI method. When done with -this UI, it should be freed using UI_free(). - -UI_OpenSSL() returns the built-in UI method (note: not necessarely the -default one, since the default can be changed. See further on). This -method is the most machine/OS dependent part of OpenSSL and normally -generates the most problems when porting. - -UI_null() returns a UI method that does nothing. Its use is to avoid -getting internal defaults for passed UI_METHOD pointers. - -UI_free() removes a UI from memory, along with all other pieces of memory -that's connected to it, like duplicated input strings, results and others. -If B is NULL nothing is done. - -UI_add_input_string() and UI_add_verify_string() add a prompt to the UI, -as well as flags and a result buffer and the desired minimum and maximum -sizes of the result, not counting the final NUL character. The given -information is used to prompt for information, for example a password, -and to verify a password (i.e. having the user enter it twice and check -that the same string was entered twice). UI_add_verify_string() takes -and extra argument that should be a pointer to the result buffer of the -input string that it's supposed to verify, or verification will fail. - -UI_add_input_boolean() adds a prompt to the UI that's supposed to be answered -in a boolean way, with a single character for yes and a different character -for no. A set of characters that can be used to cancel the prompt is given -as well. The prompt itself is divided in two, one part being the -descriptive text (given through the I argument) and one describing -the possible answers (given through the I argument). - -UI_add_info_string() and UI_add_error_string() add strings that are shown at -the same time as the prompt for extra information or to show an error string. -The difference between the two is only conceptual. With the builtin method, -there's no technical difference between them. Other methods may make a -difference between them, however. - -The flags currently supported are B, which is relevant for -UI_add_input_string() and will have the users response be echoed (when -prompting for a password, this flag should obviously not be used, and -B, which means that a default password of some -sort will be used (completely depending on the application and the UI -method). - -UI_dup_input_string(), UI_dup_verify_string(), UI_dup_input_boolean(), -UI_dup_info_string() and UI_dup_error_string() are basically the same -as their UI_add counterparts, except that they make their own copies -of all strings. - -UI_construct_prompt() is a helper function that can be used to create -a prompt from two pieces of information: an description and a name. -The default constructor (if there is none provided by the method used) -creates a string "Enter I for I:". With the -description "pass phrase" and the file name "foo.key", that becomes -"Enter pass phrase for foo.key:". Other methods may create whatever -string and may include encodings that will be processed by the other -method functions. - -UI_add_user_data() adds a piece of memory for the method to use at any -time. The builtin UI method doesn't care about this info. Note that several -calls to this function doesn't add data, it replaces the previous blob -with the one given as argument. - -UI_get0_user_data() retrieves the data that has last been given to the -UI with UI_add_user_data(). - -UI_get0_result() returns a pointer to the result buffer associated with -the information indexed by I. - -UI_process() goes through the information given so far, does all the printing -and prompting and returns the final status, which is -2 on out-of-band events -(Interrupt, Cancel, ...), -1 on error and 0 on success. - -UI_ctrl() adds extra control for the application author. For now, it -understands two commands: B, which makes UI_process() -print the OpenSSL error stack as part of processing the UI, and -B, which returns a flag saying if the used UI can -be used again or not. - -UI_set_default_method() changes the default UI method to the one given. -This function is not thread-safe and should not be called at the same time -as other OpenSSL functions. - -UI_get_default_method() returns a pointer to the current default UI method. - -UI_get_method() returns the UI method associated with a given UI. - -UI_set_method() changes the UI method associated with a given UI. - -=head1 NOTES - -The resulting strings that the built in method UI_OpenSSL() generate -are assumed to be encoded according to the current locale or (for -Windows) code page. -For applications having different demands, these strings need to be -converted appropriately by the caller. -For Windows, if the OPENSSL_WIN32_UTF8 environment variable is set, -the built-in method UI_OpenSSL() will produce UTF-8 encoded strings -instead. - -=head1 COPYRIGHT - -Copyright 2001-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 -L. - -=cut diff --git a/doc/crypto/X509_NAME_ENTRY_get_object.pod b/doc/crypto/X509_NAME_ENTRY_get_object.pod deleted file mode 100644 index 72e0f7b1..00000000 --- a/doc/crypto/X509_NAME_ENTRY_get_object.pod +++ /dev/null @@ -1,77 +0,0 @@ -=pod - -=head1 NAME - -X509_NAME_ENTRY_get_object, X509_NAME_ENTRY_get_data, -X509_NAME_ENTRY_set_object, X509_NAME_ENTRY_set_data, -X509_NAME_ENTRY_create_by_txt, X509_NAME_ENTRY_create_by_NID, -X509_NAME_ENTRY_create_by_OBJ - X509_NAME_ENTRY utility functions - -=head1 SYNOPSIS - - #include - - ASN1_OBJECT * X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne); - ASN1_STRING * X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne); - - int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj); - int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type, const unsigned char *bytes, int len); - - X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne, const char *field, int type, const unsigned char *bytes, int len); - X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid, int type, const unsigned char *bytes, int len); - X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne, const ASN1_OBJECT *obj, int type, const unsigned char *bytes, int len); - -=head1 DESCRIPTION - -X509_NAME_ENTRY_get_object() retrieves the field name of B in -and B structure. - -X509_NAME_ENTRY_get_data() retrieves the field value of B in -and B structure. - -X509_NAME_ENTRY_set_object() sets the field name of B to B. - -X509_NAME_ENTRY_set_data() sets the field value of B to string type -B and value determined by B and B. - -X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_NID() -and X509_NAME_ENTRY_create_by_OBJ() create and return an -B structure. - -=head1 NOTES - -X509_NAME_ENTRY_get_object() and X509_NAME_ENTRY_get_data() can be -used to examine an B function as returned by -X509_NAME_get_entry() for example. - -X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_NID(), -and X509_NAME_ENTRY_create_by_OBJ() create and return an - -X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_OBJ(), -X509_NAME_ENTRY_create_by_NID() and X509_NAME_ENTRY_set_data() -are seldom used in practice because B structures -are almost always part of B structures and the -corresponding B functions are typically used to -create and add new entries in a single operation. - -The arguments of these functions support similar options to the similarly -named ones of the corresponding B functions such as -X509_NAME_add_entry_by_txt(). So for example B can be set to -B but in the case of X509_set_data() the field name must be -set first so the relevant field information can be looked up internally. - -=head1 SEE ALSO - -L, L, -L - -=head1 COPYRIGHT - -Copyright 2002-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 -L. - -=cut diff --git a/doc/crypto/X509_STORE_CTX_set_verify_cb.pod b/doc/crypto/X509_STORE_CTX_set_verify_cb.pod deleted file mode 100644 index 3be256dc..00000000 --- a/doc/crypto/X509_STORE_CTX_set_verify_cb.pod +++ /dev/null @@ -1,215 +0,0 @@ -=pod - -=head1 NAME - -X509_STORE_CTX_get_cleanup, -X509_STORE_CTX_get_lookup_crls, -X509_STORE_CTX_get_lookup_certs, -X509_STORE_CTX_get_check_policy, -X509_STORE_CTX_get_cert_crl, -X509_STORE_CTX_get_check_crl, -X509_STORE_CTX_get_get_crl, -X509_STORE_CTX_get_check_revocation, -X509_STORE_CTX_get_check_issued, -X509_STORE_CTX_get_get_issuer, -X509_STORE_CTX_get_verify_cb, -X509_STORE_CTX_set_verify_cb, -X509_STORE_CTX_verify_cb -- get and set verification callback - -=head1 SYNOPSIS - - #include - - typedef int (*X509_STORE_CTX_verify_cb)(int, X509_STORE_CTX *); - - X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(X509_STORE_CTX *ctx); - - void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx, - X509_STORE_CTX_verify_cb verify_cb); - - X509_STORE_CTX_get_issuer_fn X509_STORE_CTX_get_get_issuer(X509_STORE_CTX *ctx); - X509_STORE_CTX_check_issued_fn X509_STORE_CTX_get_check_issued(X509_STORE_CTX *ctx); - X509_STORE_CTX_check_revocation_fn X509_STORE_CTX_get_check_revocation(X509_STORE_CTX *ctx); - X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(X509_STORE_CTX *ctx); - X509_STORE_CTX_check_crl_fn X509_STORE_CTX_get_check_crl(X509_STORE_CTX *ctx); - X509_STORE_CTX_cert_crl_fn X509_STORE_CTX_get_cert_crl(X509_STORE_CTX *ctx); - X509_STORE_CTX_check_policy_fn X509_STORE_CTX_get_check_policy(X509_STORE_CTX *ctx); - X509_STORE_CTX_lookup_certs_fn X509_STORE_CTX_get_lookup_certs(X509_STORE_CTX *ctx); - X509_STORE_CTX_lookup_crls_fn X509_STORE_CTX_get_lookup_crls(X509_STORE_CTX *ctx); - X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(X509_STORE_CTX *ctx); - -=head1 DESCRIPTION - -X509_STORE_CTX_set_verify_cb() sets the verification callback of B to -B overwriting any existing callback. - -The verification callback can be used to customise the operation of certificate -verification, either by overriding error conditions or logging errors for -debugging purposes. - -However a verification callback is B essential and the default operation -is often sufficient. - -The B parameter to the callback indicates the value the callback should -return to retain the default behaviour. If it is zero then an error condition -is indicated. If it is 1 then no error occurred. If the flag -B is set then B is set to 2 to indicate the -policy checking is complete. - -The B parameter to the callback is the B structure that -is performing the verification operation. A callback can examine this -structure and receive additional information about the error, for example -by calling X509_STORE_CTX_get_current_cert(). Additional application data can -be passed to the callback via the B mechanism. - -X509_STORE_CTX_get_verify_cb() returns the value of the current callback -for the specific B. - -X509_STORE_CTX_get_get_issuer(), -X509_STORE_CTX_get_check_issued(), X509_STORE_CTX_get_check_revocation(), -X509_STORE_CTX_get_get_crl(), X509_STORE_CTX_get_check_crl(), -X509_STORE_CTX_get_cert_crl(), X509_STORE_CTX_get_check_policy(), -X509_STORE_CTX_get_lookup_certs(), X509_STORE_CTX_get_lookup_crls() -and X509_STORE_CTX_get_cleanup() return the function pointers cached -from the corresponding B, please see -L for more information. - - -=head1 WARNING - -In general a verification callback should B unconditionally return 1 in -all circumstances because this will allow verification to succeed no matter -what the error. This effectively removes all security from the application -because B certificate (including untrusted generated ones) will be -accepted. - -=head1 NOTES - -The verification callback can be set and inherited from the parent structure -performing the operation. In some cases (such as S/MIME verification) the -B structure is created and destroyed internally and the -only way to set a custom verification callback is by inheriting it from the -associated B. - -=head1 RETURN VALUES - -X509_STORE_CTX_set_verify_cb() does not return a value. - -=head1 EXAMPLES - -Default callback operation: - - int verify_callback(int ok, X509_STORE_CTX *ctx) - { - return ok; - } - -Simple example, suppose a certificate in the chain is expired and we wish -to continue after this error: - - int verify_callback(int ok, X509_STORE_CTX *ctx) - { - /* Tolerate certificate expiration */ - if (X509_STORE_CTX_get_error(ctx) == X509_V_ERR_CERT_HAS_EXPIRED) - return 1; - /* Otherwise don't override */ - return ok; - } - -More complex example, we don't wish to continue after B certificate has -expired just one specific case: - - int verify_callback(int ok, X509_STORE_CTX *ctx) - { - int err = X509_STORE_CTX_get_error(ctx); - X509 *err_cert = X509_STORE_CTX_get_current_cert(ctx); - if (err == X509_V_ERR_CERT_HAS_EXPIRED) - { - if (check_is_acceptable_expired_cert(err_cert) - return 1; - } - return ok; - } - -Full featured logging callback. In this case the B is assumed to be -a global logging B, an alternative would to store a BIO in B using -B. - - int verify_callback(int ok, X509_STORE_CTX *ctx) - { - X509 *err_cert; - int err, depth; - - err_cert = X509_STORE_CTX_get_current_cert(ctx); - err = X509_STORE_CTX_get_error(ctx); - depth = X509_STORE_CTX_get_error_depth(ctx); - - BIO_printf(bio_err, "depth=%d ", depth); - if (err_cert) - { - X509_NAME_print_ex(bio_err, X509_get_subject_name(err_cert), - 0, XN_FLAG_ONELINE); - BIO_puts(bio_err, "\n"); - } - else - BIO_puts(bio_err, "\n"); - if (!ok) - BIO_printf(bio_err, "verify error:num=%d:%s\n", err, - X509_verify_cert_error_string(err)); - switch (err) - { - case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: - BIO_puts(bio_err, "issuer= "); - X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert), - 0, XN_FLAG_ONELINE); - BIO_puts(bio_err, "\n"); - break; - case X509_V_ERR_CERT_NOT_YET_VALID: - case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: - BIO_printf(bio_err, "notBefore="); - ASN1_TIME_print(bio_err, X509_get_notBefore(err_cert)); - BIO_printf(bio_err, "\n"); - break; - case X509_V_ERR_CERT_HAS_EXPIRED: - case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: - BIO_printf(bio_err, "notAfter="); - ASN1_TIME_print(bio_err, X509_get_notAfter(err_cert)); - BIO_printf(bio_err, "\n"); - break; - case X509_V_ERR_NO_EXPLICIT_POLICY: - policies_print(bio_err, ctx); - break; - } - if (err == X509_V_OK && ok == 2) - /* print out policies */ - - BIO_printf(bio_err, "verify return:%d\n", ok); - return(ok); - } - -=head1 SEE ALSO - -L -L -L - -=head1 HISTORY - -X509_STORE_CTX_get_get_issuer(), -X509_STORE_CTX_get_check_issued(), X509_STORE_CTX_get_check_revocation(), -X509_STORE_CTX_get_get_crl(), X509_STORE_CTX_get_check_crl(), -X509_STORE_CTX_get_cert_crl(), X509_STORE_CTX_get_check_policy(), -X509_STORE_CTX_get_lookup_certs(), X509_STORE_CTX_get_lookup_crls() -and X509_STORE_CTX_get_cleanup() were added in OpenSSL 1.1.0. - -=head1 COPYRIGHT - -Copyright 2009-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 -L. - -=cut diff --git a/doc/crypto/X509_get0_signature.pod b/doc/crypto/X509_get0_signature.pod deleted file mode 100644 index 61a2dda9..00000000 --- a/doc/crypto/X509_get0_signature.pod +++ /dev/null @@ -1,97 +0,0 @@ -=pod - -=head1 NAME - -X509_get0_signature, X509_get_signature_nid, X509_get0_tbs_sigalg, -X509_REQ_get0_signature, X509_REQ_get_signature_nid, X509_CRL_get0_signature, -X509_CRL_get_signature_nid - signature information - -=head1 SYNOPSIS - - #include - - void X509_get0_signature(const ASN1_BIT_STRING **psig, - const X509_ALGOR **palg, - const X509 *x); - int X509_get_signature_nid(const X509 *x); - const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x); - - void X509_REQ_get0_signature(const X509_REQ *crl, - const ASN1_BIT_STRING **psig, - const X509_ALGOR **palg); - int X509_REQ_get_signature_nid(const X509_REQ *crl); - - void X509_CRL_get0_signature(const X509_CRL *crl, - const ASN1_BIT_STRING **psig, - const X509_ALGOR **palg); - int X509_CRL_get_signature_nid(const X509_CRL *crl); - -=head1 DESCRIPTION - -X509_get0_signature() sets B<*psig> to the signature of B and B<*palg> -to the signature algorithm of B. The values returned are internal -pointers which B be freed up after the call. - -X509_get0_tbs_sigalg() returns the signature algorithm in the signed -portion of B. - -X509_get_signature_nid() returns the NID corresponding to the signature -algorithm of B. - -X509_REQ_get0_signature(), X509_REQ_get_signature_nid() -X509_CRL_get0_signature() and X509_CRL_get_signature_nid() perform the -same function for certificate requests and CRLs. - -=head1 NOTES - -These functions provide lower level access to signatures in certificates -where an application wishes to analyse or generate a signature in a form -where X509_sign() et al is not appropriate (for example a non standard -or unsupported format). - -=head1 RETURN VALUES - -X509_get_signature_nid(), X509_REQ_get_signature_nid() and -X509_CRL_get_signature_nid() return a NID. - -X509_get0_signature(), X509_REQ_get0_signature() and -X509_CRL_get0_signature() do not return values. - -=head1 SEE ALSO - -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L - -=head1 HISTORY - -X509_get0_signature() and X509_get_signature_nid() were first added to -OpenSSL 1.0.2. - -X509_REQ_get0_signature(), X509_REQ_get_signature_nid(), -X509_CRL_get0_signature() and X509_CRL_get_signature_nid() were first added -to OpenSSL 1.1.0. - -=head1 COPYRIGHT - -Copyright 2015-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 -L. - -=cut diff --git a/doc/crypto/d2i_DHparams.pod b/doc/crypto/d2i_DHparams.pod deleted file mode 100644 index cd1c162b..00000000 --- a/doc/crypto/d2i_DHparams.pod +++ /dev/null @@ -1,35 +0,0 @@ -=pod - -=head1 NAME - -d2i_DHparams, i2d_DHparams - PKCS#3 DH parameter functions - -=head1 SYNOPSIS - - #include - - DH *d2i_DHparams(DH **a, unsigned char **pp, long length); - int i2d_DHparams(DH *a, unsigned char **pp); - -=head1 DESCRIPTION - -These functions decode and encode PKCS#3 DH parameters using the -DHparameter structure described in PKCS#3. - -Otherwise these behave in a similar way to d2i_X509() and i2d_X509() -described in the L manual page. - -=head1 SEE ALSO - -L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/d2i_Netscape_RSA.pod b/doc/crypto/d2i_Netscape_RSA.pod deleted file mode 100644 index ee39bd81..00000000 --- a/doc/crypto/d2i_Netscape_RSA.pod +++ /dev/null @@ -1,38 +0,0 @@ -=pod - -=head1 NAME - -i2d_Netscape_RSA, -d2i_Netscape_RSA -- insecure RSA public and private key encoding functions - -=head1 SYNOPSIS - - #include - - int i2d_Netscape_RSA(RSA *a, unsigned char **pp, int (*cb)()); - RSA * d2i_Netscape_RSA(RSA **a, const unsigned char **pp, long length, int (*cb)()); - -=head1 DESCRIPTION - -These functions decode and encode an RSA private -key in NET format. These functions are present to provide compatibility -with very old software. This format has some severe security weaknesses -and should be avoided if possible. - -These functions are similar to the B functions. - -=head1 SEE ALSO - -L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/crypto/d2i_PKCS8PrivateKey_bio.pod b/doc/crypto/d2i_PKCS8PrivateKey_bio.pod deleted file mode 100644 index 164d93ff..00000000 --- a/doc/crypto/d2i_PKCS8PrivateKey_bio.pod +++ /dev/null @@ -1,61 +0,0 @@ -=pod - -=head1 NAME - -d2i_PKCS8PrivateKey_bio, d2i_PKCS8PrivateKey_fp, -i2d_PKCS8PrivateKey_bio, i2d_PKCS8PrivateKey_fp, -i2d_PKCS8PrivateKey_nid_bio, i2d_PKCS8PrivateKey_nid_fp - PKCS#8 format private key functions - -=head1 SYNOPSIS - - #include - - EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u); - EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u); - - int i2d_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, - char *kstr, int klen, - pem_password_cb *cb, void *u); - - int i2d_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, - char *kstr, int klen, - pem_password_cb *cb, void *u); - - int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, EVP_PKEY *x, int nid, - char *kstr, int klen, - pem_password_cb *cb, void *u); - - int i2d_PKCS8PrivateKey_nid_fp(FILE *fp, EVP_PKEY *x, int nid, - char *kstr, int klen, - pem_password_cb *cb, void *u); - -=head1 DESCRIPTION - -The PKCS#8 functions encode and decode private keys in PKCS#8 format using both -PKCS#5 v1.5 and PKCS#5 v2.0 password based encryption algorithms. - -Other than the use of DER as opposed to PEM these functions are identical to the -corresponding B function as described in L. - -=head1 NOTES - -These functions are currently the only way to store encrypted private keys using DER format. - -Currently all the functions use BIOs or FILE pointers, there are no functions which -work directly on memory: this can be readily worked around by converting the buffers -to memory BIOs, see L for details. - -=head1 SEE ALSO - -L - -=head1 COPYRIGHT - -Copyright 2002-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 -L. - -=cut diff --git a/doc/crypto/x509.pod b/doc/crypto/x509.pod deleted file mode 100644 index 483b0376..00000000 --- a/doc/crypto/x509.pod +++ /dev/null @@ -1,75 +0,0 @@ -=pod - -=for comment openssl_manual_section:7 - -=head1 NAME - -x509 - X.509 certificate handling - -=head1 SYNOPSIS - - #include - -=head1 DESCRIPTION - -An X.509 certificate is a structured grouping of information about -an individual, a device, or anything one can imagine. A X.509 CRL -(certificate revocation list) is a tool to help determine if a -certificate is still valid. The exact definition of those can be -found in the X.509 document from ITU-T, or in RFC3280 from PKIX. -In OpenSSL, the type X509 is used to express such a certificate, and -the type X509_CRL is used to express a CRL. - -A related structure is a certificate request, defined in PKCS#10 from -RSA Security, Inc, also reflected in RFC2896. In OpenSSL, the type -X509_REQ is used to express such a certificate request. - -To handle some complex parts of a certificate, there are the types -X509_NAME (to express a certificate name), X509_ATTRIBUTE (to express -a certificate attributes), X509_EXTENSION (to express a certificate -extension) and a few more. - -Finally, there's the supertype X509_INFO, which can contain a CRL, a -certificate and a corresponding private key. - -BI<...>, BI<...> and BI<...> handle X.509 -certificates, with some exceptions, shown below. - -BI<...>, BI<...> and BI<...> -handle X.509 CRLs. - -BI<...>, BI<...> and BI<...> -handle PKCS#10 certificate requests. - -BI<...> handle certificate names. - -BI<...> handle certificate attributes. - -BI<...> handle certificate extensions. - -=head1 SEE ALSO - -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L - -=head1 COPYRIGHT - -Copyright 2003-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 -L. - -=cut diff --git a/doc/apps/CA.pl.pod b/doc/man1/CA.pl.pod similarity index 83% rename from doc/apps/CA.pl.pod rename to doc/man1/CA.pl.pod index a7f3970c..6949ec62 100644 --- a/doc/apps/CA.pl.pod +++ b/doc/man1/CA.pl.pod @@ -42,28 +42,28 @@ by the use of some simple options. =item B, B<-h>, B<-help> -prints a usage message. +Prints a usage message. =item B<-newcert> -creates a new self signed certificate. The private key is written to the file +Creates a new self signed certificate. The private key is written to the file "newkey.pem" and the request written to the file "newreq.pem". This argument invokes B command. =item B<-newreq> -creates a new certificate request. The private key is written to the file +Creates a new certificate request. The private key is written to the file "newkey.pem" and the request written to the file "newreq.pem". Executes B command below the hood. =item B<-newreq-nodes> -is like B<-newreq> except that the private key will not be encrypted. +Is like B<-newreq> except that the private key will not be encrypted. Uses B command. =item B<-newca> -creates a new CA hierarchy for use with the B program (or the B<-signcert> +Creates a new CA hierarchy for use with the B program (or the B<-signcert> and B<-xsign> options). The user is prompted to enter the filename of the CA certificates (which should also contain the private key) or by hitting ENTER details of the CA will be prompted for. The relevant files and directories @@ -72,7 +72,7 @@ B and B commands are get invoked. =item B<-pkcs12> -create a PKCS#12 file containing the user certificate, private key and CA +Create a PKCS#12 file containing the user certificate, private key and CA certificate. It expects the user certificate and private key to be in the file "newcert.pem" and the CA certificate to be in the file demoCA/cacert.pem, it creates a file "newcert.p12". This command can thus be called after the @@ -84,31 +84,31 @@ Delegates work to B command. =item B<-sign>, B<-signcert>, B<-xsign> -calls the B program to sign a certificate request. It expects the request +Calls the B program to sign a certificate request. It expects the request to be in the file "newreq.pem". The new certificate is written to the file "newcert.pem" except in the case of the B<-xsign> option when it is written to standard output. Leverages B command. =item B<-signCA> -this option is the same as the B<-signreq> option except it uses the configuration -file section B and so makes the signed request a valid CA certificate. This -is useful when creating intermediate CA from a root CA. -Extra params are passed on to B command. +This option is the same as the B<-signreq> option except it uses the +configuration file section B and so makes the signed request a +valid CA certificate. This is useful when creating intermediate CA from +a root CA. Extra params are passed on to B command. =item B<-signcert> -this option is the same as B<-sign> except it expects a self signed certificate +This option is the same as B<-sign> except it expects a self signed certificate to be present in the file "newreq.pem". Extra params are passed on to B and B commands. =item B<-crl> -generate a CRL. Executes B command. +Generate a CRL. Executes B command. =item B<-revoke certfile [reason]> -revoke the certificate contained in the specified B. An optional +Revoke the certificate contained in the specified B. An optional reason may be specified, and must be one of: B, B, B, B, B, B, B, or B. @@ -116,9 +116,9 @@ Leverages B command. =item B<-verify> -verifies certificates against the CA certificate for "demoCA". If no certificates -are specified on the command line it tries to verify the file "newcert.pem". -Invokes B command. +Verifies certificates against the CA certificate for "demoCA". If no +certificates are specified on the command line it tries to verify the file +"newcert.pem". Invokes B command. =item B<-extra-req> | B<-extra-ca> | B<-extra-pkcs12> | B<-extra-x509> | B<-extra-verify> @@ -204,7 +204,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/asn1parse.pod b/doc/man1/asn1parse.pod similarity index 84% rename from doc/apps/asn1parse.pod rename to doc/man1/asn1parse.pod index 3c607e8a..0e1fcc68 100644 --- a/doc/apps/asn1parse.pod +++ b/doc/man1/asn1parse.pod @@ -23,6 +23,7 @@ B B [B<-genstr string>] [B<-genconf file>] [B<-strictpem>] +[B<-item name>] =head1 DESCRIPTION @@ -39,56 +40,56 @@ Print out a usage message. =item B<-inform> B -the input format. B is binary format and B (the default) is base64 +The input format. B is binary format and B (the default) is base64 encoded. =item B<-in filename> -the input file, default is standard input +The input file, default is standard input. =item B<-out filename> -output file to place the DER encoded data into. If this +Output file to place the DER encoded data into. If this option is not present then no data will be output. This is most useful when combined with the B<-strparse> option. =item B<-noout> -don't output the parsed version of the input file. +Don't output the parsed version of the input file. =item B<-offset number> -starting offset to begin parsing, default is start of file. +Starting offset to begin parsing, default is start of file. =item B<-length number> -number of bytes to parse, default is until end of file. +Number of bytes to parse, default is until end of file. =item B<-i> -indents the output according to the "depth" of the structures. +Indents the output according to the "depth" of the structures. =item B<-oid filename> -a file containing additional OBJECT IDENTIFIERs (OIDs). The format of this +A file containing additional OBJECT IDENTIFIERs (OIDs). The format of this file is described in the NOTES section below. =item B<-dump> -dump unknown data in hex format. +Dump unknown data in hex format. =item B<-dlimit num> -like B<-dump>, but only the first B bytes are output. +Like B<-dump>, but only the first B bytes are output. =item B<-strparse offset> -parse the contents octets of the ASN.1 object starting at B. This +Parse the contents octets of the ASN.1 object starting at B. This option can be used multiple times to "drill down" into a nested structure. =item B<-genstr string>, B<-genconf file> -generate encoded data based on B, B or both using +Generate encoded data based on B, B or both using L format. If B only is present then the string is obtained from the default section using the name B. The encoded data is passed through the ASN1 parser and printed out as @@ -103,6 +104,11 @@ processed whether it has the normal PEM BEGIN and END markers or not. This option will ignore any data prior to the start of the BEGIN marker, or after an END marker in a PEM file. +=item B<-item name> + +Attempt to decode and print the data as B. This can be used to +print out the fields of any supported ASN.1 structure if the type is known. + =back =head2 Output @@ -199,7 +205,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/ca.pod b/doc/man1/ca.pod similarity index 79% rename from doc/apps/ca.pod rename to doc/man1/ca.pod index 9918a136..9c5af4a8 100644 --- a/doc/apps/ca.pod +++ b/doc/man1/ca.pod @@ -52,7 +52,10 @@ B B [B<-subj arg>] [B<-utf8>] [B<-create_serial>] +[B<-rand_serial>] [B<-multivalue-rdn>] +[B<-rand file...>] +[B<-writerand file>] =head1 DESCRIPTION @@ -73,73 +76,73 @@ Print out a usage message. =item B<-verbose> -this prints extra details about the operations being performed. +This prints extra details about the operations being performed. =item B<-config filename> -specifies the configuration file to use. +Specifies the configuration file to use. Optional; for a description of the default value, see L. =item B<-name section> -specifies the configuration file section to use (overrides +Specifies the configuration file section to use (overrides B in the B section). =item B<-in filename> -an input filename containing a single certificate request to be +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. +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 +A file containing a single Netscape signed public key and challenge and additional field values to be signed by the CA. See the B section for information on the required input and output format. =item B<-infiles> -if present this should be the last option, all subsequent arguments +If present this should be the last option, all subsequent arguments are taken as the names of files containing certificate requests. =item B<-out filename> -the output file to output certificates to. The default is standard +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 +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. +The CA certificate file. =item B<-keyfile filename> -the private key to sign requests with. +The private key to sign requests with. =item B<-keyform PEM|DER> -the format of the data in the private key file. +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 +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 +Indicates the issued certificates are to be signed with the key the certificate requests were signed with (given with B<-keyfile>). Certificate requests signed with a different key are ignored. If B<-spkac>, B<-ss_cert> or B<-gencrl> are given, B<-selfsign> is @@ -153,47 +156,50 @@ self-signed certificate. =item B<-passin arg> -the key password source. For more information about the format of B +The key password source. For more information about the format of B see the B section in L. =item B<-notext> -don't output the text form of a certificate to the output file. +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). +This allows the start date to be explicitly set. The format of the +date is YYMMDDHHMMSSZ (the same as an ASN1 UTCTime structure), or +YYYYMMDDHHMMSSZ (the same as an ASN1 GeneralizedTime structure). In +both formats, seconds SS and timezone Z must be present. =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). +This allows the expiry date to be explicitly set. The format of the +date is YYMMDDHHMMSSZ (the same as an ASN1 UTCTime structure), or +YYYYMMDDHHMMSSZ (the same as an ASN1 GeneralizedTime structure). In +both formats, seconds SS and timezone Z must be present. =item B<-days arg> -the number of days to certify the certificate for. +The number of days to certify the certificate for. =item B<-md alg> -the message digest to use. +The message digest to use. Any digest supported by the OpenSSL B command can be used. This option also applies to CRLs. =item B<-policy arg> -this option defines the CA "policy" to use. This is a section in +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 section for more information. =item B<-msie_hack> -this is a legacy option to make B work with very old versions of +This is a deprecated option to make B 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. +its use is strongly discouraged. =item B<-preserveDN> @@ -214,12 +220,12 @@ 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 +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 +The section of the configuration file containing certificate extensions to be added when a certificate is issued (defaults to B unless the B<-extfile> option is used). If no extension section is present then, a V1 certificate is created. If the extension section @@ -229,35 +235,42 @@ extension section format. =item B<-extfile file> -an additional configuration file to read certificate extensions from +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 string) will cause B +Specifying an engine (by its unique B string) will cause B 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. +Supersedes subject name given in the request. The arg must be formatted as I, 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 +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<-create_serial> -if reading serial from the text file as specified in the configuration +If reading serial from the text file as specified in the configuration fails, specifying this option creates a new random serial to be used as next serial number. +To get random serial numbers, use the B<-rand_serial> flag instead; this +should only be used for simple error-recovery. + +=item B<-rand_serial> + +Generate a large random number to use as the serial number. +This overrides any option or configuration to use a serial number file. =item B<-multivalue-rdn> @@ -268,6 +281,19 @@ I If -multi-rdn is not used then the UID value is I<123456+CN=John Doe>. +=item B<-rand file...> + +A file or files containing random data used to seed the random number +generator. +Multiple files can be specified separated by an OS-dependent character. +The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for +all others. + +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =back =head1 CRL OPTIONS @@ -276,28 +302,28 @@ If -multi-rdn is not used then the UID value is I<123456+CN=John Doe>. =item B<-gencrl> -this option generates a CRL based on information in the index file. +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 +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. +The number of hours before the next CRL is due. =item B<-revoke filename> -a filename containing a certificate to revoke. +A filename containing a certificate to revoke. =item B<-valid filename> -a filename containing a certificate to add a Valid certificate entry. +A filename containing a certificate to add a Valid certificate entry. =item B<-status serial> -displays the revocation status of the certificate with the specified +Displays the revocation status of the certificate with the specified serial number and exits. =item B<-updatedb> @@ -306,7 +332,7 @@ Updates the database index to purge expired certificates. =item B<-crl_reason reason> -revocation reason, where B is one of: B, B, +Revocation reason, where B is one of: B, B, B, B, B, B, B or B. The matching of B is case insensitive. Setting any revocation reason will make the CRL v2. @@ -333,7 +359,7 @@ B. =item B<-crlexts section> -the section of the configuration file containing CRL extensions to +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 @@ -384,58 +410,58 @@ and long names are the same when this option is used. =item B -the same as the B<-outdir> command line option. It specifies +The same as the B<-outdir> command line option. It specifies the directory where new certificates will be placed. Mandatory. =item B -the same as B<-cert>. It gives the file containing the CA +The same as B<-cert>. It gives the file containing the CA certificate. Mandatory. =item B -same as the B<-keyfile> option. The file containing the +Same as the B<-keyfile> option. The file containing the CA private key. Mandatory. =item B -a file used to read and write random number seed information, or -an EGD socket (see L). +At startup the specified file is loaded into the random number generator, +and at exit 256 bytes will be written to it. =item B -the same as the B<-days> option. The number of days to certify +The same as the B<-days> option. The number of days to certify a certificate for. =item B -the same as the B<-startdate> option. The start date to certify +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 -the same as the B<-enddate> option. Either this option or +The same as the B<-enddate> option. Either this option or B (or the command line equivalents) must be present. =item B -the same as the B<-crlhours> and the B<-crldays> options. These +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 -the same as the B<-md> option. Mandatory. +The same as the B<-md> option. Mandatory. =item B -the text database file to use. Mandatory. This file must be present +The text database file to use. Mandatory. This file must be present though initially it will be empty. =item B -if the value B is given, the valid certificate entries in the +If the value B is given, the valid certificate entries in the database must have unique subjects. if the value B is given, several valid certificate entries may have the exact same subject. The default value is B, to be compatible with older (pre 0.9.8) @@ -443,51 +469,47 @@ versions of OpenSSL. However, to make CA certificate roll-over easier, it's recommended to use the value B, 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 -a text file containing the next serial number to use in hex. Mandatory. +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 -a text file containing the next CRL number to use in hex. The crl number +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 -the same as B<-extensions>. +The same as B<-extensions>. =item B -the same as B<-crlexts>. +The same as B<-crlexts>. =item B -the same as B<-preserveDN> +The same as B<-preserveDN> =item B -the same as B<-noemailDN>. If you want the EMAIL field to be removed +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 -the same as B<-msie_hack> +The same as B<-msie_hack> =item B -the same as B<-policy>. Mandatory. See the B section +The same as B<-policy>. Mandatory. See the B section for more information. =item B, B -these options allow the format used to display the certificate details +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 utilities B<-nameopt> and B<-certopt> switches can be used here, except the B and B are permanently set @@ -504,7 +526,7 @@ multicharacter string types and does not display extensions. =item B -determines how extensions in certificate requests should be handled. +Determines how extensions in certificate requests should be handled. If set to B or this option is not present then extensions are ignored and not copied to the certificate. If set to B then any extensions present in the request that are not already present are copied @@ -601,6 +623,7 @@ A sample configuration file with the relevant sections for B: certificate = $dir/cacert.pem # The CA cert serial = $dir/serial # serial no file + #rand_serial = yes # for random serial#'s private_key = $dir/private/cakey.pem# CA private key RANDFILE = $dir/private/.rand # random number file @@ -707,6 +730,14 @@ For example if the CA certificate has: then even if a certificate is issued with CA:TRUE it will not be valid. +=head1 HISTORY + +Since OpenSSL 1.1.1, the program follows RFC5280. Specifically, +certificate validity period (specified by any of B<-startdate>, +B<-enddate> and B<-days>) will be encoded as UTCTime if the dates are +earlier than year 2049 (included), and as GeneralizedTime if the dates +are in year 2050 or later. + =head1 SEE ALSO L, L, L, L, @@ -714,7 +745,7 @@ L, L =head1 COPYRIGHT -Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/ciphers.pod b/doc/man1/ciphers.pod similarity index 86% rename from doc/apps/ciphers.pod rename to doc/man1/ciphers.pod index 1adb0d18..129f7660 100644 --- a/doc/apps/ciphers.pod +++ b/doc/man1/ciphers.pod @@ -16,10 +16,12 @@ B B [B<-tls1>] [B<-tls1_1>] [B<-tls1_2>] +[B<-tls1_3>] [B<-s>] [B<-psk>] [B<-srp>] [B<-stdname>] +[B<-convert name>] [B] =head1 DESCRIPTION @@ -63,13 +65,18 @@ When combined with B<-s> includes cipher suites which require SRP. =item B<-v> -Verbose output: For each ciphersuite, list details as provided by +Verbose output: For each cipher suite, list details as provided by L. =item B<-V> Like B<-v>, but include the official cipher suite values in hex. +=item B<-tls1_3> + +In combination with the B<-s> option, list the ciphers which would be used if +TLSv1.3 were negotiated. + =item B<-tls1_2> In combination with the B<-s> option, list the ciphers which would be used if @@ -92,12 +99,15 @@ TLSv1.1 were negotiated. =item B<-stdname> -precede each ciphersuite by its standard name: only available is OpenSSL -is built with tracing enabled (B argument to Configure). +Precede each cipher suite by its standard name. + +=item B<-convert name> + +Convert a standard cipher B to its OpenSSL name. =item B -a cipher list to convert to a cipher preference list. If it is not included +A cipher list to convert to a cipher preference list. If it is not included then the default cipher list will be used. The format is described below. =back @@ -143,7 +153,8 @@ The cipher string B<@STRENGTH> can be used at any point to sort the current cipher list in order of encryption algorithm key length. The cipher string B<@SECLEVEL=n> can be used at any point to set the security -level to B. +level to B, which should be a number between zero and five, inclusive. +See L for a description of what each level means. =head1 CIPHER STRINGS @@ -163,7 +174,7 @@ When used, this must be the first cipherstring specified. The ciphers included in B, but not enabled by default. Currently this includes all RC4 and anonymous ciphers. Note that this rule does not cover B, which is not included by B (use B if -necessary). Note that RC4 based ciphersuites are not built into OpenSSL by +necessary). Note that RC4 based cipher suites are not built into OpenSSL by default (see the enable-weak-ssl-ciphers option to Configure). =item B @@ -178,19 +189,19 @@ The cipher suites not enabled by B, currently B. =item B -"high" encryption cipher suites. This currently means those with key lengths +"High" encryption cipher suites. This currently means those with key lengths larger than 128 bits, and some cipher suites with 128-bit keys. =item B -"medium" encryption cipher suites, currently some of those using 128 bit +"Medium" encryption cipher suites, currently some of those using 128 bit encryption. =item B -"low" encryption cipher suites, currently those using 64 or 56 bit +"Low" encryption cipher suites, currently those using 64 or 56 bit encryption algorithms but excluding export cipher suites. All these -ciphersuites have been removed as of OpenSSL 1.1.0. +cipher suites have been removed as of OpenSSL 1.1.0. =item B, B @@ -267,11 +278,11 @@ keys. =item B, B, B -Lists ciphersuites which are only supported in at least TLS v1.2, TLS v1.0 or +Lists cipher suites which are only supported in at least TLS v1.2, TLS v1.0 or SSL v3.0 respectively. -Note: there are no ciphersuites specific to TLS v1.1. +Note: there are no cipher suites specific to TLS v1.1. Since this is only the minimum version, if, for example, TLSv1.0 is negotiated -then both TLSv1.0 and SSLv3.0 ciphersuites are available. +then both TLSv1.0 and SSLv3.0 cipher suites are available. Note: these cipher strings B change the negotiated version of SSL or TLS, they only affect the list of available cipher suites. @@ -282,28 +293,33 @@ cipher suites using 128 bit AES, 256 bit AES or either 128 or 256 bit AES. =item B -AES in Galois Counter Mode (GCM): these ciphersuites are only supported +AES in Galois Counter Mode (GCM): these cipher suites are only supported in TLS v1.2. =item B, B AES in Cipher Block Chaining - Message Authentication Mode (CCM): these -ciphersuites are only supported in TLS v1.2. B references CCM +cipher suites are only supported in TLS v1.2. B references CCM cipher suites using both 16 and 8 octet Integrity Check Value (ICV) while B only references 8 octet ICV. +=item B, B, B + +Cipher suites using 128 bit ARIA, 256 bit ARIA or either 128 or 256 bit +ARIA. + =item B, B, B -cipher suites using 128 bit CAMELLIA, 256 bit CAMELLIA or either 128 or 256 bit +Cipher suites using 128 bit CAMELLIA, 256 bit CAMELLIA or either 128 or 256 bit CAMELLIA. =item B -cipher suites using ChaCha20. +Cipher suites using ChaCha20. =item B<3DES> -cipher suites using triple DES. +Cipher suites using triple DES. =item B @@ -336,7 +352,7 @@ Cipher suites using SHA1. =item B, B -Ciphersuites using SHA256 or SHA384. +Cipher suites using SHA256 or SHA384. =item B @@ -383,27 +399,12 @@ Setting Suite B mode has additional consequences required to comply with RFC6460. In particular the supported signature algorithms is reduced to support only ECDSA and SHA256 or SHA384, only the elliptic curves P-256 and P-384 can be -used and only the two suite B compliant ciphersuites +used and only the two suite B compliant cipher suites (ECDHE-ECDSA-AES128-GCM-SHA256 and ECDHE-ECDSA-AES256-GCM-SHA384) are permissible. =back -=head1 EQUAL PREFERENCE GROUPS - -If configuring a server, one may also configure equal-preference groups to -partially respect the client's preferences when -B is enabled. Ciphers in an equal-preference -group have equal priority and use the client order. This may be used to -enforce that AEADs are preferred but select AES-GCM vs. ChaCha20-Poly1305 -based on client preferences. An equal-preference is specified with square -brackets, combining multiple selectors separated by |. For example: - - [ECDHE-ECDSA-CHACHA20-POLY1305|ECDHE-ECDSA-AES128-GCM-SHA256] - -Once an equal-preference group is used, future directives must be -opcode-less. - =head1 CIPHER SUITE NAMES The following lists give the SSL or TLS cipher suites names from the @@ -449,7 +450,7 @@ e.g. DES-CBC3-SHA. In these cases, RSA authentication is used. TLS_DH_anon_WITH_RC4_128_MD5 ADH-RC4-MD5 TLS_DH_anon_WITH_3DES_EDE_CBC_SHA ADH-DES-CBC3-SHA -=head2 AES ciphersuites from RFC3268, extending TLS v1.0 +=head2 AES cipher suites from RFC3268, extending TLS v1.0 TLS_RSA_WITH_AES_128_CBC_SHA AES128-SHA TLS_RSA_WITH_AES_256_CBC_SHA AES256-SHA @@ -467,7 +468,7 @@ e.g. DES-CBC3-SHA. In these cases, RSA authentication is used. TLS_DH_anon_WITH_AES_128_CBC_SHA ADH-AES128-SHA TLS_DH_anon_WITH_AES_256_CBC_SHA ADH-AES256-SHA -=head2 Camellia ciphersuites from RFC4132, extending TLS v1.0 +=head2 Camellia cipher suites from RFC4132, extending TLS v1.0 TLS_RSA_WITH_CAMELLIA_128_CBC_SHA CAMELLIA128-SHA TLS_RSA_WITH_CAMELLIA_256_CBC_SHA CAMELLIA256-SHA @@ -485,7 +486,7 @@ e.g. DES-CBC3-SHA. In these cases, RSA authentication is used. TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA ADH-CAMELLIA128-SHA TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA ADH-CAMELLIA256-SHA -=head2 SEED ciphersuites from RFC4162, extending TLS v1.0 +=head2 SEED cipher suites from RFC4162, extending TLS v1.0 TLS_RSA_WITH_SEED_CBC_SHA SEED-SHA @@ -497,7 +498,7 @@ e.g. DES-CBC3-SHA. In these cases, RSA authentication is used. TLS_DH_anon_WITH_SEED_CBC_SHA ADH-SEED-SHA -=head2 GOST ciphersuites from draft-chudov-cryptopro-cptls, extending TLS v1.0 +=head2 GOST cipher suites from draft-chudov-cryptopro-cptls, extending TLS v1.0 Note: these ciphers require an engine which including GOST cryptographic algorithms, such as the B engine, included in the OpenSSL distribution. @@ -590,14 +591,35 @@ Note: these ciphers can also be used in SSL v3. ECDHE_ECDSA_WITH_AES_128_CCM_8 ECDHE-ECDSA-AES128-CCM8 ECDHE_ECDSA_WITH_AES_256_CCM_8 ECDHE-ECDSA-AES256-CCM8 -=head2 Camellia HMAC-Based ciphersuites from RFC6367, extending TLS v1.2 +=head2 ARIA cipher suites from RFC6209, extending TLS v1.2 + +Note: the CBC modes mentioned in this RFC are not supported. + + TLS_RSA_WITH_ARIA_128_GCM_SHA256 ARIA128-GCM-SHA256 + TLS_RSA_WITH_ARIA_256_GCM_SHA384 ARIA256-GCM-SHA384 + TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 DHE-RSA-ARIA128-GCM-SHA256 + TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 DHE-RSA-ARIA256-GCM-SHA384 + TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 DHE-DSS-ARIA128-GCM-SHA256 + TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 DHE-DSS-ARIA256-GCM-SHA384 + TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 ECDHE-ECDSA-ARIA128-GCM-SHA256 + TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 ECDHE-ECDSA-ARIA256-GCM-SHA384 + TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 ECDHE-ARIA128-GCM-SHA256 + TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 ECDHE-ARIA256-GCM-SHA384 + TLS_PSK_WITH_ARIA_128_GCM_SHA256 PSK-ARIA128-GCM-SHA256 + TLS_PSK_WITH_ARIA_256_GCM_SHA384 PSK-ARIA256-GCM-SHA384 + TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 DHE-PSK-ARIA128-GCM-SHA256 + TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 DHE-PSK-ARIA256-GCM-SHA384 + TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 RSA-PSK-ARIA128-GCM-SHA256 + TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 RSA-PSK-ARIA256-GCM-SHA384 + +=head2 Camellia HMAC-Based cipher suites from RFC6367, extending TLS v1.2 TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 ECDHE-ECDSA-CAMELLIA128-SHA256 TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 ECDHE-ECDSA-CAMELLIA256-SHA384 TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 ECDHE-RSA-CAMELLIA128-SHA256 TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 ECDHE-RSA-CAMELLIA256-SHA384 -=head2 Pre-shared keying (PSK) ciphersuites +=head2 Pre-shared keying (PSK) cipher suites PSK_WITH_NULL_SHA PSK-NULL-SHA DHE_PSK_WITH_NULL_SHA DHE-PSK-NULL-SHA @@ -681,6 +703,14 @@ Note: these ciphers can also be used in SSL v3. TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 DHE-PSK-CHACHA20-POLY1305 TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 RSA-PSK-CHACHA20-POLY1305 +=head2 TLS v1.3 cipher suites + + TLS_AES_128_GCM_SHA256 TLS13-AES-128-GCM-SHA256 + TLS_AES_256_GCM_SHA384 TLS13-AES-256-GCM-SHA384 + TLS_CHACHA20_POLY1305_SHA256 TLS13-CHACHA20-POLY1305-SHA256 + TLS_AES_128_CCM_SHA256 TLS13-AES-128-CCM-SHA256 + TLS_AES_128_CCM_8_SHA256 TLS13-AES-128-CCM-8-SHA256 + =head2 Older names used by OpenSSL The following names are accepted by older releases: @@ -734,9 +764,14 @@ L, L, L The B<-V> option for the B command was added in OpenSSL 1.0.0. +The B<-stdname> is only available if OpenSSL is built with tracing enabled +(B argument to Configure) before OpenSSL 1.1.1. + +The B<-convert> was added in OpenSSL 1.1.1. + =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/cms.pod b/doc/man1/cms.pod similarity index 85% rename from doc/apps/cms.pod rename to doc/man1/cms.pod index 96acd315..7bd1b0d3 100644 --- a/doc/apps/cms.pod +++ b/doc/man1/cms.pod @@ -68,9 +68,9 @@ B B [B<-verify_name name>] [B<-x509_strict>] [B<-md digest>] -[B<-[cipher]>] +[B<-I>] [B<-nointern>] -[B<-no_signer_cert_verify>] +[B<-noverify>] [B<-nocerts>] [B<-noattr>] [B<-nosmimecap>] @@ -93,7 +93,8 @@ B B [B<-inkey file>] [B<-keyopt name:parameter>] [B<-passin arg>] -[B<-rand file(s)>] +[B<-rand file...>] +[B<-writerand file>] [B] [B<-to addr>] [B<-from addr>] @@ -119,7 +120,7 @@ Print out a usage message. =item B<-encrypt> -encrypt mail for the given recipient certificates. Input file is the message +Encrypt mail for the given recipient certificates. Input file is the message to be encrypted. The output file is the encrypted mail in MIME format. The actual CMS type is EnvelopedData. @@ -128,33 +129,33 @@ key has been compromised, others may be able to decrypt the text. =item B<-decrypt> -decrypt mail using the supplied certificate and private key. Expects an +Decrypt mail using the supplied certificate and private key. Expects an encrypted mail message in MIME format for the input file. The decrypted mail is written to the output file. =item B<-debug_decrypt> -this option sets the B flag. This option should be used +This option sets the B flag. This option should be used with caution: see the notes section below. =item B<-sign> -sign mail using the supplied certificate and private key. Input file is +Sign mail using the supplied certificate and private key. Input file is the message to be signed. The signed message in MIME format is written to the output file. =item B<-verify> -verify signed mail. Expects a signed mail message on input and outputs +Verify signed mail. Expects a signed mail message on input and outputs the signed data. Both clear text and opaque signing is supported. =item B<-cmsout> -takes an input message and writes out a PEM encoded CMS structure. +Takes an input message and writes out a PEM encoded CMS structure. =item B<-resign> -resign a message: take an existing message and one or more new signers. +Resign a message: take an existing message and one or more new signers. =item B<-data_create> @@ -202,12 +203,12 @@ to the B<-verify> operation. =item B<-in filename> -the input message to be encrypted or signed or the message to be decrypted +The input message to be encrypted or signed or the message to be decrypted or verified. =item B<-inform SMIME|PEM|DER> -this specifies the input format for the CMS structure. The default +This specifies the input format for the CMS structure. The default is B which reads an S/MIME format message. B and B format change this to expect PEM and DER format CMS structures instead. This currently only affects the input format of the CMS @@ -216,17 +217,17 @@ B<-encrypt> or B<-sign>) this option has no effect. =item B<-rctform SMIME|PEM|DER> -specify the format for a signed receipt for use with the B<-receipt_verify> +Specify the format for a signed receipt for use with the B<-receipt_verify> operation. =item B<-out filename> -the message text that has been decrypted or verified or the output MIME +The message text that has been decrypted or verified or the output MIME format message that has been signed or verified. =item B<-outform SMIME|PEM|DER> -this specifies the output format for the CMS structure. The default +This specifies the output format for the CMS structure. The default is B which writes an S/MIME format message. B and B format change this to write PEM and DER format CMS structures instead. This currently only affects the output format of the CMS @@ -235,7 +236,7 @@ B<-verify> or B<-decrypt>) this option has no effect. =item B<-stream -indef -noindef> -the B<-stream> and B<-indef> options are equivalent and enable streaming I/O +The B<-stream> and B<-indef> options are equivalent and enable streaming I/O for encoding operations. This permits single pass processing of data without the need to hold the entire contents in memory, potentially supporting very large files. Streaming is automatically set for S/MIME signing with detached @@ -244,7 +245,7 @@ other operations. =item B<-noindef> -disable streaming I/O where it would produce and indefinite length constructed +Disable streaming I/O where it would produce and indefinite length constructed encoding. This option currently has no effect. In future streaming will be enabled by default on all relevant operations and this option will disable it. @@ -258,29 +259,29 @@ is S/MIME and it uses the multipart/signed MIME content type. =item B<-text> -this option adds plain text (text/plain) MIME headers to the supplied +This option adds plain text (text/plain) MIME headers to the supplied message if encrypting or signing. If decrypting or verifying it strips off text headers: if the decrypted or verified message is not of MIME type text/plain then an error occurs. =item B<-noout> -for the B<-cmsout> operation do not output the parsed CMS structure. This +For the B<-cmsout> operation do not output the parsed CMS structure. This is useful when combined with the B<-print> option or if the syntax of the CMS structure is being checked. =item B<-print> -for the B<-cmsout> operation print out all fields of the CMS structure. This +For the B<-cmsout> operation print out all fields of the CMS structure. This is mainly useful for testing purposes. =item B<-CAfile file> -a file containing trusted CA certificates, only used with B<-verify>. +A file containing trusted CA certificates, only used with B<-verify>. =item B<-CApath dir> -a directory containing trusted CA certificates, only used with +A directory containing trusted CA certificates, only used with B<-verify>. This directory must be a standard certificate directory: that is a hash of each subject name (using B) should be linked to each certificate. @@ -295,12 +296,12 @@ Do not load the trusted CA certificates from the default directory location =item B<-md digest> -digest algorithm to use when signing or resigning. If not present then the +Digest algorithm to use when signing or resigning. If not present then the default digest algorithm for the signing key will be used (usually SHA1). -=item B<-[cipher]> +=item B<-I> -the encryption algorithm to use. For example triple DES (168 bits) - B<-des3> +The encryption algorithm to use. For example triple DES (168 bits) - B<-des3> or 256 bit AES - B<-aes256>. Any standard algorithm name (as used by the EVP_get_cipherbyname() function) can also be used preceded by a dash, for example B<-aes-128-cbc>. See L|enc(1)> for a list of ciphers @@ -311,48 +312,48 @@ B<-EncryptedData_create> commands. =item B<-nointern> -when verifying a message normally certificates (if any) included in +When verifying a message normally certificates (if any) included in the message are searched for the signing certificate. With this option only the certificates specified in the B<-certfile> option are used. The supplied certificates can still be used as untrusted CAs however. -=item B<-no_signer_cert_verify> +=item B<-noverify> -do not verify the signers certificate of a signed message. +Do not verify the signers certificate of a signed message. =item B<-nocerts> -when signing a message the signer's certificate is normally included +When signing a message the signer's certificate is normally included with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the B<-certfile> option for example). =item B<-noattr> -normally when a message is signed a set of attributes are included which +Normally when a message is signed a set of attributes are included which include the signing time and supported symmetric algorithms. With this option they are not included. =item B<-nosmimecap> -exclude the list of supported algorithms from signed attributes, other options +Exclude the list of supported algorithms from signed attributes, other options such as signing time and content type are still included. =item B<-binary> -normally the input message is converted to "canonical" format which is +Normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this option is present no translation occurs. This is useful when handling binary data which may not be in MIME format. =item B<-crlfeol> -normally the output file uses a single B as end of line. When this +Normally the output file uses a single B as end of line. When this option is present B is used instead. =item B<-asciicrlf> -when signing use ASCII CRLF format canonicalisation. This strips trailing +When signing use ASCII CRLF format canonicalisation. This strips trailing whitespace from all lines, deletes trailing blank lines at EOF and sets the encapsulated content type. This option is normally used with detached content and an output signature format of DER. This option is not normally @@ -361,31 +362,31 @@ content format is detected. =item B<-nodetach> -when signing a message use opaque signing: this form is more resistant +When signing a message use opaque signing: this form is more resistant to translation by mail relays but it cannot be read by mail agents that do not support S/MIME. Without this option cleartext signing with the MIME type multipart/signed is used. =item B<-certfile file> -allows additional certificates to be specified. When signing these will +Allows additional certificates to be specified. When signing these will be included with the message. When verifying these will be searched for the signers certificates. The certificates should be in PEM format. =item B<-certsout file> -any certificates contained in the message are written to B. +Any certificates contained in the message are written to B. =item B<-signer file> -a signing certificate when signing or resigning a message, this option can be +A signing certificate when signing or resigning a message, this option can be used multiple times if more than one signer is required. If a message is being verified then the signers certificates will be written to this file if the verification was successful. =item B<-recip file> -when decrypting a message this specifies the recipients certificate. The +When decrypting a message this specifies the recipients certificate. The certificate must match one of the recipients of the message or an error occurs. @@ -395,19 +396,19 @@ required (for example to specify RSA-OAEP). =item B<-keyid> -use subject key identifier to identify certificates instead of issuer name and +Use subject key identifier to identify certificates instead of issuer name and serial number. The supplied certificate B include a subject key identifier extension. Supported by B<-sign> and B<-encrypt> options. =item B<-receipt_request_all -receipt_request_first> -for B<-sign> option include a signed receipt request. Indicate requests should +For B<-sign> option include a signed receipt request. Indicate requests should be provided by all recipient or first tier recipients (those mailed directly and not from a mailing list). Ignored it B<-receipt_request_from> is included. =item B<-receipt_request_from emailaddress> -for B<-sign> option include a signed receipt request. Add an explicit email +For B<-sign> option include a signed receipt request. Add an explicit email address where receipts should be supplied. =item B<-receipt_request_to emailaddress> @@ -422,7 +423,7 @@ requests. =item B<-secretkey key> -specify symmetric key to use. The key must be supplied in hex format and be +Specify symmetric key to use. The key must be supplied in hex format and be consistent with the algorithm used. Supported by the B<-EncryptedData_encrypt> B<-EncryptedData_decrypt>, B<-encrypt> and B<-decrypt> options. When used with B<-encrypt> or B<-decrypt> the supplied key is used to wrap or unwrap the @@ -430,7 +431,7 @@ content encryption key using an AES key in the B type. =item B<-secretkeyid id> -the key identifier for the supplied symmetric key for B type. +The key identifier for the supplied symmetric key for B type. This option B be present if the B<-secretkey> option is used with B<-encrypt>. With B<-decrypt> operations the B is used to locate the relevant key if it is not supplied then an attempt is used to decrypt any @@ -438,13 +439,13 @@ B structures. =item B<-econtent_type type> -set the encapsulated content type to B if not supplied the B type +Set the encapsulated content type to B if not supplied the B type is used. The B argument can be any valid OID name in either text or numerical format. =item B<-inkey file> -the private key to use when signing or decrypting. This must match the +The private key to use when signing or decrypting. This must match the corresponding certificate. If this option is not specified then the private key must be included in the certificate file specified with the B<-recip> or B<-signer> file. When signing this option can be used @@ -452,32 +453,37 @@ multiple times to specify successive keys. =item B<-keyopt name:opt> -for signing and encryption this option can be used multiple times to +For signing and encryption this option can be used multiple times to set customised parameters for the preceding key or certificate. It can currently be used to set RSA-PSS for signing, RSA-OAEP for encryption or to modify default parameters for ECDH. =item B<-passin arg> -the private key password source. For more information about the format of B +The private key password source. For more information about the format of B see the B section in L. -=item B<-rand file(s)> +=item B<-rand file...> -a file or files containing random data used to seed the random number -generator, or an EGD socket (see L). +A file or files containing random data used to seed the random number +generator. Multiple files can be specified separated by an OS-dependent character. The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for all others. +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =item B -one or more certificates of message recipients: used when encrypting +One or more certificates of message recipients: used when encrypting a message. =item B<-to, -from, -subject> -the relevant mail headers. These are included outside the signed +The relevant mail headers. These are included outside the signed portion of a message so they may be included manually. If signing then many S/MIME mail clients check the signers certificate's email address matches that specified in the From: address. @@ -549,28 +555,28 @@ with caution. For a fuller description see L). =item Z<>0 -the operation was completely successfully. +The operation was completely successfully. =item Z<>1 -an error occurred parsing the command options. +An error occurred parsing the command options. =item Z<>2 -one of the input files could not be read. +One of the input files could not be read. =item Z<>3 -an error occurred creating the CMS file or when reading the MIME +An error occurred creating the CMS file or when reading the MIME message. =item Z<>4 -an error occurred decrypting or verifying the message. +An error occurred decrypting or verifying the message. =item Z<>5 -the message was verified correctly but an error occurred writing out +The message was verified correctly but an error occurred writing out the signers certificates. =back @@ -728,7 +734,7 @@ The -no_alt_chains options was first added to OpenSSL 1.1.0. =head1 COPYRIGHT -Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2008-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 diff --git a/doc/apps/crl.pod b/doc/man1/crl.pod similarity index 75% rename from doc/apps/crl.pod rename to doc/man1/crl.pod index fded3972..9a009675 100644 --- a/doc/apps/crl.pod +++ b/doc/man1/crl.pod @@ -43,8 +43,8 @@ the DER form with 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. +This specifies the output format, the options have the same meaning and default +as the B<-inform> option. =item B<-in filename> @@ -53,52 +53,52 @@ option is not specified. =item B<-out filename> -specifies the output filename to write to or standard output by +Specifies the output filename to write to or standard output by default. =item B<-text> -print out the CRL in text form. +Print out the CRL in text form. =item B<-nameopt option> -option which determines how the subject or issuer names are displayed. See +Option which determines how the subject or issuer names are displayed. See the description of B<-nameopt> in L. =item B<-noout> -don't output the encoded version of the CRL. +Don't output the encoded version of the CRL. =item B<-hash> -output a hash of the issuer name. This can be use to lookup CRLs in +Output a hash of the issuer name. This can be use to lookup CRLs in a directory by issuer name. =item B<-hash_old> -outputs the "hash" of the CRL issuer name using the older algorithm -as used by OpenSSL versions before 1.0.0. +Outputs the "hash" of the CRL issuer name using the older algorithm +as used by OpenSSL before version 1.0.0. =item B<-issuer> -output the issuer name. +Output the issuer name. =item B<-lastupdate> -output the lastUpdate field. +Output the lastUpdate field. =item B<-nextupdate> -output the nextUpdate field. +Output the nextUpdate field. =item B<-CAfile file> -verify the signature on a CRL by looking up the issuing certificate in -B +Verify the signature on a CRL by looking up the issuing certificate in +B. =item B<-CApath dir> -verify the signature on a CRL by looking up the issuing certificate in +Verify the signature on a CRL by looking up the issuing certificate in B

. This directory must be a standard certificate directory: that is a hash of each subject name (using B) should be linked to each certificate. @@ -133,7 +133,7 @@ L, L, L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/crl2pkcs7.pod b/doc/man1/crl2pkcs7.pod similarity index 86% rename from doc/apps/crl2pkcs7.pod rename to doc/man1/crl2pkcs7.pod index 933750ad..f58a442b 100644 --- a/doc/apps/crl2pkcs7.pod +++ b/doc/man1/crl2pkcs7.pod @@ -34,13 +34,13 @@ Print out a usage message. This specifies the CRL input format. B format is DER encoded CRL structure.B (the default) is a base64 encoded version of -the DER form with header and footer lines. +the DER form with header and footer lines. The default format is PEM. =item B<-outform DER|PEM> This specifies the PKCS#7 structure output format. B format is DER encoded PKCS#7 structure.B (the default) is a base64 encoded version of -the DER form with header and footer lines. +the DER form with header and footer lines. The default format is PEM. =item B<-in filename> @@ -49,19 +49,19 @@ option is not specified. =item B<-out filename> -specifies the output filename to write the PKCS#7 structure to or standard +Specifies the output filename to write the PKCS#7 structure to or standard output by default. =item B<-certfile filename> -specifies a filename containing one or more certificates in B format. +Specifies a filename containing one or more certificates in B format. All certificates in the file will be added to the PKCS#7 structure. This option can be used more than once to read certificates form multiple files. =item B<-nocrl> -normally a CRL is included in the output file. With this option no CRL is +Normally a CRL is included in the output file. With this option no CRL is included in the output file and a CRL is not read from the input file. =back @@ -96,7 +96,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/dgst.pod b/doc/man1/dgst.pod similarity index 95% rename from doc/apps/dgst.pod rename to doc/man1/dgst.pod index 59919c32..5cad2438 100644 --- a/doc/apps/dgst.pod +++ b/doc/man1/dgst.pod @@ -3,13 +3,13 @@ =head1 NAME openssl-dgst, -dgst, sha, sha1, mdc2, ripemd160, sha224, sha256, sha384, sha512, md4, md5, blake2b, blake2s - message digests +dgst - perform digest operations =head1 SYNOPSIS -B B -[B<-help>] +B [B<-I>] +[B<-help>] [B<-c>] [B<-d>] [B<-hex>] @@ -24,13 +24,12 @@ B B [B<-signature filename>] [B<-hmac key>] [B<-fips-fingerprint>] +[B<-rand file...>] [B<-engine id>] [B<-engine_impl>] [B] -B -[I] -[B<...>] +B I [B<...>] =head1 DESCRIPTION @@ -150,14 +149,19 @@ for example exactly 32 chars for gost-mac. =back -=item B<-rand file(s)> +=item B<-rand file...> A file or files containing random data used to seed the random number -generator, or an EGD socket (see L). +generator. Multiple files can be specified separated by an OS-dependent character. The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for all others. +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =item B<-fips-fingerprint> Compute HMAC using a specific key for certain OpenSSL-FIPS operations. diff --git a/doc/apps/dhparam.pod b/doc/man1/dhparam.pod similarity index 84% rename from doc/apps/dhparam.pod rename to doc/man1/dhparam.pod index 52fc0df3..1b43b323 100644 --- a/doc/apps/dhparam.pod +++ b/doc/man1/dhparam.pod @@ -20,7 +20,8 @@ B [B<-C>] [B<-2>] [B<-5>] -[B<-rand> I] +[B<-rand file...>] +[B<-writerand file>] [B<-engine id>] [I] @@ -45,8 +46,8 @@ 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. +This specifies the output format, the options have the same meaning and default +as the B<-inform> option. =item B<-in> I @@ -83,17 +84,22 @@ input file is ignored and parameters are generated instead. If not present but B is present, parameters are generated with the default generator 2. -=item B<-rand> I +=item B<-rand file...> -a file or files containing random data used to seed the random number -generator, or an EGD socket (see L). +A file or files containing random data used to seed the random number +generator. Multiple files can be specified separated by an OS-dependent character. The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for all others. +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =item I -this option specifies that a parameter set should be generated of size +This option specifies that a parameter set should be generated of size I. It must be the last option. If this option is present then the input file is ignored and parameters are generated instead. If this option is not present but a generator (B<-2> or B<-5>) is @@ -101,20 +107,20 @@ present, parameters are generated with a default length of 2048 bits. =item B<-noout> -this option inhibits the output of the encoded version of the parameters. +This option inhibits the output of the encoded version of the parameters. =item B<-text> -this option prints out the DH parameters in human readable form. +This option prints out the DH parameters in human readable form. =item B<-C> -this option converts the parameters into C code. The parameters can then +This option converts the parameters into C code. The parameters can then be loaded by calling the get_dhNNNN() function. =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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. @@ -150,7 +156,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/dsa.pod b/doc/man1/dsa.pod similarity index 84% rename from doc/apps/dsa.pod rename to doc/man1/dsa.pod index 37358044..2428879e 100644 --- a/doc/apps/dsa.pod +++ b/doc/man1/dsa.pod @@ -18,6 +18,9 @@ B B [B<-aes128>] [B<-aes192>] [B<-aes256>] +[B<-aria128>] +[B<-aria192>] +[B<-aria256>] [B<-camellia128>] [B<-camellia192>] [B<-camellia256>] @@ -60,8 +63,8 @@ PKCS#8 format is also accepted. =item B<-outform DER|PEM> -This specifies the output format, the options have the same meaning as the -B<-inform> option. +This specifies the output format, the options have the same meaning and default +as the B<-inform> option. =item B<-in filename> @@ -71,7 +74,7 @@ prompted for. =item B<-passin arg> -the input file password source. For more information about the format of B +The input file password source. For more information about the format of B see the B section in L. =item B<-out filename> @@ -83,10 +86,10 @@ filename. =item B<-passout arg> -the output file password source. For more information about the format of B +The output file password source. For more information about the format of B see the B section in L. -=item B<-aes128|-aes192|-aes256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea> +=item B<-aes128|-aes192|-aes256|-aria128|-aria192|-aria256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea> These options encrypt the private key with the specified cipher before outputting it. A pass phrase is prompted for. @@ -98,30 +101,30 @@ These options can only be used with PEM format output files. =item B<-text> -prints out the public, private key components and parameters. +Prints out the public, private key components and parameters. =item B<-noout> -this option prevents output of the encoded version of the key. +This option prevents output of the encoded version of the key. =item B<-modulus> -this option prints out the value of the public key component of the key. +This option prints out the value of the public key component of the key. =item B<-pubin> -by default a private key is read from the input file: with this option a +By default, a private key is read from the input file. With this option a public key is read instead. =item B<-pubout> -by default a private key is output. With this option a public +By default, a private key is output. With this option a public key will be output instead. This option is automatically set if the input is a public key. =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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. @@ -169,7 +172,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/dsaparam.pod b/doc/man1/dsaparam.pod similarity index 77% rename from doc/apps/dsaparam.pod rename to doc/man1/dsaparam.pod index 0dfda660..94ea435c 100644 --- a/doc/apps/dsaparam.pod +++ b/doc/man1/dsaparam.pod @@ -16,7 +16,8 @@ B [B<-noout>] [B<-text>] [B<-C>] -[B<-rand file(s)>] +[B<-rand file...>] +[B<-writerand file>] [B<-genkey>] [B<-engine id>] [B] @@ -42,8 +43,8 @@ of the B 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. +This specifies the output format, the options have the same meaning and default +as the B<-inform> option. =item B<-in filename> @@ -59,39 +60,44 @@ as the input filename. =item B<-noout> -this option inhibits the output of the encoded version of the parameters. +This option inhibits the output of the encoded version of the parameters. =item B<-text> -this option prints out the DSA parameters in human readable form. +This option prints out the DSA parameters in human readable form. =item B<-C> -this option converts the parameters into C code. The parameters can then +This option converts the parameters into C code. The parameters can then be loaded by calling the get_dsaXXX() function. =item B<-genkey> -this option will generate a DSA either using the specified or generated +This option will generate a DSA either using the specified or generated parameters. -=item B<-rand file(s)> +=item B<-rand file...> -a file or files containing random data used to seed the random number -generator, or an EGD socket (see L). +A file or files containing random data used to seed the random number +generator. Multiple files can be specified separated by an OS-dependent character. The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for all others. +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =item B -this option specifies that a parameter set should be generated of size +This option specifies that a parameter set should be generated of size B. It must be the last option. If this option is included then the input file (if any) is ignored. =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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. @@ -115,7 +121,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/ec.pod b/doc/man1/ec.pod similarity index 88% rename from doc/apps/ec.pod rename to doc/man1/ec.pod index c06005d8..0b836603 100644 --- a/doc/apps/ec.pod +++ b/doc/man1/ec.pod @@ -56,8 +56,8 @@ PKCS#8 format is also accepted. =item B<-outform DER|PEM> -This specifies the output format, the options have the same meaning as the -B<-inform> option. +This specifies the output format, the options have the same meaning and default +as the B<-inform> option. =item B<-in filename> @@ -67,7 +67,7 @@ prompted for. =item B<-passin arg> -the input file password source. For more information about the format of B +The input file password source. For more information about the format of B see the B section in L. =item B<-out filename> @@ -79,7 +79,7 @@ filename. =item B<-passout arg> -the output file password source. For more information about the format of B +The output file password source. For more information about the format of B see the B section in L. =item B<-des|-des3|-idea> @@ -95,24 +95,24 @@ These options can only be used with PEM format output files. =item B<-text> -prints out the public, private key components and parameters. +Prints out the public, private key components and parameters. =item B<-noout> -this option prevents output of the encoded version of the key. +This option prevents output of the encoded version of the key. =item B<-modulus> -this option prints out the value of the public key component of the key. +This option prints out the value of the public key component of the key. =item B<-pubin> -by default a private key is read from the input file: with this option a +By default, a private key is read from the input file. With this option a public key is read instead. =item B<-pubout> -by default a private key is output. With this option a public +By default a private key is output. With this option a public key will be output instead. This option is automatically set if the input is a public key. @@ -142,11 +142,11 @@ This option omits the public key components from the private key output. =item B<-check> -this option checks the consistency of an EC private or public key. +This option checks the consistency of an EC private or public key. =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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. @@ -197,7 +197,7 @@ L, L, L =head1 COPYRIGHT -Copyright 2003-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2003-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 diff --git a/doc/apps/ecparam.pod b/doc/man1/ecparam.pod similarity index 88% rename from doc/apps/ecparam.pod rename to doc/man1/ecparam.pod index 69a26319..dc07caf4 100644 --- a/doc/apps/ecparam.pod +++ b/doc/man1/ecparam.pod @@ -22,7 +22,8 @@ B [B<-conv_form arg>] [B<-param_enc arg>] [B<-no_seed>] -[B<-rand file(s)>] +[B<-rand file...>] +[B<-writerand file>] [B<-genkey>] [B<-engine id>] @@ -47,8 +48,8 @@ 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. +This specifies the output format, the options have the same meaning and default +as the B<-inform> option. =item B<-in filename> @@ -91,8 +92,8 @@ 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, B (the -default value) and B. For more information regarding +into octet strings. Possible values are: B (the default +value), B and B. For more information regarding the point conversion forms please read the X9.62 standard. B Due to patent issues the B option is disabled by default for binary curves and can be enabled by defining @@ -117,17 +118,22 @@ is included in the ECParameters structure (see RFC 3279). This option will generate an EC private key using the specified parameters. -=item B<-rand file(s)> +=item B<-rand file...> -a file or files containing random data used to seed the random number -generator, or an EGD socket (see L). +A file or files containing random data used to seed the random number +generator. Multiple files can be specified separated by an OS-dependent character. The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for all others. +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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. @@ -176,7 +182,7 @@ L, L =head1 COPYRIGHT -Copyright 2003-2018 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2003-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 diff --git a/doc/man1/enc.pod b/doc/man1/enc.pod new file mode 100644 index 00000000..01cca4ea --- /dev/null +++ b/doc/man1/enc.pod @@ -0,0 +1,407 @@ +=pod + +=head1 NAME + +openssl-enc, +enc - symmetric cipher routines + +=head1 SYNOPSIS + +B> +[B<-help>] +[B<-ciphers>] +[B<-in filename>] +[B<-out filename>] +[B<-pass arg>] +[B<-e>] +[B<-d>] +[B<-a>] +[B<-base64>] +[B<-A>] +[B<-k password>] +[B<-kfile filename>] +[B<-K key>] +[B<-iv IV>] +[B<-S salt>] +[B<-salt>] +[B<-nosalt>] +[B<-z>] +[B<-md digest>] +[B<-iter count>] +[B<-pbkdf2>] +[B<-p>] +[B<-P>] +[B<-bufsize number>] +[B<-nopad>] +[B<-debug>] +[B<-none>] +[B<-rand file...>] +[B<-writerand file>] +[B<-engine id>] + +B I<[cipher]> [B<...>] + +=head1 DESCRIPTION + +The symmetric cipher commands allow data to be encrypted or decrypted +using various block and stream ciphers using keys based on passwords +or explicitly provided. Base64 encoding or decoding can also be performed +either by itself or in addition to the encryption or decryption. + +=head1 OPTIONS + +=over 4 + +=item B<-help> + +Print out a usage message. + +=item B<-ciphers> + +List all supported ciphers. + +=item B<-in filename> + +The input filename, standard input by default. + +=item B<-out filename> + +The output filename, standard output by default. + +=item B<-pass arg> + +The password source. For more information about the format of B +see the B section in L. + +=item B<-e> + +Encrypt the input data: this is the default. + +=item B<-d> + +Decrypt the input data. + +=item B<-a> + +Base64 process the data. This means that if encryption is taking place +the data is base64 encoded after encryption. If decryption is set then +the input data is base64 decoded before being decrypted. + +=item B<-base64> + +Same as B<-a> + +=item B<-A> + +If the B<-a> option is set then base64 process the data on one line. + +=item B<-k password> + +The password to derive the key from. This is for compatibility with previous +versions of OpenSSL. Superseded by the B<-pass> argument. + +=item B<-kfile filename> + +Read the password to derive the key from the first line of B. +This is for compatibility with previous versions of OpenSSL. Superseded by +the B<-pass> argument. + +=item B<-md digest> + +Use the specified digest to create the key from the passphrase. +The default algorithm is sha-256. + +=item B<-iter count> + +Use a given number of iterations on the password in deriving the encryption key. +High values increase the time required to brute-force the resulting file. +This option enables the use of PBKDF2 algorithm to derive the key. + +=item B<-pbkdf2> + +Use PBKDF2 algorithm with default iteration count unless otherwise specified. + +=item B<-nosalt> + +Don't use a salt in the key derivation routines. This option B be +used except for test purposes or compatibility with ancient versions of +OpenSSL. + +=item B<-salt> + +Use salt (randomly generated or provide with B<-S> option) when +encrypting, this is the default. + +=item B<-S salt> + +The actual salt to use: this must be represented as a string of hex digits. + +=item B<-K key> + +The actual key to use: this must be represented as a string comprised only +of hex digits. If only the key is specified, the IV must additionally specified +using the B<-iv> option. When both a key and a password are specified, the +key given with the B<-K> option will be used and the IV generated from the +password will be taken. It does not make much sense to specify both key +and password. + +=item B<-iv IV> + +The actual IV to use: this must be represented as a string comprised only +of hex digits. When only the key is specified using the B<-K> option, the +IV must explicitly be defined. When a password is being specified using +one of the other options, the IV is generated from this password. + +=item B<-p> + +Print out the key and IV used. + +=item B<-P> + +Print out the key and IV used then immediately exit: don't do any encryption +or decryption. + +=item B<-bufsize number> + +Set the buffer size for I/O. + +=item B<-nopad> + +Disable standard block padding. + +=item B<-debug> + +Debug the BIOs used for I/O. + +=item B<-z> + +Compress or decompress clear text using zlib before encryption or after +decryption. This option exists only if OpenSSL with compiled with zlib +or zlib-dynamic option. + +=item B<-none> + +Use NULL cipher (no encryption or decryption of input). + +=item B<-rand file...> + +A file or files containing random data used to seed the random number +generator. +Multiple files can be specified separated by an OS-dependent character. +The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for +all others. + +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + +=back + +=head1 NOTES + +The program can be called either as B or +B. The first form doesn't work with +engine-provided ciphers, because this form is processed before the +configuration file is read and any ENGINEs loaded. +Use the B command to get a list of supported ciphers. + +Engines which provide entirely new encryption algorithms (such as the ccgost +engine which provides gost89 algorithm) should be configured in the +configuration file. Engines specified on the command line using -engine +options can only be used for hardware-assisted implementations of +ciphers which are supported by the OpenSSL core or another engine specified +in the configuration file. + +When the enc command lists supported ciphers, ciphers provided by engines, +specified in the configuration files are listed too. + +A password will be prompted for to derive the key and IV if necessary. + +The B<-salt> option should B be used if the key is being derived +from a password unless you want compatibility with previous versions of +OpenSSL. + +Without the B<-salt> option it is possible to perform efficient dictionary +attacks on the password and to attack stream cipher encrypted data. The reason +for this is that without the salt the same password always generates the same +encryption key. When the salt is being used the first eight bytes of the +encrypted data are reserved for the salt: it is generated at random when +encrypting a file and read from the encrypted file when it is decrypted. + +Some of the ciphers do not have large keys and others have security +implications if not used correctly. A beginner is advised to just use +a strong block cipher, such as AES, in CBC mode. + +All the block ciphers normally use PKCS#5 padding, also known as standard +block padding. This allows a rudimentary integrity or password check to +be performed. However since the chance of random data passing the test +is better than 1 in 256 it isn't a very good test. + +If padding is disabled then the input data must be a multiple of the cipher +block length. + +All RC2 ciphers have the same key and effective key length. + +Blowfish and RC5 algorithms use a 128 bit key. + +=head1 SUPPORTED CIPHERS + +Note that some of these ciphers can be disabled at compile time +and some are available only if an appropriate engine is configured +in the configuration file. The output of the B command run with +the B<-ciphers> option (that is B) produces a +list of ciphers, supported by your version of OpenSSL, including +ones provided by configured engines. + +The B program does not support authenticated encryption modes +like CCM and GCM, and will not support such modes in the future. +The B interface by necessity must begin streaming output (e.g., +to standard output when B<-out> is not used before the authentication +tag could be validated, leading to the usage of B in pipelines +that begin processing untrusted data and are not capable of rolling +back upon authentication failure. The AEAD modes currently in common +use also suffer from catastrophic failure of confidentiality and/or +integrity upon reuse of key/iv/nonce, and since B places the +entire burden of key/iv/nonce management upon the user, the risk of +exposing AEAD modes is too great to allow. These key/iv/nonce +management issues also affect other modes currently exposed in B, +but the failure modes are less extreme in these cases, and the +functionality cannot be removed with a stable release branch. +For bulk encryption of data, whether using authenticated encryption +modes or other modes, L is recommended, as it provides a +standard data format and performs the needed key/iv/nonce management. + + + base64 Base 64 + + bf-cbc Blowfish in CBC mode + bf Alias for bf-cbc + bf-cfb Blowfish in CFB mode + bf-ecb Blowfish in ECB mode + bf-ofb Blowfish in OFB mode + + cast-cbc CAST in CBC mode + cast Alias for cast-cbc + cast5-cbc CAST5 in CBC mode + cast5-cfb CAST5 in CFB mode + cast5-ecb CAST5 in ECB mode + cast5-ofb CAST5 in OFB mode + + des-cbc DES in CBC mode + des Alias for des-cbc + des-cfb DES in CFB mode + des-ofb DES in OFB mode + des-ecb DES in ECB mode + + des-ede-cbc Two key triple DES EDE in CBC mode + des-ede Two key triple DES EDE in ECB mode + des-ede-cfb Two key triple DES EDE in CFB mode + des-ede-ofb Two key triple DES EDE in OFB mode + + des-ede3-cbc Three key triple DES EDE in CBC mode + des-ede3 Three key triple DES EDE in ECB mode + des3 Alias for des-ede3-cbc + des-ede3-cfb Three key triple DES EDE CFB mode + des-ede3-ofb Three key triple DES EDE in OFB mode + + desx DESX algorithm. + + gost89 GOST 28147-89 in CFB mode (provided by ccgost engine) + gost89-cnt `GOST 28147-89 in CNT mode (provided by ccgost engine) + + idea-cbc IDEA algorithm in CBC mode + idea same as idea-cbc + idea-cfb IDEA in CFB mode + idea-ecb IDEA in ECB mode + idea-ofb IDEA in OFB mode + + rc2-cbc 128 bit RC2 in CBC mode + rc2 Alias for rc2-cbc + rc2-cfb 128 bit RC2 in CFB mode + rc2-ecb 128 bit RC2 in ECB mode + rc2-ofb 128 bit RC2 in OFB mode + rc2-64-cbc 64 bit RC2 in CBC mode + rc2-40-cbc 40 bit RC2 in CBC mode + + rc4 128 bit RC4 + rc4-64 64 bit RC4 + rc4-40 40 bit RC4 + + rc5-cbc RC5 cipher in CBC mode + rc5 Alias for rc5-cbc + rc5-cfb RC5 cipher in CFB mode + rc5-ecb RC5 cipher in ECB mode + rc5-ofb RC5 cipher in OFB mode + + aes-[128|192|256]-cbc 128/192/256 bit AES in CBC mode + aes[128|192|256] Alias for aes-[128|192|256]-cbc + aes-[128|192|256]-cfb 128/192/256 bit AES in 128 bit CFB mode + aes-[128|192|256]-cfb1 128/192/256 bit AES in 1 bit CFB mode + aes-[128|192|256]-cfb8 128/192/256 bit AES in 8 bit CFB mode + aes-[128|192|256]-ctr 128/192/256 bit AES in CTR mode + aes-[128|192|256]-ecb 128/192/256 bit AES in ECB mode + aes-[128|192|256]-ofb 128/192/256 bit AES in OFB mode + + camellia-[128|192|256]-cbc 128/192/256 bit Camellia in CBC mode + camellia[128|192|256] Alias for camellia-[128|192|256]-cbc + camellia-[128|192|256]-cfb 128/192/256 bit Camellia in 128 bit CFB mode + camellia-[128|192|256]-cfb1 128/192/256 bit Camellia in 1 bit CFB mode + camellia-[128|192|256]-cfb8 128/192/256 bit Camellia in 8 bit CFB mode + camellia-[128|192|256]-ctr 128/192/256 bit Camellia in CTR mode + camellia-[128|192|256]-ecb 128/192/256 bit Camellia in ECB mode + camellia-[128|192|256]-ofb 128/192/256 bit Camellia in OFB mode + +=head1 EXAMPLES + +Just base64 encode a binary file: + + openssl base64 -in file.bin -out file.b64 + +Decode the same file + + openssl base64 -d -in file.b64 -out file.bin + +Encrypt a file using triple DES in CBC mode using a prompted password: + + openssl des3 -salt -in file.txt -out file.des3 + +Decrypt a file using a supplied password: + + openssl des3 -d -salt -in file.des3 -out file.txt -k mypassword + +Encrypt a file then base64 encode it (so it can be sent via mail for example) +using Blowfish in CBC mode: + + openssl bf -a -salt -in file.txt -out file.bf + +Base64 decode a file then decrypt it: + + openssl bf -d -salt -a -in file.bf -out file.txt + +Decrypt some data using a supplied 40 bit RC4 key: + + openssl rc4-40 -in file.rc4 -out file.txt -K 0102030405 + +=head1 BUGS + +The B<-A> option when used with large files doesn't work properly. + +The B program only supports a fixed number of algorithms with +certain parameters. So if, for example, you want to use RC2 with a +76 bit key or RC4 with an 84 bit key you can't use this program. + +=head1 HISTORY + +The default digest was changed from MD5 to SHA256 in Openssl 1.1.0. + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/apps/engine.pod b/doc/man1/engine.pod similarity index 96% rename from doc/apps/engine.pod rename to doc/man1/engine.pod index 155cc629..24f1b32c 100644 --- a/doc/apps/engine.pod +++ b/doc/man1/engine.pod @@ -68,7 +68,7 @@ See the example below. To list all the commands available to a dynamic engine: - % openssl engine -t -tt -vvvv dynamic + $ openssl engine -t -tt -vvvv dynamic (dynamic) Dynamic engine loading support [ unavailable ] SO_PATH: Specifies the path to the new ENGINE shared library @@ -88,7 +88,7 @@ To list all the commands available to a dynamic engine: To list the capabilities of the I engine: - % openssl engine -c + $ openssl engine -c (rsax) RSAX engine support [RSA] (dynamic) Dynamic engine loading support @@ -103,6 +103,10 @@ The path to the engines directory. =back +=head1 SEE ALSO + +L + =head1 COPYRIGHT Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved. diff --git a/doc/apps/errstr.pod b/doc/man1/errstr.pod similarity index 100% rename from doc/apps/errstr.pod rename to doc/man1/errstr.pod diff --git a/doc/apps/gendsa.pod b/doc/man1/gendsa.pod similarity index 77% rename from doc/apps/gendsa.pod rename to doc/man1/gendsa.pod index 36c810a9..7984b74c 100644 --- a/doc/apps/gendsa.pod +++ b/doc/man1/gendsa.pod @@ -13,13 +13,17 @@ B B [B<-aes128>] [B<-aes192>] [B<-aes256>] +[B<-aria128>] +[B<-aria192>] +[B<-aria256>] [B<-camellia128>] [B<-camellia192>] [B<-camellia256>] [B<-des>] [B<-des3>] [B<-idea>] -[B<-rand file(s)>] +[B<-rand file...>] +[B<-writerand file>] [B<-engine id>] [B] @@ -41,23 +45,28 @@ Print out a usage message. Output the key to the specified file. If this argument is not specified then standard output is used. -=item B<-aes128|-aes192|-aes256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea> +=item B<-aes128|-aes192|-aes256|-aria128|-aria192|-aria256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea> These options encrypt the private key with specified cipher before outputting it. A pass phrase is prompted for. If none of these options is specified no encryption is used. -=item B<-rand file(s)> +=item B<-rand file...> -a file or files containing random data used to seed the random number -generator, or an EGD socket (see L). +A file or files containing random data used to seed the random number +generator. Multiple files can be specified separated by an OS-dependent character. The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for all others. +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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. @@ -82,7 +91,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/genpkey.pod b/doc/man1/genpkey.pod similarity index 80% rename from doc/apps/genpkey.pod rename to doc/man1/genpkey.pod index d4869520..d8f1c24f 100644 --- a/doc/apps/genpkey.pod +++ b/doc/man1/genpkey.pod @@ -12,7 +12,7 @@ B B [B<-out filename>] [B<-outform PEM|DER>] [B<-pass arg>] -[B<-cipher>] +[B<-I>] [B<-engine id>] [B<-paramfile file>] [B<-algorithm alg>] @@ -39,21 +39,21 @@ standard output is used. =item B<-outform DER|PEM> -This specifies the output format DER or PEM. +This specifies the output format DER or PEM. The default format is PEM. =item B<-pass arg> -the output file password source. For more information about the format of B +The output file password source. For more information about the format of B see the B section in L. -=item B<-cipher> +=item B<-I> This option encrypts the private key with the supplied cipher. Any algorithm name accepted by EVP_get_cipherbyname() is acceptable such as B. =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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. If used this option should precede all other @@ -61,19 +61,19 @@ options. =item B<-algorithm alg> -public key algorithm to use such as RSA, DSA or DH. If used this option must +Public key algorithm to use such as RSA, DSA or DH. If used this option must precede any B<-pkeyopt> options. The options B<-paramfile> and B<-algorithm> are mutually exclusive. =item B<-pkeyopt opt:value> -set the public key algorithm option B to B. The precise set of +Set the public key algorithm option B to B. The precise set of options supported depends on the public key algorithm used and its implementation. See B below for more details. =item B<-genparam> -generate a set of parameters instead of a private key. If used this option must +Generate a set of parameters instead of a private key. If used this option must precede any B<-algorithm>, B<-paramfile> or B<-pkeyopt> options. =item B<-paramfile filename> @@ -105,6 +105,10 @@ below. The number of bits in the generated key. If not specified 1024 is used. +=item B + +The number of primes in the generated key. If not specified 2 is used. + =item B The RSA public exponent value. This can be a large decimal or @@ -112,6 +116,50 @@ hexadecimal value if preceded by B<0x>. Default value is 65537. =back +=head1 RSA-PSS KEY GENERATION OPTIONS + +Note: by default an B key has no parameter restrictions. + +=over 4 + +=item B, B + +These options have the same meaning as the B algorithm. + +=item B + +=item B + +The RSA public exponent value. This can be a large decimal or +hexadecimal value if preceded by B<0x>. Default value is 65537. + +=back + +=head1 RSA-PSS KEY GENERATION OPTIONS + +Note: by default an B key has no parameter restrictions. + +=over 4 + +=item B, B + +These options have the same meaning as the B algorithm. + +=item B + +If set the key is restricted and can only use B for signing. + +=item B + +If set the key is restricted and can only use B as it's MGF1 +parameter. + +=item B + +If set the key is restricted and B specifies the minimum salt length. + +=back + =head1 DSA PARAMETER GENERATION OPTIONS =over 4 @@ -155,11 +203,11 @@ key from a named curve without the need to use an explicit parameter file. =item B -the EC curve to use. OpenSSL supports NIST curve names such as "P-256". +The EC curve to use. OpenSSL supports NIST curve names such as "P-256". =item B -the encoding to use for parameters. The "encoding" parameter must be either +The encoding to use for parameters. The "encoding" parameter must be either "named_curve" or "explicit". =back @@ -268,7 +316,7 @@ were added in OpenSSL 1.0.2. =head1 COPYRIGHT -Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2006-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 diff --git a/doc/man1/genrsa.pod b/doc/man1/genrsa.pod new file mode 100644 index 00000000..25562dc8 --- /dev/null +++ b/doc/man1/genrsa.pod @@ -0,0 +1,128 @@ +=pod + +=head1 NAME + +openssl-genrsa, +genrsa - generate an RSA private key + +=head1 SYNOPSIS + +B B +[B<-help>] +[B<-out filename>] +[B<-passout arg>] +[B<-aes128>] +[B<-aes192>] +[B<-aes256>] +[B<-aria128>] +[B<-aria192>] +[B<-aria256>] +[B<-camellia128>] +[B<-camellia192>] +[B<-camellia256>] +[B<-des>] +[B<-des3>] +[B<-idea>] +[B<-f4>] +[B<-3>] +[B<-rand file...>] +[B<-writerand file>] +[B<-engine id>] +[B<-primes num>] +[B] + +=head1 DESCRIPTION + +The B command generates an RSA private key. + +=head1 OPTIONS + +=over 4 + +=item B<-help> + +Print out a usage message. + +=item B<-out filename> + +Output the key to the specified file. If this argument is not specified then +standard output is used. + +=item B<-passout arg> + +The output file password source. For more information about the format +of B see the B section in L. + +=item B<-aes128|-aes192|-aes256|-aria128|-aria192|-aria256|-camellia128|-camellia192|-camellia256|-des|-des3|-idea> + +These options encrypt the private key with specified +cipher before outputting it. If none of these options is +specified no encryption is used. If encryption is used a pass phrase is prompted +for if it is not supplied via the B<-passout> argument. + +=item B<-F4|-3> + +The public exponent to use, either 65537 or 3. The default is 65537. + +=item B<-rand file...> + +A file or files containing random data used to seed the random number +generator. +Multiple files can be specified separated by an OS-dependent character. +The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for +all others. + +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + +=item B<-engine id> + +Specifying an engine (by its unique B string) will cause B +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<-primes num> + +Specify the number of primes to use while generating the RSA key. The B +parameter must be a positive integer that is greater than 1 and less than 16. +If B is greater than 2, then the generated key is called a 'multi-prime' +RSA key, which is defined in RFC 8017. + +=item B + +The size of the private key to generate in bits. This must be the last option +specified. The default is 2048 and values less than 512 are not allowed. + +=back + +=head1 NOTES + +RSA private key generation essentially involves the generation of two or more +prime numbers. When generating a private key various symbols will be output to +indicate the progress of the generation. A B<.> represents each number which +has passed an initial sieve test, B<+> means a number has passed a single +round of the Miller-Rabin primality test, B<*> means the current prime starts +a regenerating progress due to some failed tests. A newline means that the number +has passed all the prime tests (the actual number depends on the key size). + +Because key generation is a random process the time taken to generate a key +may vary somewhat. But in general, more primes lead to less generation time +of a key. + +=head1 SEE ALSO + +L + +=head1 COPYRIGHT + +Copyright 2000-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 +L. + +=cut diff --git a/doc/apps/list.pod b/doc/man1/list.pod similarity index 79% rename from doc/apps/list.pod rename to doc/man1/list.pod index 10887626..bed39b0c 100644 --- a/doc/apps/list.pod +++ b/doc/man1/list.pod @@ -9,12 +9,14 @@ list - list algorithms and features B [B<-help>] +[B<-1>] [B<-commands>] [B<-digest-commands>] [B<-digest-algorithms>] [B<-cipher-commands>] [B<-cipher-algorithms>] [B<-public-key-algorithms>] +[B<-public-key-methods>] [B<-disabled>] =head1 DESCRIPTION @@ -28,7 +30,12 @@ features. =item B<-help> -Display out a usage message. +Display a usage message. + +=item B<-1> + +List the commands, digest-commands, or cipher-commands in a single column. +If used, this option must be given first. =item B<-commands> @@ -63,6 +70,11 @@ then B is an alias for the official algorithm name, B. Display a list of public key algorithms, with each algorithm as a block of multiple lines, all but the first are indented. +=item B<-public-key-methods> + +Display a list of public key method OIDs: this also includes public key methods +without an associated ASN.1 method, for example, KDF algorithms. + =item B<-disabled> Display a list of disabled features, those that were compiled out @@ -72,7 +84,7 @@ of the installation. =head1 COPYRIGHT -Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2016-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 diff --git a/doc/apps/nseq.pod b/doc/man1/nseq.pod similarity index 87% rename from doc/apps/nseq.pod rename to doc/man1/nseq.pod index 6b25e221..7d5f009a 100644 --- a/doc/apps/nseq.pod +++ b/doc/man1/nseq.pod @@ -35,11 +35,11 @@ option is not specified. =item B<-out filename> -specifies the output filename or standard output by default. +Specifies the output filename or standard output by default. =item B<-toseq> -normally a Netscape certificate sequence will be input and the output +Normally a Netscape certificate sequence will be input and the output is the certificates contained in it. With the B<-toseq> option the situation is reversed: a Netscape certificate sequence is created from a file of certificates. @@ -63,7 +63,7 @@ The B encoded form uses the same headers and footers as a certificate: -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- -A Netscape certificate sequence is a Netscape specific form that can be sent +A Netscape certificate sequence is a Netscape specific format that can be sent to browsers as an alternative to the standard PKCS#7 format when several certificates are sent to the browser: for example during certificate enrollment. It is used by Netscape certificate server for example. @@ -75,7 +75,7 @@ output files and allowing multiple certificate files to be used. =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/ocsp.pod b/doc/man1/ocsp.pod similarity index 82% rename from doc/apps/ocsp.pod rename to doc/man1/ocsp.pod index 5e273cfe..e32a68c5 100644 --- a/doc/apps/ocsp.pod +++ b/doc/man1/ocsp.pod @@ -75,17 +75,19 @@ B B [B<-no_cert_checks>] [B<-no_explicit>] [B<-port num>] +[B<-ignore_err>] [B<-index file>] [B<-CA file>] [B<-rsigner file>] [B<-rkey file>] [B<-rother file>] +[B<-rsigopt nm:v>] [B<-resp_no_certs>] [B<-nmin n>] [B<-ndays n>] [B<-resp_key_id>] [B<-nrequest n>] -[B<-md5|-sha1|...>] +[B<-I>] =head1 DESCRIPTION @@ -154,25 +156,25 @@ a nonce is automatically added specifying B overrides this. =item B<-req_text>, B<-resp_text>, B<-text> -print out the text form of the OCSP request, response or both respectively. +Print out the text form of the OCSP request, response or both respectively. =item B<-reqout file>, B<-respout file> -write out the DER encoded certificate request or response to B. +Write out the DER encoded certificate request or response to B. =item B<-reqin file>, B<-respin file> -read OCSP request or response file from B. These option are ignored +Read OCSP request or response file from B. These option are ignored if OCSP request or response creation is implied by other options (for example with B, B and B options). =item B<-url responder_url> -specify the responder URL. Both HTTP and HTTPS (SSL/TLS) URLs can be specified. +Specify the responder URL. Both HTTP and HTTPS (SSL/TLS) URLs can be specified. =item B<-host hostname:port>, B<-path pathname> -if the B option is present then the OCSP request is sent to the host +If the B option is present then the OCSP request is sent to the host B on port B. B specifies the HTTP path name to use or "/" by default. This is equivalent to specifying B<-url> with scheme http:// and the given hostname, port, and pathname. @@ -185,11 +187,11 @@ This may be repeated. =item B<-timeout seconds> -connection timeout to the OCSP responder in seconds +Connection timeout to the OCSP responder in seconds =item B<-CAfile file>, B<-CApath pathname> -file or pathname containing trusted CA certificates. These are used to verify +File or pathname containing trusted CA certificates. These are used to verify the signature on the OCSP response. =item B<-no-CAfile> @@ -213,65 +215,66 @@ See L manual page for details. =item B<-verify_other file> -file containing additional certificates to search when attempting to locate +File containing additional certificates to search when attempting to locate the OCSP response signing certificate. Some responders omit the actual signer's certificate from the response: this option can be used to supply the necessary certificate in such cases. =item B<-trust_other> -the certificates specified by the B<-verify_other> option should be explicitly +The certificates specified by the B<-verify_other> option should be explicitly trusted and no additional checks will be performed on them. This is useful when the complete responder certificate chain is not available or trusting a root CA is not appropriate. =item B<-VAfile file> -file containing explicitly trusted responder certificates. Equivalent to the +File containing explicitly trusted responder certificates. Equivalent to the B<-verify_other> and B<-trust_other> options. =item B<-noverify> -don't attempt to verify the OCSP response signature or the nonce values. This -option will normally only be used for debugging since it disables all verification -of the responders certificate. +Don't attempt to verify the OCSP response signature or the nonce +values. This option will normally only be used for debugging since it +disables all verification of the responders certificate. =item B<-no_intern> -ignore certificates contained in the OCSP response when searching for the +Ignore certificates contained in the OCSP response when searching for the signers certificate. With this option the signers certificate must be specified with either the B<-verify_other> or B<-VAfile> options. =item B<-no_signature_verify> -don't check the signature on the OCSP response. Since this option tolerates invalid -signatures on OCSP responses it will normally only be used for testing purposes. +Don't check the signature on the OCSP response. Since this option +tolerates invalid signatures on OCSP responses it will normally only be +used for testing purposes. =item B<-no_cert_verify> -don't verify the OCSP response signers certificate at all. Since this option allows -the OCSP response to be signed by any certificate it should only be used for -testing purposes. +Don't verify the OCSP response signers certificate at all. Since this +option allows the OCSP response to be signed by any certificate it should +only be used for testing purposes. =item B<-no_chain> -do not use certificates in the response as additional untrusted CA +Do not use certificates in the response as additional untrusted CA certificates. =item B<-no_explicit> -do not explicitly trust the root CA if it is set to be trusted for OCSP signing. +Do not explicitly trust the root CA if it is set to be trusted for OCSP signing. =item B<-no_cert_checks> -don't perform any additional checks on the OCSP response signers certificate. +Don't perform any additional checks on the OCSP response signers certificate. That is do not make any checks to see if the signers certificate is authorised to provide the necessary status information: as a result this option should only be used for testing purposes. =item B<-validity_period nsec>, B<-status_age age> -these options specify the range of times, in seconds, which will be tolerated +These options specify the range of times, in seconds, which will be tolerated in an OCSP response. Each certificate status response includes a B time and an optional B time. The current time should fall between these two values, but the interval between the two times may be only a few @@ -285,9 +288,9 @@ status information is immediately available. In this case the age of the B field is checked to see it is not older than B seconds old. By default this additional check is not performed. -=item B<-[digest]> +=item B<-I> -this option sets digest algorithm to use for certificate identification in the +This option sets digest algorithm to use for certificate identification in the OCSP request. Any digest supported by the OpenSSL B command can be used. The default is SHA-1. This option may be used multiple times to specify the digest used by subsequent certificate identifiers. @@ -300,16 +303,17 @@ digest used by subsequent certificate identifiers. =item B<-index indexfile> -B is a text index file in B format containing certificate revocation -information. +The B parameter is the name of a text index file in B +format containing certificate revocation information. -If the B option is specified the B utility is in responder mode, otherwise -it is in client mode. The request(s) the responder processes can be either specified on -the command line (using B and B options), supplied in a file (using the -B option) or via external OCSP clients (if B or B is specified). +If the B option is specified the B utility is in responder +mode, otherwise it is in client mode. The request(s) the responder +processes can be either specified on the command line (using B +and B options), supplied in a file (using the B option) +or via external OCSP clients (if B or B is specified). -If the B option is present then the B and B options must also be -present. +If the B option is present then the B and B options +must also be present. =item B<-CA file> @@ -329,17 +333,29 @@ Don't include any certificates in the OCSP response. =item B<-resp_key_id> -Identify the signer certificate using the key ID, default is to use the subject name. +Identify the signer certificate using the key ID, default is to use the +subject name. =item B<-rkey file> -The private key to sign OCSP responses with: if not present the file specified in the -B option is used. +The private key to sign OCSP responses with: if not present the file +specified in the B option is used. + +=item B<-rsigopt nm:v> + +Pass options to the signature algorithm when signing OCSP responses. +Names and values of these options are algorithm-specific. =item B<-port portnum> -Port to listen for OCSP requests on. The port may also be specified using the B -option. +Port to listen for OCSP requests on. The port may also be specified +using the B option. + +=item B<-ignore_err> + +Ignore malformed requests or responses: When acting as an OCSP client, retry if +a malformed response is received. When acting as an OCSP responder, continue +running instead of terminating upon receiving a malformed request. =item B<-nrequest number> @@ -347,9 +363,10 @@ The OCSP server will exit after receiving B requests, default unlimited. =item B<-nmin minutes>, B<-ndays days> -Number of minutes or days when fresh revocation information is available: used in the -B field. If neither option is present then the B field -is omitted meaning fresh revocation information is immediately available. +Number of minutes or days when fresh revocation information is available: +used in the B field. If neither option is present then the +B field is omitted meaning fresh revocation information is +immediately available. =back @@ -457,7 +474,7 @@ The -no_alt_chains options was first added to OpenSSL 1.1.0. =head1 COPYRIGHT -Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2001-2018 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 diff --git a/doc/apps/openssl.pod b/doc/man1/openssl.pod similarity index 96% rename from doc/apps/openssl.pod rename to doc/man1/openssl.pod index 6e822a61..bda9ecf4 100644 --- a/doc/apps/openssl.pod +++ b/doc/man1/openssl.pod @@ -198,13 +198,17 @@ Public key algorithm parameter management. Public key algorithm cryptographic operation utility. +=item L|prime(1)> + +Compute prime numbers. + =item L|rand(1)> Generate pseudo-random bytes. =item L|rehash(1)> -Create symbolic links to certificate and CRL files named by the hash values. +Create symbolic links to certficate and CRL files named by the hash values. =item L|req(1)> @@ -256,6 +260,14 @@ Algorithm Speed Measurement. SPKAC printing and generating utility. +=item L|srp(1)> + +Maintain SRP password file. + +=item L|storeutl(1)> + +Utility to list and display certificates, keys, CRLs, etc. + =item L|ts(1)> Time Stamping Authority tool (client/server). @@ -434,11 +446,11 @@ L, L, L, L, L, L, L, L, L, L, L, L, -L, L, L, +L, L, L, L, L, L, L, L, L, L, L, L, L, -L, L, L, +L, L, L, L, L, L, L, L, L, L, L, L diff --git a/doc/man1/passwd.pod b/doc/man1/passwd.pod new file mode 100644 index 00000000..6c3d811e --- /dev/null +++ b/doc/man1/passwd.pod @@ -0,0 +1,128 @@ +=pod + +=head1 NAME + +openssl-passwd, +passwd - compute password hashes + +=head1 SYNOPSIS + +B +[B<-help>] +[B<-crypt>] +[B<-1>] +[B<-apr1>] +[B<-aixmd5>] +[B<-5>] +[B<-6>] +[B<-salt> I] +[B<-in> I] +[B<-stdin>] +[B<-noverify>] +[B<-quiet>] +[B<-table>] +[B<-rand file...>] +[B<-writerand file>] +{I} + +=head1 DESCRIPTION + +The B command computes the hash of a password typed at +run-time or the hash of each password in a list. The password list is +taken from the named file for option B<-in file>, from stdin for +option B<-stdin>, or from the command line, or from the terminal otherwise. +The Unix standard algorithm B and the MD5-based BSD password +algorithm B<1>, its Apache variant B, and its AIX variant are available. + +=head1 OPTIONS + +=over 4 + +=item B<-help> + +Print out a usage message. + +=item B<-crypt> + +Use the B algorithm (default). + +=item B<-1> + +Use the MD5 based BSD password algorithm B<1>. + +=item B<-apr1> + +Use the B algorithm (Apache variant of the BSD algorithm). + +=item B<-aixmd5> + +Use the B algorithm (AIX variant of the BSD algorithm). + +=item B<-5> + +=item B<-6> + +Use the B / B based algorithms defined by Ulrich Drepper. +See L. + +=item B<-salt> I + +Use the specified salt. +When reading a password from the terminal, this implies B<-noverify>. + +=item B<-in> I + +Read passwords from I. + +=item B<-stdin> + +Read passwords from B. + +=item B<-noverify> + +Don't verify when reading a password from the terminal. + +=item B<-quiet> + +Don't output warnings when passwords given at the command line are truncated. + +=item B<-table> + +In the output list, prepend the cleartext password and a TAB character +to each password hash. + +=item B<-rand file...> + +A file or files containing random data used to seed the random number +generator. +Multiple files can be specified separated by an OS-dependent character. +The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for +all others. + +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + +=back + +=head1 EXAMPLES + +B prints B. + +B prints B<$1$xxxxxxxx$UYCIxa628.9qXjpQCjM4a.>. + +B prints B<$apr1$xxxxxxxx$dxHfLAsjHkDRmG83UXe8K0>. + +B prints B. + +=head1 COPYRIGHT + +Copyright 2000-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 +L. + +=cut diff --git a/doc/apps/pkcs12.pod b/doc/man1/pkcs12.pod similarity index 81% rename from doc/apps/pkcs12.pod rename to doc/man1/pkcs12.pod index 44ee3d4e..3389e595 100644 --- a/doc/apps/pkcs12.pod +++ b/doc/man1/pkcs12.pod @@ -24,7 +24,7 @@ B B [B<-cacerts>] [B<-nokeys>] [B<-info>] -[B<-des | -des3 | -idea | -aes128 | -aes192 | -aes256 | -camellia128 | -camellia192 | -camellia256 | -nodes>] +[B<-des | -des3 | -idea | -aes128 | -aes192 | -aes256 | -aria128 | -aria192 | -aria256 | -camellia128 | -camellia192 | -camellia256 | -nodes>] [B<-noiter>] [B<-maciter | -nomaciter | -nomac>] [B<-twopass>] @@ -37,7 +37,8 @@ B B [B<-password arg>] [B<-passin arg>] [B<-passout arg>] -[B<-rand file(s)>] +[B<-rand file...>] +[B<-writerand file>] [B<-CAfile file>] [B<-CApath dir>] [B<-no-CAfile>] @@ -76,13 +77,13 @@ default. They are all written in PEM format. =item B<-passin arg> -the PKCS#12 file (i.e. input file) password source. For more information about +The PKCS#12 file (i.e. input file) password source. For more information about the format of B see the B section in L. =item B<-passout arg> -pass phrase source to encrypt any outputted private keys with. For more +Pass phrase source to encrypt any outputted private keys with. For more information about the format of B see the B section in L. @@ -93,61 +94,65 @@ Otherwise, -password is equivalent to -passin. =item B<-noout> -this option inhibits output of the keys and certificates to the output file +This option inhibits output of the keys and certificates to the output file version of the PKCS#12 file. =item B<-clcerts> -only output client certificates (not CA certificates). +Only output client certificates (not CA certificates). =item B<-cacerts> -only output CA certificates (not client certificates). +Only output CA certificates (not client certificates). =item B<-nocerts> -no certificates at all will be output. +No certificates at all will be output. =item B<-nokeys> -no private keys will be output. +No private keys will be output. =item B<-info> -output additional information about the PKCS#12 file structure, algorithms used and -iteration counts. +Output additional information about the PKCS#12 file structure, algorithms +used and iteration counts. =item B<-des> -use DES to encrypt private keys before outputting. +Use DES to encrypt private keys before outputting. =item B<-des3> -use triple DES to encrypt private keys before outputting, this is the default. +Use triple DES to encrypt private keys before outputting, this is the default. =item B<-idea> -use IDEA to encrypt private keys before outputting. +Use IDEA to encrypt private keys before outputting. =item B<-aes128>, B<-aes192>, B<-aes256> -use AES to encrypt private keys before outputting. +Use AES to encrypt private keys before outputting. + +=item B<-aria128>, B<-aria192>, B<-aria256> + +Use ARIA to encrypt private keys before outputting. =item B<-camellia128>, B<-camellia192>, B<-camellia256> -use Camellia to encrypt private keys before outputting. +Use Camellia to encrypt private keys before outputting. =item B<-nodes> -don't encrypt the private keys at all. +Don't encrypt the private keys at all. =item B<-nomacver> -don't attempt to verify the integrity MAC before reading the file. +Don't attempt to verify the integrity MAC before reading the file. =item B<-twopass> -prompt for separate integrity and encryption passwords: most software +Prompt for separate integrity and encryption passwords: most software always assumes these are the same so this option will render such PKCS#12 files unreadable. @@ -176,7 +181,7 @@ certificates are present they will also be included in the PKCS#12 file. =item B<-inkey file_or_id> -file to read private key from. If not present then a private key must be present +File to read private key from. If not present then a private key must be present in the input file. If no engine is used, the argument is taken as a file; if an engine is specified, the argument is given to the engine as a key identifier. @@ -199,31 +204,31 @@ displays them. =item B<-pass arg>, B<-passout arg> -the PKCS#12 file (i.e. output file) password source. For more information about +The PKCS#12 file (i.e. output file) password source. For more information about the format of B see the B section in L. =item B<-passin password> -pass phrase source to decrypt any input private keys with. For more information +Pass phrase source to decrypt any input private keys with. For more information about the format of B see the B section in L. =item B<-chain> -if this option is present then an attempt is made to include the entire +If this option is present then an attempt is made to include the entire certificate chain of the user certificate. The standard CA store is used for this search. If the search fails it is considered a fatal error. =item B<-descert> -encrypt the certificate using triple DES, this may render the PKCS#12 +Encrypt the certificate using triple DES, this may render the PKCS#12 file unreadable by some "export grade" software. By default the private key is encrypted using triple DES and the certificate using 40 bit RC2. =item B<-keypbe alg>, B<-certpbe alg> -these options allow the algorithm used to encrypt the private key and +These options allow the algorithm used to encrypt the private key and certificates to be selected. Any PKCS#5 v1.5 or PKCS#12 PBE algorithm name can be used (see B section for more information). If a cipher name (as output by the B command is specified then it @@ -232,7 +237,7 @@ use PKCS#12 algorithms. =item B<-keyex|-keysig> -specifies that the private key is to be used for key exchange or just signing. +Specifies that the private key is to be used for key exchange or just signing. This option is only interpreted by MSIE and similar MS software. Normally "export grade" software will only allow 512 bit RSA keys to be used for encryption purposes but arbitrary length keys for signing. The B<-keysig> @@ -243,11 +248,11 @@ the use of signing only keys for SSL client authentication. =item B<-macalg digest> -specify the MAC digest algorithm. If not included them SHA1 will be used. +Specify the MAC digest algorithm. If not included them SHA1 will be used. =item B<-nomaciter>, B<-noiter> -these options affect the iteration counts on the MAC and key algorithms. +These options affect the iteration counts on the MAC and key algorithms. Unless you wish to produce files compatible with MSIE 4.0 you should leave these options alone. @@ -270,16 +275,21 @@ to be needed to use MAC iterations counts but they are now used by default. =item B<-nomac> -don't attempt to provide the MAC integrity. +Don't attempt to provide the MAC integrity. -=item B<-rand file(s)> +=item B<-rand file...> -a file or files containing random data used to seed the random number -generator, or an EGD socket (see L). +A file or files containing random data used to seed the random number +generator. Multiple files can be specified separated by an OS-dependent character. The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for all others. +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =item B<-CAfile file> CA storage as a file. @@ -292,15 +302,15 @@ linked to each certificate. =item B<-no-CAfile> -Do not load the trusted CA certificates from the default file location +Do not load the trusted CA certificates from the default file location. =item B<-no-CApath> -Do not load the trusted CA certificates from the default directory location +Do not load the trusted CA certificates from the default directory location. =item B<-CSP name> -write B as a Microsoft CSP name. +Write B as a Microsoft CSP name. =back @@ -371,7 +381,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/pkcs7.pod b/doc/man1/pkcs7.pod similarity index 83% rename from doc/apps/pkcs7.pod rename to doc/man1/pkcs7.pod index 340b72da..cf445b3d 100644 --- a/doc/apps/pkcs7.pod +++ b/doc/man1/pkcs7.pod @@ -38,8 +38,8 @@ the DER form with 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. +This specifies the output format, the options have the same meaning and default +as the B<-inform> option. =item B<-in filename> @@ -48,27 +48,27 @@ option is not specified. =item B<-out filename> -specifies the output filename to write to or standard output by +Specifies the output filename to write to or standard output by default. =item B<-print_certs> -prints out any certificates or CRLs contained in the file. They are +Prints out any certificates or CRLs contained in the file. They are preceded by their subject and issuer names in one line format. =item B<-text> -prints out certificates details in full rather than just subject and +Prints out certificates details in full rather than just subject and issuer names. =item B<-noout> -don't output the encoded version of the PKCS#7 structure (or certificates +Don't output the encoded version of the PKCS#7 structure (or certificates is B<-print_certs> is set). =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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. @@ -110,7 +110,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/pkcs8.pod b/doc/man1/pkcs8.pod similarity index 90% rename from doc/apps/pkcs8.pod rename to doc/man1/pkcs8.pod index 402e7b2b..84a10e88 100644 --- a/doc/apps/pkcs8.pod +++ b/doc/man1/pkcs8.pod @@ -18,6 +18,8 @@ B B [B<-passout arg>] [B<-iter count>] [B<-noiter>] +[B<-rand file...>] +[B<-writerand file>] [B<-nocrypt>] [B<-traditional>] [B<-v2 alg>] @@ -51,11 +53,13 @@ reversed: it reads a private key and writes a PKCS#8 format key. =item B<-inform DER|PEM> -This specifies the input format: see L for more details. +This specifies the input format: see L for more details. The default +format is PEM. =item B<-outform DER|PEM> -This specifies the output format: see L for more details. +This specifies the output format: see L for more details. The default +format is PEM. =item B<-traditional> @@ -70,7 +74,7 @@ prompted for. =item B<-passin arg> -the input file password source. For more information about the format of B +The input file password source. For more information about the format of B see the B section in L. =item B<-out filename> @@ -82,7 +86,7 @@ filename. =item B<-passout arg> -the output file password source. For more information about the format of B +The output file password source. For more information about the format of B see the B section in L. =item B<-iter count> @@ -100,6 +104,19 @@ This option does not encrypt private keys at all and should only be used when absolutely necessary. Certain software such as some versions of Java code signing software used unencrypted private keys. +=item B<-rand file...> + +A file or files containing random data used to seed the random number +generator. +Multiple files can be specified separated by an OS-dependent character. +The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for +all others. + +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =item B<-v2 alg> This option sets the PKCS#5 v2.0 algorithm. @@ -125,21 +142,21 @@ If not specified PKCS#5 v2.0 form is used. =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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<-scrypt> -uses the B algorithm for private key encryption using default +Uses the B algorithm for private key encryption using default parameters: currently N=16384, r=8 and p=1 and AES in CBC mode with a 256 bit key. These parameters can be modified using the B<-scrypt_N>, B<-scrypt_r>, B<-scrypt_p> and B<-v2> options. -B<-scrypt_N N> B<-scrypt_r r> B<-scrypt_p p> +=item B<-scrypt_N N> B<-scrypt_r r> B<-scrypt_p p> -sets the scrypt B, B or B

parameters. +Sets the scrypt B, B or B

parameters. =back @@ -292,7 +309,7 @@ The B<-iter> option was added to OpenSSL 1.1.0. =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/apps/pkey.pod b/doc/man1/pkey.pod similarity index 75% rename from doc/apps/pkey.pod rename to doc/man1/pkey.pod index ef2e4633..9569fe0e 100644 --- a/doc/apps/pkey.pod +++ b/doc/man1/pkey.pod @@ -16,13 +16,15 @@ B B [B<-out filename>] [B<-passout arg>] [B<-traditional>] -[B<-cipher>] +[B<-I>] [B<-text>] [B<-text_pub>] [B<-noout>] [B<-pubin>] [B<-pubout>] [B<-engine id>] +[B<-check>] +[B<-pubcheck>] =head1 DESCRIPTION @@ -39,12 +41,12 @@ Print out a usage message. =item B<-inform DER|PEM> -This specifies the input format DER or PEM. +This specifies the input format DER or PEM. The default format is PEM. =item B<-outform DER|PEM> -This specifies the output format, the options have the same meaning as the -B<-inform> option. +This specifies the output format, the options have the same meaning and default +as the B<-inform> option. =item B<-in filename> @@ -54,7 +56,7 @@ prompted for. =item B<-passin arg> -the input file password source. For more information about the format of B +The input file password source. For more information about the format of B see the B section in L. =item B<-out filename> @@ -66,51 +68,61 @@ filename. =item B<-passout password> -the output file password source. For more information about the format of B +The output file password source. For more information about the format of B see the B section in L. =item B<-traditional> -normally a private key is written using standard format: this is PKCS#8 form +Normally a private key is written using standard format: this is PKCS#8 form with the appropriate encryption algorithm (if any). If the B<-traditional> option is specified then the older "traditional" format is used instead. -=item B<-cipher> +=item B<-I> These options encrypt the private key with the supplied cipher. Any algorithm name accepted by EVP_get_cipherbyname() is acceptable such as B. =item B<-text> -prints out the various public or private key components in +Prints out the various public or private key components in plain text in addition to the encoded version. =item B<-text_pub> -print out only public key components even if a private key is being processed. +Print out only public key components even if a private key is being processed. =item B<-noout> -do not output the encoded version of the key. +Do not output the encoded version of the key. =item B<-pubin> -by default a private key is read from the input file: with this +By default a private key is read from the input file: with this option a public key is read instead. =item B<-pubout> -by default a private key is output: with this option a public +By default a private key is output: with this option a public key will be output instead. This option is automatically set if the input is a public key. =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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<-check> + +This option checks the consistency of a key pair for both public and private +components. + +=item B<-pubcheck> + +This option checks the correctness of either a public key or the public component +of a key pair. + =back =head1 EXAMPLES @@ -146,7 +158,7 @@ L, L, L =head1 COPYRIGHT -Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2006-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 diff --git a/doc/apps/pkeyparam.pod b/doc/man1/pkeyparam.pod similarity index 76% rename from doc/apps/pkeyparam.pod rename to doc/man1/pkeyparam.pod index 309e2495..50949657 100644 --- a/doc/apps/pkeyparam.pod +++ b/doc/man1/pkeyparam.pod @@ -14,11 +14,12 @@ B B [B<-text>] [B<-noout>] [B<-engine id>] +[B<-check>] =head1 DESCRIPTION -The B command processes public or private keys. They can be converted -between various forms and their components printed out. +The B command processes public key algorithm parameters. +They can be checked for correctness and their components printed out. =head1 OPTIONS @@ -40,19 +41,23 @@ this option is not specified. =item B<-text> -prints out the parameters in plain text in addition to the encoded version. +Prints out the parameters in plain text in addition to the encoded version. =item B<-noout> -do not output the encoded version of the parameters. +Do not output the encoded version of the parameters. =item B<-engine id> -specifying an engine (by its unique B string) will cause B +Specifying an engine (by its unique B string) will cause B 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<-check> + +This option checks the correctness of parameters. + =back =head1 EXAMPLE @@ -73,7 +78,7 @@ L, L, L =head1 COPYRIGHT -Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2006-2018 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 diff --git a/doc/man1/pkeyutl.pod b/doc/man1/pkeyutl.pod new file mode 100644 index 00000000..4c12f13b --- /dev/null +++ b/doc/man1/pkeyutl.pod @@ -0,0 +1,333 @@ +=pod + +=head1 NAME + +openssl-pkeyutl, +pkeyutl - public key algorithm utility + +=head1 SYNOPSIS + +B B +[B<-help>] +[B<-in file>] +[B<-out file>] +[B<-sigfile file>] +[B<-inkey file>] +[B<-keyform PEM|DER|ENGINE>] +[B<-passin arg>] +[B<-peerkey file>] +[B<-peerform PEM|DER|ENGINE>] +[B<-pubin>] +[B<-certin>] +[B<-rev>] +[B<-sign>] +[B<-verify>] +[B<-verifyrecover>] +[B<-encrypt>] +[B<-decrypt>] +[B<-derive>] +[B<-kdf algorithm>] +[B<-kdflen length>] +[B<-pkeyopt opt:value>] +[B<-hexdump>] +[B<-asn1parse>] +[B<-rand file...>] +[B<-writerand file>] +[B<-engine id>] +[B<-engine_impl>] + +=head1 DESCRIPTION + +The B command can be used to perform public key operations using +any supported algorithm. + +=head1 OPTIONS + +=over 4 + +=item B<-help> + +Print out a usage message. + +=item B<-in filename> + +This specifies the input filename to read data from or standard input +if this option is not specified. + +=item B<-out filename> + +Specifies the output filename to write to or standard output by +default. + +=item B<-sigfile file> + +Signature file, required for B operations only + +=item B<-inkey file> + +The input key file, by default it should be a private key. + +=item B<-keyform PEM|DER|ENGINE> + +The key format PEM, DER or ENGINE. Default is PEM. + +=item B<-passin arg> + +The input key password source. For more information about the format of B +see the B section in L. + +=item B<-peerkey file> + +The peer key file, used by key derivation (agreement) operations. + +=item B<-peerform PEM|DER|ENGINE> + +The peer key format PEM, DER or ENGINE. Default is PEM. + +=item B<-pubin> + +The input file is a public key. + +=item B<-certin> + +The input is a certificate containing a public key. + +=item B<-rev> + +Reverse the order of the input buffer. This is useful for some libraries +(such as CryptoAPI) which represent the buffer in little endian format. + +=item B<-sign> + +Sign the input data and output the signed result. This requires +a private key. + +=item B<-verify> + +Verify the input data against the signature file and indicate if the +verification succeeded or failed. + +=item B<-verifyrecover> + +Verify the input data and output the recovered data. + +=item B<-encrypt> + +Encrypt the input data using a public key. + +=item B<-decrypt> + +Decrypt the input data using a private key. + +=item B<-derive> + +Derive a shared secret using the peer key. + +=item B<-kdf algorithm> + +Use key derivation function B. The supported algorithms are +at present B and B. +Note: additional parameters and the KDF output length will normally have to be +set for this to work. +See L and L +for the supported string parameters of each algorithm. + +=item B<-kdflen length> + +Set the output length for KDF. + +=item B<-pkeyopt opt:value> + +Public key options specified as opt:value. See NOTES below for more details. + +=item B<-hexdump> + +hex dump the output data. + +=item B<-asn1parse> + +Parse the ASN.1 output data, this is useful when combined with the +B<-verifyrecover> option when an ASN1 structure is signed. + +=item B<-rand file...> + +A file or files containing random data used to seed the random number +generator. +Multiple files can be specified separated by an OS-dependent character. +The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for +all others. + +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + +=item B<-engine id> + +Specifying an engine (by its unique B string) will cause B +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<-engine_impl> + +When used with the B<-engine> option, it specifies to also use +engine B for crypto operations. + +=back + +=head1 NOTES + +The operations and options supported vary according to the key algorithm +and its implementation. The OpenSSL operations and options are indicated below. + +Unless otherwise mentioned all algorithms support the B option +which specifies the digest in use for sign, verify and verifyrecover operations. +The value B should represent a digest name as used in the +EVP_get_digestbyname() function for example B. +This value is used only for sanity-checking the lengths of data passed in to +the B and for creating the structures that make up the signature +(e.g. B in RSASSA PKCS#1 v1.5 signatures). +In case of RSA, ECDSA and DSA signatures, this utility +will not perform hashing on input data but rather use the data directly as +input of signature algorithm. Depending on key type, signature type and mode +of padding, the maximum acceptable lengths of input data differ. In general, +with RSA the signed data can't be longer than the key modulus, in case of ECDSA +and DSA the data shouldn't be longer than field size, otherwise it will be +silently truncated to field size. + +In other words, if the value of digest is B the input should be 20 bytes +long binary encoding of SHA-1 hash function output. + +=head1 RSA ALGORITHM + +The RSA algorithm generally supports the encrypt, decrypt, sign, +verify and verifyrecover operations. However, some padding modes +support only a subset of these operations. The following additional +B values are supported: + +=over 4 + +=item B + +This sets the RSA padding mode. Acceptable values for B are B for +PKCS#1 padding, B for SSLv23 padding, B for no padding, B +for B mode, B for X9.31 mode and B for PSS. + +In PKCS#1 padding if the message digest is not set then the supplied data is +signed or verified directly instead of using a B structure. If a +digest is set then the a B structure is used and its the length +must correspond to the digest type. + +For B mode only encryption and decryption is supported. + +For B if the digest type is set it is used to format the block data +otherwise the first byte is used to specify the X9.31 digest ID. Sign, +verify and verifyrecover are can be performed in this mode. + +For B mode only sign and verify are supported and the digest type must be +specified. + +=item B + +For B mode only this option specifies the salt length. Three special +values are supported: "digest" sets the salt length to the digest length, +"max" sets the salt length to the maximum permissible value. When verifying +"auto" causes the salt length to be automatically determined based on the +B block structure. + +=item B + +For PSS and OAEP padding sets the MGF1 digest. If the MGF1 digest is not +explicitly set in PSS mode then the signing digest is used. + +=back + +=head1 RSA-PSS ALGORITHM + +The RSA-PSS algorithm is a restricted version of the RSA algorithm which only +supports the sign and verify operations with PSS padding. The following +additional B values are supported: + +=over 4 + +=item B, B, B + +These have the same meaning as the B algorithm with some additional +restrictions. The padding mode can only be set to B which is the +default value. + +If the key has parameter restrictions than the digest, MGF1 +digest and salt length are set to the values specified in the parameters. +The digest and MG cannot be changed and the salt length cannot be set to a +value less than the minimum restriction. + +=back + +=head1 DSA ALGORITHM + +The DSA algorithm supports signing and verification operations only. Currently +there are no additional options other than B. Only the SHA1 +digest can be used and this digest is assumed by default. + +=head1 DH ALGORITHM + +The DH algorithm only supports the derivation operation and no additional +options. + +=head1 EC ALGORITHM + +The EC algorithm supports sign, verify and derive operations. The sign and +verify operations use ECDSA and derive uses ECDH. Currently there are no +additional options other than B. Only the SHA1 digest can be used and +this digest is assumed by default. + +=head1 X25519 ALGORITHM + +The X25519 algorithm supports key derivation only. Currently there are no +additional options. + +=head1 EXAMPLES + +Sign some data using a private key: + + openssl pkeyutl -sign -in file -inkey key.pem -out sig + +Recover the signed data (e.g. if an RSA key is used): + + openssl pkeyutl -verifyrecover -in sig -inkey key.pem + +Verify the signature (e.g. a DSA key): + + openssl pkeyutl -verify -in file -sigfile sig -inkey key.pem + +Sign data using a message digest value (this is currently only valid for RSA): + + openssl pkeyutl -sign -in file -inkey key.pem -out sig -pkeyopt digest:sha256 + +Derive a shared secret value: + + openssl pkeyutl -derive -inkey key.pem -peerkey pubkey.pem -out secret + +Hexdump 48 bytes of TLS1 PRF using digest B and shared secret and +seed consisting of the single byte 0xFF: + + openssl pkeyutl -kdf TLS1-PRF -kdflen 48 -pkeyopt md:SHA256 \ + -pkeyopt hexsecret:ff -pkeyopt hexseed:ff -hexdump + +=head1 SEE ALSO + +L, L, L +L, L, L, +L, L + +=head1 COPYRIGHT + +Copyright 2006-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 +L. + +=cut diff --git a/doc/man1/prime.pod b/doc/man1/prime.pod new file mode 100644 index 00000000..1d25954a --- /dev/null +++ b/doc/man1/prime.pod @@ -0,0 +1,68 @@ +=pod + +=head1 NAME + +openssl-prime, +prime - compute prime numbers + +=head1 SYNOPSIS + +B +[B<-help>] +[B<-hex>] +[B<-generate>] +[B<-bits>] +[B<-safe>] +[B<-checks>] +[I] + +=head1 DESCRIPTION + +The B command checks if the specified numbers are prime. + +If no numbers are given on the command line, the B<-generate> flag should +be used to generate primes according to the requirements specified by the +rest of the flags. + +=head1 OPTIONS + +=over 4 + +=item [B<-help>] + +Display an option summary. + +=item [B<-hex>] + +Generate hex output. + +=item [B<-generate>] + +Generate a prime number. + +=item [B<-bits num>] + +Generate a prime with B bits. + +=item [B<-safe>] + +When used with B<-generate>, generates a "safe" prime. If the number +generated is B, then check that B<(n-1)/2> is also prime. + +=item [B<-checks num>] + +Perform the checks B times to see that the generated number +is prime. The default is 20. + +=back + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/apps/rand.pod b/doc/man1/rand.pod similarity index 81% rename from doc/apps/rand.pod rename to doc/man1/rand.pod index 4cdb3705..5dd9e8e0 100644 --- a/doc/apps/rand.pod +++ b/doc/man1/rand.pod @@ -10,7 +10,8 @@ rand - generate pseudo-random bytes B [B<-help>] [B<-out> I] -[B<-rand> I] +[B<-rand file...>] +[B<-writerand file>] [B<-base64>] [B<-hex>] I @@ -32,18 +33,23 @@ seeding was obtained from these sources. Print out a usage message. -=item B<-out> I +=item B<-out file> Write to I instead of standard output. -=item B<-rand> I +=item B<-rand file...> -Use specified file or files or EGD socket (see L) -for seeding the random number generator. +A file or files containing random data used to seed the random number +generator. Multiple files can be specified separated by an OS-dependent character. The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for all others. +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =item B<-base64> Perform base64 encoding on the output. diff --git a/doc/apps/rehash.pod b/doc/man1/rehash.pod similarity index 100% rename from doc/apps/rehash.pod rename to doc/man1/rehash.pod diff --git a/doc/apps/req.pod b/doc/man1/req.pod similarity index 83% rename from doc/apps/req.pod rename to doc/man1/req.pod index c5b5260c..db467bba 100644 --- a/doc/apps/req.pod +++ b/doc/man1/req.pod @@ -21,7 +21,8 @@ B B [B<-verify>] [B<-modulus>] [B<-new>] -[B<-rand file(s)>] +[B<-rand file...>] +[B<-writerand file>] [B<-newkey rsa:bits>] [B<-newkey alg:file>] [B<-nodes>] @@ -29,15 +30,17 @@ B B [B<-keyform PEM|DER>] [B<-keyout filename>] [B<-keygen_engine id>] -[B<-[digest]>] +[B<-I>] [B<-config filename>] [B<-multivalue-rdn>] [B<-x509>] [B<-days n>] [B<-set_serial n>] [B<-newhdr>] +[B<-addext ext>] [B<-extensions section>] [B<-reqexts section>] +[B<-precert>] [B<-utf8>] [B<-nameopt>] [B<-reqopt>] @@ -70,8 +73,8 @@ footer lines. =item B<-outform DER|PEM> -This specifies the output format, the options have the same meaning as the -B<-inform> option. +This specifies the output format, the options have the same meaning and default +as the B<-inform> option. =item B<-in filename> @@ -81,7 +84,7 @@ options (B<-new> and B<-newkey>) are not specified. =item B<-passin arg> -the input file password source. For more information about the format of B +The input file password source. For more information about the format of B see the B section in L. =item B<-out filename> @@ -91,38 +94,38 @@ default. =item B<-passout arg> -the output file password source. For more information about the format of B +The output file password source. For more information about the format of B see the B section in L. =item B<-text> -prints out the certificate request in text form. +Prints out the certificate request in text form. =item B<-subject> -prints out the request subject (or certificate subject if B<-x509> is +Prints out the request subject (or certificate subject if B<-x509> is specified) =item B<-pubkey> -outputs the public key. +Outputs the public key. =item B<-noout> -this option prevents output of the encoded version of the request. +This option prevents output of the encoded version of the request. =item B<-modulus> -this option prints out the value of the modulus of the public key +This option prints out the value of the modulus of the public key contained in the request. =item B<-verify> -verifies the signature on the request. +Verifies the signature on the request. =item B<-new> -this option generates a new certificate request. It will prompt +This option generates a new certificate request. It will prompt the user for the relevant field values. The actual fields prompted for and their maximum and minimum sizes are specified in the configuration file and any requested extensions. @@ -130,17 +133,22 @@ in the configuration file and any requested extensions. If the B<-key> option is not used it will generate a new RSA private key using information specified in the configuration file. -=item B<-rand file(s)> +=item B<-rand file...> -a file or files containing random data used to seed the random number -generator, or an EGD socket (see L). +A file or files containing random data used to seed the random number +generator. Multiple files can be specified separated by an OS-dependent character. The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for all others. +=item [B<-writerand file>] + +Writes random data to the specified I upon exit. +This can be used with a subsequent B<-rand> flag. + =item B<-newkey arg> -this option creates a new certificate request and a new private +This option creates a new certificate request and a new private key. The argument takes one of several forms. B, where B is the number of bits, generates an RSA key B in size. If B is omitted, i.e. B<-newkey rsa> specified, @@ -166,7 +174,7 @@ specified by B<-pkeyopt paramset:X> =item B<-pkeyopt opt:value> -set the public key algorithm option B to B. The precise set of +Set the public key algorithm option B to B. The precise set of options supported depends on the public key algorithm used and its implementation. See B in the B manual page for more details. @@ -178,23 +186,23 @@ accepts PKCS#8 format private keys for PEM format files. =item B<-keyform PEM|DER> -the format of the private key file specified in the B<-key> +The format of the private key file specified in the B<-key> argument. PEM is the default. =item B<-keyout filename> -this gives the filename to write the newly created private key to. +This gives the filename to write the newly created private key to. If this option is not specified then the filename present in the configuration file is used. =item B<-nodes> -if this option is specified then if a private key is created it +If this option is specified then if a private key is created it will not be encrypted. -=item B<-[digest]> +=item B<-I> -this specifies the message digest to sign the request. +This specifies the message digest to sign the request. Any digest supported by the OpenSSL B command can be used. This overrides the digest algorithm specified in the configuration file. @@ -205,20 +213,20 @@ GOST R 34.11-94 (B<-md_gost94>). =item B<-config filename> -this allows an alternative configuration file to be specified. +This allows an alternative configuration file to be specified. Optional; for a description of the default value, see L. =item B<-subj arg> -sets subject name for new request or supersedes the subject name +Sets subject name for new request or supersedes the subject name when processing a request. The arg must be formatted as I, characters may be escaped by \ (backslash), no spaces are skipped. =item B<-multivalue-rdn> -this option causes the -subj argument to be interpreted with full +This option causes the -subj argument to be interpreted with full support for multivalued RDNs. Example: I @@ -227,7 +235,7 @@ If -multi-rdn is not used then the UID value is I<123456+CN=John Doe>. =item B<-x509> -this option outputs a self signed certificate instead of a certificate +This option outputs a self signed certificate instead of a certificate request. This is typically used to generate a test certificate or a self signed root CA. The extensions added to the certificate (if any) are specified in the configuration file. Unless specified @@ -239,41 +247,60 @@ to the self signed certificate otherwise new request is created. =item B<-days n> -when the B<-x509> option is being used this specifies the number of -days to certify the certificate for. The default is 30 days. +When the B<-x509> option is being used this specifies the number of +days to certify the certificate for, otherwise it is ignored. B should +be a positive integer. The default is 30 days. =item B<-set_serial n> -serial number to use when outputting a self signed certificate. This +Serial number to use when outputting a self signed certificate. This may be specified as a decimal value or a hex value if preceded by B<0x>. +=item B<-addext ext> + +Add a specific extension to the certificate (if the B<-x509> option is +present) or certificate request. The argument must have the form of +a key=value pair as it would appear in a config file. + +This option can be given multiple times. + =item B<-extensions section> =item B<-reqexts section> -these options specify alternative sections to include certificate +These options specify alternative sections to include certificate extensions (if the B<-x509> option is present) or certificate request extensions. This allows several different sections to be used in the same configuration file to specify requests for a variety of purposes. +=item B<-precert> + +A poison extension will be added to the certificate, making it a +"pre-certificate" (see RFC6962). This can be submitted to Certificate +Transparency logs in order to obtain signed certificate timestamps (SCTs). +These SCTs can then be embedded into the pre-certificate as an extension, before +removing the poison and signing the certificate. + +This implies the B<-new> flag. + =item B<-utf8> -this option causes field values to be interpreted as UTF8 strings, by +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<-nameopt option> -option which determines how the subject or issuer names are displayed. The +Option which determines how the subject or issuer names are displayed. The B

+ +Send some plain text down the underlying TCP connection: this should +cause the client to disconnect due to a protocol violation. + +=item B + +Print out some session cache status information. + +=back + +=head1 NOTES + +B can be used to debug SSL clients. To accept connections from +a web browser the command: + + openssl s_server -accept 443 -www + +can be used for example. + +Although specifying an empty list of CAs when requesting a client certificate +is strictly speaking a protocol violation, some SSL clients interpret this to +mean any CA is acceptable. This is useful for debugging purposes. + +The session parameters can printed out using the B program. + +=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 B is rather hard to +read and not a model of how things should be done. +A typical SSL server program would be much simpler. + +The output of common ciphers is wrong: it just gives the list of ciphers that +OpenSSL recognizes and the client supports. + +There should be a way for the B program to print out details of any +unknown cipher suites a client says it supports. + +=head1 SEE ALSO + +L, L, L, L +L, L +L + +=head1 HISTORY + +The -no_alt_chains option was first added to OpenSSL 1.1.0. + +The -allow-no-dhe-kex and -prioritize_chacha options were first added to +OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2000-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 +L. + +=cut diff --git a/doc/apps/s_time.pod b/doc/man1/s_time.pod similarity index 87% rename from doc/apps/s_time.pod rename to doc/man1/s_time.pod index d44dd935..ecdac17c 100644 --- a/doc/apps/s_time.pod +++ b/doc/man1/s_time.pod @@ -14,13 +14,13 @@ B B [B<-cert filename>] [B<-key filename>] [B<-CApath directory>] -[B<-CAfile filename>] +[B<-cafile filename>] [B<-no-CAfile>] [B<-no-CApath>] [B<-reuse>] [B<-new>] [B<-verify depth>] -[B<-nbio>] +[B<-nameopt option>] [B<-time seconds>] [B<-ssl3>] [B<-bugs>] @@ -71,6 +71,13 @@ 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<-nameopt option> + +Option which determines how the subject or issuer names are displayed. The +B

and B are likely enough to +be valid. +This is a lightweight check, if a more thorough check is needed, use +DH_check(). +The value of B<*codes> is updated with any problems found. +If B<*codes> is zero then no problems were found, otherwise the +following bits may be set: + +=over 4 + +=item DH_CHECK_P_NOT_PRIME + +The parameter B

has been determined to not being an odd prime. +Note that the lack of this bit doesn't guarantee that B

is a +prime. + +=item DH_NOT_SUITABLE_GENERATOR + +The generator B is not suitable. +Note that the lack of this bit doesn't guarantee that B is +suitable, unless B

is known to be a strong prime. + +=back + +DH_check() confirms that the Diffie-Hellman parameters B are valid. The +value of B<*codes> is updated with any problems found. If B<*codes> is zero then +no problems were found, otherwise the following bits may be set: + +=over 4 + +=item DH_CHECK_P_NOT_PRIME + +The parameter B

is not prime. + +=item DH_CHECK_P_NOT_SAFE_PRIME + +The parameter B

is not a safe prime and no B value is present. + +=item DH_UNABLE_TO_CHECK_GENERATOR + +The generator B cannot be checked for suitability. + +=item DH_NOT_SUITABLE_GENERATOR + +The generator B is not suitable. + +=item DH_CHECK_Q_NOT_PRIME + +The parameter B is not prime. + +=item DH_CHECK_INVALID_Q_VALUE + +The parameter B is invalid. + +=item DH_CHECK_INVALID_J_VALUE + +The parameter B is invalid. + +=back + +DH_check_ex(), DH_check_params() and DH_check_pub_key_ex() are similiar with +DH_check() and DH_check_params() respectively, but the error reasons are set +to the OpenSSL error handling framework instead of returning by the function +parameters. + +=head1 RETURN VALUES + +DH_generate_parameters_ex(), DH_check() and DH_check_params() return 1 +if the check could be performed, 0 otherwise. + +DH_generate_parameters() returns a pointer to the DH structure or NULL if +the parameter generation fails. + +DH_check_ex(), DH_check_params() and DH_check_pub_key_ex() return 1 if the +check is successful, 0 for failed. + +The error codes can be obtained by L. + +=head1 SEE ALSO + +L, L, L, +L + +=head1 HISTORY + +DH_generate_parameters() was deprecated in OpenSSL 0.9.8; use +DH_generate_parameters_ex() instead. + +=head1 COPYRIGHT + +Copyright 2000-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 +L. + +=cut diff --git a/doc/crypto/DH_get0_pqg.pod b/doc/man3/DH_get0_pqg.pod similarity index 98% rename from doc/crypto/DH_get0_pqg.pod rename to doc/man3/DH_get0_pqg.pod index 38098135..ec476a7d 100644 --- a/doc/crypto/DH_get0_pqg.pod +++ b/doc/man3/DH_get0_pqg.pod @@ -91,7 +91,7 @@ or zero if no such length has been explicitly set. =head1 SEE ALSO -L, L, L, L, +L, L, L, L, L, L, L =head1 HISTORY diff --git a/doc/crypto/DH_get_1024_160.pod b/doc/man3/DH_get_1024_160.pod similarity index 100% rename from doc/crypto/DH_get_1024_160.pod rename to doc/man3/DH_get_1024_160.pod diff --git a/doc/crypto/DH_meth_new.pod b/doc/man3/DH_meth_new.pod similarity index 88% rename from doc/crypto/DH_meth_new.pod rename to doc/man3/DH_meth_new.pod index d768da8c..708f389f 100644 --- a/doc/crypto/DH_meth_new.pod +++ b/doc/man3/DH_meth_new.pod @@ -15,40 +15,51 @@ DH_meth_set_generate_params - Routines to build up DH methods #include DH_METHOD *DH_meth_new(const char *name, int flags); + void DH_meth_free(DH_METHOD *dhm); + DH_METHOD *DH_meth_dup(const DH_METHOD *dhm); + const char *DH_meth_get0_name(const DH_METHOD *dhm); int DH_meth_set1_name(DH_METHOD *dhm, const char *name); + int DH_meth_get_flags(DH_METHOD *dhm); int DH_meth_set_flags(DH_METHOD *dhm, int flags); + void *DH_meth_get0_app_data(const DH_METHOD *dhm); int DH_meth_set0_app_data(DH_METHOD *dhm, void *app_data); - int (*DH_meth_get_generate_key(const DH_METHOD *dhm)) (DH *); - int DH_meth_set_generate_key(DH_METHOD *dhm, int (*generate_key) (DH *)); + + int (*DH_meth_get_generate_key(const DH_METHOD *dhm))(DH *); + int DH_meth_set_generate_key(DH_METHOD *dhm, int (*generate_key)(DH *)); + int (*DH_meth_get_compute_key(const DH_METHOD *dhm)) - (unsigned char *key, const BIGNUM *pub_key, DH *dh); + (unsigned char *key, const BIGNUM *pub_key, DH *dh); int DH_meth_set_compute_key(DH_METHOD *dhm, - int (*compute_key) (unsigned char *key, const BIGNUM *pub_key, DH *dh)); + int (*compute_key)(unsigned char *key, const BIGNUM *pub_key, DH *dh)); + int (*DH_meth_get_bn_mod_exp(const DH_METHOD *dhm)) (const DH *dh, BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); int DH_meth_set_bn_mod_exp(DH_METHOD *dhm, - int (*bn_mod_exp) (const DH *dh, BIGNUM *r, const BIGNUM *a, - const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, - BN_MONT_CTX *m_ctx)); + int (*bn_mod_exp)(const DH *dh, BIGNUM *r, const BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *m_ctx)); + int (*DH_meth_get_init(const DH_METHOD *dhm))(DH *); int DH_meth_set_init(DH_METHOD *dhm, int (*init)(DH *)); - int (*DH_meth_get_finish(const DH_METHOD *dhm)) (DH *); - int DH_meth_set_finish(DH_METHOD *dhm, int (*finish) (DH *)); + + int (*DH_meth_get_finish(const DH_METHOD *dhm))(DH *); + int DH_meth_set_finish(DH_METHOD *dhm, int (*finish)(DH *)); + int (*DH_meth_get_generate_params(const DH_METHOD *dhm)) - (DH *, int, int, BN_GENCB *); + (DH *, int, int, BN_GENCB *); int DH_meth_set_generate_params(DH_METHOD *dhm, - int (*generate_params) (DH *, int, int, BN_GENCB *)); + int (*generate_params)(DH *, int, int, BN_GENCB *)); =head1 DESCRIPTION The B type is a structure used for the provision of custom DH -implementations. It provides a set of of functions used by OpenSSL for the +implementations. It provides a set of functions used by OpenSSL for the implementation of the various DH capabilities. DH_meth_new() creates a new B structure. It should be given a @@ -137,7 +148,7 @@ DH_meth_set1_name() and all DH_meth_set_*() functions return 1 on success or =head1 SEE ALSO -L, L, L, L, +L, L, L, L, L, L, L =head1 HISTORY @@ -146,7 +157,7 @@ The functions described here were added in OpenSSL 1.1.0. =head1 COPYRIGHT -Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2016-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 diff --git a/doc/crypto/DH_new.pod b/doc/man3/DH_new.pod similarity index 96% rename from doc/crypto/DH_new.pod rename to doc/man3/DH_new.pod index 959a470e..7e60c9a5 100644 --- a/doc/crypto/DH_new.pod +++ b/doc/man3/DH_new.pod @@ -30,7 +30,7 @@ DH_free() returns no value. =head1 SEE ALSO -L, L, +L, L, L, L diff --git a/doc/man3/DH_new_by_nid.pod b/doc/man3/DH_new_by_nid.pod new file mode 100644 index 00000000..73636c5d --- /dev/null +++ b/doc/man3/DH_new_by_nid.pod @@ -0,0 +1,39 @@ +=pod + +=head1 NAME + +DH_new_by_nid, DH_get_nid - get or find DH named parameters + +=head1 SYNOPSIS + + #include + DH *DH_new_by_nid(int nid); + int *DH_get_nid(const DH *dh); + +=head1 DESCRIPTION + +DH_new_by_nid() creates and returns a DH structure containing named parameters +B. Currently B must be B, B, +B, B or B. + +DH_get_nid() determines if the parameters contained in B match +any named set. It returns the NID corresponding to the matching parameters or +B if there is no match. + +=head1 RETURN VALUES + +DH_new_by_nid() returns a set of DH parameters or B if an error occurred. + +DH_get_nid() returns the NID of the matching set of parameters or +B if there is no match. + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/crypto/DH_set_method.pod b/doc/man3/DH_set_method.pod similarity index 98% rename from doc/crypto/DH_set_method.pod rename to doc/man3/DH_set_method.pod index 21006086..ea45961f 100644 --- a/doc/crypto/DH_set_method.pod +++ b/doc/man3/DH_set_method.pod @@ -74,7 +74,7 @@ returns a pointer to the newly allocated structure. =head1 SEE ALSO -L, L, L +L, L, L =head1 COPYRIGHT diff --git a/doc/man3/DH_size.pod b/doc/man3/DH_size.pod new file mode 100644 index 00000000..3b65d7ea --- /dev/null +++ b/doc/man3/DH_size.pod @@ -0,0 +1,57 @@ +=pod + +=head1 NAME + +DH_size, DH_bits, DH_security_bits - get Diffie-Hellman prime size and +security bits + +=head1 SYNOPSIS + + #include + + int DH_size(const DH *dh); + + int DH_bits(const DH *dh); + + int DH_security_bits(const DH *dh); + +=head1 DESCRIPTION + +DH_size() returns the Diffie-Hellman prime size in bytes. It can be used +to determine how much memory must be allocated for the shared secret +computed by L. + +DH_bits() returns the number of significant bits. + +B and Bp> must not be B. + +DH_security_bits() returns the number of security bits of the given B +key. See L. + +=head1 RETURN VALUES + +DH_size() returns the prime size of Diffie-Hellman in bytes. + +DH_bits() returns the number of bits in the key. + +DH_security_bits() returns the number of security bits. + +=head1 SEE ALSO + +L, L, +L + +=head1 HISTORY + +DH_bits() was added in OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/crypto/DSA_SIG_new.pod b/doc/man3/DSA_SIG_new.pod similarity index 97% rename from doc/crypto/DSA_SIG_new.pod rename to doc/man3/DSA_SIG_new.pod index 7503460a..92c7bfdf 100644 --- a/doc/crypto/DSA_SIG_new.pod +++ b/doc/man3/DSA_SIG_new.pod @@ -43,7 +43,7 @@ DSA_SIG_set0() returns 1 on success or 0 on failure. =head1 SEE ALSO -L, L, +L, L, L =head1 COPYRIGHT diff --git a/doc/crypto/DSA_do_sign.pod b/doc/man3/DSA_do_sign.pod similarity index 93% rename from doc/crypto/DSA_do_sign.pod rename to doc/man3/DSA_do_sign.pod index 5e56d209..a0dd8bb2 100644 --- a/doc/crypto/DSA_do_sign.pod +++ b/doc/man3/DSA_do_sign.pod @@ -11,7 +11,7 @@ DSA_do_sign, DSA_do_verify - raw DSA signature operations DSA_SIG *DSA_do_sign(const unsigned char *dgst, int dlen, DSA *dsa); int DSA_do_verify(const unsigned char *dgst, int dgst_len, - DSA_SIG *sig, DSA *dsa); + DSA_SIG *sig, DSA *dsa); =head1 DESCRIPTION @@ -36,7 +36,7 @@ L. =head1 SEE ALSO -L, L, L, +L, L, L, L, L diff --git a/doc/crypto/DSA_dup_DH.pod b/doc/man3/DSA_dup_DH.pod similarity index 82% rename from doc/crypto/DSA_dup_DH.pod rename to doc/man3/DSA_dup_DH.pod index 6967ef3d..09cbf4b3 100644 --- a/doc/crypto/DSA_dup_DH.pod +++ b/doc/man3/DSA_dup_DH.pod @@ -8,7 +8,7 @@ DSA_dup_DH - create a DH structure out of DSA structure #include - DH * DSA_dup_DH(const DSA *r); + DH *DSA_dup_DH(const DSA *r); =head1 DESCRIPTION @@ -16,7 +16,7 @@ DSA_dup_DH() duplicates DSA parameters/keys as DH parameters/keys. q is lost during that conversion, but the resulting DH parameters contain its length. -=head1 RETURN VALUE +=head1 RETURN VALUES DSA_dup_DH() returns the new B structure, and NULL on error. The error codes can be obtained by L. @@ -27,11 +27,11 @@ Be careful to avoid small subgroup attacks when using this. =head1 SEE ALSO -L, L, L +L, L, L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-2018 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 diff --git a/doc/crypto/DSA_generate_key.pod b/doc/man3/DSA_generate_key.pod similarity index 81% rename from doc/crypto/DSA_generate_key.pod rename to doc/man3/DSA_generate_key.pod index 4781abed..9ff75533 100644 --- a/doc/crypto/DSA_generate_key.pod +++ b/doc/man3/DSA_generate_key.pod @@ -17,19 +17,19 @@ a new key pair and stores it in Bpub_key> and Bpriv_key>. The PRNG must be seeded prior to calling DSA_generate_key(). -=head1 RETURN VALUE +=head1 RETURN VALUES DSA_generate_key() returns 1 on success, 0 otherwise. The error codes can be obtained by L. =head1 SEE ALSO -L, L, L, -L +L, L, L, +L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-2018 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 diff --git a/doc/crypto/DSA_generate_parameters.pod b/doc/man3/DSA_generate_parameters.pod similarity index 78% rename from doc/crypto/DSA_generate_parameters.pod rename to doc/man3/DSA_generate_parameters.pod index fc051495..970f6a6b 100644 --- a/doc/crypto/DSA_generate_parameters.pod +++ b/doc/man3/DSA_generate_parameters.pod @@ -9,15 +9,16 @@ DSA_generate_parameters_ex, DSA_generate_parameters - generate DSA parameters #include int DSA_generate_parameters_ex(DSA *dsa, int bits, - const unsigned char *seed, int seed_len, - int *counter_ret, unsigned long *h_ret, BN_GENCB *cb); + const unsigned char *seed, int seed_len, + int *counter_ret, unsigned long *h_ret, + BN_GENCB *cb); Deprecated: #if OPENSSL_API_COMPAT < 0x00908000L - DSA *DSA_generate_parameters(int bits, unsigned char *seed, - int seed_len, int *counter_ret, unsigned long *h_ret, - void (*callback)(int, int, void *), void *cb_arg); + DSA *DSA_generate_parameters(int bits, unsigned char *seed, int seed_len, + int *counter_ret, unsigned long *h_ret, + void (*callback)(int, int, void *), void *cb_arg); #endif =head1 DESCRIPTION @@ -42,6 +43,10 @@ called as shown below. For information on the BN_GENCB structure and the BN_GENCB_call function discussed below, refer to L. +DSA_generate_prime() is similar to DSA_generate_prime_ex() but +expects an old-style callback function; see +L for information on the old-style callback. + =over 2 =item * @@ -87,32 +92,31 @@ When the generator has been found, B is called. =back -DSA_generate_parameters() (deprecated) works in much the same way as for DSA_generate_parameters_ex, except that no B parameter is passed and -instead a newly allocated B structure is returned. Additionally "old -style" callbacks are used instead of the newer BN_GENCB based approach. -Refer to L for further information. - -=head1 RETURN VALUE +=head1 RETURN VALUES DSA_generate_parameters_ex() returns a 1 on success, or 0 otherwise. - -DSA_generate_parameters() returns a pointer to the DSA structure, or -B if the parameter generation fails. - The error codes can be obtained by L. +DSA_generate_parameters() returns a pointer to the DSA structure or +B if the parameter generation fails. + =head1 BUGS -Seed lengths E 20 are not supported. +Seed lengths greater than 20 are not supported. =head1 SEE ALSO L, L, L, L, L +=head1 HISTORY + +DSA_generate_parameters() was deprecated in OpenSSL 0.9.8; use +DSA_generate_parameters_ex() instead. + =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-2018 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 diff --git a/doc/crypto/DSA_get0_pqg.pod b/doc/man3/DSA_get0_pqg.pod similarity index 98% rename from doc/crypto/DSA_get0_pqg.pod rename to doc/man3/DSA_get0_pqg.pod index 6c1c09a5..58e3ab5b 100644 --- a/doc/crypto/DSA_get0_pqg.pod +++ b/doc/man3/DSA_get0_pqg.pod @@ -82,7 +82,7 @@ has been set. =head1 SEE ALSO -L, L, L, L, +L, L, L, L, L, L, L, L, L, L, L diff --git a/doc/man3/DSA_meth_new.pod b/doc/man3/DSA_meth_new.pod new file mode 100644 index 00000000..087a5dc6 --- /dev/null +++ b/doc/man3/DSA_meth_new.pod @@ -0,0 +1,215 @@ +=pod + +=head1 NAME + +DSA_meth_new, DSA_meth_free, DSA_meth_dup, DSA_meth_get0_name, +DSA_meth_set1_name, DSA_meth_get_flags, DSA_meth_set_flags, +DSA_meth_get0_app_data, DSA_meth_set0_app_data, DSA_meth_get_sign, +DSA_meth_set_sign, DSA_meth_get_sign_setup, DSA_meth_set_sign_setup, +DSA_meth_get_verify, DSA_meth_set_verify, DSA_meth_get_mod_exp, +DSA_meth_set_mod_exp, DSA_meth_get_bn_mod_exp, DSA_meth_set_bn_mod_exp, +DSA_meth_get_init, DSA_meth_set_init, DSA_meth_get_finish, DSA_meth_set_finish, +DSA_meth_get_paramgen, DSA_meth_set_paramgen, DSA_meth_get_keygen, +DSA_meth_set_keygen - Routines to build up DSA methods + +=head1 SYNOPSIS + + #include + + DSA_METHOD *DSA_meth_new(const char *name, int flags); + + void DSA_meth_free(DSA_METHOD *dsam); + + DSA_METHOD *DSA_meth_dup(const DSA_METHOD *meth); + + const char *DSA_meth_get0_name(const DSA_METHOD *dsam); + int DSA_meth_set1_name(DSA_METHOD *dsam, const char *name); + + int DSA_meth_get_flags(DSA_METHOD *dsam); + int DSA_meth_set_flags(DSA_METHOD *dsam, int flags); + + void *DSA_meth_get0_app_data(const DSA_METHOD *dsam); + int DSA_meth_set0_app_data(DSA_METHOD *dsam, void *app_data); + + DSA_SIG *(*DSA_meth_get_sign(const DSA_METHOD *dsam))(const unsigned char *, + int, DSA *); + int DSA_meth_set_sign(DSA_METHOD *dsam, DSA_SIG *(*sign)(const unsigned char *, + int, DSA *)); + + int (*DSA_meth_get_sign_setup(const DSA_METHOD *dsam))(DSA *, BN_CTX *,$ + BIGNUM **, BIGNUM **); + int DSA_meth_set_sign_setup(DSA_METHOD *dsam, int (*sign_setup)(DSA *, BN_CTX *, + BIGNUM **, BIGNUM **)); + + int (*DSA_meth_get_verify(const DSA_METHOD *dsam))(const unsigned char *, + int, DSA_SIG *, DSA *); + int DSA_meth_set_verify(DSA_METHOD *dsam, int (*verify)(const unsigned char *, + int, DSA_SIG *, DSA *)); + + int (*DSA_meth_get_mod_exp(const DSA_METHOD *dsam))(DSA *dsa, BIGNUM *rr, BIGNUM *a1, + BIGNUM *p1, BIGNUM *a2, BIGNUM *p2, + BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *in_mont); + int DSA_meth_set_mod_exp(DSA_METHOD *dsam, int (*mod_exp)(DSA *dsa, BIGNUM *rr, + BIGNUM *a1, BIGNUM *p1, + BIGNUM *a2, BIGNUM *p2, + BIGNUM *m, BN_CTX *ctx, + BN_MONT_CTX *mont)); + + int (*DSA_meth_get_bn_mod_exp(const DSA_METHOD *dsam))(DSA *dsa, BIGNUM *r, BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *mont); + int DSA_meth_set_bn_mod_exp(DSA_METHOD *dsam, int (*bn_mod_exp)(DSA *dsa, + BIGNUM *r, + BIGNUM *a, + const BIGNUM *p, + const BIGNUM *m, + BN_CTX *ctx, + BN_MONT_CTX *mont)); + + int (*DSA_meth_get_init(const DSA_METHOD *dsam))(DSA *); + int DSA_meth_set_init(DSA_METHOD *dsam, int (*init)(DSA *)); + + int (*DSA_meth_get_finish(const DSA_METHOD *dsam))(DSA *); + int DSA_meth_set_finish(DSA_METHOD *dsam, int (*finish)(DSA *)); + + int (*DSA_meth_get_paramgen(const DSA_METHOD *dsam))(DSA *, int, + const unsigned char *, + int, int *, unsigned long *, + BN_GENCB *); + int DSA_meth_set_paramgen(DSA_METHOD *dsam, + int (*paramgen)(DSA *, int, const unsigned char *, + int, int *, unsigned long *, BN_GENCB *)); + + int (*DSA_meth_get_keygen(const DSA_METHOD *dsam))(DSA *); + int DSA_meth_set_keygen(DSA_METHOD *dsam, int (*keygen)(DSA *)); + +=head1 DESCRIPTION + +The B type is a structure used for the provision of custom DSA +implementations. It provides a set of functions used by OpenSSL for the +implementation of the various DSA capabilities. See the L page for more +information. + +DSA_meth_new() creates a new B structure. It should be given a +unique B and a set of B. The B should be a NULL terminated +string, which will be duplicated and stored in the B object. It is +the callers responsibility to free the original string. The flags will be used +during the construction of a new B object based on this B. Any +new B object will have those flags set by default. + +DSA_meth_dup() creates a duplicate copy of the B object passed as a +parameter. This might be useful for creating a new B based on an +existing one, but with some differences. + +DSA_meth_free() destroys a B structure and frees up any memory +associated with it. + +DSA_meth_get0_name() will return a pointer to the name of this DSA_METHOD. This +is a pointer to the internal name string and so should not be freed by the +caller. DSA_meth_set1_name() sets the name of the DSA_METHOD to B. The +string is duplicated and the copy is stored in the DSA_METHOD structure, so the +caller remains responsible for freeing the memory associated with the name. + +DSA_meth_get_flags() returns the current value of the flags associated with this +DSA_METHOD. DSA_meth_set_flags() provides the ability to set these flags. + +The functions DSA_meth_get0_app_data() and DSA_meth_set0_app_data() provide the +ability to associate implementation specific data with the DSA_METHOD. It is +the application's responsibility to free this data before the DSA_METHOD is +freed via a call to DSA_meth_free(). + +DSA_meth_get_sign() and DSA_meth_set_sign() get and set the function used for +creating a DSA signature respectively. This function will be +called in response to the application calling DSA_do_sign() (or DSA_sign()). The +parameters for the function have the same meaning as for DSA_do_sign(). + +DSA_meth_get_sign_setup() and DSA_meth_set_sign_setup() get and set the function +used for precalculating the DSA signature values B and B. This function +will be called in response to the application calling DSA_sign_setup(). The +parameters for the function have the same meaning as for DSA_sign_setup(). + +DSA_meth_get_verify() and DSA_meth_set_verify() get and set the function used +for verifying a DSA signature respectively. This function will be called in +response to the application calling DSA_do_verify() (or DSA_verify()). The +parameters for the function have the same meaning as for DSA_do_verify(). + +DSA_meth_get_mod_exp() and DSA_meth_set_mod_exp() get and set the function used +for computing the following value: + + rr = a1^p1 * a2^p2 mod m + +This function will be called by the default OpenSSL method during verification +of a DSA signature. The result is stored in the B parameter. This function +may be NULL. + +DSA_meth_get_bn_mod_exp() and DSA_meth_set_bn_mod_exp() get and set the function +used for computing the following value: + + r = a ^ p mod m + +This function will be called by the default OpenSSL function for +DSA_sign_setup(). The result is stored in the B parameter. This function +may be NULL. + +DSA_meth_get_init() and DSA_meth_set_init() get and set the function used +for creating a new DSA instance respectively. This function will be +called in response to the application calling DSA_new() (if the current default +DSA_METHOD is this one) or DSA_new_method(). The DSA_new() and DSA_new_method() +functions will allocate the memory for the new DSA object, and a pointer to this +newly allocated structure will be passed as a parameter to the function. This +function may be NULL. + +DSA_meth_get_finish() and DSA_meth_set_finish() get and set the function used +for destroying an instance of a DSA object respectively. This function will be +called in response to the application calling DSA_free(). A pointer to the DSA +to be destroyed is passed as a parameter. The destroy function should be used +for DSA implementation specific clean up. The memory for the DSA itself should +not be freed by this function. This function may be NULL. + +DSA_meth_get_paramgen() and DSA_meth_set_paramgen() get and set the function +used for generating DSA parameters respectively. This function will be called in +response to the application calling DSA_generate_parameters_ex() (or +DSA_generate_parameters()). The parameters for the function have the same +meaning as for DSA_generate_parameters_ex(). + +DSA_meth_get_keygen() and DSA_meth_set_keygen() get and set the function +used for generating a new DSA key pair respectively. This function will be +called in response to the application calling DSA_generate_key(). The parameter +for the function has the same meaning as for DSA_generate_key(). + +=head1 RETURN VALUES + +DSA_meth_new() and DSA_meth_dup() return the newly allocated DSA_METHOD object +or NULL on failure. + +DSA_meth_get0_name() and DSA_meth_get_flags() return the name and flags +associated with the DSA_METHOD respectively. + +All other DSA_meth_get_*() functions return the appropriate function pointer +that has been set in the DSA_METHOD, or NULL if no such pointer has yet been +set. + +DSA_meth_set1_name() and all DSA_meth_set_*() functions return 1 on success or +0 on failure. + +=head1 SEE ALSO + +L, L, L, L, +L, L, L, L, +L, L, L + +=head1 HISTORY + +The functions described here were added in OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2016-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 +L. + +=cut diff --git a/doc/crypto/DSA_new.pod b/doc/man3/DSA_new.pod similarity index 96% rename from doc/crypto/DSA_new.pod rename to doc/man3/DSA_new.pod index a967ab5d..22474251 100644 --- a/doc/crypto/DSA_new.pod +++ b/doc/man3/DSA_new.pod @@ -32,7 +32,7 @@ DSA_free() returns no value. =head1 SEE ALSO -L, L, +L, L, L, L diff --git a/doc/crypto/DSA_set_method.pod b/doc/man3/DSA_set_method.pod similarity index 98% rename from doc/crypto/DSA_set_method.pod rename to doc/man3/DSA_set_method.pod index d870f56f..f10307e6 100644 --- a/doc/crypto/DSA_set_method.pod +++ b/doc/man3/DSA_set_method.pod @@ -74,7 +74,7 @@ fails. Otherwise it returns a pointer to the newly allocated structure. =head1 SEE ALSO -L, L, L +L, L, L =head1 COPYRIGHT diff --git a/doc/crypto/DSA_sign.pod b/doc/man3/DSA_sign.pod similarity index 85% rename from doc/crypto/DSA_sign.pod rename to doc/man3/DSA_sign.pod index ba0f6b86..458e16a3 100644 --- a/doc/crypto/DSA_sign.pod +++ b/doc/man3/DSA_sign.pod @@ -8,13 +8,12 @@ DSA_sign, DSA_sign_setup, DSA_verify - DSA signatures #include - int DSA_sign(int type, const unsigned char *dgst, int len, - unsigned char *sigret, unsigned int *siglen, DSA *dsa); + int DSA_sign(int type, const unsigned char *dgst, int len, + unsigned char *sigret, unsigned int *siglen, DSA *dsa); - int DSA_sign_setup(DSA *dsa, BN_CTX *ctx, BIGNUM **kinvp, - BIGNUM **rp); + int DSA_sign_setup(DSA *dsa, BN_CTX *ctx, BIGNUM **kinvp, BIGNUM **rp); - int DSA_verify(int type, const unsigned char *dgst, int len, + int DSA_verify(int type, const unsigned char *dgst, int len, unsigned char *sigbuf, int siglen, DSA *dsa); =head1 DESCRIPTION @@ -55,7 +54,7 @@ Standard, DSS), ANSI X9.30 =head1 SEE ALSO -L, L, L, +L, L, L, L =head1 COPYRIGHT diff --git a/doc/man3/DSA_size.pod b/doc/man3/DSA_size.pod new file mode 100644 index 00000000..ff7df3d2 --- /dev/null +++ b/doc/man3/DSA_size.pod @@ -0,0 +1,48 @@ +=pod + +=head1 NAME + +DSA_size, DSA_bits, DSA_security_bits - get DSA signature size, key bits or security bits + +=head1 SYNOPSIS + + #include + + int DSA_size(const DSA *dsa); + int DSA_bits(const DSA *dsa); + int DSA_security_bits(const DSA *dsa); + +=head1 DESCRIPTION + +DSA_size() returns the maximum size of an ASN.1 encoded DSA signature +for key B in bytes. It can be used to determine how much memory must +be allocated for a DSA signature. + +Bq> must not be B. + +DSA_bits() returns the number of bits in key B: this is the number +of bits in the B

parameter. + +DSA_security_bits() returns the number of security bits of the given B +key. See L. + +=head1 RETURN VALUES + +DSA_size() returns the signature size in bytes. + +DSA_bits() returns the number of bits in the key. + +=head1 SEE ALSO + +L, L + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/man3/DTLS_get_data_mtu.pod b/doc/man3/DTLS_get_data_mtu.pod new file mode 100644 index 00000000..ab714721 --- /dev/null +++ b/doc/man3/DTLS_get_data_mtu.pod @@ -0,0 +1,36 @@ +=pod + +=head1 NAME + +DTLS_get_data_mtu - Get maximum data payload size + +=head1 SYNOPSIS + + #include + + size_t DTLS_get_data_mtu(const SSL *ssl); + +=head1 DESCRIPTION + +This function obtains the maximum data payload size for the established +DTLS connection B, based on the DTLS record MTU and the overhead +of the DTLS record header, encryption and authentication currently in use. + +=head1 RETURN VALUES + +Returns the maximum data payload size on success, or 0 on failure. + +=head1 HISTORY + +This function was added in OpenSSL 1.1.1 + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/man3/DTLS_set_timer_cb.pod b/doc/man3/DTLS_set_timer_cb.pod new file mode 100644 index 00000000..6e134721 --- /dev/null +++ b/doc/man3/DTLS_set_timer_cb.pod @@ -0,0 +1,40 @@ +=pod + +=head1 NAME + +DTLS_timer_cb, +DTLS_set_timer_cb +- Set callback for controlling DTLS timer duration + +=head1 SYNOPSIS + + #include + + typedef unsigned int (*DTLS_timer_cb)(SSL *s, unsigned int timer_us); + + void DTLS_set_timer_cb(SSL *s, DTLS_timer_cb cb); + +=head1 DESCRIPTION + +This function sets an optional callback function for controlling the +timeout interval on the DTLS protocol. The callback function will be +called by DTLS for every new DTLS packet that is sent. + +=head1 RETURN VALUES + +Returns void. + +=head1 HISTORY + +This function was added in OpenSSL 1.1.1 + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/man3/DTLSv1_listen.pod b/doc/man3/DTLSv1_listen.pod new file mode 100644 index 00000000..50f16bc8 --- /dev/null +++ b/doc/man3/DTLSv1_listen.pod @@ -0,0 +1,132 @@ +=pod + +=head1 NAME + +SSL_stateless, +DTLSv1_listen +- Statelessly listen for incoming connections + +=head1 SYNOPSIS + + #include + + int SSL_stateless(SSL *s); + int DTLSv1_listen(SSL *ssl, BIO_ADDR *peer); + +=head1 DESCRIPTION + +SSL_stateless() statelessly listens for new incoming TLSv1.3 connections. +DTLSv1_listen() statelessly listens for new incoming DTLS connections. If a +ClientHello is received that does not contain a cookie, then they respond with a +request for a new ClientHello that does contain a cookie. If a ClientHello is +received with a cookie that is verified then the function returns in order to +enable the handshake to be completed (for example by using SSL_accept()). + +=head1 NOTES + +Some transport protocols (such as UDP) can be susceptible to amplification +attacks. Unlike TCP there is no initial connection setup in UDP that +validates that the client can actually receive messages on its advertised source +address. An attacker could forge its source IP address and then send handshake +initiation messages to the server. The server would then send its response to +the forged source IP. If the response messages are larger than the original +message then the amplification attack has succeeded. + +If DTLS is used over UDP (or any datagram based protocol that does not validate +the source IP) then it is susceptible to this type of attack. TLSv1.3 is +designed to operate over a stream-based transport protocol (such as TCP). +If TCP is being used then there is no need to use SSL_stateless(). However some +stream-based transport protocols (e.g. QUIC) may not validate the source +address. In this case a TLSv1.3 application would be susceptible to this attack. + +As a countermeasure to this issue TLSv1.3 and DTLS include a stateless cookie +mechanism. The idea is that when a client attempts to connect to a server it +sends a ClientHello message. The server responds with a HelloRetryRequest (in +TLSv1.3) or a HelloVerifyRequest (in DTLS) which contains a unique cookie. The +client then resends the ClientHello, but this time includes the cookie in the +message thus proving that the client is capable of receiving messages sent to +that address. All of this can be done by the server without allocating any +state, and thus without consuming expensive resources. + +OpenSSL implements this capability via the SSL_stateless() and DTLSv1_listen() +functions. The B parameter should be a newly allocated SSL object with its +read and write BIOs set, in the same way as might be done for a call to +SSL_accept(). Typically, for DTLS, the read BIO will be in an "unconnected" +state and thus capable of receiving messages from any peer. + +When a ClientHello is received that contains a cookie that has been verified, +then these functions will return with the B parameter updated into a state +where the handshake can be continued by a call to (for example) SSL_accept(). +Additionally, for DTLSv1_listen(), the B pointed to by B will be +filled in with details of the peer that sent the ClientHello. If the underlying +BIO is unable to obtain the B of the peer (for example because the BIO +does not support this), then B<*peer> will be cleared and the family set to +AF_UNSPEC. Typically user code is expected to "connect" the underlying socket to +the peer and continue the handshake in a connected state. + +Prior to calling these functions user code must ensure that cookie generation +and verification callbacks have been set up using +SSL_CTX_set_cookie_generate_cb() and SSL_CTX_set_cookie_verify_cb() +respectively. + +Since DTLSv1_listen() operates entirely statelessly whilst processing incoming +ClientHellos it is unable to process fragmented messages (since this would +require the allocation of state). An implication of this is that DTLSv1_listen() +B supports ClientHellos that fit inside a single datagram. + +For SSL_stateless() if an entire ClientHello message cannot be read without the +"read" BIO becoming empty then the SSL_stateless() call will fail. It is the +application's responsibility to ensure that data read from the "read" BIO during +a single SSL_stateless() call is all from the same peer. + +SSL_stateless() will fail (with a 0 return value) if some TLS version less than +TLSv1.3 is used. + +Both SSL_stateless() and DTLSv1_listen() will clear the error queue when they +start. + +=head1 RETURN VALUES + +For SSL_stateless() a return value of 1 indicates success and the B object +will be set up ready to continue the handshake. A return value of 0 indicates +failure. User code may retry the SSL_stateless() call. + +For DTLSv1_listen() a return value of >= 1 indicates success. The B object +will be set up ready to continue the handshake. the B value will also be +filled in. + +A return value of 0 indicates a non-fatal error. This could (for +example) be because of non-blocking IO, or some invalid message having been +received from a peer. Errors may be placed on the OpenSSL error queue with +further information if appropriate. Typically user code is expected to retry the +call to DTLSv1_listen() in the event of a non-fatal error. + +A return value of <0 indicates a fatal error. This could (for example) be +because of a failure to allocate sufficient memory for the operation. + +For DTLSv1_listen(), prior to OpenSSL 1.1.0, fatal and non-fatal errors both +produce return codes <= 0 (in typical implementations user code treats all +errors as non-fatal), whilst return codes >0 indicate success. + +=head1 SEE ALSO + +L, L, +L, L + +=head1 HISTORY + +SSL_stateless() was first added in OpenSSL 1.1.1. + +DTLSv1_listen() return codes were clarified in OpenSSL 1.1.0. The type of "peer" +also changed in OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2015-2018 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 +L. + +=cut diff --git a/doc/crypto/ECDSA_SIG_new.pod b/doc/man3/ECDSA_SIG_new.pod similarity index 94% rename from doc/crypto/ECDSA_SIG_new.pod rename to doc/man3/ECDSA_SIG_new.pod index 9e1f662c..9d3cdcee 100644 --- a/doc/crypto/ECDSA_SIG_new.pod +++ b/doc/man3/ECDSA_SIG_new.pod @@ -136,35 +136,33 @@ named curve prime256v1 (aka P-256). First step: create an EC_KEY object (note: this part is B ECDSA specific) - int ret; + int ret; ECDSA_SIG *sig; - EC_KEY *eckey; + EC_KEY *eckey; + eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); - if (eckey == NULL) { - /* error */ - } - if (EC_KEY_generate_key(eckey) == 0) { - /* error */ - } + if (eckey == NULL) + /* error */ + if (EC_KEY_generate_key(eckey) == 0) + /* error */ Second step: compute the ECDSA signature of a SHA-256 hash value using ECDSA_do_sign(): sig = ECDSA_do_sign(digest, 32, eckey); - if (sig == NULL) { - /* error */ - } + if (sig == NULL) + /* error */ or using ECDSA_sign(): unsigned char *buffer, *pp; - int buf_len; + int buf_len; + buf_len = ECDSA_size(eckey); - buffer = OPENSSL_malloc(buf_len); + buffer = OPENSSL_malloc(buf_len); pp = buffer; - if (ECDSA_sign(0, dgst, dgstlen, pp, &buf_len, eckey) == 0) { - /* error */ - } + if (ECDSA_sign(0, dgst, dgstlen, pp, &buf_len, eckey) == 0) + /* error */ Third step: verify the created ECDSA signature using ECDSA_do_verify(): @@ -176,13 +174,12 @@ or using ECDSA_verify(): and finally evaluate the return value: - if (ret == 1) { - /* signature ok */ - } else if (ret == 0) { - /* incorrect signature */ - } else { - /* error */ - } + if (ret == 1) + /* signature ok */ + else if (ret == 0) + /* incorrect signature */ + else + /* error */ =head1 CONFORMING TO diff --git a/doc/crypto/ECPKParameters_print.pod b/doc/man3/ECPKParameters_print.pod similarity index 100% rename from doc/crypto/ECPKParameters_print.pod rename to doc/man3/ECPKParameters_print.pod diff --git a/doc/crypto/EC_GFp_simple_method.pod b/doc/man3/EC_GFp_simple_method.pod similarity index 100% rename from doc/crypto/EC_GFp_simple_method.pod rename to doc/man3/EC_GFp_simple_method.pod diff --git a/doc/crypto/EC_GROUP_copy.pod b/doc/man3/EC_GROUP_copy.pod similarity index 98% rename from doc/crypto/EC_GROUP_copy.pod rename to doc/man3/EC_GROUP_copy.pod index fd5f58c9..ee20f952 100644 --- a/doc/crypto/EC_GROUP_copy.pod +++ b/doc/man3/EC_GROUP_copy.pod @@ -23,7 +23,8 @@ EC_GROUP_get_pentanomial_basis const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *group); - int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator, const BIGNUM *order, const BIGNUM *cofactor); + int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator, + const BIGNUM *order, const BIGNUM *cofactor); const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *group); int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, BN_CTX *ctx); @@ -56,7 +57,7 @@ EC_GROUP_get_pentanomial_basis int EC_GROUP_get_basis_type(const EC_GROUP *); int EC_GROUP_get_trinomial_basis(const EC_GROUP *, unsigned int *k); int EC_GROUP_get_pentanomial_basis(const EC_GROUP *, unsigned int *k1, - unsigned int *k2, unsigned int *k3); + unsigned int *k2, unsigned int *k3); =head1 DESCRIPTION diff --git a/doc/crypto/EC_GROUP_new.pod b/doc/man3/EC_GROUP_new.pod similarity index 89% rename from doc/crypto/EC_GROUP_new.pod rename to doc/man3/EC_GROUP_new.pod index 2f658dc2..e36c3cb3 100644 --- a/doc/crypto/EC_GROUP_new.pod +++ b/doc/man3/EC_GROUP_new.pod @@ -21,14 +21,20 @@ objects void EC_GROUP_free(EC_GROUP *group); void EC_GROUP_clear_free(EC_GROUP *group); - EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); - EC_GROUP *EC_GROUP_new_curve_GF2m(const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); + EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a, + const BIGNUM *b, BN_CTX *ctx); + EC_GROUP *EC_GROUP_new_curve_GF2m(const BIGNUM *p, const BIGNUM *a, + const BIGNUM *b, BN_CTX *ctx); EC_GROUP *EC_GROUP_new_by_curve_name(int nid); - int EC_GROUP_set_curve_GFp(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); - int EC_GROUP_get_curve_GFp(const EC_GROUP *group, BIGNUM *p, BIGNUM *a, BIGNUM *b, BN_CTX *ctx); - int EC_GROUP_set_curve_GF2m(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); - int EC_GROUP_get_curve_GF2m(const EC_GROUP *group, BIGNUM *p, BIGNUM *a, BIGNUM *b, BN_CTX *ctx); + int EC_GROUP_set_curve_GFp(EC_GROUP *group, const BIGNUM *p, + const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); + int EC_GROUP_get_curve_GFp(const EC_GROUP *group, BIGNUM *p, + BIGNUM *a, BIGNUM *b, BN_CTX *ctx); + int EC_GROUP_set_curve_GF2m(EC_GROUP *group, const BIGNUM *p, + const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); + int EC_GROUP_get_curve_GF2m(const EC_GROUP *group, BIGNUM *p, + BIGNUM *a, BIGNUM *b, BN_CTX *ctx); ECPARAMETERS *EC_GROUP_get_ecparameters(const EC_GROUP *group, ECPARAMETERS *params) ECPKPARAMETERS *EC_GROUP_get_ecpkparameters(const EC_GROUP *group, ECPKPARAMETERS *params) diff --git a/doc/crypto/EC_KEY_get_enc_flags.pod b/doc/man3/EC_KEY_get_enc_flags.pod similarity index 100% rename from doc/crypto/EC_KEY_get_enc_flags.pod rename to doc/man3/EC_KEY_get_enc_flags.pod diff --git a/doc/crypto/EC_KEY_new.pod b/doc/man3/EC_KEY_new.pod similarity index 95% rename from doc/crypto/EC_KEY_new.pod rename to doc/man3/EC_KEY_new.pod index 591529fd..9d32d78a 100644 --- a/doc/crypto/EC_KEY_new.pod +++ b/doc/man3/EC_KEY_new.pod @@ -5,6 +5,7 @@ EC_KEY_get_method, EC_KEY_set_method, EC_KEY_new, EC_KEY_get_flags, EC_KEY_set_flags, EC_KEY_clear_flags, EC_KEY_new_by_curve_name, EC_KEY_free, EC_KEY_copy, EC_KEY_dup, EC_KEY_up_ref, +EC_KEY_get0_engine, EC_KEY_get0_group, EC_KEY_set_group, EC_KEY_get0_private_key, EC_KEY_set_private_key, EC_KEY_get0_public_key, EC_KEY_set_public_key, EC_KEY_get_conv_form, @@ -27,6 +28,7 @@ EC_KEY objects EC_KEY *EC_KEY_copy(EC_KEY *dst, const EC_KEY *src); EC_KEY *EC_KEY_dup(const EC_KEY *src); int EC_KEY_up_ref(EC_KEY *key); + ENGINE *EC_KEY_get0_engine(const EC_KEY *eckey); const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key); int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group); const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key); @@ -39,13 +41,11 @@ EC_KEY objects int EC_KEY_precompute_mult(EC_KEY *key, BN_CTX *ctx); int EC_KEY_generate_key(EC_KEY *key); int EC_KEY_check_key(const EC_KEY *key); - int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key, - BIGNUM *x, BIGNUM *y); + int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key, BIGNUM *x, BIGNUM *y); const EC_KEY_METHOD *EC_KEY_get_method(const EC_KEY *key); int EC_KEY_set_method(EC_KEY *key, const EC_KEY_METHOD *meth); - int EC_KEY_oct2key(EC_KEY *eckey, const unsigned char *buf, size_t len, - BN_CTX *ctx); + int EC_KEY_oct2key(EC_KEY *eckey, const unsigned char *buf, size_t len, BN_CTX *ctx); size_t EC_KEY_key2buf(const EC_KEY *eckey, point_conversion_form_t form, unsigned char **pbuf, BN_CTX *ctx); @@ -78,6 +78,9 @@ EC_KEY_dup() creates a new EC_KEY object and copies B into it. EC_KEY_up_ref() increments the reference count associated with the EC_KEY object. +EC_KEY_get0_engine() returns a handle to the ENGINE that has been set for +this EC_KEY object. + EC_KEY_generate_key() generates a new public and private key for the supplied B object. B must have an EC_GROUP object associated with it before calling this function. The private key is a random integer (0 < priv_key @@ -149,6 +152,8 @@ integer. EC_KEY_copy() returns a pointer to the destination key, or NULL on error. +EC_KEY_get0_engine() returns a pointer to an ENGINE, or NULL if it wasn't set. + EC_KEY_up_ref(), EC_KEY_set_group(), EC_KEY_set_private_key(), EC_KEY_set_public_key(), EC_KEY_precompute_mult(), EC_KEY_generate_key(), EC_KEY_check_key(), EC_KEY_set_public_key_affine_coordinates(), diff --git a/doc/crypto/EC_POINT_add.pod b/doc/man3/EC_POINT_add.pod similarity index 91% rename from doc/crypto/EC_POINT_add.pod rename to doc/man3/EC_POINT_add.pod index 6f3e2308..3c047e1a 100644 --- a/doc/crypto/EC_POINT_add.pod +++ b/doc/man3/EC_POINT_add.pod @@ -8,16 +8,20 @@ EC_POINT_add, EC_POINT_dbl, EC_POINT_invert, EC_POINT_is_at_infinity, EC_POINT_i #include - int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, const EC_POINT *b, BN_CTX *ctx); + int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, + const EC_POINT *b, BN_CTX *ctx); int EC_POINT_dbl(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a, BN_CTX *ctx); int EC_POINT_invert(const EC_GROUP *group, EC_POINT *a, BN_CTX *ctx); int EC_POINT_is_at_infinity(const EC_GROUP *group, const EC_POINT *p); int EC_POINT_is_on_curve(const EC_GROUP *group, const EC_POINT *point, BN_CTX *ctx); int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, const EC_POINT *b, BN_CTX *ctx); int EC_POINT_make_affine(const EC_GROUP *group, EC_POINT *point, BN_CTX *ctx); - int EC_POINTs_make_affine(const EC_GROUP *group, size_t num, EC_POINT *points[], BN_CTX *ctx); - int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n, size_t num, const EC_POINT *p[], const BIGNUM *m[], BN_CTX *ctx); - int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n, const EC_POINT *q, const BIGNUM *m, BN_CTX *ctx); + int EC_POINTs_make_affine(const EC_GROUP *group, size_t num, + EC_POINT *points[], BN_CTX *ctx); + int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n, size_t num, + const EC_POINT *p[], const BIGNUM *m[], BN_CTX *ctx); + int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n, + const EC_POINT *q, const BIGNUM *m, BN_CTX *ctx); int EC_GROUP_precompute_mult(EC_GROUP *group, BN_CTX *ctx); int EC_GROUP_have_precompute_mult(const EC_GROUP *group); diff --git a/doc/crypto/EC_POINT_new.pod b/doc/man3/EC_POINT_new.pod similarity index 100% rename from doc/crypto/EC_POINT_new.pod rename to doc/man3/EC_POINT_new.pod diff --git a/doc/crypto/ENGINE_add.pod b/doc/man3/ENGINE_add.pod similarity index 85% rename from doc/crypto/ENGINE_add.pod rename to doc/man3/ENGINE_add.pod index d5a7d724..b009949d 100644 --- a/doc/crypto/ENGINE_add.pod +++ b/doc/man3/ENGINE_add.pod @@ -2,10 +2,10 @@ =head1 NAME -ENGINE_get_DH, ENGINE_get_DSA, ENGINE_get_ECDH, ENGINE_get_ECDSA, +ENGINE_get_DH, ENGINE_get_DSA, ENGINE_by_id, ENGINE_get_cipher_engine, ENGINE_get_default_DH, -ENGINE_get_default_DSA, ENGINE_get_default_ECDH, -ENGINE_get_default_ECDSA, ENGINE_get_default_RAND, +ENGINE_get_default_DSA, +ENGINE_get_default_RAND, ENGINE_get_default_RSA, ENGINE_get_digest_engine, ENGINE_get_first, ENGINE_get_last, ENGINE_get_next, ENGINE_get_prev, ENGINE_new, ENGINE_get_ciphers, ENGINE_get_ctrl_function, ENGINE_get_digests, @@ -17,15 +17,15 @@ ENGINE_get_name, ENGINE_get_cmd_defns, ENGINE_get_cipher, ENGINE_get_digest, ENGINE_add, ENGINE_cmd_is_executable, ENGINE_ctrl, ENGINE_ctrl_cmd, ENGINE_ctrl_cmd_string, ENGINE_finish, ENGINE_free, ENGINE_get_flags, ENGINE_init, -ENGINE_register_DH, ENGINE_register_DSA, ENGINE_register_ECDH, -ENGINE_register_ECDSA, ENGINE_register_RAND, ENGINE_register_RSA, +ENGINE_register_DH, ENGINE_register_DSA, +ENGINE_register_RAND, ENGINE_register_RSA, ENGINE_register_all_complete, ENGINE_register_ciphers, ENGINE_register_complete, ENGINE_register_digests, ENGINE_remove, -ENGINE_set_DH, ENGINE_set_DSA, ENGINE_set_ECDH, ENGINE_set_ECDSA, +ENGINE_set_DH, ENGINE_set_DSA, ENGINE_set_RAND, ENGINE_set_RSA, ENGINE_set_ciphers, ENGINE_set_cmd_defns, ENGINE_set_ctrl_function, ENGINE_set_default, -ENGINE_set_default_DH, ENGINE_set_default_DSA, ENGINE_set_default_ECDH, -ENGINE_set_default_ECDSA, ENGINE_set_default_RAND, ENGINE_set_default_RSA, +ENGINE_set_default_DH, ENGINE_set_default_DSA, +ENGINE_set_default_RAND, ENGINE_set_default_RSA, ENGINE_set_default_ciphers, ENGINE_set_default_digests, ENGINE_set_default_string, ENGINE_set_destroy_function, ENGINE_set_digests, ENGINE_set_finish_function, ENGINE_set_flags, @@ -33,11 +33,11 @@ ENGINE_set_id, ENGINE_set_init_function, ENGINE_set_load_privkey_function, ENGINE_set_load_pubkey_function, ENGINE_set_name, ENGINE_up_ref, ENGINE_get_table_flags, ENGINE_cleanup, ENGINE_load_builtin_engines, ENGINE_register_all_DH, -ENGINE_register_all_DSA, ENGINE_register_all_ECDH, -ENGINE_register_all_ECDSA, ENGINE_register_all_RAND, +ENGINE_register_all_DSA, +ENGINE_register_all_RAND, ENGINE_register_all_RSA, ENGINE_register_all_ciphers, ENGINE_register_all_digests, ENGINE_set_table_flags, ENGINE_unregister_DH, -ENGINE_unregister_DSA, ENGINE_unregister_ECDH, ENGINE_unregister_ECDSA, +ENGINE_unregister_DSA, ENGINE_unregister_RAND, ENGINE_unregister_RSA, ENGINE_unregister_ciphers, ENGINE_unregister_digests - ENGINE cryptographic module support @@ -63,8 +63,6 @@ ENGINE_unregister_digests ENGINE *ENGINE_get_default_RSA(void); ENGINE *ENGINE_get_default_DSA(void); - ENGINE *ENGINE_get_default_ECDH(void); - ENGINE *ENGINE_get_default_ECDSA(void); ENGINE *ENGINE_get_default_DH(void); ENGINE *ENGINE_get_default_RAND(void); ENGINE *ENGINE_get_cipher_engine(int nid); @@ -72,8 +70,6 @@ ENGINE_unregister_digests int ENGINE_set_default_RSA(ENGINE *e); int ENGINE_set_default_DSA(ENGINE *e); - int ENGINE_set_default_ECDH(ENGINE *e); - int ENGINE_set_default_ECDSA(ENGINE *e); int ENGINE_set_default_DH(ENGINE *e); int ENGINE_set_default_RAND(ENGINE *e); int ENGINE_set_default_ciphers(ENGINE *e); @@ -91,12 +87,6 @@ ENGINE_unregister_digests int ENGINE_register_DSA(ENGINE *e); void ENGINE_unregister_DSA(ENGINE *e); void ENGINE_register_all_DSA(void); - int ENGINE_register_ECDH(ENGINE *e); - void ENGINE_unregister_ECDH(ENGINE *e); - void ENGINE_register_all_ECDH(void); - int ENGINE_register_ECDSA(ENGINE *e); - void ENGINE_unregister_ECDSA(ENGINE *e); - void ENGINE_register_all_ECDSA(void); int ENGINE_register_DH(ENGINE *e); void ENGINE_unregister_DH(ENGINE *e); void ENGINE_register_all_DH(void); @@ -115,9 +105,9 @@ ENGINE_unregister_digests int ENGINE_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)); int ENGINE_cmd_is_executable(ENGINE *e, int cmd); int ENGINE_ctrl_cmd(ENGINE *e, const char *cmd_name, - long i, void *p, void (*f)(void), int cmd_optional); + long i, void *p, void (*f)(void), int cmd_optional); int ENGINE_ctrl_cmd_string(ENGINE *e, const char *cmd_name, const char *arg, - int cmd_optional); + int cmd_optional); ENGINE *ENGINE_new(void); int ENGINE_free(ENGINE *e); @@ -127,8 +117,6 @@ ENGINE_unregister_digests int ENGINE_set_name(ENGINE *e, const char *name); int ENGINE_set_RSA(ENGINE *e, const RSA_METHOD *rsa_meth); int ENGINE_set_DSA(ENGINE *e, const DSA_METHOD *dsa_meth); - int ENGINE_set_ECDH(ENGINE *e, const ECDH_METHOD *dh_meth); - int ENGINE_set_ECDSA(ENGINE *e, const ECDSA_METHOD *dh_meth); int ENGINE_set_DH(ENGINE *e, const DH_METHOD *dh_meth); int ENGINE_set_RAND(ENGINE *e, const RAND_METHOD *rand_meth); int ENGINE_set_destroy_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR destroy_f); @@ -146,8 +134,6 @@ ENGINE_unregister_digests const char *ENGINE_get_name(const ENGINE *e); const RSA_METHOD *ENGINE_get_RSA(const ENGINE *e); const DSA_METHOD *ENGINE_get_DSA(const ENGINE *e); - const ECDH_METHOD *ENGINE_get_ECDH(const ENGINE *e); - const ECDSA_METHOD *ENGINE_get_ECDSA(const ENGINE *e); const DH_METHOD *ENGINE_get_DH(const ENGINE *e); const RAND_METHOD *ENGINE_get_RAND(const ENGINE *e); ENGINE_GEN_INT_FUNC_PTR ENGINE_get_destroy_function(const ENGINE *e); @@ -164,9 +150,9 @@ ENGINE_unregister_digests const ENGINE_CMD_DEFN *ENGINE_get_cmd_defns(const ENGINE *e); EVP_PKEY *ENGINE_load_private_key(ENGINE *e, const char *key_id, - UI_METHOD *ui_method, void *callback_data); + UI_METHOD *ui_method, void *callback_data); EVP_PKEY *ENGINE_load_public_key(ENGINE *e, const char *key_id, - UI_METHOD *ui_method, void *callback_data); + UI_METHOD *ui_method, void *callback_data); Deprecated: @@ -335,29 +321,6 @@ consideration is whether any/all available ENGINE implementations should be made visible to OpenSSL - this is controlled by calling the various "load" functions. -Having called any of these functions, ENGINE objects would have been -dynamically allocated and populated with these implementations and linked -into OpenSSL's internal linked list. At this point it is important to -mention an important API function; - - void ENGINE_cleanup(void) - -If no ENGINE API functions are called at all in an application, then there -are no inherent memory leaks to worry about from the ENGINE functionality. -However, prior to OpenSSL 1.1.0 if any ENGINEs are loaded, even if they are -never registered or used, it was necessary to use the ENGINE_cleanup() function -to correspondingly cleanup before program exit, if the caller wishes to avoid -memory leaks. This mechanism used an internal callback registration table -so that any ENGINE API functionality that knows it requires cleanup can -register its cleanup details to be called during ENGINE_cleanup(). This -approach allowed ENGINE_cleanup() to clean up after any ENGINE functionality -at all that your program uses, yet doesn't automatically create linker -dependencies to all possible ENGINE functionality - only the cleanup -callbacks required by the functionality you do use will be required by the -linker. From OpenSSL 1.1.0 it is no longer necessary to explicitly call -ENGINE_cleanup and this function is deprecated. Cleanup automatically takes -place at program exit. - The fact that ENGINEs are made visible to OpenSSL (and thus are linked into the program and loaded into memory at run-time) does not mean they are "registered" or called into use by OpenSSL automatically - that behaviour @@ -372,6 +335,11 @@ things, so we will simply illustrate the consequences as they apply to a couple of simple cases and leave developers to consider these and the source code to openssl's builtin utilities as guides. +If no ENGINE API functions are called within an application, then OpenSSL +will not allocate any internal resources. Prior to OpenSSL 1.1.0, however, +if any ENGINEs are loaded, even if not registered or used, it was necessary to +call ENGINE_cleanup() before the program exits. + I Here we'll assume an application has been configured by its user or admin @@ -385,17 +353,19 @@ illustrates how to approach this; const char *engine_id = "ACME"; ENGINE_load_builtin_engines(); e = ENGINE_by_id(engine_id); - if(!e) + if (!e) /* the engine isn't available */ return; - if(!ENGINE_init(e)) { + if (!ENGINE_init(e)) { /* the engine couldn't initialise, release 'e' */ ENGINE_free(e); return; } - if(!ENGINE_set_default_RSA(e)) - /* This should only happen when 'e' can't initialise, but the previous - * statement suggests it did. */ + if (!ENGINE_set_default_RSA(e)) + /* + * This should only happen when 'e' can't initialise, but the previous + * statement suggests it did. + */ abort(); ENGINE_set_default_DSA(e); ENGINE_set_default_ciphers(e); @@ -474,9 +444,9 @@ boolean success or failure. ENGINE *e = ENGINE_by_id(engine_id); if (!e) return 0; while (pre_num--) { - if(!ENGINE_ctrl_cmd_string(e, pre_cmds[0], pre_cmds[1], 0)) { + if (!ENGINE_ctrl_cmd_string(e, pre_cmds[0], pre_cmds[1], 0)) { fprintf(stderr, "Failed command (%s - %s:%s)\n", engine_id, - pre_cmds[0], pre_cmds[1] ? pre_cmds[1] : "(NULL)"); + pre_cmds[0], pre_cmds[1] ? pre_cmds[1] : "(NULL)"); ENGINE_free(e); return 0; } @@ -487,13 +457,15 @@ boolean success or failure. ENGINE_free(e); return 0; } - /* ENGINE_init() returned a functional reference, so free the structural - * reference from ENGINE_by_id(). */ + /* + * ENGINE_init() returned a functional reference, so free the structural + * reference from ENGINE_by_id(). + */ ENGINE_free(e); - while(post_num--) { - if(!ENGINE_ctrl_cmd_string(e, post_cmds[0], post_cmds[1], 0)) { + while (post_num--) { + if (!ENGINE_ctrl_cmd_string(e, post_cmds[0], post_cmds[1], 0)) { fprintf(stderr, "Failed command (%s - %s:%s)\n", engine_id, - post_cmds[0], post_cmds[1] ? post_cmds[1] : "(NULL)"); + post_cmds[0], post_cmds[1] ? post_cmds[1] : "(NULL)"); ENGINE_finish(e); return 0; } @@ -546,7 +518,7 @@ If an ENGINE specifies the ENGINE_FLAGS_MANUAL_CMD_CTRL flag, then it will simply pass all these "core" control commands directly to the ENGINE's ctrl() handler (and thus, it must have supplied one), so it is up to the ENGINE to reply to these "discovery" commands itself. If that flag is not set, then the -OpenSSL framework code will work with the following rules; +OpenSSL framework code will work with the following rules: if no ctrl() handler supplied; ENGINE_HAS_CTRL_FUNCTION returns FALSE (zero), @@ -599,15 +571,88 @@ The path to the engines directory. =back +=head1 RETURN VALUES + +ENGINE_get_first(), ENGINE_get_last(), ENGINE_get_next() and ENGINE_get_prev() +return a valid B structure or NULL if an error occurred. + +ENGINE_add() and ENGINE_remove() return 1 on success or 0 on error. + +ENGINE_by_id() returns a valid B structure or NULL if an error occurred. + +ENGINE_init() and ENGINE_finish() return 1 on success or 0 on error. + +All ENGINE_get_default_TYPE() functions, ENGINE_get_cipher_engine() and +ENGINE_get_digest_engine() return a valid B structure on success or NULL +if an error occurred. + +All ENGINE_set_default_TYPE() functions return 1 on success or 0 on error. + +ENGINE_set_default() returns 1 on success or 0 on error. + +ENGINE_get_table_flags() returns an unsigned integer value representing the +global table flags which are used to control the registration behaviour of +B implementations. + +All ENGINE_register_TYPE() functions return 1 on success or 0 on error. + +ENGINE_register_complete() and ENGINE_register_all_complete() return 1 on success +or 0 on error. + +ENGINE_ctrl() returns a positive value on success or others on error. + +ENGINE_cmd_is_executable() returns 1 if B is executable or 0 otherwise. + +ENGINE_ctrl_cmd() and ENGINE_ctrl_cmd_string() return 1 on success or 0 on error. + +ENGINE_new() returns a valid B structure on success or NULL if an error +occurred. + +ENGINE_free() returns 1 on success or 0 on error. + +ENGINE_up_ref() returns 1 on success or 0 on error. + +ENGINE_set_id() and ENGINE_set_name() return 1 on success or 0 on error. + +All other B functions return 1 on success or 0 on error. + +ENGINE_get_id() and ENGINE_get_name() return a string representing the identifier +and the name of the ENGINE B respectively. + +ENGINE_get_RSA(), ENGINE_get_DSA(), ENGINE_get_DH() and ENGINE_get_RAND() +return corresponding method structures for each algorithms. + +ENGINE_get_destroy_function(), ENGINE_get_init_function(), +ENGINE_get_finish_function(), ENGINE_get_ctrl_function(), +ENGINE_get_load_privkey_function(), ENGINE_get_load_pubkey_function(), +ENGINE_get_ciphers() and ENGINE_get_digests() return corresponding function +pointers of the callbacks. + +ENGINE_get_cipher() returns a valid B structure on success or NULL +if an error occurred. + +ENGINE_get_digest() returns a valid B structure on success or NULL if an +error occurred. + +ENGINE_get_flags() returns an integer representing the ENGINE flags which are +used to control various behaviours of an ENGINE. + +ENGINE_get_cmd_defns() returns an B structure or NULL if it's +not set. + +ENGINE_load_private_key() and ENGINE_load_public_key() return a valid B +structure on success or NULL if an error occurred. + =head1 SEE ALSO -L, L, L, L, L +L, L, L, L, +L, L =head1 HISTORY -ENGINE_cleanup(), ENGINE_load_openssl(), ENGINE_load_dynamic(), and -ENGINE_load_cryptodev() were deprecated in OpenSSL 1.1.0 by -OPENSSL_init_crypto(). +ENGINE_cleanup() was deprecated in OpenSSL 1.1.0 by the automatic cleanup +done by OPENSSL_cleanup() +and should not be used. =head1 COPYRIGHT diff --git a/doc/crypto/ERR_GET_LIB.pod b/doc/man3/ERR_GET_LIB.pod similarity index 100% rename from doc/crypto/ERR_GET_LIB.pod rename to doc/man3/ERR_GET_LIB.pod diff --git a/doc/crypto/ERR_clear_error.pod b/doc/man3/ERR_clear_error.pod similarity index 100% rename from doc/crypto/ERR_clear_error.pod rename to doc/man3/ERR_clear_error.pod diff --git a/doc/crypto/ERR_error_string.pod b/doc/man3/ERR_error_string.pod similarity index 100% rename from doc/crypto/ERR_error_string.pod rename to doc/man3/ERR_error_string.pod diff --git a/doc/crypto/ERR_get_error.pod b/doc/man3/ERR_get_error.pod similarity index 92% rename from doc/crypto/ERR_get_error.pod rename to doc/man3/ERR_get_error.pod index 3b223c99..a76df038 100644 --- a/doc/crypto/ERR_get_error.pod +++ b/doc/man3/ERR_get_error.pod @@ -20,11 +20,11 @@ ERR_peek_last_error_line_data - obtain error code and data unsigned long ERR_peek_last_error_line(const char **file, int *line); unsigned long ERR_get_error_line_data(const char **file, int *line, - const char **data, int *flags); + const char **data, int *flags); unsigned long ERR_peek_error_line_data(const char **file, int *line, - const char **data, int *flags); + const char **data, int *flags); unsigned long ERR_peek_last_error_line_data(const char **file, int *line, - const char **data, int *flags); + const char **data, int *flags); =head1 DESCRIPTION diff --git a/doc/crypto/ERR_load_crypto_strings.pod b/doc/man3/ERR_load_crypto_strings.pod similarity index 76% rename from doc/crypto/ERR_load_crypto_strings.pod rename to doc/man3/ERR_load_crypto_strings.pod index 56d91d5d..c503241d 100644 --- a/doc/crypto/ERR_load_crypto_strings.pod +++ b/doc/man3/ERR_load_crypto_strings.pod @@ -24,16 +24,12 @@ Deprecated: =head1 DESCRIPTION -All of the following functions are deprecated from OpenSSL 1.1.0. No explicit -initialisation or de-initialisation is necessary. See L -and L. - ERR_load_crypto_strings() registers the error strings for all B functions. SSL_load_error_strings() does the same, but also registers the B error strings. -In versions of OpenSSL prior to 1.1.0 ERR_free_strings() freed all previously -loaded error strings. However from OpenSSL 1.1.0 it does nothing. +In versions prior to OpenSSL 1.1.0, +ERR_free_strings() releases any resources created by the above functions. =head1 RETURN VALUES @@ -48,7 +44,7 @@ L The ERR_load_crypto_strings(), SSL_load_error_strings(), and ERR_free_strings() functions were deprecated in OpenSSL 1.1.0 by -OPENSSL_init_crypto() and OPENSSL_init_ssl(). +OPENSSL_init_crypto() and OPENSSL_init_ssl() and should not be used. =head1 COPYRIGHT diff --git a/doc/crypto/ERR_load_strings.pod b/doc/man3/ERR_load_strings.pod similarity index 90% rename from doc/crypto/ERR_load_strings.pod rename to doc/man3/ERR_load_strings.pod index ee8de2c9..3167f271 100644 --- a/doc/crypto/ERR_load_strings.pod +++ b/doc/man3/ERR_load_strings.pod @@ -23,8 +23,8 @@ B is an array of error string data: typedef struct ERR_string_data_st { - unsigned long error; - char *string; + unsigned long error; + char *string; } ERR_STRING_DATA; The error code is generated from the library number and a function and @@ -36,7 +36,7 @@ The last entry in the array is {0,0}. ERR_get_next_error_library() can be used to assign library numbers to user libraries at runtime. -=head1 RETURN VALUE +=head1 RETURN VALUES ERR_load_strings() returns no value. ERR_PACK() return the error code. ERR_get_next_error_library() returns zero on failure, otherwise a new @@ -48,7 +48,7 @@ L =head1 COPYRIGHT -Copyright 2000-2017 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-2018 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 diff --git a/doc/crypto/ERR_print_errors.pod b/doc/man3/ERR_print_errors.pod similarity index 97% rename from doc/crypto/ERR_print_errors.pod rename to doc/man3/ERR_print_errors.pod index 134b374d..f7e612f6 100644 --- a/doc/crypto/ERR_print_errors.pod +++ b/doc/man3/ERR_print_errors.pod @@ -11,8 +11,7 @@ ERR_print_errors, ERR_print_errors_fp, ERR_print_errors_cb void ERR_print_errors(BIO *bp); void ERR_print_errors_fp(FILE *fp); - void ERR_print_errors_cb(int (*cb)(const char *str, size_t len, void *u), - void *u) + void ERR_print_errors_cb(int (*cb)(const char *str, size_t len, void *u), void *u) =head1 DESCRIPTION diff --git a/doc/crypto/ERR_put_error.pod b/doc/man3/ERR_put_error.pod similarity index 94% rename from doc/crypto/ERR_put_error.pod rename to doc/man3/ERR_put_error.pod index 14695baa..4fba618d 100644 --- a/doc/crypto/ERR_put_error.pod +++ b/doc/man3/ERR_put_error.pod @@ -2,17 +2,16 @@ =head1 NAME -ERR_put_error, ERR_add_error_data - record an error +ERR_put_error, ERR_add_error_data, ERR_add_error_vdata - record an error =head1 SYNOPSIS #include - void ERR_put_error(int lib, int func, int reason, const char *file, - int line); + void ERR_put_error(int lib, int func, int reason, const char *file, int line); void ERR_add_error_data(int num, ...); - void ERR_add_error_data(int num, va_list arg); + void ERR_add_error_vdata(int num, va_list arg); =head1 DESCRIPTION diff --git a/doc/man3/ERR_remove_state.pod b/doc/man3/ERR_remove_state.pod new file mode 100644 index 00000000..8f4d3fca --- /dev/null +++ b/doc/man3/ERR_remove_state.pod @@ -0,0 +1,49 @@ +=pod + +=head1 NAME + +ERR_remove_thread_state, ERR_remove_state - DEPRECATED + +=head1 SYNOPSIS + +Deprecated: + + #if OPENSSL_API_COMPAT < 0x10000000L + void ERR_remove_state(unsigned long tid); + #endif + + #if OPENSSL_API_COMPAT < 0x10100000L + void ERR_remove_thread_state(void *tid); + #endif + +=head1 DESCRIPTION + +ERR_remove_state() frees the error queue associated with the specified +thread, identified by B. +ERR_remove_thread_state() does the same thing, except the identifier is +an opaque pointer. + +=head1 RETURN VALUES + +ERR_remove_state() and ERR_remove_thread_state() return no value. + +=head1 SEE ALSO + +LL + +=head1 HISTORY + +ERR_remove_state() was deprecated in OpenSSL 1.0.0 and +ERR_remove_thread_state() was deprecated in OpenSSL 1.1.0; these functions +and should not be used. + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/crypto/ERR_set_mark.pod b/doc/man3/ERR_set_mark.pod similarity index 100% rename from doc/crypto/ERR_set_mark.pod rename to doc/man3/ERR_set_mark.pod diff --git a/doc/crypto/EVP_BytesToKey.pod b/doc/man3/EVP_BytesToKey.pod similarity index 98% rename from doc/crypto/EVP_BytesToKey.pod rename to doc/man3/EVP_BytesToKey.pod index 728c94e9..8d49648f 100644 --- a/doc/crypto/EVP_BytesToKey.pod +++ b/doc/man3/EVP_BytesToKey.pod @@ -62,7 +62,7 @@ or 0 on error. =head1 SEE ALSO -L, L, +L, L, L, L diff --git a/doc/crypto/EVP_CIPHER_CTX_get_cipher_data.pod b/doc/man3/EVP_CIPHER_CTX_get_cipher_data.pod similarity index 100% rename from doc/crypto/EVP_CIPHER_CTX_get_cipher_data.pod rename to doc/man3/EVP_CIPHER_CTX_get_cipher_data.pod diff --git a/doc/crypto/EVP_CIPHER_meth_new.pod b/doc/man3/EVP_CIPHER_meth_new.pod similarity index 89% rename from doc/crypto/EVP_CIPHER_meth_new.pod rename to doc/man3/EVP_CIPHER_meth_new.pod index 08e8290b..a33cb763 100644 --- a/doc/crypto/EVP_CIPHER_meth_new.pod +++ b/doc/man3/EVP_CIPHER_meth_new.pod @@ -24,26 +24,26 @@ EVP_CIPHER_meth_get_ctrl - Routines to build up EVP_CIPHER methods int EVP_CIPHER_meth_set_flags(EVP_CIPHER *cipher, unsigned long flags); int EVP_CIPHER_meth_set_impl_ctx_size(EVP_CIPHER *cipher, int ctx_size); int EVP_CIPHER_meth_set_init(EVP_CIPHER *cipher, - int (*init) (EVP_CIPHER_CTX *ctx, - const unsigned char *key, - const unsigned char *iv, - int enc)); + int (*init)(EVP_CIPHER_CTX *ctx, + const unsigned char *key, + const unsigned char *iv, + int enc)); int EVP_CIPHER_meth_set_do_cipher(EVP_CIPHER *cipher, - int (*do_cipher) (EVP_CIPHER_CTX *ctx, - unsigned char *out, - const unsigned char *in, - size_t inl)); + int (*do_cipher)(EVP_CIPHER_CTX *ctx, + unsigned char *out, + const unsigned char *in, + size_t inl)); int EVP_CIPHER_meth_set_cleanup(EVP_CIPHER *cipher, - int (*cleanup) (EVP_CIPHER_CTX *)); + int (*cleanup)(EVP_CIPHER_CTX *)); int EVP_CIPHER_meth_set_set_asn1_params(EVP_CIPHER *cipher, - int (*set_asn1_parameters) (EVP_CIPHER_CTX *, - ASN1_TYPE *)); + int (*set_asn1_parameters)(EVP_CIPHER_CTX *, + ASN1_TYPE *)); int EVP_CIPHER_meth_set_get_asn1_params(EVP_CIPHER *cipher, - int (*get_asn1_parameters) (EVP_CIPHER_CTX *, - ASN1_TYPE *)); + int (*get_asn1_parameters)(EVP_CIPHER_CTX *, + ASN1_TYPE *)); int EVP_CIPHER_meth_set_ctrl(EVP_CIPHER *cipher, - int (*ctrl) (EVP_CIPHER_CTX *, int type, - int arg, void *ptr)); + int (*ctrl)(EVP_CIPHER_CTX *, int type, + int arg, void *ptr)); int (*EVP_CIPHER_meth_get_init(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *ctx, const unsigned char *key, @@ -57,7 +57,7 @@ EVP_CIPHER_meth_get_ctrl - Routines to build up EVP_CIPHER methods int (*EVP_CIPHER_meth_get_set_asn1_params(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, ASN1_TYPE *); int (*EVP_CIPHER_meth_get_get_asn1_params(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, - ASN1_TYPE *); + ASN1_TYPE *); int (*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, int type, int arg, void *ptr); @@ -148,7 +148,7 @@ Use the default EVP routines to pass IV to and from ASN.1. =item EVP_CIPH_FLAG_LENGTH_BITS Signals that the length of the input buffer for encryption / -decryption is to be understood as the number of bits bits instead of +decryption is to be understood as the number of bits instead of bytes for this implementation. This is only useful for CFB1 ciphers. @@ -237,8 +237,6 @@ L =head1 HISTORY -The B structure was openly available in OpenSSL before version -1.1.0. The functions described here were added in OpenSSL 1.1.0. =head1 COPYRIGHT diff --git a/doc/man3/EVP_DigestInit.pod b/doc/man3/EVP_DigestInit.pod new file mode 100644 index 00000000..187292fc --- /dev/null +++ b/doc/man3/EVP_DigestInit.pod @@ -0,0 +1,324 @@ +=pod + +=head1 NAME + +EVP_MD_CTX_new, EVP_MD_CTX_reset, EVP_MD_CTX_free, EVP_MD_CTX_copy_ex, +EVP_MD_CTX_ctrl, EVP_DigestInit_ex, EVP_DigestInit, EVP_DigestUpdate, +EVP_DigestFinal_ex, EVP_DigestFinalXOF, EVP_DigestFinal, +EVP_MD_CTX_copy, EVP_MD_type, EVP_MD_pkey_type, EVP_MD_size, +EVP_MD_block_size, EVP_MD_CTX_md, EVP_MD_CTX_size, +EVP_MD_CTX_block_size, EVP_MD_CTX_type, EVP_md_null, +EVP_get_digestbyname, EVP_get_digestbynid, +EVP_get_digestbyobj - EVP digest routines + +=head1 SYNOPSIS + + #include + + EVP_MD_CTX *EVP_MD_CTX_new(void); + int EVP_MD_CTX_reset(EVP_MD_CTX *ctx); + void EVP_MD_CTX_free(EVP_MD_CTX *ctx); + void EVP_MD_CTX_ctrl(EVP_MD_CTX *ctx, int cmd, int p1, void* p2); + + int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl); + int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt); + int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s); + int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, unsigned char *md, size_t len); + + int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in); + + int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type); + int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s); + + int EVP_MD_CTX_copy(EVP_MD_CTX *out, EVP_MD_CTX *in); + + int EVP_MD_type(const EVP_MD *md); + int EVP_MD_pkey_type(const EVP_MD *md); + int EVP_MD_size(const EVP_MD *md); + int EVP_MD_block_size(const EVP_MD *md); + + const EVP_MD *EVP_MD_CTX_md(const EVP_MD_CTX *ctx); + int EVP_MD_CTX_size(const EVP_MD *ctx); + int EVP_MD_CTX_block_size(const EVP_MD *ctx); + int EVP_MD_CTX_type(const EVP_MD *ctx); + + const EVP_MD *EVP_md_null(void); + + const EVP_MD *EVP_get_digestbyname(const char *name); + const EVP_MD *EVP_get_digestbynid(int type); + const EVP_MD *EVP_get_digestbyobj(const ASN1_OBJECT *o); + +=head1 DESCRIPTION + +The EVP digest routines are a high level interface to message digests, +and should be used instead of the cipher-specific functions. + +=over 4 + +=item EVP_MD_CTX_new() + +Allocates and returns a digest context. + +=item EVP_MD_CTX_reset() + +Resets the digest context B. This can be used to reuse an already +existing context. + +=item EVP_MD_CTX_free() + +Cleans up digest context B and frees up the space allocated to it. + +=item EVP_MD_CTX_ctrl() + +Performs digest-specific control actions on context B. + +=item EVP_DigestInit_ex() + +Sets up digest context B to use a digest B from ENGINE B. +B will typically be supplied by a function such as EVP_sha1(). If +B is NULL then the default implementation of digest B is used. + +=item EVP_DigestUpdate() + +Hashes B bytes of data at B into the digest context B. This +function can be called several times on the same B to hash additional +data. + +=item EVP_DigestFinal_ex() + +Retrieves the digest value from B and places it in B. If the B +parameter is not NULL then the number of bytes of data written (i.e. the +length of the digest) will be written to the integer at B, at most +B bytes will be written. After calling EVP_DigestFinal_ex() +no additional calls to EVP_DigestUpdate() can be made, but +EVP_DigestInit_ex() can be called to initialize a new digest operation. + +=item EVP_DigestFinalXOF() + +Interfaces to extendable-output functions, XOFs, such as SHAKE128 and SHAKE256. +It retrieves the digest value from B and places it in B-sized md. +After calling this function no additional calls to EVP_DigestUpdate() can be +made, but EVP_DigestInit_ex() can be called to initialize a new operation. + +=item EVP_MD_CTX_copy_ex() + +Can be used to copy the message digest state from B to B. This is +useful if large amounts of data are to be hashed which only differ in the last +few bytes. + +=item EVP_DigestInit() + +Behaves in the same way as EVP_DigestInit_ex() except it always uses the +default digest implementation. + +=item EVP_DigestFinal() + +Similar to EVP_DigestFinal_ex() except the digest context B is +automatically cleaned up. + +=item EVP_MD_CTX_copy() + +Similar to EVP_MD_CTX_copy_ex() except the destination B does not have to +be initialized. + +=item EVP_MD_size(), +EVP_MD_CTX_size() + +Return the size of the message digest when passed an B or an +B structure, i.e. the size of the hash. + +=item EVP_MD_block_size(), +EVP_MD_CTX_block_size() + +Return the block size of the message digest when passed an B or an +B structure. + +=item EVP_MD_type(), +EVP_MD_CTX_type() + +Return the NID of the OBJECT IDENTIFIER representing the given message digest +when passed an B structure. For example, C +returns B. This function is normally used when setting ASN1 OIDs. + +=item EVP_MD_CTX_md() + +Returns the B structure corresponding to the passed B. + +=item EVP_MD_pkey_type() + +Returns the NID of the public key signing algorithm associated with this +digest. For example EVP_sha1() is associated with RSA so this will return +B. Since digests and signature algorithms are no +longer linked this function is only retained for compatibility reasons. + +=item EVP_md_null() + +A "null" message digest that does nothing: i.e. the hash it returns is of zero +length. + +=item EVP_get_digestbyname(), +EVP_get_digestbynid(), +EVP_get_digestbyobj() + +Returns an B structure when passed a digest name, a digest B or an +B structure respectively. + +=back + +=head1 RETURN VALUES + +=over 4 + +=item EVP_DigestInit_ex(), +EVP_DigestUpdate(), +EVP_DigestFinal_ex() + +Returns 1 for +success and 0 for failure. + +=item EVP_MD_CTX_ctrl() + +Returns 1 if successful or 0 for failure. + +=item EVP_MD_CTX_copy_ex() + +Returns 1 if successful or 0 for failure. + +=item EVP_MD_type(), +EVP_MD_pkey_type(), +EVP_MD_type() + +Returns the NID of the corresponding OBJECT IDENTIFIER or NID_undef if none +exists. + +=item EVP_MD_size(), +EVP_MD_block_size(), +EVP_MD_CTX_size(), +EVP_MD_CTX_block_size() + +Returns the digest or block size in bytes. + +=item EVP_md_null() + +Returns a pointer to the B structure of the "null" message digest. + +=item EVP_get_digestbyname(), +EVP_get_digestbynid(), +EVP_get_digestbyobj() + +Returns either an B structure or NULL if an error occurs. + +=back + +=head1 NOTES + +The B interface to message digests should almost always be used in +preference to the low level interfaces. This is because the code then becomes +transparent to the digest used and much more flexible. + +New applications should use the SHA-2 (such as L) or the SHA-3 +digest algorithms (such as L). The other digest algorithms are +still in common use. + +For most applications the B parameter to EVP_DigestInit_ex() will be +set to NULL to use the default digest implementation. + +The functions EVP_DigestInit(), EVP_DigestFinal() and EVP_MD_CTX_copy() are +obsolete but are retained to maintain compatibility with existing code. New +applications should use EVP_DigestInit_ex(), EVP_DigestFinal_ex() and +EVP_MD_CTX_copy_ex() because they can efficiently reuse a digest context +instead of initializing and cleaning it up on each call and allow non default +implementations of digests to be specified. + +If digest contexts are not cleaned up after use +memory leaks will occur. + +EVP_MD_CTX_size(), EVP_MD_CTX_block_size(), EVP_MD_CTX_type(), +EVP_get_digestbynid() and EVP_get_digestbyobj() are defined as +macros. + +EVP_MD_CTX_ctrl() sends commands to message digests for additional configuration +or control. + +=head1 EXAMPLE + +This example digests the data "Test Message\n" and "Hello World\n", using the +digest name passed on the command line. + + #include + #include + + main(int argc, char *argv[]) + { + EVP_MD_CTX *mdctx; + const EVP_MD *md; + char mess1[] = "Test Message\n"; + char mess2[] = "Hello World\n"; + unsigned char md_value[EVP_MAX_MD_SIZE]; + int md_len, i; + + if (argv[1] == NULL) { + printf("Usage: mdtest digestname\n"); + exit(1); + } + + md = EVP_get_digestbyname(argv[1]); + if (md == NULL) { + printf("Unknown message digest %s\n", argv[1]); + exit(1); + } + + mdctx = EVP_MD_CTX_new(); + EVP_DigestInit_ex(mdctx, md, NULL); + EVP_DigestUpdate(mdctx, mess1, strlen(mess1)); + EVP_DigestUpdate(mdctx, mess2, strlen(mess2)); + EVP_DigestFinal_ex(mdctx, md_value, &md_len); + EVP_MD_CTX_free(mdctx); + + printf("Digest is: "); + for (i = 0; i < md_len; i++) + printf("%02x", md_value[i]); + printf("\n"); + + exit(0); + } + +=head1 SEE ALSO + +L, +L + +The full list of digest algorithms are provided below. + +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L + +=head1 HISTORY + +EVP_MD_CTX_create() and EVP_MD_CTX_destroy() were renamed to +EVP_MD_CTX_new() and EVP_MD_CTX_free() in OpenSSL 1.1.0. + +The link between digests and signing algorithms was fixed in OpenSSL 1.0 and +later, so now EVP_sha1() can be used with RSA and DSA. + +EVP_dss1() was removed in OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/crypto/EVP_DigestSignInit.pod b/doc/man3/EVP_DigestSignInit.pod similarity index 76% rename from doc/crypto/EVP_DigestSignInit.pod rename to doc/man3/EVP_DigestSignInit.pod index 7ec06b7a..c3513f53 100644 --- a/doc/crypto/EVP_DigestSignInit.pod +++ b/doc/man3/EVP_DigestSignInit.pod @@ -2,7 +2,8 @@ =head1 NAME -EVP_DigestSignInit, EVP_DigestSignUpdate, EVP_DigestSignFinal - EVP signing functions +EVP_DigestSignInit, EVP_DigestSignUpdate, EVP_DigestSignFinal, +EVP_DigestSign - EVP signing functions =head1 SYNOPSIS @@ -13,12 +14,16 @@ EVP_DigestSignInit, EVP_DigestSignUpdate, EVP_DigestSignFinal - EVP signing func int EVP_DigestSignUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt); int EVP_DigestSignFinal(EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen); + int EVP_DigestSign(EVP_MD_CTX *ctx, unsigned char *sigret, + size_t *siglen, const unsigned char *tbs, + size_t tbslen); + =head1 DESCRIPTION The EVP signature routines are a high level interface to digital signatures. EVP_DigestSignInit() sets up signing context B to use digest B from -ENGINE B and private key B. B must be created with +ENGINE B and private key B. B must be created with EVP_MD_CTX_new() before calling this function. If B is not NULL the EVP_PKEY_CTX of the signing operation will be written to B<*pctx>: this can be used to set alternative signing options. @@ -35,12 +40,16 @@ B parameter should contain the length of the B buffer, if the call is successful the signature is written to B and the amount of data written to B. +EVP_DigestSign() signs B bytes of data at B and places the +signature in B and its length in B in a similar way to +EVP_DigestSignFinal(). + =head1 RETURN VALUES -EVP_DigestSignInit() EVP_DigestSignUpdate() and EVP_DigestSignaFinal() return -1 for success and 0 or a negative value for failure. In particular a return -value of -2 indicates the operation is not supported by the public key -algorithm. +EVP_DigestSignInit(), EVP_DigestSignUpdate(), EVP_DigestSignaFinal() and +EVP_DigestSign() return 1 for success and 0 or a negative value for failure. In +particular a return value of -2 indicates the operation is not supported by the +public key algorithm. The error codes can be obtained from L. @@ -50,6 +59,11 @@ The B interface to digital signatures should almost always be used in preference to the low level interfaces. This is because the code then becomes transparent to the algorithm used and much more flexible. +EVP_DigestSign() is a one shot operation which signs a single block of data +in one function. For algorithms that support streaming it is equivalent to +calling EVP_DigestSignUpdate() and EVP_DigestSignFinal(). For algorithms which +do not support streaming (e.g. PureEdDSA) it is the only way to sign data. + In previous versions of OpenSSL there was a link between message digest types and public key algorithms. This meant that "clone" digests such as EVP_dss1() needed to be used to sign using SHA1 and DSA. This is no longer necessary and diff --git a/doc/man3/EVP_DigestVerifyInit.pod b/doc/man3/EVP_DigestVerifyInit.pod new file mode 100644 index 00000000..2191b9ed --- /dev/null +++ b/doc/man3/EVP_DigestVerifyInit.pod @@ -0,0 +1,104 @@ +=pod + +=head1 NAME + +EVP_DigestVerifyInit, EVP_DigestVerifyUpdate, EVP_DigestVerifyFinal, +EVP_DigestVerify - EVP signature verification functions + +=head1 SYNOPSIS + + #include + + int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, + const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey); + int EVP_DigestVerifyUpdate(EVP_MD_CTX *ctx, const void *d, size_t cnt); + int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig, + size_t siglen); + int EVP_DigestVerify(EVP_MD_CTX *ctx, const unsigned char *sigret, + size_t siglen, const unsigned char *tbs, size_t tbslen); + +=head1 DESCRIPTION + +The EVP signature routines are a high level interface to digital signatures. + +EVP_DigestVerifyInit() sets up verification context B to use digest +B from ENGINE B and public key B. B must be created +with EVP_MD_CTX_new() before calling this function. If B is not NULL the +EVP_PKEY_CTX of the verification operation will be written to B<*pctx>: this +can be used to set alternative verification options. + +EVP_DigestVerifyUpdate() hashes B bytes of data at B into the +verification context B. This function can be called several times on the +same B to include additional data. This function is currently implemented +using a macro. + +EVP_DigestVerifyFinal() verifies the data in B against the signature in +B of length B. + +EVP_DigestVerify() verifies B bytes at B against the signature +in B of length B. + +=head1 RETURN VALUES + +EVP_DigestVerifyInit() and EVP_DigestVerifyUpdate() return 1 for success and 0 +for failure. + +EVP_DigestVerifyFinal() and EVP_DigestVerify() return 1 for success; any other +value indicates failure. A return value of zero indicates that the signature +did not verify successfully (that is, B did not match the original data or +the signature had an invalid form), while other values indicate a more serious +error (and sometimes also indicate an invalid signature form). + +The error codes can be obtained from L. + +=head1 NOTES + +The B interface to digital signatures should almost always be used in +preference to the low level interfaces. This is because the code then becomes +transparent to the algorithm used and much more flexible. + +EVP_DigestVerify() is a one shot operation which verifies a single block of +data in one function. For algorithms that support streaming it is equivalent +to calling EVP_DigestVerifyUpdate() and EVP_DigestVerifyFinal(). For +algorithms which do not support streaming (e.g. PureEdDSA) it is the only way +to verify data. + +In previous versions of OpenSSL there was a link between message digest types +and public key algorithms. This meant that "clone" digests such as EVP_dss1() +needed to be used to sign using SHA1 and DSA. This is no longer necessary and +the use of clone digest is now discouraged. + +For some key types and parameters the random number generator must be seeded +or the operation will fail. + +The call to EVP_DigestVerifyFinal() internally finalizes a copy of the digest +context. This means that EVP_VerifyUpdate() and EVP_VerifyFinal() can +be called later to digest and verify additional data. + +Since only a copy of the digest context is ever finalized the context must +be cleaned up after use by calling EVP_MD_CTX_cleanup() or a memory leak +will occur. + +=head1 SEE ALSO + +L, +L, +L, L, L, +L, L, L, +L, L + +=head1 HISTORY + +EVP_DigestVerifyInit(), EVP_DigestVerifyUpdate() and EVP_DigestVerifyFinal() +were first added to OpenSSL 1.0.0. + +=head1 COPYRIGHT + +Copyright 2006-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 +L. + +=cut diff --git a/doc/crypto/EVP_EncodeInit.pod b/doc/man3/EVP_EncodeInit.pod similarity index 98% rename from doc/crypto/EVP_EncodeInit.pod rename to doc/man3/EVP_EncodeInit.pod index d919b14b..8055b100 100644 --- a/doc/crypto/EVP_EncodeInit.pod +++ b/doc/man3/EVP_EncodeInit.pod @@ -24,8 +24,7 @@ EVP_DecodeBlock - EVP base 64 encode/decode routines void EVP_DecodeInit(EVP_ENCODE_CTX *ctx); int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl); - int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned - char *out, int *outl); + int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl); int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n); =head1 DESCRIPTION @@ -148,7 +147,7 @@ EVP_DecodeBlock() returns the length of the data decoded or -1 on error. =head1 SEE ALSO -L +L =head1 COPYRIGHT diff --git a/doc/man3/EVP_EncryptInit.pod b/doc/man3/EVP_EncryptInit.pod new file mode 100644 index 00000000..619a94ec --- /dev/null +++ b/doc/man3/EVP_EncryptInit.pod @@ -0,0 +1,652 @@ +=pod + +=head1 NAME + +EVP_CIPHER_CTX_new, +EVP_CIPHER_CTX_reset, +EVP_CIPHER_CTX_free, +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_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 cipher routines + +=head1 SYNOPSIS + +=for comment generic + + #include + + EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void); + int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *ctx); + void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx); + + int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, + ENGINE *impl, unsigned char *key, 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); + 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); + int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, + int *outl, 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); + 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); + 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); + 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_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key); + + const EVP_CIPHER *EVP_get_cipherbyname(const char *name); + const EVP_CIPHER *EVP_get_cipherbynid(int nid); + const EVP_CIPHER *EVP_get_cipherbyobj(const ASN1_OBJECT *a); + + int EVP_CIPHER_nid(const EVP_CIPHER *e); + int EVP_CIPHER_block_size(const EVP_CIPHER *e); + int EVP_CIPHER_key_length(const EVP_CIPHER *e) + int EVP_CIPHER_key_length(const EVP_CIPHER *e); + int EVP_CIPHER_iv_length(const EVP_CIPHER *e); + unsigned long EVP_CIPHER_flags(const EVP_CIPHER *e); + unsigned long EVP_CIPHER_mode(const EVP_CIPHER *e); + int EVP_CIPHER_type(const EVP_CIPHER *ctx); + + const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx); + int EVP_CIPHER_CTX_nid(const EVP_CIPHER_CTX *ctx); + int EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx); + int EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx); + int EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx); + void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx); + void EVP_CIPHER_CTX_set_app_data(const EVP_CIPHER_CTX *ctx, void *data); + int EVP_CIPHER_CTX_type(const EVP_CIPHER_CTX *ctx); + int EVP_CIPHER_CTX_mode(const EVP_CIPHER_CTX *ctx); + + int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type); + int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type); + +=head1 DESCRIPTION + +The EVP cipher routines are a high level interface to certain +symmetric ciphers. + +EVP_CIPHER_CTX_new() creates a cipher context. + +EVP_CIPHER_CTX_free() clears all information from a cipher context +and free up any allocated memory associate with it, including B +itself. This function should be called after all operations using a +cipher are complete so sensitive information does not remain in +memory. + +EVP_EncryptInit_ex() sets up cipher context B for encryption +with cipher B from ENGINE B. B must be created +before calling this function. B is normally supplied +by a function such as EVP_aes_256_cbc(). If B is NULL then the +default implementation is used. B is the symmetric key to use +and B 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 in an initial call and supply +the remaining parameters in subsequent calls, all of which have B +set to NULL. This is done when the default cipher parameters are not +appropriate. + +EVP_EncryptUpdate() encrypts B bytes from the buffer B and +writes the encrypted version to B. 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 should contain sufficient +room. The actual number of bytes written is placed in B. It also +checks if B and B are partially overlapping, and if they are +0 is returned to indicate failure. + +If padding is enabled (the default) then EVP_EncryptFinal_ex() encrypts +the "final" data, that is any data that remains in a partial block. +It uses standard block padding (aka PKCS padding) as described in +the NOTES section, below. The encrypted +final data is written to B which should have sufficient space for +one cipher block. The number of bytes written is placed in B. 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 +passed to EVP_DecryptUpdate() should have sufficient room for +(B + cipher_block_size) bytes unless the cipher block size is 1 in +which case B 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 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_reset() clears all information from a cipher context +and free up any allocated memory associate with it, except the B +itself. This function should be called anytime B is to be reused +for another EVP_CipherInit() / EVP_CipherUpdate() / EVP_CipherFinal() +series of calls. + +EVP_EncryptInit(), EVP_DecryptInit() and EVP_CipherInit() behave in a +similar way to EVP_EncryptInit_ex(), EVP_DecryptInit_ex() and +EVP_CipherInit_ex() except 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, 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 or B 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. This +function should be called after the context is set up for encryption +or decryption with EVP_EncryptInit_ex(), EVP_DecryptInit_ex() or +EVP_CipherInit_ex(). By default encryption operations are padded using +standard block padding and the padding is checked and removed when +decrypting. If the B 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 or B +structure. The constant B 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 or B. +It will return zero if the cipher does not use an IV. The constant +B 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 or B +structure. The constant B 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. + +EVP_CIPHER_CTX_cipher() returns the B structure when passed +an B 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, EVP_CIPH_OFB_MODE, +EVP_CIPH_CTR_MODE, EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE, EVP_CIPH_XTS_MODE, +EVP_CIPH_WRAP_MODE or EVP_CIPH_OCB_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. + +EVP_CIPHER_CTX_rand_key() generates 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. B must point to a +buffer at least as big as the value returned by EVP_CIPHER_CTX_key_length(). + +=head1 RETURN VALUES + +EVP_CIPHER_CTX_new() returns a pointer to a newly created +B for success and B for failure. + +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_reset() returns 1 for success and 0 for failure. + +EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj() +return an B 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 structure. + +EVP_CIPHER_param_to_asn1() and EVP_CIPHER_asn1_to_param() return greater +than zero for success and zero or a negative number. + +EVP_CIPHER_CTX_rand_key() returns 1 for success. + +=head1 CIPHER LISTING + +All algorithms have a fixed key length unless otherwise stated. + +Refer to L for the full list of ciphers available through the EVP +interface. + +=over 4 + +=item EVP_enc_null() + +Null cipher: does nothing. + +=back + +=head1 AEAD Interface + +The EVP interface for Authenticated Encryption with Associated Data (AEAD) +modes are subtly altered and several additional I operations are supported +depending on the mode specified. + +To specify additional authenticated data (AAD), a call to EVP_CipherUpdate(), +EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made with the output +parameter B set to B. + +When decrypting, the return value of EVP_DecryptFinal() or EVP_CipherFinal() +indicates whether the operation was successful. If it does not indicate success, +the authentication operation has failed and any output data B be used +as it is corrupted. + +=head2 GCM and OCB Modes + +The following Is are supported in GCM and OCB modes. + +=over 4 + +=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL) + +Sets the IV length. This call can only be made before specifying an IV. If +not called a default IV length is used. + +For GCM AES and OCB AES the default is 12 (i.e. 96 bits). For OCB mode the +maximum is 15. + +=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag) + +Writes C bytes of the tag value to the buffer indicated by C. +This call can only be made when encrypting data and B all data has been +processed (e.g. after an EVP_EncryptFinal() call). + +For OCB, C must either be 16 or the value previously set via +B. + +=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag) + +Sets the expected tag to C bytes from C. +The tag length can only be set before specifying an IV. +C must be between 1 and 16 inclusive. + +For GCM, this call is only valid when decrypting data. + +For OCB, this call is valid when decrypting data to set the expected tag, +and before encryption to set the desired tag length. + +In OCB mode, calling this before encryption with C set to C sets the +tag length. If this is not called prior to encryption, a default tag length is +used. + +For OCB AES, the default tag length is 16 (i.e. 128 bits). It is also the +maximum tag length for OCB. + +=back + +=head2 CCM Mode + +The EVP interface for CCM mode is similar to that of the GCM mode but with a +few additional requirements and different I values. + +For CCM mode, the total plaintext or ciphertext length B be passed to +EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() with the output +and input parameters (B and B) set to B and the length passed in +the B parameter. + +The following Is are supported in CCM mode. + +=over 4 + +=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag) + +This call is made to set the expected B tag value when decrypting or +the length of the tag (with the C parameter set to NULL) when encrypting. +The tag length is often referred to as B. If not set a default value is +used (12 for AES). + +=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, ivlen, NULL) + +Sets the CCM B value. If not set a default is used (8 for AES). + +=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL) + +Sets the CCM nonce (IV) length. This call can only be made before specifying an +nonce value. The nonce length is given by B<15 - L> so it is 7 by default for +AES. + +=back + +=head2 ChaCha20-Poly1305 + +The following Is are supported for the ChaCha20-Poly1305 AEAD algorithm. + +=over 4 + +=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL) + +Sets the nonce length. This call can only be made before specifying the nonce. +If not called a default nonce length of 12 (i.e. 96 bits) is used. The maximum +nonce length is 16 (B, i.e. 128-bits). + +=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag) + +Writes C bytes of the tag value to the buffer indicated by C. +This call can only be made when encrypting data and B all data has been +processed (e.g. after an EVP_EncryptFinal() call). + +C specified here must be 16 (B, i.e. 128-bits) or +less. + +=item EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, taglen, tag) + +Sets the expected tag to C bytes from C. +The tag length can only be set before specifying an IV. +C must be between 1 and 16 (B) inclusive. +This call is only valid when decrypting data. + +=back + +=head1 NOTES + +Where possible the B 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 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 padding bytes of value B 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 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. + +EVP_get_cipherbynid(), and EVP_get_cipherbyobj() are implemented as macros. + +=head1 BUGS + +B and B only refer to the internal +ciphers with default key lengths. If custom ciphers exceed these values the +results are unpredictable. This is because it has become standard practice to +define a generic key as a fixed unsigned char array containing +B bytes. + +The ASN1 code is incomplete (and sometimes inaccurate) it has only been tested +for certain common S/MIME ciphers (RC2, DES, triple DES) in CBC mode. + +=head1 EXAMPLES + +Encrypt a string using IDEA: + + int do_crypt(char *outfile) + { + unsigned char outbuf[1024]; + int outlen, tmplen; + /* + * Bogus key and IV: we'd normally set these from + * another source. + */ + unsigned char key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; + unsigned char iv[] = {1,2,3,4,5,6,7,8}; + char intext[] = "Some Crypto Text"; + EVP_CIPHER_CTX *ctx; + FILE *out; + + ctx = EVP_CIPHER_CTX_new(); + EVP_EncryptInit_ex(ctx, EVP_idea_cbc(), NULL, key, iv); + + if (!EVP_EncryptUpdate(ctx, outbuf, &outlen, intext, strlen(intext))) { + /* Error */ + EVP_CIPHER_CTX_free(ctx); + return 0; + } + /* + * Buffer passed to EVP_EncryptFinal() must be after data just + * encrypted to avoid overwriting it. + */ + if (!EVP_EncryptFinal_ex(ctx, outbuf + outlen, &tmplen)) { + /* Error */ + EVP_CIPHER_CTX_free(ctx); + return 0; + } + outlen += tmplen; + EVP_CIPHER_CTX_free(ctx); + /* + * Need binary mode for fopen because encrypted data is + * binary data. Also cannot use strlen() on it because + * it won't be NUL terminated and may contain embedded + * NULs. + */ + out = fopen(outfile, "wb"); + if (out == NULL) { + /* Error */ + return 0; + } + fwrite(outbuf, 1, outlen, out); + fclose(out); + return 1; + } + +The ciphertext from the above example can be decrypted using the B +utility with the command line (shown on two lines for clarity): + + openssl idea -d \ + -K 000102030405060708090A0B0C0D0E0F -iv 0102030405060708 + +Supported ciphers are listed in: + +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L + +=head1 HISTORY + +Support for OCB mode was added in OpenSSL 1.1.0 + +B was made opaque in OpenSSL 1.1.0. As a result, +EVP_CIPHER_CTX_reset() appeared and EVP_CIPHER_CTX_cleanup() +disappeared. EVP_CIPHER_CTX_init() remains as an alias for +EVP_CIPHER_CTX_reset(). + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/crypto/EVP_MD_meth_new.pod b/doc/man3/EVP_MD_meth_new.pod similarity index 99% rename from doc/crypto/EVP_MD_meth_new.pod rename to doc/man3/EVP_MD_meth_new.pod index 4dac6722..0265c7d5 100644 --- a/doc/crypto/EVP_MD_meth_new.pod +++ b/doc/man3/EVP_MD_meth_new.pod @@ -165,7 +165,7 @@ L, L, L =head1 HISTORY The B structure was openly available in OpenSSL before version -1.1.0. The functions described here were added in OpenSSL 1.1.0. +1.1. The functions described here were added in OpenSSL 1.1. =head1 COPYRIGHT diff --git a/doc/crypto/EVP_OpenInit.pod b/doc/man3/EVP_OpenInit.pod similarity index 90% rename from doc/crypto/EVP_OpenInit.pod rename to doc/man3/EVP_OpenInit.pod index ff84490a..61b4307b 100644 --- a/doc/crypto/EVP_OpenInit.pod +++ b/doc/man3/EVP_OpenInit.pod @@ -9,11 +9,10 @@ EVP_OpenInit, EVP_OpenUpdate, EVP_OpenFinal - EVP envelope decryption #include int EVP_OpenInit(EVP_CIPHER_CTX *ctx, EVP_CIPHER *type, unsigned char *ek, - int ekl, unsigned char *iv, EVP_PKEY *priv); + int ekl, unsigned char *iv, EVP_PKEY *priv); int EVP_OpenUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *outl, unsigned char *in, int inl); - int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *outl); + int *outl, unsigned char *in, int inl); + int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); =head1 DESCRIPTION @@ -54,7 +53,7 @@ EVP_OpenFinal() returns 0 if the decrypt failed or 1 for success. =head1 SEE ALSO -L, L, +L, L, L, L diff --git a/doc/crypto/EVP_PKEY_ASN1_METHOD.pod b/doc/man3/EVP_PKEY_ASN1_METHOD.pod similarity index 88% rename from doc/crypto/EVP_PKEY_ASN1_METHOD.pod rename to doc/man3/EVP_PKEY_ASN1_METHOD.pod index 0eece53c..cb03b473 100644 --- a/doc/crypto/EVP_PKEY_ASN1_METHOD.pod +++ b/doc/man3/EVP_PKEY_ASN1_METHOD.pod @@ -14,6 +14,10 @@ EVP_PKEY_asn1_set_param, EVP_PKEY_asn1_set_free, EVP_PKEY_asn1_set_ctrl, EVP_PKEY_asn1_set_item, +EVP_PKEY_asn1_set_siginf, +EVP_PKEY_asn1_set_check, +EVP_PKEY_asn1_set_public_check, +EVP_PKEY_asn1_set_param_check, EVP_PKEY_asn1_set_security_bits, EVP_PKEY_get0_asn1 - manipulating and registering EVP_PKEY_ASN1_METHOD structure @@ -90,6 +94,20 @@ EVP_PKEY_get0_asn1 X509_ALGOR *alg2, ASN1_BIT_STRING *sig)); + void EVP_PKEY_asn1_set_siginf(EVP_PKEY_ASN1_METHOD *ameth, + int (*siginf_set) (X509_SIG_INFO *siginf, + const X509_ALGOR *alg, + const ASN1_STRING *sig)); + + void EVP_PKEY_asn1_set_check(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_check) (const EVP_PKEY *pk)); + + void EVP_PKEY_asn1_set_public_check(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_pub_check) (const EVP_PKEY *pk)); + + void EVP_PKEY_asn1_set_param_check(EVP_PKEY_ASN1_METHOD *ameth, + int (*pkey_param_check) (const EVP_PKEY *pk)); + void EVP_PKEY_asn1_set_security_bits(EVP_PKEY_ASN1_METHOD *ameth, int (*pkey_security_bits) (const EVP_PKEY *pk)); @@ -289,6 +307,26 @@ item_verify() and item_sign() are called by L and L, and by extension, L, L, L, L, ... + int (*siginf_set) (X509_SIG_INFO *siginf, const X509_ALGOR *alg, + const ASN1_STRING *sig); + +The siginf_set() method is used to set custom B +parameters. +It MUST return 0 on error, or 1 on success. +It's called as part of L, L +and L. + + int (*pkey_check) (const EVP_PKEY *pk); + int (*pkey_public_check) (const EVP_PKEY *pk); + int (*pkey_param_check) (const EVP_PKEY *pk); + +The pkey_check(), pkey_public_check() and pkey_param_check() methods are used +to check the validity of B for key-pair, public component and parameters, +respectively. +They MUST return 0 for an invalid key, or 1 for a valid key. +They are called by L, L and +L respectively. + =head2 Functions EVP_PKEY_asn1_new() creates and returns a new B @@ -328,7 +366,9 @@ when initializing the application. EVP_PKEY_asn1_set_public(), EVP_PKEY_asn1_set_private(), EVP_PKEY_asn1_set_param(), EVP_PKEY_asn1_set_free(), -EVP_PKEY_asn1_set_ctrl(), EVP_PKEY_asn1_set_item(), and +EVP_PKEY_asn1_set_ctrl(), EVP_PKEY_asn1_set_item(), +EVP_PKEY_asn1_set_siginf(), EVP_PKEY_asn1_set_check(), +EVP_PKEY_asn1_set_public_check(), EVP_PKEY_asn1_set_param_check() and EVP_PKEY_asn1_set_security_bits() set the diverse methods of the given B object. diff --git a/doc/crypto/EVP_PKEY_CTX_ctrl.pod b/doc/man3/EVP_PKEY_CTX_ctrl.pod similarity index 79% rename from doc/crypto/EVP_PKEY_CTX_ctrl.pod rename to doc/man3/EVP_PKEY_CTX_ctrl.pod index a30450bb..2ad470b5 100644 --- a/doc/crypto/EVP_PKEY_CTX_ctrl.pod +++ b/doc/man3/EVP_PKEY_CTX_ctrl.pod @@ -4,10 +4,11 @@ EVP_PKEY_CTX_ctrl, EVP_PKEY_CTX_ctrl_str, EVP_PKEY_CTX_set_signature_md, EVP_PKEY_CTX_set_rsa_padding, -EVP_PKEY_CTX_set_rsa_pss_saltlen, EVP_PKEY_CTX_set_rsa_rsa_keygen_bits, +EVP_PKEY_CTX_set_rsa_pss_saltlen, EVP_PKEY_CTX_set_rsa_keygen_bits, EVP_PKEY_CTX_set_rsa_keygen_pubexp, EVP_PKEY_CTX_set_dsa_paramgen_bits, EVP_PKEY_CTX_set_dh_paramgen_prime_len, EVP_PKEY_CTX_set_dh_paramgen_generator, +EVP_PKEY_CTX_set_dh_pad, EVP_PKEY_CTX_set_dh_nid, EVP_PKEY_CTX_set_ec_paramgen_curve_nid, EVP_PKEY_CTX_set_ec_param_enc - algorithm specific control operations @@ -16,9 +17,9 @@ EVP_PKEY_CTX_set_ec_param_enc - algorithm specific control operations #include int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype, - int cmd, int p1, void *p2); + int cmd, int p1, void *p2); int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, - const char *value); + const char *value); #include @@ -26,7 +27,7 @@ EVP_PKEY_CTX_set_ec_param_enc - algorithm specific control operations int EVP_PKEY_CTX_set_rsa_padding(EVP_PKEY_CTX *ctx, int pad); int EVP_PKEY_CTX_set_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int len); - int EVP_PKEY_CTX_set_rsa_rsa_keygen_bits(EVP_PKEY_CTX *ctx, int mbits); + int EVP_PKEY_CTX_set_rsa_keygen_bits(EVP_PKEY_CTX *ctx, int mbits); int EVP_PKEY_CTX_set_rsa_keygen_pubexp(EVP_PKEY_CTX *ctx, BIGNUM *pubexp); #include @@ -35,6 +36,8 @@ EVP_PKEY_CTX_set_ec_param_enc - algorithm specific control operations #include int EVP_PKEY_CTX_set_dh_paramgen_prime_len(EVP_PKEY_CTX *ctx, int len); int EVP_PKEY_CTX_set_dh_paramgen_generator(EVP_PKEY_CTX *ctx, int gen); + int EVP_PKEY_CTX_set_dh_pad(EVP_PKEY_CTX *ctx, int pad); + int EVP_PKEY_CTX_set_dh_nid(EVP_PKEY_CTX *ctx, int nid); #include int EVP_PKEY_CTX_set_ec_paramgen_curve_nid(EVP_PKEY_CTX *ctx, int nid); @@ -48,6 +51,9 @@ B is a mask indicating which operations the control can be applied to. The control command is indicated in B and any additional arguments in B and B. +For B = B, B is the length of the MAC key, +and B is MAC key. This is used by Poly1305, SipHash, HMAC and CMAC. + Applications will not normally call EVP_PKEY_CTX_ctrl() directly but will instead call one of the algorithm specific macros below. @@ -82,14 +88,15 @@ if this control is called. If it is not called then the first byte of the plaint buffer is expected to be the algorithm identifier byte. The EVP_PKEY_CTX_set_rsa_pss_saltlen() macro sets the RSA PSS salt length to -B as its name implies it is only supported for PSS padding. Two special -values are supported: -1 sets the salt length to the digest length. When -signing -2 sets the salt length to the maximum permissible value. When -verifying -2 causes the salt length to be automatically determined based on the -B block structure. If this macro is not called a salt length value of -2 -is used by default. +B as its name implies it is only supported for PSS padding. Three special +values are supported: RSA_PSS_SALTLEN_DIGEST sets the salt length to the +digest length, RSA_PSS_SALTLEN_MAX sets the salt length to the maximum +permissible value. When verifying RSA_PSS_SALTLEN_AUTO causes the salt length +to be automatically determined based on the B block structure. If this +macro is not called maximum salt length is used when signing and auto detection +when verifying is used by default. -The EVP_PKEY_CTX_set_rsa_rsa_keygen_bits() macro sets the RSA key length for +The EVP_PKEY_CTX_set_rsa_keygen_bits() macro sets the RSA key length for RSA key generation to B. If not specified 1024 bits is used. The EVP_PKEY_CTX_set_rsa_keygen_pubexp() macro sets the public exponent value @@ -107,6 +114,15 @@ then 1024 is used. The EVP_PKEY_CTX_set_dh_paramgen_generator() macro sets DH generator to B for DH parameter generation. If not specified 2 is used. +The EVP_PKEY_CTX_set_dh_pad() macro sets the DH padding mode. If B is +1 the shared secret is padded with zeroes up to the size of the DH prime B

. +If B is zero (the default) then no padding is performed. + +EVP_PKEY_CTX_set_dh_nid() sets the DH parameters to values corresponding to +B. The B parameter must be B, B, +B, B or B. This macro can be +called during parameter or key generation. + The EVP_PKEY_CTX_set_ec_paramgen_curve_nid() sets the EC curve for EC parameter generation to B. For EC parameter generation this macro must be called or an error occurs because there is no default curve. diff --git a/doc/crypto/EVP_PKEY_CTX_new.pod b/doc/man3/EVP_PKEY_CTX_new.pod similarity index 100% rename from doc/crypto/EVP_PKEY_CTX_new.pod rename to doc/man3/EVP_PKEY_CTX_new.pod diff --git a/doc/man3/EVP_PKEY_CTX_set_hkdf_md.pod b/doc/man3/EVP_PKEY_CTX_set_hkdf_md.pod new file mode 100644 index 00000000..333b8da0 --- /dev/null +++ b/doc/man3/EVP_PKEY_CTX_set_hkdf_md.pod @@ -0,0 +1,166 @@ +=pod + +=head1 NAME + +EVP_PKEY_CTX_set_hkdf_md, EVP_PKEY_CTX_set1_hkdf_salt, +EVP_PKEY_CTX_set1_hkdf_key, EVP_PKEY_CTX_add1_hkdf_info, +EVP_PKEY_CTX_hkdf_mode - +HMAC-based Extract-and-Expand key derivation algorithm + +=head1 SYNOPSIS + + #include + + int EVP_PKEY_CTX_hkdf_mode(EVP_PKEY_CTX *pctx, int mode); + + int EVP_PKEY_CTX_set_hkdf_md(EVP_PKEY_CTX *pctx, const EVP_MD *md); + + int EVP_PKEY_CTX_set1_hkdf_salt(EVP_PKEY_CTX *pctx, unsigned char *salt, + int saltlen); + + int EVP_PKEY_CTX_set1_hkdf_key(EVP_PKEY_CTX *pctx, unsigned char *key, + int keylen); + + int EVP_PKEY_CTX_add1_hkdf_info(EVP_PKEY_CTX *pctx, unsigned char *info, + int infolen); + +=head1 DESCRIPTION + +The EVP_PKEY_HKDF algorithm implements the HKDF key derivation function. +HKDF follows the "extract-then-expand" paradigm, where the KDF logically +consists of two modules. The first stage takes the input keying material +and "extracts" from it a fixed-length pseudorandom key K. The second stage +"expands" the key K into several additional pseudorandom keys (the output +of the KDF). + +EVP_PKEY_CTX_hkdf_mode() sets the mode for the HKDF operation. There are three +modes that are currently defined: + +=over 4 + +=item EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND + +This is the default mode. Calling L on an EVP_PKEY_CTX set +up for HKDF will perform an extract followed by an expand operation in one go. +The derived key returned will be the result after the expand operation. The +intermediate fixed-length pseudorandom key K is not returned. + +In this mode the digest, key, salt and info values must be set before a key is +derived or an error occurs. + +=item EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY + +In this mode calling L will just perform the extract +operation. The value returned will be the intermediate fixed-length pseudorandom +key K. + +The digest, key and salt values must be set before a key is derived or an +error occurs. + +=item EVP_PKEY_HKDEF_MODE_EXPAND_ONLY + +In this mode calling L will just perform the expand +operation. The input key should be set to the intermediate fixed-length +pseudorandom key K returned from a previous extract operation. + +The digest, key and info values must be set before a key is derived or an +error occurs. + +=back + +EVP_PKEY_set_hkdf_md() sets the message digest associated with the HKDF. + +EVP_PKEY_CTX_set1_hkdf_salt() sets the salt to B bytes of the +buffer B. Any existing value is replaced. + +EVP_PKEY_CTX_set_hkdf_key() sets the key to B bytes of the buffer +B. Any existing value is replaced. + +EVP_PKEY_CTX_add1_hkdf_info() sets the info value to B bytes of the +buffer B. If a value is already set, it is appended to the existing +value. + +=head1 STRING CTRLS + +HKDF also supports string based control operations via +L. +The B parameter "md" uses the supplied B as the name of the digest +algorithm to use. +The B parameter "mode" uses the values "EXTRACT_AND_EXPAND", +"EXTRACT_ONLY" and "EXPAND_ONLY" to determine the mode to use. +The B parameters "salt", "key" and "info" use the supplied B +parameter as a B, B or B value. +The names "hexsalt", "hexkey" and "hexinfo" are similar except they take a hex +string which is converted to binary. + +=head1 NOTES + +All these functions are implemented as macros. + +A context for HKDF can be obtained by calling: + + EVP_PKEY_CTX *pctx = EVP_PKEY_new_id(EVP_PKEY_HKDF, NULL); + +The total length of the info buffer cannot exceed 1024 bytes in length: this +should be more than enough for any normal use of HKDF. + +The output length of an HKDF expand operation is specified via the length +parameter to the L function. +Since the HKDF output length is variable, passing a B buffer as a means +to obtain the requisite length is not meaningful with HKDF in any mode that +performs an expand operation. Instead, the caller must allocate a buffer of the +desired length, and pass that buffer to L along with (a +pointer initialized to) the desired length. Passing a B buffer to obtain +the length is allowed when using EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY. + +Optimised versions of HKDF can be implemented in an ENGINE. + +=head1 RETURN VALUES + +All these functions return 1 for success and 0 or a negative value for failure. +In particular a return value of -2 indicates the operation is not supported by +the public key algorithm. + +=head1 EXAMPLE + +This example derives 10 bytes using SHA-256 with the secret key "secret", +salt value "salt" and info value "label": + + EVP_PKEY_CTX *pctx; + unsigned char out[10]; + size_t outlen = sizeof(out); + pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL); + + if (EVP_PKEY_derive_init(pctx) <= 0) + /* Error */ + if (EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()) <= 0) + /* Error */ + if (EVP_PKEY_CTX_set1_hkdf_salt(pctx, "salt", 4) <= 0) + /* Error */ + if (EVP_PKEY_CTX_set1_hkdf_key(pctx, "secret", 6) <= 0) + /* Error */ + if (EVP_PKEY_CTX_add1_hkdf_info(pctx, "label", 5) <= 0) + /* Error */ + if (EVP_PKEY_derive(pctx, out, &outlen) <= 0) + /* Error */ + +=head1 CONFORMING TO + +RFC 5869 + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/crypto/EVP_PKEY_CTX_set_tls1_prf_md.pod b/doc/man3/EVP_PKEY_CTX_set_tls1_prf_md.pod similarity index 95% rename from doc/crypto/EVP_PKEY_CTX_set_tls1_prf_md.pod rename to doc/man3/EVP_PKEY_CTX_set_tls1_prf_md.pod index f1f0ae4f..30e50bc6 100644 --- a/doc/crypto/EVP_PKEY_CTX_set_tls1_prf_md.pod +++ b/doc/man3/EVP_PKEY_CTX_set_tls1_prf_md.pod @@ -50,7 +50,7 @@ All these functions are implemented as macros. A context for the TLS PRF can be obtained by calling: - EVP_PKEY_CTX *pctx = EVP_PKEY_new_id(EVP_PKEY_TLS1_PRF, NULL); + EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL); The digest, secret value and seed must be set before a key is derived or an error occurs. @@ -78,17 +78,18 @@ and seed value "seed": EVP_PKEY_CTX *pctx; unsigned char out[10]; size_t outlen = sizeof(out); + pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL); if (EVP_PKEY_derive_init(pctx) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_set_tls1_prf_md(pctx, EVP_sha256()) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, "secret", 6) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, "seed", 4) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_derive(pctx, out, &outlen) <= 0) - /* Error */ + /* Error */ =head1 SEE ALSO diff --git a/doc/crypto/EVP_PKEY_asn1_get_count.pod b/doc/man3/EVP_PKEY_asn1_get_count.pod similarity index 100% rename from doc/crypto/EVP_PKEY_asn1_get_count.pod rename to doc/man3/EVP_PKEY_asn1_get_count.pod diff --git a/doc/crypto/EVP_PKEY_cmp.pod b/doc/man3/EVP_PKEY_cmp.pod similarity index 100% rename from doc/crypto/EVP_PKEY_cmp.pod rename to doc/man3/EVP_PKEY_cmp.pod diff --git a/doc/crypto/EVP_PKEY_decrypt.pod b/doc/man3/EVP_PKEY_decrypt.pod similarity index 85% rename from doc/crypto/EVP_PKEY_decrypt.pod rename to doc/man3/EVP_PKEY_decrypt.pod index ca732ed0..2a691a61 100644 --- a/doc/crypto/EVP_PKEY_decrypt.pod +++ b/doc/man3/EVP_PKEY_decrypt.pod @@ -10,8 +10,8 @@ EVP_PKEY_decrypt_init, EVP_PKEY_decrypt - decrypt using a public key algorithm int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, - unsigned char *out, size_t *outlen, - const unsigned char *in, size_t inlen); + unsigned char *out, size_t *outlen, + const unsigned char *in, size_t inlen); =head1 DESCRIPTION @@ -49,31 +49,34 @@ Decrypt data using OAEP (for RSA keys): #include EVP_PKEY_CTX *ctx; + ENGINE *eng; unsigned char *out, *in; size_t outlen, inlen; EVP_PKEY *key; - /* NB: assumes key in, inlen are already set up + + /* + * NB: assumes key, eng, in, inlen are already set up * and that key is an RSA private key */ - ctx = EVP_PKEY_CTX_new(key); + ctx = EVP_PKEY_CTX_new(key, eng); if (!ctx) - /* Error occurred */ + /* Error occurred */ if (EVP_PKEY_decrypt_init(ctx) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_OAEP_PADDING) <= 0) - /* Error */ + /* Error */ /* Determine buffer length */ if (EVP_PKEY_decrypt(ctx, NULL, &outlen, in, inlen) <= 0) - /* Error */ + /* Error */ out = OPENSSL_malloc(outlen); if (!out) - /* malloc failure */ + /* malloc failure */ if (EVP_PKEY_decrypt(ctx, out, &outlen, in, inlen) <= 0) - /* Error */ + /* Error */ /* Decrypted data is outlen bytes written to buffer out */ @@ -92,7 +95,7 @@ These functions were first added to OpenSSL 1.0.0. =head1 COPYRIGHT -Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2006-2018 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 diff --git a/doc/crypto/EVP_PKEY_derive.pod b/doc/man3/EVP_PKEY_derive.pod similarity index 89% rename from doc/crypto/EVP_PKEY_derive.pod rename to doc/man3/EVP_PKEY_derive.pod index f70a0b8d..8cd0b547 100644 --- a/doc/crypto/EVP_PKEY_derive.pod +++ b/doc/man3/EVP_PKEY_derive.pod @@ -50,30 +50,31 @@ Derive shared secret (for example DH or EC keys): #include EVP_PKEY_CTX *ctx; + ENGINE *eng; unsigned char *skey; size_t skeylen; EVP_PKEY *pkey, *peerkey; - /* NB: assumes pkey, peerkey have been already set up */ + /* NB: assumes pkey, eng, peerkey have been already set up */ - ctx = EVP_PKEY_CTX_new(pkey); + ctx = EVP_PKEY_CTX_new(pkey, eng); if (!ctx) - /* Error occurred */ + /* Error occurred */ if (EVP_PKEY_derive_init(ctx) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_derive_set_peer(ctx, peerkey) <= 0) - /* Error */ + /* Error */ /* Determine buffer length */ if (EVP_PKEY_derive(ctx, NULL, &skeylen) <= 0) - /* Error */ + /* Error */ skey = OPENSSL_malloc(skeylen); if (!skey) - /* malloc failure */ + /* malloc failure */ if (EVP_PKEY_derive(ctx, skey, &skeylen) <= 0) - /* Error */ + /* Error */ /* Shared secret is skey bytes written to buffer skey */ @@ -92,7 +93,7 @@ These functions were first added to OpenSSL 1.0.0. =head1 COPYRIGHT -Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2006-2018 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 diff --git a/doc/crypto/EVP_PKEY_encrypt.pod b/doc/man3/EVP_PKEY_encrypt.pod similarity index 89% rename from doc/crypto/EVP_PKEY_encrypt.pod rename to doc/man3/EVP_PKEY_encrypt.pod index 01336e12..4e9a34e7 100644 --- a/doc/crypto/EVP_PKEY_encrypt.pod +++ b/doc/man3/EVP_PKEY_encrypt.pod @@ -10,8 +10,8 @@ EVP_PKEY_encrypt_init, EVP_PKEY_encrypt - encrypt using a public key algorithm int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, - unsigned char *out, size_t *outlen, - const unsigned char *in, size_t inlen); + unsigned char *out, size_t *outlen, + const unsigned char *in, size_t inlen); =head1 DESCRIPTION @@ -56,35 +56,37 @@ set 'eng = NULL;' to start with the default OpenSSL RSA implementation: unsigned char *out, *in; size_t outlen, inlen; EVP_PKEY *key; - /* NB: assumes eng, key, in, inlen are already set up, + + /* + * NB: assumes eng, key, in, inlen are already set up, * and that key is an RSA public key */ ctx = EVP_PKEY_CTX_new(key, eng); if (!ctx) - /* Error occurred */ + /* Error occurred */ if (EVP_PKEY_encrypt_init(ctx) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_OAEP_PADDING) <= 0) - /* Error */ + /* Error */ /* Determine buffer length */ if (EVP_PKEY_encrypt(ctx, NULL, &outlen, in, inlen) <= 0) - /* Error */ + /* Error */ out = OPENSSL_malloc(outlen); if (!out) - /* malloc failure */ + /* malloc failure */ if (EVP_PKEY_encrypt(ctx, out, &outlen, in, inlen) <= 0) - /* Error */ + /* Error */ /* Encrypted data is outlen bytes written to buffer out */ =head1 SEE ALSO L, -L, +L, L, L, L, diff --git a/doc/crypto/EVP_PKEY_get_default_digest_nid.pod b/doc/man3/EVP_PKEY_get_default_digest_nid.pod similarity index 100% rename from doc/crypto/EVP_PKEY_get_default_digest_nid.pod rename to doc/man3/EVP_PKEY_get_default_digest_nid.pod diff --git a/doc/man3/EVP_PKEY_keygen.pod b/doc/man3/EVP_PKEY_keygen.pod new file mode 100644 index 00000000..0b86eaaa --- /dev/null +++ b/doc/man3/EVP_PKEY_keygen.pod @@ -0,0 +1,206 @@ +=pod + +=head1 NAME + +EVP_PKEY_keygen_init, EVP_PKEY_keygen, EVP_PKEY_paramgen_init, +EVP_PKEY_paramgen, EVP_PKEY_CTX_set_cb, EVP_PKEY_CTX_get_cb, +EVP_PKEY_CTX_get_keygen_info, EVP_PKEY_CTX_set_app_data, +EVP_PKEY_CTX_get_app_data, +EVP_PKEY_gen_cb, EVP_PKEY_check, EVP_PKEY_public_check, +EVP_PKEY_param_check +- key and parameter generation and check functions + +=head1 SYNOPSIS + + #include + + int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx); + int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey); + int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx); + int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey); + + typedef int EVP_PKEY_gen_cb(EVP_PKEY_CTX *ctx); + + void EVP_PKEY_CTX_set_cb(EVP_PKEY_CTX *ctx, EVP_PKEY_gen_cb *cb); + EVP_PKEY_gen_cb *EVP_PKEY_CTX_get_cb(EVP_PKEY_CTX *ctx); + + int EVP_PKEY_CTX_get_keygen_info(EVP_PKEY_CTX *ctx, int idx); + + void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX *ctx, void *data); + void *EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX *ctx); + + int EVP_PKEY_check(EVP_PKEY_CTX *ctx); + int EVP_PKEY_public_check(EVP_PKEY_CTX *ctx); + int EVP_PKEY_param_check(EVP_PKEY_CTX *ctx); + +=head1 DESCRIPTION + +The EVP_PKEY_keygen_init() function initializes a public key algorithm +context using key B for a key generation operation. + +The EVP_PKEY_keygen() function performs a key generation operation, the +generated key is written to B. + +The functions EVP_PKEY_paramgen_init() and EVP_PKEY_paramgen() are similar +except parameters are generated. + +The function EVP_PKEY_set_cb() sets the key or parameter generation callback +to B. The function EVP_PKEY_CTX_get_cb() returns the key or parameter +generation callback. + +The function EVP_PKEY_CTX_get_keygen_info() returns parameters associated +with the generation operation. If B is -1 the total number of +parameters available is returned. Any non negative value returns the value of +that parameter. EVP_PKEY_CTX_gen_keygen_info() with a non-negative value for +B should only be called within the generation callback. + +If the callback returns 0 then the key generation operation is aborted and an +error occurs. This might occur during a time consuming operation where +a user clicks on a "cancel" button. + +The functions EVP_PKEY_CTX_set_app_data() and EVP_PKEY_CTX_get_app_data() set +and retrieve an opaque pointer. This can be used to set some application +defined value which can be retrieved in the callback: for example a handle +which is used to update a "progress dialog". + +EVP_PKEY_check() validates the key-pair given by B. This function first tries +to use customized key check method in B if it's present; otherwise +it calls a default one defined in B. + +EVP_PKEY_public_check() validates the public component of the key-pair given by B. +This function first tries to use customized key check method in B +if it's present; otherwise it calls a default one defined in B. + +EVP_PKEY_param_check() validates the algorithm parameters of the key-pair given by B. +This function first tries to use customized key check method in B +if it's present; otherwise it calls a default one defined in B. + +=head1 NOTES + +After the call to EVP_PKEY_keygen_init() or EVP_PKEY_paramgen_init() algorithm +specific control operations can be performed to set any appropriate parameters +for the operation. + +The functions EVP_PKEY_keygen() and EVP_PKEY_paramgen() can be called more than +once on the same context if several operations are performed using the same +parameters. + +The meaning of the parameters passed to the callback will depend on the +algorithm and the specific implementation of the algorithm. Some might not +give any useful information at all during key or parameter generation. Others +might not even call the callback. + +The operation performed by key or parameter generation depends on the algorithm +used. In some cases (e.g. EC with a supplied named curve) the "generation" +option merely sets the appropriate fields in an EVP_PKEY structure. + +In OpenSSL an EVP_PKEY structure containing a private key also contains the +public key components and parameters (if any). An OpenSSL private key is +equivalent to what some libraries call a "key pair". A private key can be used +in functions which require the use of a public key or parameters. + +=head1 RETURN VALUES + +EVP_PKEY_keygen_init(), EVP_PKEY_paramgen_init(), EVP_PKEY_keygen() and +EVP_PKEY_paramgen() return 1 for success and 0 or a negative value for failure. +In particular a return value of -2 indicates the operation is not supported by +the public key algorithm. + +EVP_PKEY_check(), EVP_PKEY_public_check() and EVP_PKEY_param_check() return 1 +for success or others for failure. They return -2 if the operation is not supported +for the specific algorithm. + +=head1 EXAMPLES + +Generate a 2048 bit RSA key: + + #include + #include + + EVP_PKEY_CTX *ctx; + EVP_PKEY *pkey = NULL; + + ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL); + if (!ctx) + /* Error occurred */ + if (EVP_PKEY_keygen_init(ctx) <= 0) + /* Error */ + if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048) <= 0) + /* Error */ + + /* Generate key */ + if (EVP_PKEY_keygen(ctx, &pkey) <= 0) + /* Error */ + +Generate a key from a set of parameters: + + #include + #include + + EVP_PKEY_CTX *ctx; + ENGINE *eng; + EVP_PKEY *pkey = NULL, *param; + + /* Assumed param, eng are set up already */ + ctx = EVP_PKEY_CTX_new(param, eng); + if (!ctx) + /* Error occurred */ + if (EVP_PKEY_keygen_init(ctx) <= 0) + /* Error */ + + /* Generate key */ + if (EVP_PKEY_keygen(ctx, &pkey) <= 0) + /* Error */ + +Example of generation callback for OpenSSL public key implementations: + + /* Application data is a BIO to output status to */ + + EVP_PKEY_CTX_set_app_data(ctx, status_bio); + + static int genpkey_cb(EVP_PKEY_CTX *ctx) + { + char c = '*'; + BIO *b = EVP_PKEY_CTX_get_app_data(ctx); + int p = EVP_PKEY_CTX_get_keygen_info(ctx, 0); + + if (p == 0) + c = '.'; + if (p == 1) + c = '+'; + if (p == 2) + c = '*'; + if (p == 3) + c = '\n'; + BIO_write(b, &c, 1); + (void)BIO_flush(b); + return 1; + } + +=head1 SEE ALSO + +L, +L, +L, +L, +L, +L, +L + +=head1 HISTORY + +These functions were first added to OpenSSL 1.0.0. + +EVP_PKEY_check(), EVP_PKEY_public_check() and EVP_PKEY_param_check() were added +in OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2006-2018 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 +L. + +=cut diff --git a/doc/man3/EVP_PKEY_meth_get_count.pod b/doc/man3/EVP_PKEY_meth_get_count.pod new file mode 100644 index 00000000..4d2eab50 --- /dev/null +++ b/doc/man3/EVP_PKEY_meth_get_count.pod @@ -0,0 +1,50 @@ +=pod + +=head1 NAME + +EVP_PKEY_meth_get_count, EVP_PKEY_meth_get0, EVP_PKEY_meth_get0_info - enumerate public key methods + +=head1 SYNOPSIS + + #include + + size_t EVP_PKEY_meth_get_count(void); + const EVP_PKEY_METHOD *EVP_PKEY_meth_get0(size_t idx); + void EVP_PKEY_meth_get0_info(int *ppkey_id, int *pflags, + const EVP_PKEY_METHOD *meth); + +=head1 DESCRIPTION + +EVP_PKEY_meth_count() returns a count of the number of public key methods +available: it includes standard methods and any methods added by the +application. + +EVP_PKEY_meth_get0() returns the public key method B. The value of B +must be between zero and EVP_PKEY_meth_get_count() - 1. + +EVP_PKEY_meth_get0_info() returns the public key ID (a NID) and any flags +associated with the public key method B<*meth>. + +=head1 RETURN VALUES + +EVP_PKEY_meth_count() returns the number of available public key methods. + +EVP_PKEY_meth_get0() return a public key method or B if B is +out of range. + +EVP_PKEY_meth_get0_info() does not return a value. + +=head1 SEE ALSO + +L + +=head1 COPYRIGHT + +Copyright 2002-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 +L. + +=cut diff --git a/doc/man3/EVP_PKEY_meth_new.pod b/doc/man3/EVP_PKEY_meth_new.pod new file mode 100644 index 00000000..918e4fa1 --- /dev/null +++ b/doc/man3/EVP_PKEY_meth_new.pod @@ -0,0 +1,407 @@ +=pod + +=head1 NAME + +EVP_PKEY_meth_new, EVP_PKEY_meth_free, EVP_PKEY_meth_copy, EVP_PKEY_meth_find, +EVP_PKEY_meth_add0, EVP_PKEY_METHOD, +EVP_PKEY_meth_set_init, EVP_PKEY_meth_set_copy, EVP_PKEY_meth_set_cleanup, +EVP_PKEY_meth_set_paramgen, EVP_PKEY_meth_set_keygen, EVP_PKEY_meth_set_sign, +EVP_PKEY_meth_set_verify, EVP_PKEY_meth_set_verify_recover, EVP_PKEY_meth_set_signctx, +EVP_PKEY_meth_set_verifyctx, EVP_PKEY_meth_set_encrypt, EVP_PKEY_meth_set_decrypt, +EVP_PKEY_meth_set_derive, EVP_PKEY_meth_set_ctrl, EVP_PKEY_meth_set_check, +EVP_PKEY_meth_set_public_check, EVP_PKEY_meth_set_param_check, +EVP_PKEY_meth_get_init, EVP_PKEY_meth_get_copy, EVP_PKEY_meth_get_cleanup, +EVP_PKEY_meth_get_paramgen, EVP_PKEY_meth_get_keygen, EVP_PKEY_meth_get_sign, +EVP_PKEY_meth_get_verify, EVP_PKEY_meth_get_verify_recover, EVP_PKEY_meth_get_signctx, +EVP_PKEY_meth_get_verifyctx, EVP_PKEY_meth_get_encrypt, EVP_PKEY_meth_get_decrypt, +EVP_PKEY_meth_get_derive, EVP_PKEY_meth_get_ctrl, EVP_PKEY_meth_get_check, +EVP_PKEY_meth_get_public_check, EVP_PKEY_meth_get_param_check, +EVP_PKEY_meth_remove +- manipulating EVP_PKEY_METHOD structure + +=head1 SYNOPSIS + + #include + + typedef struct evp_pkey_method_st EVP_PKEY_METHOD; + + EVP_PKEY_METHOD *EVP_PKEY_meth_new(int id, int flags); + void EVP_PKEY_meth_free(EVP_PKEY_METHOD *pmeth); + void EVP_PKEY_meth_copy(EVP_PKEY_METHOD *dst, const EVP_PKEY_METHOD *src); + const EVP_PKEY_METHOD *EVP_PKEY_meth_find(int type); + int EVP_PKEY_meth_add0(const EVP_PKEY_METHOD *pmeth); + int EVP_PKEY_meth_remove(const EVP_PKEY_METHOD *pmeth); + + void EVP_PKEY_meth_set_init(EVP_PKEY_METHOD *pmeth, + int (*init) (EVP_PKEY_CTX *ctx)); + void EVP_PKEY_meth_set_copy(EVP_PKEY_METHOD *pmeth, + int (*copy) (EVP_PKEY_CTX *dst, + EVP_PKEY_CTX *src)); + void EVP_PKEY_meth_set_cleanup(EVP_PKEY_METHOD *pmeth, + void (*cleanup) (EVP_PKEY_CTX *ctx)); + void EVP_PKEY_meth_set_paramgen(EVP_PKEY_METHOD *pmeth, + int (*paramgen_init) (EVP_PKEY_CTX *ctx), + int (*paramgen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)); + void EVP_PKEY_meth_set_keygen(EVP_PKEY_METHOD *pmeth, + int (*keygen_init) (EVP_PKEY_CTX *ctx), + int (*keygen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)); + void EVP_PKEY_meth_set_sign(EVP_PKEY_METHOD *pmeth, + int (*sign_init) (EVP_PKEY_CTX *ctx), + int (*sign) (EVP_PKEY_CTX *ctx, + unsigned char *sig, size_t *siglen, + const unsigned char *tbs, + size_t tbslen)); + void EVP_PKEY_meth_set_verify(EVP_PKEY_METHOD *pmeth, + int (*verify_init) (EVP_PKEY_CTX *ctx), + int (*verify) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + size_t siglen, + const unsigned char *tbs, + size_t tbslen)); + void EVP_PKEY_meth_set_verify_recover(EVP_PKEY_METHOD *pmeth, + int (*verify_recover_init) (EVP_PKEY_CTX + *ctx), + int (*verify_recover) (EVP_PKEY_CTX + *ctx, + unsigned char + *sig, + size_t *siglen, + const unsigned + char *tbs, + size_t tbslen)); + void EVP_PKEY_meth_set_signctx(EVP_PKEY_METHOD *pmeth, + int (*signctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (*signctx) (EVP_PKEY_CTX *ctx, + unsigned char *sig, + size_t *siglen, + EVP_MD_CTX *mctx)); + void EVP_PKEY_meth_set_verifyctx(EVP_PKEY_METHOD *pmeth, + int (*verifyctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (*verifyctx) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + int siglen, + EVP_MD_CTX *mctx)); + void EVP_PKEY_meth_set_encrypt(EVP_PKEY_METHOD *pmeth, + int (*encrypt_init) (EVP_PKEY_CTX *ctx), + int (*encryptfn) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)); + void EVP_PKEY_meth_set_decrypt(EVP_PKEY_METHOD *pmeth, + int (*decrypt_init) (EVP_PKEY_CTX *ctx), + int (*decrypt) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)); + void EVP_PKEY_meth_set_derive(EVP_PKEY_METHOD *pmeth, + int (*derive_init) (EVP_PKEY_CTX *ctx), + int (*derive) (EVP_PKEY_CTX *ctx, + unsigned char *key, + size_t *keylen)); + void EVP_PKEY_meth_set_ctrl(EVP_PKEY_METHOD *pmeth, + int (*ctrl) (EVP_PKEY_CTX *ctx, int type, int p1, + void *p2), + int (*ctrl_str) (EVP_PKEY_CTX *ctx, + const char *type, + const char *value)); + void EVP_PKEY_meth_set_check(EVP_PKEY_METHOD *pmeth, + int (*check) (EVP_PKEY *pkey)); + void EVP_PKEY_meth_set_public_check(EVP_PKEY_METHOD *pmeth, + int (*check) (EVP_PKEY *pkey)); + void EVP_PKEY_meth_set_param_check(EVP_PKEY_METHOD *pmeth, + int (*check) (EVP_PKEY *pkey)); + + void EVP_PKEY_meth_get_init(EVP_PKEY_METHOD *pmeth, + int (**pinit) (EVP_PKEY_CTX *ctx)); + void EVP_PKEY_meth_get_copy(EVP_PKEY_METHOD *pmeth, + int (**pcopy) (EVP_PKEY_CTX *dst, + EVP_PKEY_CTX *src)); + void EVP_PKEY_meth_get_cleanup(EVP_PKEY_METHOD *pmeth, + void (**pcleanup) (EVP_PKEY_CTX *ctx)); + void EVP_PKEY_meth_get_paramgen(EVP_PKEY_METHOD *pmeth, + int (**pparamgen_init) (EVP_PKEY_CTX *ctx), + int (**pparamgen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)); + void EVP_PKEY_meth_get_keygen(EVP_PKEY_METHOD *pmeth, + int (**pkeygen_init) (EVP_PKEY_CTX *ctx), + int (**pkeygen) (EVP_PKEY_CTX *ctx, + EVP_PKEY *pkey)); + void EVP_PKEY_meth_get_sign(EVP_PKEY_METHOD *pmeth, + int (**psign_init) (EVP_PKEY_CTX *ctx), + int (**psign) (EVP_PKEY_CTX *ctx, + unsigned char *sig, size_t *siglen, + const unsigned char *tbs, + size_t tbslen)); + void EVP_PKEY_meth_get_verify(EVP_PKEY_METHOD *pmeth, + int (**pverify_init) (EVP_PKEY_CTX *ctx), + int (**pverify) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + size_t siglen, + const unsigned char *tbs, + size_t tbslen)); + void EVP_PKEY_meth_get_verify_recover(EVP_PKEY_METHOD *pmeth, + int (**pverify_recover_init) (EVP_PKEY_CTX + *ctx), + int (**pverify_recover) (EVP_PKEY_CTX + *ctx, + unsigned char + *sig, + size_t *siglen, + const unsigned + char *tbs, + size_t tbslen)); + void EVP_PKEY_meth_get_signctx(EVP_PKEY_METHOD *pmeth, + int (**psignctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (**psignctx) (EVP_PKEY_CTX *ctx, + unsigned char *sig, + size_t *siglen, + EVP_MD_CTX *mctx)); + void EVP_PKEY_meth_get_verifyctx(EVP_PKEY_METHOD *pmeth, + int (**pverifyctx_init) (EVP_PKEY_CTX *ctx, + EVP_MD_CTX *mctx), + int (**pverifyctx) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, + int siglen, + EVP_MD_CTX *mctx)); + void EVP_PKEY_meth_get_encrypt(EVP_PKEY_METHOD *pmeth, + int (**pencrypt_init) (EVP_PKEY_CTX *ctx), + int (**pencryptfn) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)); + void EVP_PKEY_meth_get_decrypt(EVP_PKEY_METHOD *pmeth, + int (**pdecrypt_init) (EVP_PKEY_CTX *ctx), + int (**pdecrypt) (EVP_PKEY_CTX *ctx, + unsigned char *out, + size_t *outlen, + const unsigned char *in, + size_t inlen)); + void EVP_PKEY_meth_get_derive(EVP_PKEY_METHOD *pmeth, + int (**pderive_init) (EVP_PKEY_CTX *ctx), + int (**pderive) (EVP_PKEY_CTX *ctx, + unsigned char *key, + size_t *keylen)); + void EVP_PKEY_meth_get_ctrl(EVP_PKEY_METHOD *pmeth, + int (**pctrl) (EVP_PKEY_CTX *ctx, int type, int p1, + void *p2), + int (**pctrl_str) (EVP_PKEY_CTX *ctx, + const char *type, + const char *value)); + void EVP_PKEY_meth_get_check(EVP_PKEY_METHOD *pmeth, + int (**pcheck) (EVP_PKEY *pkey)); + void EVP_PKEY_meth_get_public_check(EVP_PKEY_METHOD *pmeth, + int (**pcheck) (EVP_PKEY *pkey)); + void EVP_PKEY_meth_get_param_check(EVP_PKEY_METHOD *pmeth, + int (**pcheck) (EVP_PKEY *pkey)); + +=head1 DESCRIPTION + +B is a structure which holds a set of methods for a +specific public key cryptographic algorithm. Those methods are usually +used to perform different jobs, such as generating a key, signing or +verifying, encrypting or decrypting, etc. + +There are two places where the B objects are stored: one +is a built-in static array representing the standard methods for different +algorithms, and the other one is a stack of user-defined application-specific +methods, which can be manipulated by using L. + +The B objects are usually referenced by B +objects. + +=head2 Methods + +The methods are the underlying implementations of a particular public key +algorithm present by the B object. + + int (*init) (EVP_PKEY_CTX *ctx); + int (*copy) (EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src); + void (*cleanup) (EVP_PKEY_CTX *ctx); + +The init() method is called to initialize algorithm-specific data when a new +B is created. As opposed to init(), the cleanup() method is called +when an B is freed. The copy() method is called when an B +is being duplicated. Refer to L, L, +L and L. + + int (*paramgen_init) (EVP_PKEY_CTX *ctx); + int (*paramgen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey); + +The paramgen_init() and paramgen() methods deal with key parameter generation. +They are called by L and L to +handle the parameter generation process. + + int (*keygen_init) (EVP_PKEY_CTX *ctx); + int (*keygen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey); + +The keygen_init() and keygen() methods are used to generate the actual key for +the specified algorithm. They are called by L and +L. + + int (*sign_init) (EVP_PKEY_CTX *ctx); + int (*sign) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, + const unsigned char *tbs, size_t tbslen); + +The sign_init() and sign() methods are used to generate the signature of a +piece of data using a private key. They are called by L +and L. + + int (*verify_init) (EVP_PKEY_CTX *ctx); + int (*verify) (EVP_PKEY_CTX *ctx, + const unsigned char *sig, size_t siglen, + const unsigned char *tbs, size_t tbslen); + +The verify_init() and verify() methods are used to verify whether a signature is +valid. They are called by L and L. + + int (*verify_recover_init) (EVP_PKEY_CTX *ctx); + int (*verify_recover) (EVP_PKEY_CTX *ctx, + unsigned char *rout, size_t *routlen, + const unsigned char *sig, size_t siglen); + +The verify_recover_init() and verify_recover() methods are used to verify a +signature and then recover the digest from the signature (for instance, a +signature that was generated by RSA signing algorithm). They are called by +L and L. + + int (*signctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx); + int (*signctx) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, + EVP_MD_CTX *mctx); + +The signctx_init() and signctx() methods are used to sign a digest present by +a B object. They are called by the EVP_DigestSign functions. See +L for detail. + + int (*verifyctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx); + int (*verifyctx) (EVP_PKEY_CTX *ctx, const unsigned char *sig, int siglen, + EVP_MD_CTX *mctx); + +The verifyctx_init() and verifyctx() methods are used to verify a signature +against the data in a B object. They are called by the various +EVP_DigestVerify functions. See L for detail. + + int (*encrypt_init) (EVP_PKEY_CTX *ctx); + int (*encrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, + const unsigned char *in, size_t inlen); + +The encrypt_init() and encrypt() methods are used to encrypt a piece of data. +They are called by L and L. + + int (*decrypt_init) (EVP_PKEY_CTX *ctx); + int (*decrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, + const unsigned char *in, size_t inlen); + +The decrypt_init() and decrypt() methods are used to decrypt a piece of data. +They are called by L and L. + + int (*derive_init) (EVP_PKEY_CTX *ctx); + int (*derive) (EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen); + +The derive_init() and derive() methods are used to derive the shared secret +from a public key algorithm (for instance, the DH algorithm). They are called by +L and L. + + int (*ctrl) (EVP_PKEY_CTX *ctx, int type, int p1, void *p2); + int (*ctrl_str) (EVP_PKEY_CTX *ctx, const char *type, const char *value); + +The ctrl() and ctrl_str() methods are used to adjust algorithm-specific +settings. See L and related functions for detail. + + int (*digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen, + const unsigned char *tbs, size_t tbslen); + int (*digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig, + size_t siglen, const unsigned char *tbs, + size_t tbslen); + +The digestsign() and digestverify() methods are used to generate or verify +a signature in a one-shot mode. They could be called by L +and L. + + int (*check) (EVP_PKEY *pkey); + int (*public_check) (EVP_PKEY *pkey); + int (*param_check) (EVP_PKEY *pkey); + +The check(), public_check() and param_check() methods are used to validate a +key-pair, the public component and parameters respectively for a given B. +They could be called by L, L and +L respectively. + +=head2 Functions + +EVP_PKEY_meth_new() creates and returns a new B object, +and associates the given B and B. The following flags are +supported: + + EVP_PKEY_FLAG_AUTOARGLEN + EVP_PKEY_FLAG_SIGCTX_CUSTOM + +If an B is set with the B flag, the +maximum size of the output buffer will be automatically calculated or checked +in corresponding EVP methods by the EVP framework. Thus the implementations of +these methods don't need to care about handling the case of returning output +buffer size by themselves. For details on the output buffer size, refer to +L. + +The B is used to indicate the signctx() method +of an B is always called by the EVP framework while doing a +digest signing operation by calling L. + +EVP_PKEY_meth_free() frees an existing B pointed by +B. + +EVP_PKEY_meth_copy() copies an B object from B +to B. + +EVP_PKEY_meth_find() finds an B object with the B. +This function first searches through the user-defined method objects and +then the built-in objects. + +EVP_PKEY_meth_add0() adds B to the user defined stack of methods. + +EVP_PKEY_meth_remove() removes an B object added by +EVP_PKEY_meth_add0(). + +The EVP_PKEY_meth_set functions set the corresponding fields of +B structure with the arguments passed. + +The EVP_PKEY_meth_get functions get the corresponding fields of +B structure to the arguments provided. + +=head1 RETURN VALUES + +EVP_PKEY_meth_new() returns a pointer to a new B +object or returns NULL on error. + +EVP_PKEY_meth_free() and EVP_PKEY_meth_copy() do not return values. + +EVP_PKEY_meth_find() returns a pointer to the found B +object or returns NULL if not found. + +EVP_PKEY_meth_add0() returns 1 if method is added successfully or 0 +if an error occurred. + +EVP_PKEY_meth_remove() returns 1 if method is removed successfully or +0 if an error occurred. + +All EVP_PKEY_meth_set and EVP_PKEY_meth_get functions have no return +values. For the 'get' functions, function pointers are returned by +arguments. + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/crypto/EVP_PKEY_new.pod b/doc/man3/EVP_PKEY_new.pod similarity index 100% rename from doc/crypto/EVP_PKEY_new.pod rename to doc/man3/EVP_PKEY_new.pod diff --git a/doc/crypto/EVP_PKEY_print_private.pod b/doc/man3/EVP_PKEY_print_private.pod similarity index 86% rename from doc/crypto/EVP_PKEY_print_private.pod rename to doc/man3/EVP_PKEY_print_private.pod index 9f1d324f..3ebd086a 100644 --- a/doc/crypto/EVP_PKEY_print_private.pod +++ b/doc/man3/EVP_PKEY_print_private.pod @@ -9,11 +9,11 @@ EVP_PKEY_print_public, EVP_PKEY_print_private, EVP_PKEY_print_params - public ke #include int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey, - int indent, ASN1_PCTX *pctx); + int indent, ASN1_PCTX *pctx); int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey, - int indent, ASN1_PCTX *pctx); + int indent, ASN1_PCTX *pctx); int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey, - int indent, ASN1_PCTX *pctx); + int indent, ASN1_PCTX *pctx); =head1 DESCRIPTION @@ -28,8 +28,7 @@ be used. =head1 NOTES -Currently no public key algorithms include any options in the B parameter -parameter. +Currently no public key algorithms include any options in the B parameter. If the key does not include all the components indicated by the function then only those contained in the key will be printed. For example passing a public @@ -52,7 +51,7 @@ These functions were first added to OpenSSL 1.0.0. =head1 COPYRIGHT -Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2006-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 diff --git a/doc/crypto/EVP_PKEY_set1_RSA.pod b/doc/man3/EVP_PKEY_set1_RSA.pod similarity index 100% rename from doc/crypto/EVP_PKEY_set1_RSA.pod rename to doc/man3/EVP_PKEY_set1_RSA.pod diff --git a/doc/crypto/EVP_PKEY_sign.pod b/doc/man3/EVP_PKEY_sign.pod similarity index 91% rename from doc/crypto/EVP_PKEY_sign.pod rename to doc/man3/EVP_PKEY_sign.pod index 9b3c8d45..bdebf0b9 100644 --- a/doc/crypto/EVP_PKEY_sign.pod +++ b/doc/man3/EVP_PKEY_sign.pod @@ -10,8 +10,8 @@ EVP_PKEY_sign_init, EVP_PKEY_sign - sign using a public key algorithm int EVP_PKEY_sign_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_sign(EVP_PKEY_CTX *ctx, - unsigned char *sig, size_t *siglen, - const unsigned char *tbs, size_t tbslen); + unsigned char *sig, size_t *siglen, + const unsigned char *tbs, size_t tbslen); =head1 DESCRIPTION @@ -66,25 +66,25 @@ Sign data using RSA with PKCS#1 padding and SHA256 digest: */ ctx = EVP_PKEY_CTX_new(signing_key, NULL /* no engine */); if (!ctx) - /* Error occurred */ + /* Error occurred */ if (EVP_PKEY_sign_init(ctx) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha256()) <= 0) - /* Error */ + /* Error */ /* Determine buffer length */ if (EVP_PKEY_sign(ctx, NULL, &siglen, md, mdlen) <= 0) - /* Error */ + /* Error */ sig = OPENSSL_malloc(siglen); if (!sig) - /* malloc failure */ + /* malloc failure */ if (EVP_PKEY_sign(ctx, sig, &siglen, md, mdlen) <= 0) - /* Error */ + /* Error */ /* Signature is siglen bytes written to buffer sig */ diff --git a/doc/crypto/EVP_PKEY_verify.pod b/doc/man3/EVP_PKEY_verify.pod similarity index 82% rename from doc/crypto/EVP_PKEY_verify.pod rename to doc/man3/EVP_PKEY_verify.pod index e84f8804..57d7f8cf 100644 --- a/doc/crypto/EVP_PKEY_verify.pod +++ b/doc/man3/EVP_PKEY_verify.pod @@ -10,8 +10,8 @@ EVP_PKEY_verify_init, EVP_PKEY_verify - signature verification using a public ke int EVP_PKEY_verify_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_verify(EVP_PKEY_CTX *ctx, - const unsigned char *sig, size_t siglen, - const unsigned char *tbs, size_t tbslen); + const unsigned char *sig, size_t siglen, + const unsigned char *tbs, size_t tbslen); =head1 DESCRIPTION @@ -36,7 +36,7 @@ context if several operations are performed using the same parameters. EVP_PKEY_verify_init() and EVP_PKEY_verify() return 1 if the verification was successful and 0 if it failed. Unlike other functions the return value 0 from -EVP_PKEY_verify() only indicates that the signature did not not verify +EVP_PKEY_verify() only indicates that the signature did not verify successfully (that is tbs did not match the original data or the signature was of invalid form) it is not an indication of a more serious error. @@ -55,23 +55,26 @@ Verify signature using PKCS#1 and SHA256 digest: unsigned char *md, *sig; size_t mdlen, siglen; EVP_PKEY *verify_key; - /* NB: assumes verify_key, sig, siglen md and mdlen are already set up + + /* + * NB: assumes verify_key, sig, siglen md and mdlen are already set up * and that verify_key is an RSA public key */ - ctx = EVP_PKEY_CTX_new(verify_key); + ctx = EVP_PKEY_CTX_new(verify_key, NULL /* no engine */); if (!ctx) - /* Error occurred */ + /* Error occurred */ if (EVP_PKEY_verify_init(ctx) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha256()) <= 0) - /* Error */ + /* Error */ /* Perform operation */ ret = EVP_PKEY_verify(ctx, sig, siglen, md, mdlen); - /* ret == 1 indicates success, 0 verify failure and < 0 for some + /* + * ret == 1 indicates success, 0 verify failure and < 0 for some * other error. */ @@ -90,7 +93,7 @@ These functions were first added to OpenSSL 1.0.0. =head1 COPYRIGHT -Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2006-2018 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 diff --git a/doc/crypto/EVP_PKEY_verify_recover.pod b/doc/man3/EVP_PKEY_verify_recover.pod similarity index 86% rename from doc/crypto/EVP_PKEY_verify_recover.pod rename to doc/man3/EVP_PKEY_verify_recover.pod index 837bc64e..85d76f84 100644 --- a/doc/crypto/EVP_PKEY_verify_recover.pod +++ b/doc/man3/EVP_PKEY_verify_recover.pod @@ -10,8 +10,8 @@ EVP_PKEY_verify_recover_init, EVP_PKEY_verify_recover - recover signature using int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX *ctx); int EVP_PKEY_verify_recover(EVP_PKEY_CTX *ctx, - unsigned char *rout, size_t *routlen, - const unsigned char *sig, size_t siglen); + unsigned char *rout, size_t *routlen, + const unsigned char *sig, size_t siglen); =head1 DESCRIPTION @@ -60,30 +60,32 @@ Recover digest originally signed using PKCS#1 and SHA256 digest: unsigned char *rout, *sig; size_t routlen, siglen; EVP_PKEY *verify_key; - /* NB: assumes verify_key, sig and siglen are already set up + + /* + * NB: assumes verify_key, sig and siglen are already set up * and that verify_key is an RSA public key */ - ctx = EVP_PKEY_CTX_new(verify_key); + ctx = EVP_PKEY_CTX_new(verify_key, NULL /* no engine */); if (!ctx) - /* Error occurred */ + /* Error occurred */ if (EVP_PKEY_verify_recover_init(ctx) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0) - /* Error */ + /* Error */ if (EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha256()) <= 0) - /* Error */ + /* Error */ /* Determine buffer length */ if (EVP_PKEY_verify_recover(ctx, NULL, &routlen, sig, siglen) <= 0) - /* Error */ + /* Error */ rout = OPENSSL_malloc(routlen); if (!rout) - /* malloc failure */ + /* malloc failure */ if (EVP_PKEY_verify_recover(ctx, rout, &routlen, sig, siglen) <= 0) - /* Error */ + /* Error */ /* Recovered data is routlen bytes written to buffer rout */ @@ -102,7 +104,7 @@ These functions were first added to OpenSSL 1.0.0. =head1 COPYRIGHT -Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2013-2018 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 diff --git a/doc/crypto/EVP_SealInit.pod b/doc/man3/EVP_SealInit.pod similarity index 95% rename from doc/crypto/EVP_SealInit.pod rename to doc/man3/EVP_SealInit.pod index 30bd6808..29d89c30 100644 --- a/doc/crypto/EVP_SealInit.pod +++ b/doc/man3/EVP_SealInit.pod @@ -12,9 +12,8 @@ EVP_SealInit, EVP_SealUpdate, EVP_SealFinal - EVP envelope encryption unsigned char **ek, int *ekl, unsigned char *iv, EVP_PKEY **pubk, int npubk); int EVP_SealUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *outl, unsigned char *in, int inl); - int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *outl); + int *outl, unsigned char *in, int inl); + int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); =head1 DESCRIPTION @@ -74,7 +73,7 @@ with B set to NULL. =head1 SEE ALSO -L, L, +L, L, L, L diff --git a/doc/crypto/EVP_SignInit.pod b/doc/man3/EVP_SignInit.pod similarity index 84% rename from doc/crypto/EVP_SignInit.pod rename to doc/man3/EVP_SignInit.pod index 21eb868b..987526c4 100644 --- a/doc/crypto/EVP_SignInit.pod +++ b/doc/man3/EVP_SignInit.pod @@ -3,7 +3,8 @@ =head1 NAME EVP_PKEY_size, -EVP_SignInit, EVP_SignInit_ex, EVP_SignUpdate, EVP_SignFinal - EVP signing +EVP_SignInit, EVP_SignInit_ex, EVP_SignUpdate, EVP_SignFinal, +EVP_PKEY_security_bits - EVP signing functions =head1 SYNOPSIS @@ -17,6 +18,7 @@ functions void EVP_SignInit(EVP_MD_CTX *ctx, const EVP_MD *type); int EVP_PKEY_size(EVP_PKEY *pkey); + int EVP_PKEY_security_bits(const EVP_PKEY *pkey); =head1 DESCRIPTION @@ -44,6 +46,9 @@ implementation of digest B. EVP_PKEY_size() returns the maximum size of a signature in bytes. The actual signature returned by EVP_SignFinal() may be smaller. +EVP_PKEY_security_bits() returns the number of security bits of the given B, +bits of security is defined in NIST SP800-57. + =head1 RETURN VALUES EVP_SignInit_ex(), EVP_SignUpdate() and EVP_SignFinal() return 1 @@ -53,12 +58,19 @@ EVP_PKEY_size() returns the maximum size of a signature in bytes. The error codes can be obtained by L. +EVP_PKEY_security_bits() returns the number of security bits. + =head1 NOTES The B interface to digital signatures should almost always be used in preference to the low level interfaces. This is because the code then becomes transparent to the algorithm used and much more flexible. +Due to the link between message digests and public key algorithms the correct +digest algorithm must be used with the correct public key type. A list of +algorithms and associated public key algorithms appears in +L. + When signing with DSA private keys the random number generator must be seeded or the operation will fail. The random number generator does not need to be seeded for RSA signatures. @@ -95,7 +107,7 @@ L, L =head1 COPYRIGHT -Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/crypto/EVP_VerifyInit.pod b/doc/man3/EVP_VerifyInit.pod similarity index 89% rename from doc/crypto/EVP_VerifyInit.pod rename to doc/man3/EVP_VerifyInit.pod index 92146098..ad8a8c01 100644 --- a/doc/crypto/EVP_VerifyInit.pod +++ b/doc/man3/EVP_VerifyInit.pod @@ -12,7 +12,8 @@ EVP_VerifyInit, EVP_VerifyUpdate, EVP_VerifyFinal int EVP_VerifyInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl); int EVP_VerifyUpdate(EVP_MD_CTX *ctx, const void *d, unsigned int cnt); - int EVP_VerifyFinal(EVP_MD_CTX *ctx, unsigned char *sigbuf, unsigned int siglen, EVP_PKEY *pkey); + int EVP_VerifyFinal(EVP_MD_CTX *ctx, unsigned char *sigbuf, unsigned int siglen, + EVP_PKEY *pkey); int EVP_VerifyInit(EVP_MD_CTX *ctx, const EVP_MD *type); @@ -51,6 +52,11 @@ The B interface to digital signatures should almost always be used in preference to the low level interfaces. This is because the code then becomes transparent to the algorithm used and much more flexible. +Due to the link between message digests and public key algorithms the correct +digest algorithm must be used with the correct public key type. A list of +algorithms and associated public key algorithms appears in +L. + The call to EVP_VerifyFinal() internally finalizes a copy of the digest context. This means that calls to EVP_VerifyUpdate() and EVP_VerifyFinal() can be called later to digest and verify additional data. @@ -84,7 +90,7 @@ L, L =head1 COPYRIGHT -Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/man3/EVP_aes.pod b/doc/man3/EVP_aes.pod new file mode 100644 index 00000000..6a893993 --- /dev/null +++ b/doc/man3/EVP_aes.pod @@ -0,0 +1,181 @@ +=pod + +=head1 NAME + +EVP_aes_128_cbc, +EVP_aes_192_cbc, +EVP_aes_256_cbc, +EVP_aes_128_cfb, +EVP_aes_192_cfb, +EVP_aes_256_cfb, +EVP_aes_128_cfb1, +EVP_aes_192_cfb1, +EVP_aes_256_cfb1, +EVP_aes_128_cfb8, +EVP_aes_192_cfb8, +EVP_aes_256_cfb8, +EVP_aes_128_ctr, +EVP_aes_192_ctr, +EVP_aes_256_ctr, +EVP_aes_128_ecb, +EVP_aes_192_ecb, +EVP_aes_256_ecb, +EVP_aes_128_ofb, +EVP_aes_192_ofb, +EVP_aes_256_ofb, +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_aes_128_ccm, +EVP_aes_192_ccm, +EVP_aes_256_ccm, +EVP_aes_128_gcm, +EVP_aes_192_gcm, +EVP_aes_256_gcm, +EVP_aes_128_ocb, +EVP_aes_192_ocb, +EVP_aes_256_ocb, +EVP_aes_128_wrap, +EVP_aes_192_wrap, +EVP_aes_256_wrap, +EVP_aes_128_wrap_pad, +EVP_aes_192_wrap_pad, +EVP_aes_256_wrap_pad, +EVP_aes_128_xts, +EVP_aes_256_xts +- EVP AES cipher + +=head1 SYNOPSIS + +=for comment generic + + #include + + const EVP_CIPHER *EVP_ciphername(void) + +I is used a placeholder for any of the described cipher +functions, such as I. + +=head1 DESCRIPTION + +The AES encryption algorithm for EVP. + +=over 4 + +=item EVP_aes_128_cbc(), +EVP_aes_192_cbc(), +EVP_aes_256_cbc(), +EVP_aes_128_cfb(), +EVP_aes_192_cfb(), +EVP_aes_256_cfb(), +EVP_aes_128_cfb1(), +EVP_aes_192_cfb1(), +EVP_aes_256_cfb1(), +EVP_aes_128_cfb8(), +EVP_aes_192_cfb8(), +EVP_aes_256_cfb8(), +EVP_aes_128_ctr(), +EVP_aes_192_ctr(), +EVP_aes_256_ctr(), +EVP_aes_128_ecb(), +EVP_aes_192_ecb(), +EVP_aes_256_ecb(), +EVP_aes_128_ofb(), +EVP_aes_192_ofb(), +EVP_aes_256_ofb() + +AES for 128, 192 and 256 bit keys in the following modes: CBC, CFB with 128-bit +shift, CFB with 1-bit shift, CFB with 8-bit shift, CTR, ECB, and OFB. + +=item EVP_aes_128_cbc_hmac_sha1(), +EVP_aes_256_cbc_hmac_sha1() + +Authenticated encryption with AES in CBC mode using SHA-1 as HMAC, with keys of +128 and 256 bits length respectively. The authentication tag is 160 bits long. + +WARNING: this is not intended for usage outside of TLS and requires calling of +some undocumented ctrl functions. These ciphers do not conform to the EVP AEAD +interface. + +=item EVP_aes_128_cbc_hmac_sha256(), +EVP_aes_256_cbc_hmac_sha256() + +Authenticated encryption with AES in CBC mode using SHA256 (SHA-2, 256-bits) as +HMAC, with keys of 128 and 256 bits length respectively. The authentication tag +is 256 bits long. + +WARNING: this is not intended for usage outside of TLS and requires calling of +some undocumented ctrl functions. These ciphers do not conform to the EVP AEAD +interface. + +=item EVP_aes_128_ccm(), +EVP_aes_192_ccm(), +EVP_aes_256_ccm(), +EVP_aes_128_gcm(), +EVP_aes_192_gcm(), +EVP_aes_256_gcm(), +EVP_aes_128_ocb(), +EVP_aes_192_ocb(), +EVP_aes_256_ocb() + +AES for 128, 192 and 256 bit keys in CBC-MAC Mode (CCM), Galois Counter Mode +(GCM) and OCB Mode respectively. These ciphers require additional control +operations to function correctly, see the L +section for details. + +=item EVP_aes_128_wrap(), +EVP_aes_192_wrap(), +EVP_aes_256_wrap(), +EVP_aes_128_wrap_pad(), +EVP_aes_128_wrap(), +EVP_aes_192_wrap(), +EVP_aes_256_wrap(), +EVP_aes_192_wrap_pad(), +EVP_aes_128_wrap(), +EVP_aes_192_wrap(), +EVP_aes_256_wrap(), +EVP_aes_256_wrap_pad() + +AES key wrap with 128, 192 and 256 bit keys, as according to RFC 3394 section +2.2.1 ("wrap") and RFC 5649 section 4.1 ("wrap with padding") respectively. + +=item EVP_aes_128_xts(), +EVP_aes_256_xts() + +AES XTS mode (XTS-AES) is standardized in IEEE Std. 1619-2007 and described in NIST +SP 800-38E. The XTS (XEX-based tweaked-codebook mode with ciphertext stealing) +mode was designed by Prof. Phillip Rogaway of University of California, Davis, +intended for encrypting data on a storage device. + +XTS-AES provides confidentiality but not authentication of data. It also +requires a key of double-length for protection of a certain key size. +In particular, XTS-AES-128 (B) takes input of a 256-bit key to +achieve AES 128-bit security, and XTS-AES-256 (B) takes input +of a 512-bit key to achieve AES 256-bit security. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_aria.pod b/doc/man3/EVP_aria.pod new file mode 100644 index 00000000..3b6ad357 --- /dev/null +++ b/doc/man3/EVP_aria.pod @@ -0,0 +1,111 @@ +=pod + +=head1 NAME + +EVP_aria_128_cbc, +EVP_aria_192_cbc, +EVP_aria_256_cbc, +EVP_aria_128_cfb, +EVP_aria_192_cfb, +EVP_aria_256_cfb, +EVP_aria_128_cfb1, +EVP_aria_192_cfb1, +EVP_aria_256_cfb1, +EVP_aria_128_cfb8, +EVP_aria_192_cfb8, +EVP_aria_256_cfb8, +EVP_aria_128_ctr, +EVP_aria_192_ctr, +EVP_aria_256_ctr, +EVP_aria_128_ecb, +EVP_aria_192_ecb, +EVP_aria_256_ecb, +EVP_aria_128_ofb, +EVP_aria_192_ofb, +EVP_aria_256_ofb, +EVP_aria_128_ccm, +EVP_aria_192_ccm, +EVP_aria_256_ccm, +EVP_aria_128_gcm, +EVP_aria_192_gcm, +EVP_aria_256_gcm, +- EVP AES cipher + +=head1 SYNOPSIS + +=for comment generic + + #include + + const EVP_CIPHER *EVP_ciphername(void) + +I is used a placeholder for any of the described cipher +functions, such as I. + +=head1 DESCRIPTION + +The ARIA encryption algorithm for EVP. + +=over 4 + +=item EVP_aria_128_cbc(), +EVP_aria_192_cbc(), +EVP_aria_256_cbc(), +EVP_aria_128_cfb(), +EVP_aria_192_cfb(), +EVP_aria_256_cfb(), +EVP_aria_128_cfb1(), +EVP_aria_192_cfb1(), +EVP_aria_256_cfb1(), +EVP_aria_128_cfb8(), +EVP_aria_192_cfb8(), +EVP_aria_256_cfb8(), +EVP_aria_128_ctr(), +EVP_aria_192_ctr(), +EVP_aria_256_ctr(), +EVP_aria_128_ecb(), +EVP_aria_192_ecb(), +EVP_aria_256_ecb(), +EVP_aria_128_ofb(), +EVP_aria_192_ofb(), +EVP_aria_256_ofb() + +ARIA for 128, 192 and 256 bit keys in the following modes: CBC, CFB with +128-bit shift, CFB with 1-bit shift, CFB with 8-bit shift, CTR, ECB and OFB. + +=item EVP_aria_128_ccm(), +EVP_aria_192_ccm(), +EVP_aria_256_ccm(), +EVP_aria_128_gcm(), +EVP_aria_192_gcm(), +EVP_aria_256_gcm(), + +ARIA for 128, 192 and 256 bit keys in CBC-MAC Mode (CCM) and Galois Counter +Mode (GCM). These ciphers require additional control operations to function +correctly, see the L section for details. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_bf_cbc.pod b/doc/man3/EVP_bf_cbc.pod new file mode 100644 index 00000000..4a9d3a9f --- /dev/null +++ b/doc/man3/EVP_bf_cbc.pod @@ -0,0 +1,59 @@ +=pod + +=head1 NAME + +EVP_bf_cbc, +EVP_bf_cfb, +EVP_bf_ecb, +EVP_bf_ofb +- EVP Blowfish cipher + +=head1 SYNOPSIS + + #include + + const EVP_CIPHER *EVP_bf_cbc(void) + const EVP_CIPHER *EVP_bf_cfb(void) + const EVP_CIPHER *EVP_bf_ecb(void) + const EVP_CIPHER *EVP_bf_ofb(void) + +=head1 DESCRIPTION + +The Blowfish encryption algorithm for EVP. + +This is a variable key length cipher. + +=over 4 + +=item EVP_bf_cbc(), +EVP_bf_cfb(), +EVP_bf_ecb(), +EVP_bf_ofb() + +Blowfish encryption algorithm in CBC, CFB, ECB and OFB modes respectively. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_blake2b512.pod b/doc/man3/EVP_blake2b512.pod new file mode 100644 index 00000000..9b56f3e5 --- /dev/null +++ b/doc/man3/EVP_blake2b512.pod @@ -0,0 +1,65 @@ +=pod + +=head1 NAME + +EVP_blake2b512, +EVP_blake2s256 +- BLAKE2 For EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_blake2b512(void); + const EVP_MD *EVP_blake2s256(void); + +=head1 DESCRIPTION + +BLAKE2 is an improved version of BLAKE, which was submitted to the NIST SHA-3 +algorithm competition. The BLAKE2s and BLAKE2b algorithms are described in +RFC 7693. + +=over 4 + +=item EVP_blake2s256() + +The BLAKE2s algorithm that produces a 256-bit output from a given input. + +=item EVP_blake2b512() + +The BLAKE2b algorithm that produces a 512-bit output from a given input. + +=back + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +RFC 7693. + +=head1 NOTES + +While the BLAKE2b and BLAKE2s algorithms supports a variable length digest, +this implementation outputs a digest of a fixed length (the maximum length +supported), which is 512-bits for BLAKE2b and 256-bits for BLAKE2s. + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_camellia.pod b/doc/man3/EVP_camellia.pod new file mode 100644 index 00000000..75602cf6 --- /dev/null +++ b/doc/man3/EVP_camellia.pod @@ -0,0 +1,94 @@ +=pod + +=head1 NAME + +EVP_camellia_128_cbc, +EVP_camellia_192_cbc, +EVP_camellia_256_cbc, +EVP_camellia_128_cfb, +EVP_camellia_192_cfb, +EVP_camellia_256_cfb, +EVP_camellia_128_cfb1, +EVP_camellia_192_cfb1, +EVP_camellia_256_cfb1, +EVP_camellia_128_cfb8, +EVP_camellia_192_cfb8, +EVP_camellia_256_cfb8, +EVP_camellia_128_ctr, +EVP_camellia_192_ctr, +EVP_camellia_256_ctr, +EVP_camellia_128_ecb, +EVP_camellia_192_ecb, +EVP_camellia_256_ecb, +EVP_camellia_128_ofb, +EVP_camellia_192_ofb, +EVP_camellia_256_ofb +- EVP Camellia cipher + +=head1 SYNOPSIS + +=for comment generic + + #include + + const EVP_CIPHER *EVP_ciphername(void) + +I is used a placeholder for any of the described cipher +functions, such as I. + +=head1 DESCRIPTION + +The Camellia encryption algorithm for EVP. + +=over 4 + +=item EVP_camellia_128_cbc(), +EVP_camellia_192_cbc(), +EVP_camellia_256_cbc(), +EVP_camellia_128_cfb(), +EVP_camellia_192_cfb(), +EVP_camellia_256_cfb(), +EVP_camellia_128_cfb1(), +EVP_camellia_192_cfb1(), +EVP_camellia_256_cfb1(), +EVP_camellia_128_cfb8(), +EVP_camellia_192_cfb8(), +EVP_camellia_256_cfb8(), +EVP_camellia_128_ctr(), +EVP_camellia_192_ctr(), +EVP_camellia_256_ctr(), +EVP_camellia_128_ecb(), +EVP_camellia_192_ecb(), +EVP_camellia_256_ecb(), +EVP_camellia_128_ofb(), +EVP_camellia_192_ofb(), +EVP_camellia_256_ofb() + +Camellia for 128, 192 and 256 bit keys in the following modes: CBC, CFB with +128-bit shift, CFB with 1-bit shift, CFB with 8-bit shift, CTR, ECB and OFB. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_cast5_cbc.pod b/doc/man3/EVP_cast5_cbc.pod new file mode 100644 index 00000000..01c38414 --- /dev/null +++ b/doc/man3/EVP_cast5_cbc.pod @@ -0,0 +1,59 @@ +=pod + +=head1 NAME + +EVP_cast5_cbc, +EVP_cast5_cfb, +EVP_cast5_ecb, +EVP_cast5_ofb +- EVP CAST cipher + +=head1 SYNOPSIS + + #include + + const EVP_CIPHER *EVP_cast5_cbc(void) + const EVP_CIPHER *EVP_cast5_cfb(void) + const EVP_CIPHER *EVP_cast5_ecb(void) + const EVP_CIPHER *EVP_cast5_ofb(void) + +=head1 DESCRIPTION + +The CAST encryption algorithm for EVP. + +This is a variable key length cipher. + +=over 4 + +=item EVP_cast5_cbc(), +EVP_cast5_ecb(), +EVP_cast5_cfb(), +EVP_cast5_ofb() + +CAST encryption algorithm in CBC, ECB, CFB and OFB modes respectively. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_chacha20.pod b/doc/man3/EVP_chacha20.pod new file mode 100644 index 00000000..96da825c --- /dev/null +++ b/doc/man3/EVP_chacha20.pod @@ -0,0 +1,57 @@ +=pod + +=head1 NAME + +EVP_chacha20, +EVP_chacha20_poly1305 +- EVP ChaCha20 stream cipher + +=head1 SYNOPSIS + + #include + + const EVP_CIPHER *EVP_chacha20(void) + const EVP_CIPHER *EVP_chacha20_poly1305(void) + +=head1 DESCRIPTION + +The ChaCha20 stream cipher for EVP. + +=over 4 + +=item EVP_chacha20() + +The ChaCha20 stream cipher. The key length is 256 bits, the IV is 96 bits long. + +=item EVP_chacha20_poly1305() + +Authenticated encryption with ChaCha20-Poly1305. Like EVP_chacha20(), the key +is 256 bits and the IV is 96 bits. This supports additional authenticated data +(AAD) and produces a 128-bit authentication tag. See the +L section for more information. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_des.pod b/doc/man3/EVP_des.pod new file mode 100644 index 00000000..836c399c --- /dev/null +++ b/doc/man3/EVP_des.pod @@ -0,0 +1,96 @@ +=pod + +=head1 NAME + +EVP_des_cbc, +EVP_des_cfb, +EVP_des_cfb1, +EVP_des_cfb8, +EVP_des_ecb, +EVP_des_ede, +EVP_des_ede_cfb, +EVP_des_ede_ofb, +EVP_des_ofb, +EVP_des_ede3, +EVP_des_ede3_cbc, +EVP_des_ede3_cfb, +EVP_des_ede3_cfb1, +EVP_des_ede3_cfb8, +EVP_des_ede3_ofb, +EVP_des_ede3_wrap, +EVP_des_ede_cbc +- EVP DES cipher + +=head1 SYNOPSIS + +=for comment generic + + #include + + const EVP_CIPHER *EVP_ciphername(void) + +I is used a placeholder for any of the described cipher +functions, such as I. + +=head1 DESCRIPTION + +The DES encryption algorithm for EVP. + +=over 4 + +=item EVP_des_cbc(), +EVP_des_ecb(), +EVP_des_cfb(), +EVP_des_cfb1(), +EVP_des_cfb8(), +EVP_des_ofb() + +DES in CBC, ECB, CFB with 128-bit shift, CFB with 1-bit shift, CFB with 8-bit +shift and OFB modes respectively. + +=item EVP_des_ede(), +EVP_des_ede_cbc(), +EVP_des_ede_ofb(), +EVP_des_ede_cfb() + +Two key triple DES in ECB, CBC, CFB and OFB modes respectively. + +=item EVP_des_ede3(), +EVP_des_ede3_cbc(), +EVP_des_ede3_cfb(), +EVP_des_ede3_cfb1(), +EVP_des_ede3_cfb8(), +EVP_des_ede3_ofb() + +Three-key triple DES in ECB, CBC, CFB with 128-bit shift, CFB with 1-bit shift, +CFB with 8-bit shift and OFB modes respectively. + +=item EVP_des_ede3_wrap() + +Triple-DES key wrap according to RFC 3217 Section 3. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_desx_cbc.pod b/doc/man3/EVP_desx_cbc.pod new file mode 100644 index 00000000..321378e1 --- /dev/null +++ b/doc/man3/EVP_desx_cbc.pod @@ -0,0 +1,50 @@ +=pod + +=head1 NAME + +EVP_desx_cbc +- EVP DES-X cipher + +=head1 SYNOPSIS + + #include + + const EVP_CIPHER *EVP_desx_cbc(void) + +=head1 DESCRIPTION + +The DES-X encryption algorithm for EVP. + +All modes below use a key length of 128 bits and acts on blocks of 128-bits. + +=over 4 + +=item EVP_desx_cbc() + +The DES-X algorithm in CBC mode. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_idea_cbc.pod b/doc/man3/EVP_idea_cbc.pod new file mode 100644 index 00000000..ace79885 --- /dev/null +++ b/doc/man3/EVP_idea_cbc.pod @@ -0,0 +1,57 @@ +=pod + +=head1 NAME + +EVP_idea_cbc, +EVP_idea_cfb, +EVP_idea_ecb, +EVP_idea_ofb +- EVP IDEA cipher + +=head1 SYNOPSIS + + #include + + const EVP_CIPHER *EVP_idea_cbc(void) + const EVP_CIPHER *EVP_idea_cfb(void) + const EVP_CIPHER *EVP_idea_ecb(void) + const EVP_CIPHER *EVP_idea_ofb(void) + +=head1 DESCRIPTION + +The IDEA encryption algorithm for EVP. + +=over 4 + +=item EVP_idea_cbc(), +EVP_idea_cfb(), +EVP_idea_ecb(), +EVP_idea_ofb() + +The IDEA encryption algorithm in CBC, CFB, ECB and OFB modes respectively. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_md2.pod b/doc/man3/EVP_md2.pod new file mode 100644 index 00000000..c66fb6f8 --- /dev/null +++ b/doc/man3/EVP_md2.pod @@ -0,0 +1,53 @@ +=pod + +=head1 NAME + +EVP_md2 +- MD2 For EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_md2(void); + +=head1 DESCRIPTION + +MD2 is a cryptographic hash function standardized in RFC 1319 and designed by +Ronald Rivest. + +=over 4 + +=item EVP_md2() + +The MD2 algorithm which produces a 128-bit output from a given input. + +=back + + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +IETF RFC 1319. + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_md4.pod b/doc/man3/EVP_md4.pod new file mode 100644 index 00000000..778ed028 --- /dev/null +++ b/doc/man3/EVP_md4.pod @@ -0,0 +1,53 @@ +=pod + +=head1 NAME + +EVP_md4 +- MD4 For EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_md4(void); + +=head1 DESCRIPTION + +MD4 is a cryptographic hash function standardized in RFC 1320 and designed by +Ronald Rivest, first published in 1990. + +=over 4 + +=item EVP_md4() + +The MD4 algorithm which produces a 128-bit output from a given input. + +=back + + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +IETF RFC 1320. + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_md5.pod b/doc/man3/EVP_md5.pod new file mode 100644 index 00000000..1048c0fd --- /dev/null +++ b/doc/man3/EVP_md5.pod @@ -0,0 +1,63 @@ +=pod + +=head1 NAME + +EVP_md5 +- MD5 For EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_md5(void); + +=head1 DESCRIPTION + +MD5 is a cryptographic hash function standardized in RFC 1321 and designed by +Ronald Rivest. + +The CMU Software Engieneering Institute considers MD5 unsuitable for further +use since its security has been severely compromised. + +=over 4 + +=item EVP_md5() + +The MD5 algorithm which produces a 128-bit output from a given input. + +=item EVP_md5_sha1() + +A hash algorithm of SSL v3 that combines MD5 with SHA-1 as decirbed in RFC +6101. + +WARNING: this algorithm is not intended for non-SSL usage. + +=back + + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +IETF RFC 1321. + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_mdc2.pod b/doc/man3/EVP_mdc2.pod new file mode 100644 index 00000000..13ff9cfb --- /dev/null +++ b/doc/man3/EVP_mdc2.pod @@ -0,0 +1,53 @@ +=pod + +=head1 NAME + +EVP_mdc2 +- MDC-2 For EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_mdc2(void); + +=head1 DESCRIPTION + +MDC-2 (Modification Detection Code 2 or Meyer-Schilling) is a cryptographic +hash function based on a block cipher. + +=over 4 + +=item EVP_mdc2() + +The MDC-2DES algorithm of using MDC-2 with the DES block cipher. It produces a +128-bit output from a given input. + +=back + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +ISO/IEC 10118-2:2000 Hash-Function 2, with DES as the underlying block cipher. + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_rc2_cbc.pod b/doc/man3/EVP_rc2_cbc.pod new file mode 100644 index 00000000..0958e930 --- /dev/null +++ b/doc/man3/EVP_rc2_cbc.pod @@ -0,0 +1,73 @@ +=pod + +=head1 NAME + +EVP_rc2_cbc, +EVP_rc2_cfb, +EVP_rc2_ecb, +EVP_rc2_ofb, +EVP_rc2_40_cbc, +EVP_rc2_64_cbc +- EVP RC2 cipher + +=head1 SYNOPSIS + + #include + + const EVP_CIPHER *EVP_rc2_cbc(void) + const EVP_CIPHER *EVP_rc2_cfb(void) + const EVP_CIPHER *EVP_rc2_ecb(void) + const EVP_CIPHER *EVP_rc2_ofb(void) + const EVP_CIPHER *EVP_rc2_40_cbc(void) + const EVP_CIPHER *EVP_rc2_64_cbc(void) + +=head1 DESCRIPTION + +The RC2 encryption algorithm for EVP. + +=over 4 + +=item EVP_rc2_cbc(), +EVP_rc2_cfb(), +EVP_rc2_ecb(), +EVP_rc2_ofb() + +RC2 encryption algorithm in CBC, CFB, ECB 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(), +EVP_rc2_64_cbc() + +RC2 algorithm in CBC mode with a default key length and effective key length of +40 and 64 bits. + +WARNING: these functions are obsolete. Their usage should be replaced with the +EVP_rc2_cbc(), EVP_CIPHER_CTX_set_key_length() and EVP_CIPHER_CTX_ctrl() +functions to set the key length and effective key length. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_rc4.pod b/doc/man3/EVP_rc4.pod new file mode 100644 index 00000000..7d642efd --- /dev/null +++ b/doc/man3/EVP_rc4.pod @@ -0,0 +1,68 @@ +=pod + +=head1 NAME + +EVP_rc4, +EVP_rc4_40, +EVP_rc4_hmac_md5 +- EVP RC4 stream cipher + +=head1 SYNOPSIS + + #include + + const EVP_CIPHER *EVP_rc4(void) + const EVP_CIPHER *EVP_rc4_40(void) + const EVP_CIPHER *EVP_rc4_hmac_md5(void) + +=head1 DESCRIPTION + +The RC4 stream cipher for EVP. + +=over 4 + +=item EVP_rc4() + +RC4 stream cipher. This is a variable key length cipher with a default key +length of 128 bits. + +=item EVP_rc4_40() + +RC4 stream cipher with 40 bit key length. + +WARNING: this function is obsolete. Its usage should be replaced with the +EVP_rc4() and the EVP_CIPHER_CTX_set_key_length() functions. + +=item EVP_rc4_hmac_md5() + +Authenticated encryption with the RC4 stream cipher with MD5 as HMAC. + +WARNING: this is not intended for usage outside of TLS and requires calling of +some undocumented ctrl functions. These ciphers do not conform to the EVP AEAD +interface. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_rc5_32_12_16_cbc.pod b/doc/man3/EVP_rc5_32_12_16_cbc.pod new file mode 100644 index 00000000..56175e99 --- /dev/null +++ b/doc/man3/EVP_rc5_32_12_16_cbc.pod @@ -0,0 +1,64 @@ +=pod + +=head1 NAME + +EVP_rc5_32_12_16_cbc, +EVP_rc5_32_12_16_cfb, +EVP_rc5_32_12_16_ecb, +EVP_rc5_32_12_16_ofb +- EVP RC5 cipher + +=head1 SYNOPSIS + + #include + + const EVP_CIPHER *EVP_rc5_32_12_16_cbc(void) + const EVP_CIPHER *EVP_rc5_32_12_16_cfb(void) + const EVP_CIPHER *EVP_rc5_32_12_16_ecb(void) + const EVP_CIPHER *EVP_rc5_32_12_16_ofb(void) + +=head1 DESCRIPTION + +The RC5 encryption algorithm for EVP. + +=over 4 + +=item EVP_rc5_32_12_16_cbc(), +EVP_rc5_32_12_16_cfb(), +EVP_rc5_32_12_16_ecb(), +EVP_rc5_32_12_16_ofb() + +RC5 encryption algorithm in CBC, CFB, ECB 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. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 BUGS + +Currently the number of rounds in RC5 can only be set to 8, 12 or 16. +This is a limitation of the current RC5 code rather than the EVP interface. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_ripemd160.pod b/doc/man3/EVP_ripemd160.pod new file mode 100644 index 00000000..bbb2dd95 --- /dev/null +++ b/doc/man3/EVP_ripemd160.pod @@ -0,0 +1,52 @@ +=pod + +=head1 NAME + +EVP_ripemd160 +- RIPEMD160 For EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_ripemd160(void); + +=head1 DESCRIPTION + +RIPEMD-160 is a cryptographic hash function first published in 1996 belonging +to the RIPEMD family (RACE Integrity Primitives Evaluation Message Digest). + +=over 4 + +=item EVP_ripemd160() + +The RIPEMD-160 algorithm which produces a 160-bit output from a given input. + +=back + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +ISO/IEC 10118-3:2016 Dedicated Hash-Function 1 (RIPEMD-160). + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_seed_cbc.pod b/doc/man3/EVP_seed_cbc.pod new file mode 100644 index 00000000..e9f1f695 --- /dev/null +++ b/doc/man3/EVP_seed_cbc.pod @@ -0,0 +1,59 @@ +=pod + +=head1 NAME + +EVP_seed_cbc, +EVP_seed_cfb, +EVP_seed_ecb, +EVP_seed_ofb +- EVP SEED cipher + +=head1 SYNOPSIS + + #include + + const EVP_CIPHER *EVP_seed_cbc(void) + const EVP_CIPHER *EVP_seed_cfb(void) + const EVP_CIPHER *EVP_seed_ecb(void) + const EVP_CIPHER *EVP_seed_ofb(void) + +=head1 DESCRIPTION + +The SEED encryption algorithm for EVP. + +All modes below use a key length of 128 bits and acts on blocks of 128-bits. + +=over 4 + +=item EVP_seed_cbc(), +EVP_seed_cfb(), +EVP_seed_ecb(), +EVP_seed_ofb() + +The SEED encryption algorithm in CBC, CFB, ECB and OFB modes respectively. + +=back + +=head1 RETURN VALUES + +These functions return an B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_sha1.pod b/doc/man3/EVP_sha1.pod new file mode 100644 index 00000000..93ba6441 --- /dev/null +++ b/doc/man3/EVP_sha1.pod @@ -0,0 +1,54 @@ +=pod + +=head1 NAME + +EVP_sha1 +- SHA-1 For EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_sha1(void); + +=head1 DESCRIPTION + +SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function standardized +in NIST FIPS 180-4. The algorithm was designed by the United States National +Security Agency and initially published in 1995. + +=over 4 + +=item EVP_sha1() + +The SHA-1 algorithm which produces a 160-bit output from a given input. + +=back + + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +NIST FIPS 180-4. + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_sha224.pod b/doc/man3/EVP_sha224.pod new file mode 100644 index 00000000..2de20bb1 --- /dev/null +++ b/doc/man3/EVP_sha224.pod @@ -0,0 +1,74 @@ +=pod + +=head1 NAME + +EVP_sha224, +EVP_sha256, +EVP_sha512_224, +EVP_sha512_256, +EVP_sha384, +EVP_sha512 +- SHA-2 For EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_sha224(void); + const EVP_MD *EVP_sha256(void); + const EVP_MD *EVP_sha512_224(void); + const EVP_MD *EVP_sha512_256(void); + const EVP_MD *EVP_sha384(void); + const EVP_MD *EVP_sha512(void); + +=head1 DESCRIPTION + +SHA-2 (Secure Hash Algorithm 2) is a family of cryptographic hash functions +standardized in NIST FIPS 180-4, first published in 2001. + +=over 4 + +=item EVP_sha224(), +EVP_sha256(), +EVP_sha512_224, +EVP_sha512_256, +EVP_sha384(), +EVP_sha512() + +The SHA-2 SHA-224, SHA-256, SHA-512/224, SHA512/256, SHA-384 and SHA-512 +algorithms, which generate 224, 256, 224, 256, 384 and 512 bits +respectively of output from a given input. + +The two algorithms: SHA-512/224 and SHA512/256 are truncated forms of the +SHA-512 algorithm. They are distinct from SHA-224 and SHA-256 even though +their outputs are of the same size. + +=back + + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +NIST FIPS 180-4. + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +Copyright 2017-2018 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 +L. + +=cut + diff --git a/doc/man3/EVP_sha3_224.pod b/doc/man3/EVP_sha3_224.pod new file mode 100644 index 00000000..c7bccc9f --- /dev/null +++ b/doc/man3/EVP_sha3_224.pod @@ -0,0 +1,79 @@ +=pod + +=head1 NAME + +EVP_sha3_224, +EVP_sha3_256, +EVP_sha3_384, +EVP_sha3_512, +EVP_shake128, +EVP_shake256 +- SHA-3 For EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_sha3_224(void); + const EVP_MD *EVP_sha3_256(void); + const EVP_MD *EVP_sha3_384(void); + const EVP_MD *EVP_sha3_512(void); + + const EVP_MD *EVP_shake128(void); + const EVP_MD *EVP_shake256(void); + +=head1 DESCRIPTION + +SHA-3 (Secure Hash Algorithm 3) is a family of cryptographic hash functions +standardized in NIST FIPS 202, first published in 2015. It is based on the +Keccak algorithm. + +=over 4 + +=item EVP_sha3_224(), +EVP_sha3_256(), +EVP_sha3_384(), +EVP_sha3_512() + +The SHA-3 SHA-3-224, SHA-3-256, SHA-3-384, and SHA-3-512 algorithms +respectively. They produce 224, 256, 384 and 512 bits of output from a given +input. + +=item EVP_shake128(), +EVP_shake256() + +The SHAKE-128 and SHAKE-256 Extendable Output Functions (XOF) that can generate +a variable hash length. + +Specifically, B provides an overall security of 128 bits, while +B provides that of 256 bits. + +=back + + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +NIST FIPS 202. + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/man3/EVP_sm3.pod b/doc/man3/EVP_sm3.pod new file mode 100644 index 00000000..a68fe667 --- /dev/null +++ b/doc/man3/EVP_sm3.pod @@ -0,0 +1,54 @@ +=pod + +=head1 NAME + +EVP_sm3 +- SM3 for EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_sm3(void) + +=head1 DESCRIPTION + +SM3 is a cryptographic hash function with a 256-bit output, defined in GB/T +32905-2016. + +=over 4 + +=item EVP_sm3() + +The SM3 hash function. + +=back + + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +GB/T 32905-2016 and GM/T 0004-2012. + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2017 Ribose Inc. 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 +L. + +=cut + diff --git a/doc/man3/EVP_sm4_cbc.pod b/doc/man3/EVP_sm4_cbc.pod new file mode 100644 index 00000000..38abfada --- /dev/null +++ b/doc/man3/EVP_sm4_cbc.pod @@ -0,0 +1,64 @@ +=pod + +=head1 NAME + +EVP_sm4_cbc, +EVP_sm4_ecb, +EVP_sm4_cfb, +EVP_sm4_ofb, +EVP_sm4_ctr +- EVP SM4 cipher + +=head1 SYNOPSIS + + #include + + const EVP_CIPHER *EVP_sm4_cbc(void) + const EVP_CIPHER *EVP_sm4_ecb(void) + const EVP_CIPHER *EVP_sm4_cfb(void) + const EVP_CIPHER *EVP_sm4_ofb(void) + const EVP_CIPHER *EVP_sm4_ctr(void) + +=head1 DESCRIPTION + +The SM4 blockcipher (GB/T 32907-2016) for EVP. + +All modes below use a key length of 128 bits and acts on blocks of 128 bits. + +=over 4 + +=item EVP_sm4_cbc(), +EVP_sm4_ecb(), +EVP_sm4_cfb(), +EVP_sm4_ofb(), +EVP_sm4_ctr() + +The SM4 blockcipher with a 128-bit key in CBC, ECB, CFB, OFB and CTR modes +respectively. + +=back + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +Copyright 2017 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2017 Ribose Inc. 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 +L. + +=cut + diff --git a/doc/man3/EVP_whirlpool.pod b/doc/man3/EVP_whirlpool.pod new file mode 100644 index 00000000..bf60b126 --- /dev/null +++ b/doc/man3/EVP_whirlpool.pod @@ -0,0 +1,54 @@ +=pod + +=head1 NAME + +EVP_whirlpool +- WHIRLPOOL For EVP + +=head1 SYNOPSIS + + #include + + const EVP_MD *EVP_whirlpool(void); + +=head1 DESCRIPTION + +WHIRLPOOL is a cryptographic hash function standardized in ISO/IEC 10118-3:2004 +designed by Vincent Rijmen and Paulo S. L. M. Barreto. + +=over 4 + +=item EVP_whirlpool() + +The WHIRLPOOL algorithm that produces a message digest of 512-bits from a given +input. + +=back + + +=head1 RETURN VALUES + +These functions return a B structure that contains the +implementation of the symmetric cipher. See L for +details of the B structure. + +=head1 CONFORMING TO + +ISO/IEC 10118-3:2004. + +=head1 SEE ALSO + +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut + diff --git a/doc/crypto/HMAC.pod b/doc/man3/HMAC.pod similarity index 81% rename from doc/crypto/HMAC.pod rename to doc/man3/HMAC.pod index 219c9ba2..c480a9c9 100644 --- a/doc/crypto/HMAC.pod +++ b/doc/man3/HMAC.pod @@ -12,7 +12,8 @@ HMAC_Update, HMAC_Final, HMAC_CTX_copy, HMAC_CTX_set_flags, -HMAC_CTX_get_md +HMAC_CTX_get_md, +HMAC_size - HMAC message authentication code =head1 SYNOPSIS @@ -20,14 +21,14 @@ HMAC_CTX_get_md #include unsigned char *HMAC(const EVP_MD *evp_md, const void *key, - int key_len, const unsigned char *d, int n, - unsigned char *md, unsigned int *md_len); + int key_len, const unsigned char *d, int n, + unsigned char *md, unsigned int *md_len); HMAC_CTX *HMAC_CTX_new(void); int HMAC_CTX_reset(HMAC_CTX *ctx); int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int key_len, - const EVP_MD *md, ENGINE *impl); + const EVP_MD *md, ENGINE *impl); int HMAC_Update(HMAC_CTX *ctx, const unsigned char *data, int len); int HMAC_Final(HMAC_CTX *ctx, unsigned char *md, unsigned int *len); @@ -37,6 +38,8 @@ HMAC_CTX_get_md void HMAC_CTX_set_flags(HMAC_CTX *ctx, unsigned long flags); const EVP_MD *HMAC_CTX_get_md(const HMAC_CTX *ctx); + size_t HMAC_size(const HMAC_CTX *e); + Deprecated: #if OPENSSL_API_COMPAT < 0x10100000L @@ -75,23 +78,21 @@ itself. The following functions may be used if the message is not completely stored in memory: -HMAC_Init() initializes a B structure to use the hash -function B and the key B which is B bytes -long. It is deprecated and only included for backward compatibility -with OpenSSL 0.9.6b. - HMAC_Init_ex() initializes or reuses a B structure to use the hash -function B and key B. If both are NULL (or B is the same -as the previous digest used by B and B is NULL) the existing key is +function B and key B. If both are NULL, or if B is NULL +and B is the same as the previous call, then the +existing key is reused. B must have been created with HMAC_CTX_new() before the first use -of an B in this function. B. +of an B in this function. -B If HMAC_Init_ex() is called with B NULL and B is not the +If HMAC_Init_ex() is called with B NULL and B is not the same as the previous digest used by B then an error is returned because reuse of an existing key with a different digest is not supported. +HMAC_Init() initializes a B structure to use the hash +function B and the key B which is B bytes +long. + HMAC_Update() can be called repeatedly with chunks of the message to be authenticated (B bytes at B). @@ -106,6 +107,8 @@ These flags have the same meaning as for L. HMAC_CTX_get_md() returns the EVP_MD that has previously been set for the supplied HMAC_CTX. +HMAC_size() returns the length in bytes of the underlying hash function output. + =head1 RETURN VALUES HMAC() returns a pointer to the message authentication code or NULL if @@ -120,25 +123,27 @@ HMAC_CTX_copy() return 1 for success or 0 if an error occurred. HMAC_CTX_get_md() return the EVP_MD previously set for the supplied HMAC_CTX or NULL if no EVP_MD has been set. +HMAC_size() returns the length in bytes of the underlying hash function output +or zero on error. + =head1 CONFORMING TO RFC 2104 =head1 SEE ALSO -L, L +L, L =head1 HISTORY -HMAC_CTX_init() was replaced with HMAC_CTX_reset() in OpenSSL versions 1.1.0. +HMAC_CTX_init() was replaced with HMAC_CTX_reset() in OpenSSL 1.1.0. -HMAC_CTX_cleanup() existed in OpenSSL versions before 1.1.0. +HMAC_CTX_cleanup() existed in OpenSSL before version 1.1.0. -HMAC_CTX_new(), HMAC_CTX_free() and HMAC_CTX_get_md() are new in OpenSSL version -1.1.0. +HMAC_CTX_new(), HMAC_CTX_free() and HMAC_CTX_get_md() are new in OpenSSL 1.1.0. HMAC_Init_ex(), HMAC_Update() and HMAC_Final() did not return values in -versions of OpenSSL before 1.0.0. +OpenSSL before version 1.0.0. =head1 COPYRIGHT diff --git a/doc/crypto/MD5.pod b/doc/man3/MD5.pod similarity index 80% rename from doc/crypto/MD5.pod rename to doc/man3/MD5.pod index 78da7507..83547f2c 100644 --- a/doc/crypto/MD5.pod +++ b/doc/man3/MD5.pod @@ -9,34 +9,28 @@ MD4_Final, MD5_Init, MD5_Update, MD5_Final - MD2, MD4, and MD5 hash functions #include - unsigned char *MD2(const unsigned char *d, unsigned long n, - unsigned char *md); + unsigned char *MD2(const unsigned char *d, unsigned long n, unsigned char *md); int MD2_Init(MD2_CTX *c); - int MD2_Update(MD2_CTX *c, const unsigned char *data, - unsigned long len); + int MD2_Update(MD2_CTX *c, const unsigned char *data, unsigned long len); int MD2_Final(unsigned char *md, MD2_CTX *c); #include - unsigned char *MD4(const unsigned char *d, unsigned long n, - unsigned char *md); + unsigned char *MD4(const unsigned char *d, unsigned long n, unsigned char *md); int MD4_Init(MD4_CTX *c); - int MD4_Update(MD4_CTX *c, const void *data, - unsigned long len); + int MD4_Update(MD4_CTX *c, const void *data, unsigned long len); int MD4_Final(unsigned char *md, MD4_CTX *c); #include - unsigned char *MD5(const unsigned char *d, unsigned long n, - unsigned char *md); + unsigned char *MD5(const unsigned char *d, unsigned long n, unsigned char *md); int MD5_Init(MD5_CTX *c); - int MD5_Update(MD5_CTX *c, const void *data, - unsigned long len); + int MD5_Update(MD5_CTX *c, const void *data, unsigned long len); int MD5_Final(unsigned char *md, MD5_CTX *c); =head1 DESCRIPTION diff --git a/doc/crypto/MDC2_Init.pod b/doc/man3/MDC2_Init.pod similarity index 88% rename from doc/crypto/MDC2_Init.pod rename to doc/man3/MDC2_Init.pod index f7db71b4..b384b8c8 100644 --- a/doc/crypto/MDC2_Init.pod +++ b/doc/man3/MDC2_Init.pod @@ -9,11 +9,11 @@ MDC2, MDC2_Init, MDC2_Update, MDC2_Final - MDC2 hash function #include unsigned char *MDC2(const unsigned char *d, unsigned long n, - unsigned char *md); + unsigned char *md); int MDC2_Init(MDC2_CTX *c); int MDC2_Update(MDC2_CTX *c, const unsigned char *data, - unsigned long len); + unsigned long len); int MDC2_Final(unsigned char *md, MDC2_CTX *c); =head1 DESCRIPTION @@ -50,7 +50,7 @@ MDC2_Init(), MDC2_Update() and MDC2_Final() return 1 for success, 0 otherwise. =head1 CONFORMING TO -ISO/IEC 10118-2, with DES +ISO/IEC 10118-2:2000 Hash-Function 2, with DES as the underlying block cipher. =head1 SEE ALSO @@ -58,7 +58,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/crypto/OBJ_nid2obj.pod b/doc/man3/OBJ_nid2obj.pod similarity index 91% rename from doc/crypto/OBJ_nid2obj.pod rename to doc/man3/OBJ_nid2obj.pod index 3ada6679..6c1aa132 100644 --- a/doc/crypto/OBJ_nid2obj.pod +++ b/doc/man3/OBJ_nid2obj.pod @@ -91,11 +91,7 @@ OBJ_length() returns the size of the content octets of B. OBJ_get0_data() returns a pointer to the content octets of B. The returned pointer is an internal pointer which B be freed. -In OpenSSL versions prior to 1.1.0 OBJ_cleanup() cleaned up OpenSSLs internal -object table and was called before an application exits if any new objects were -added using OBJ_create(). This function is deprecated in version 1.1.0 and now -does nothing if called. No explicit de-initialisation is now required. See -L for further information. +OBJ_cleanup() releases any resources allocated by creating new objects. =head1 NOTES @@ -137,22 +133,17 @@ The latter cannot be constant because it needs to be freed after use. Create an object for B: - ASN1_OBJECT *o; - o = OBJ_nid2obj(NID_commonName); + ASN1_OBJECT *o = OBJ_nid2obj(NID_commonName); Check if an object is B if (OBJ_obj2nid(obj) == NID_commonName) - /* Do something */ + /* Do something */ Create a new NID and initialize an object from it: - int new_nid; - ASN1_OBJECT *obj; - - new_nid = OBJ_create("1.2.3.4", "NewOID", "New Object Identifier"); - - obj = OBJ_nid2obj(new_nid); + int new_nid = OBJ_create("1.2.3.4", "NewOID", "New Object Identifier"); + ASN1_OBJECT *obj = OBJ_nid2obj(new_nid); Create a new object directly: @@ -184,7 +175,8 @@ L =head1 HISTORY -OBJ_cleanup() was deprecated in OpenSSL 1.1.0. +OBJ_cleanup() was deprecated in OpenSSL 1.1.0 by L +and should not be used. =head1 COPYRIGHT diff --git a/doc/crypto/OCSP_REQUEST_new.pod b/doc/man3/OCSP_REQUEST_new.pod similarity index 97% rename from doc/crypto/OCSP_REQUEST_new.pod rename to doc/man3/OCSP_REQUEST_new.pod index 97c2337d..a382b16e 100644 --- a/doc/crypto/OCSP_REQUEST_new.pod +++ b/doc/man3/OCSP_REQUEST_new.pod @@ -93,16 +93,16 @@ B: if (OCSP_REQUEST_add0_id(req, cid) == NULL) /* error */ - /* Do something with req, e.g. query responder */ + /* Do something with req, e.g. query responder */ OCSP_REQUEST_free(req); =head1 SEE ALSO -L, +L, L, L, -L, +L, L, L diff --git a/doc/crypto/OCSP_cert_to_id.pod b/doc/man3/OCSP_cert_to_id.pod similarity index 98% rename from doc/crypto/OCSP_cert_to_id.pod rename to doc/man3/OCSP_cert_to_id.pod index 0e37937f..f1a4b151 100644 --- a/doc/crypto/OCSP_cert_to_id.pod +++ b/doc/man3/OCSP_cert_to_id.pod @@ -70,10 +70,10 @@ B structure is freed. =head1 SEE ALSO -L, +L, L, L, -L, +L, L, L diff --git a/doc/crypto/OCSP_request_add1_nonce.pod b/doc/man3/OCSP_request_add1_nonce.pod similarity index 98% rename from doc/crypto/OCSP_request_add1_nonce.pod rename to doc/man3/OCSP_request_add1_nonce.pod index dab42c67..66e4c7b8 100644 --- a/doc/crypto/OCSP_request_add1_nonce.pod +++ b/doc/man3/OCSP_request_add1_nonce.pod @@ -65,10 +65,10 @@ condition. =head1 SEE ALSO -L, +L, L, L, -L, +L, L, L diff --git a/doc/crypto/OCSP_resp_find_status.pod b/doc/man3/OCSP_resp_find_status.pod similarity index 93% rename from doc/crypto/OCSP_resp_find_status.pod rename to doc/man3/OCSP_resp_find_status.pod index 5123f0ad..af7fb1de 100644 --- a/doc/crypto/OCSP_resp_find_status.pod +++ b/doc/man3/OCSP_resp_find_status.pod @@ -5,6 +5,7 @@ OCSP_resp_get0_certs, OCSP_resp_get0_signer, OCSP_resp_get0_id, +OCSP_resp_get1_id, OCSP_resp_get0_produced_at, OCSP_resp_find_status, OCSP_resp_count, OCSP_resp_get0, OCSP_resp_find, OCSP_single_get0_status, OCSP_check_validity @@ -39,6 +40,9 @@ OCSP_single_get0_status, OCSP_check_validity int OCSP_resp_get0_id(const OCSP_BASICRESP *bs, const ASN1_OCTET_STRING **pid, const X509_NAME **pname); + int OCSP_resp_get1_id(const OCSP_BASICRESP *bs, + ASN1_OCTET_STRING **pid, + X509_NAME **pname); int OCSP_check_validity(ASN1_GENERALIZEDTIME *thisupd, ASN1_GENERALIZEDTIME *nextupd, @@ -85,7 +89,10 @@ signed the response are known via some out-of-band mechanism. OCSP_resp_get0_id() gets the responder id of B. If the responder ID is a name then <*pname> is set to the name and B<*pid> is set to NULL. If the responder ID is by key ID then B<*pid> is set to the key ID and B<*pname> -is set to NULL. +is set to NULL. OCSP_resp_get1_id() leaves ownership of B<*pid> and B<*pname> +with the caller, who is responsible for freeing them. Both functions return 1 +in case of success and 0 in case of failure. If OCSP_resp_get1_id() returns 0, +no freeing of the results is necessary. OCSP_check_validity() checks the validity of B and B values which will be typically obtained from OCSP_resp_find_status() or @@ -133,7 +140,7 @@ parameters can be set to NULL if their value is not required. =head1 SEE ALSO -L, +L, L, L, L, diff --git a/doc/man3/OCSP_response_status.pod b/doc/man3/OCSP_response_status.pod new file mode 100644 index 00000000..82f95b3a --- /dev/null +++ b/doc/man3/OCSP_response_status.pod @@ -0,0 +1,117 @@ +=pod + +=head1 NAME + +OCSP_response_status, OCSP_response_get1_basic, OCSP_response_create, +OCSP_RESPONSE_free, OCSP_RESPID_set_by_name, +OCSP_RESPID_set_by_key, OCSP_RESPID_match, +OCSP_basic_sign, OCSP_basic_sign_ctx - OCSP response functions + +=head1 SYNOPSIS + + #include + + int OCSP_response_status(OCSP_RESPONSE *resp); + OCSP_BASICRESP *OCSP_response_get1_basic(OCSP_RESPONSE *resp); + OCSP_RESPONSE *OCSP_response_create(int status, OCSP_BASICRESP *bs); + void OCSP_RESPONSE_free(OCSP_RESPONSE *resp); + + int OCSP_RESPID_set_by_name(OCSP_RESPID *respid, X509 *cert); + int OCSP_RESPID_set_by_key(OCSP_RESPID *respid, X509 *cert); + int OCSP_RESPID_match(OCSP_RESPID *respid, X509 *cert); + + int OCSP_basic_sign(OCSP_BASICRESP *brsp, X509 *signer, EVP_PKEY *key, + const EVP_MD *dgst, STACK_OF(X509) *certs, + unsigned long flags); + int OCSP_basic_sign_ctx(OCSP_BASICRESP *brsp, X509 *signer, EVP_MD_CTX *ctx, + STACK_OF(X509) *certs, unsigned long flags); + +=head1 DESCRIPTION + +OCSP_response_status() returns the OCSP response status of B. It returns +one of the values: B, +B, +B, B +B, or B. + +OCSP_response_get1_basic() decodes and returns the B structure +contained in B. + +OCSP_response_create() creates and returns an B structure for +B and optionally including basic response B. + +OCSP_RESPONSE_free() frees up OCSP response B. + +OCSP_RESPID_set_by_name() sets the name of the OCSP_RESPID to be the same as the +subject name in the supplied X509 certificate B for the OCSP responder. + +OCSP_RESPID_set_by_key() sets the key of the OCSP_RESPID to be the same as the +key in the supplied X509 certificate B for the OCSP responder. The key is +stored as a SHA1 hash. + +Note that an OCSP_RESPID can only have one of the name, or the key set. Calling +OCSP_RESPID_set_by_name() or OCSP_RESPID_set_by_key() will clear any existing +setting. + +OCSP_RESPID_match() tests whether the OCSP_RESPID given in B matches +with the X509 certificate B. + +OCSP_basic_sign() signs OCSP response B using certificate B, private key +B, digest B and additional certificates B. If the B option +B is set then no certificates will be included in the request. If the +B option B is set then the responder is identified by key ID +rather than by name. OCSP_basic_sign_ctx() also signs OCSP response B but +uses the parameters contained in digest context B. + +=head1 RETURN VALUES + +OCSP_RESPONSE_status() returns a status value. + +OCSP_response_get1_basic() returns an B structure pointer or +B if an error occurred. + +OCSP_response_create() returns an B structure pointer or B +if an error occurred. + +OCSP_RESPONSE_free() does not return a value. + +OCSP_RESPID_set_by_name(), OCSP_RESPID_set_by_key(), OCSP_basic_sign(), and +OCSP_basic_sign_ctx() return 1 on success or 0 +on failure. + +OCSP_RESPID_match() returns 1 if the OCSP_RESPID and the X509 certificate match +or 0 otherwise. + +=head1 NOTES + +OCSP_response_get1_basic() is only called if the status of a response is +B. + +=head1 SEE ALSO + +L +L +L +L +L +L +L +L + +=head1 HISTORY + +The OCSP_RESPID_set_by_name(), OCSP_RESPID_set_by_key() and OCSP_RESPID_match() +functions were added in OpenSSL 1.1.0a. + +The OCSP_basic_sign_ctx() function was added in OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2015-2018 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 +L. + +=cut diff --git a/doc/crypto/OCSP_sendreq_new.pod b/doc/man3/OCSP_sendreq_new.pod similarity index 98% rename from doc/crypto/OCSP_sendreq_new.pod rename to doc/man3/OCSP_sendreq_new.pod index c7fdc9b1..65ba235c 100644 --- a/doc/crypto/OCSP_sendreq_new.pod +++ b/doc/man3/OCSP_sendreq_new.pod @@ -103,11 +103,11 @@ applications is not recommended. =head1 SEE ALSO -L, +L, L, L, L, -L, +L, L =head1 COPYRIGHT diff --git a/doc/crypto/OPENSSL_Applink.pod b/doc/man3/OPENSSL_Applink.pod similarity index 90% rename from doc/crypto/OPENSSL_Applink.pod rename to doc/man3/OPENSSL_Applink.pod index d3a461ba..85930786 100644 --- a/doc/crypto/OPENSSL_Applink.pod +++ b/doc/man3/OPENSSL_Applink.pod @@ -19,9 +19,13 @@ compiler of their choice and link it into the target application. The referred module is available as F, located alongside the public header files (only on the platforms where applicable). +=head1 RETURN VALUES + +Not available. + =head1 COPYRIGHT -Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2004-2018 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 diff --git a/doc/crypto/OPENSSL_LH_COMPFUNC.pod b/doc/man3/OPENSSL_LH_COMPFUNC.pod similarity index 94% rename from doc/crypto/OPENSSL_LH_COMPFUNC.pod rename to doc/man3/OPENSSL_LH_COMPFUNC.pod index e760ae3b..06908a49 100644 --- a/doc/crypto/OPENSSL_LH_COMPFUNC.pod +++ b/doc/man3/OPENSSL_LH_COMPFUNC.pod @@ -2,7 +2,7 @@ =head1 NAME -DECLARE_LHASH_OF, +LHASH, DECLARE_LHASH_OF, OPENSSL_LH_COMPFUNC, OPENSSL_LH_HASHFUNC, OPENSSL_LH_DOALL_FUNC, LHASH_DOALL_ARG_FN_TYPE, IMPLEMENT_LHASH_HASH_FN, IMPLEMENT_LHASH_COMP_FN, @@ -10,10 +10,10 @@ lh_TYPE_new, lh_TYPE_free, lh_TYPE_insert, lh_TYPE_delete, lh_TYPE_retrieve, lh_TYPE_doall, lh_TYPE_doall_arg, lh_TYPE_error - dynamic hash table -=for comment generic - =head1 SYNOPSIS +=for comment generic + #include DECLARE_LHASH_OF(TYPE); @@ -184,6 +184,13 @@ audit/verify and also opens the window of opportunity for stack corruption and other hard-to-find bugs. It also, apparently, violates ANSI-C. +The LHASH code is not thread safe. All updating operations must be +performed under a write lock. All retrieve operations should be performed +under a read lock, I accurate usage statistics are desired. +In which case, a write lock should be used for retrieve operations +as well. For output of the usage statistics, using the functions from +L, a read lock suffices. + The LHASH code regards table entries as constant data. As such, it internally represents lh_insert()'d items with a "const void *" pointer type. This is why callbacks such as those used by lh_doall() @@ -220,7 +227,7 @@ lh_TYPE_insert() returns B both for success and error. =head1 SEE ALSO -L +L =head1 HISTORY @@ -229,7 +236,7 @@ type checking. =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/crypto/OPENSSL_LH_stats.pod b/doc/man3/OPENSSL_LH_stats.pod similarity index 86% rename from doc/crypto/OPENSSL_LH_stats.pod rename to doc/man3/OPENSSL_LH_stats.pod index c454a47e..231485ad 100644 --- a/doc/crypto/OPENSSL_LH_stats.pod +++ b/doc/man3/OPENSSL_LH_stats.pod @@ -21,9 +21,7 @@ OPENSSL_LH_node_stats_bio, OPENSSL_LH_node_usage_stats_bio - LHASH statistics =head1 DESCRIPTION The B structure records statistics about most aspects of -accessing the hash table. This is mostly a legacy of Eric Young -writing this library for the reasons of implementing what looked like -a nice algorithm rather than for a particular software product. +accessing the hash table. OPENSSL_LH_stats() prints out statistics on the size of the hash table, how many entries are in it, and the number and result of calls to the @@ -48,13 +46,19 @@ are the same as the above, except that the output goes to a B. These functions do not return values. +=head1 NOTE + +These calls should be made under a read lock. Refer to +L for more details about the locks required +when using the LHASH data structure. + =head1 SEE ALSO -L, L +L, L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/crypto/OPENSSL_VERSION_NUMBER.pod b/doc/man3/OPENSSL_VERSION_NUMBER.pod similarity index 95% rename from doc/crypto/OPENSSL_VERSION_NUMBER.pod rename to doc/man3/OPENSSL_VERSION_NUMBER.pod index f50faec7..d5842c0e 100644 --- a/doc/crypto/OPENSSL_VERSION_NUMBER.pod +++ b/doc/man3/OPENSSL_VERSION_NUMBER.pod @@ -91,13 +91,15 @@ if available or "ENGINESDIR: N/A" otherwise. For an unknown B, the text "not available" is returned. -=head1 RETURN VALUE +=head1 RETURN VALUES -The version number. +OpenSSL_version_num() returns the version number. + +OpenSSL_version() returns requested version strings. =head1 SEE ALSO -L +L =head1 COPYRIGHT diff --git a/doc/crypto/OPENSSL_config.pod b/doc/man3/OPENSSL_config.pod similarity index 99% rename from doc/crypto/OPENSSL_config.pod rename to doc/man3/OPENSSL_config.pod index eae634a8..e70fcd54 100644 --- a/doc/crypto/OPENSSL_config.pod +++ b/doc/man3/OPENSSL_config.pod @@ -54,7 +54,7 @@ Neither OPENSSL_config() nor OPENSSL_no_config() return a value. =head1 SEE ALSO -L, +L, L =head1 HISTORY diff --git a/doc/man3/OPENSSL_fork_prepare.pod b/doc/man3/OPENSSL_fork_prepare.pod new file mode 100644 index 00000000..eda83603 --- /dev/null +++ b/doc/man3/OPENSSL_fork_prepare.pod @@ -0,0 +1,63 @@ +=pod + +=head1 NAME + +OPENSSL_fork_prepare, +OPENSSL_fork_parent, +OPENSSL_fork_child +- OpenSSL fork handlers + +=head1 SYNOPSIS + + #include + + void OPENSSL_fork_prepare(void); + void OPENSSL_fork_parent(void); + void OPENSSL_fork_child(void); + +=head1 DESCRIPTION + +OpenSSL has state that should be reset when a process forks. For example, +the entropy pool used to generate random numbers (and therefore encryption +keys) should not be shared across multiple programs. +The OPENSSL_fork_prepare(), OPENSSL_fork_parent(), and OPENSSL_fork_child() +functions are used to reset this internal state. + +Platforms without fork(2) will probably not need to use these functions. +Platforms with fork(2) but without pthreads_atfork(3) will probably need +to call them manually, as described in the following paragraph. Platforms +such as Linux that have both functions will normally not need to call these +functions as the OpenSSL library will do so automatically. + +L will register these functions with the appropriate +hander, when the B flag is used. For other +applications, these functions can be called directly. They should be used +according to the calling sequence described by the pthreads_atfork(3) +documentation, which is summarized here. OPENSSL_fork_prepare() should +be called before a fork() is done. After the fork() returns, the parent +process should call OPENSSL_fork_parent() and the child process should +call OPENSSL_fork_child(). + +=head1 RETURN VALUES + +OPENSSL_fork_prepare(), OPENSSL_fork_parent() and OPENSSL_fork_child() do not +return values. + +=head1 SEE ALSO + +L + +=head1 HISTORY + +These functions were added in OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2017-2018 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 +L. + +=cut diff --git a/doc/crypto/OPENSSL_ia32cap.pod b/doc/man3/OPENSSL_ia32cap.pod similarity index 81% rename from doc/crypto/OPENSSL_ia32cap.pod rename to doc/man3/OPENSSL_ia32cap.pod index b0ab0ce5..93ee30ae 100644 --- a/doc/crypto/OPENSSL_ia32cap.pod +++ b/doc/man3/OPENSSL_ia32cap.pod @@ -101,12 +101,19 @@ and RORX; =item bit #64+19 denoting availability of ADCX and ADOX instructions; +=item bit #64+21 denoting availability of VPMADD52[LH]UQ instructions, +a.k.a. AVX512IFMA extension; + =item bit #64+29 denoting availability of SHA extension; =item bit #64+30 denoting availability of AVX512BW extension; =item bit #64+31 denoting availability of AVX512VL extension; +=item bit #64+41 denoting availability of VAES extension; + +=item bit #64+42 denoting availability of VPCLMULQDQ extension; + =back To control this extended capability word use ':' as delimiter when @@ -124,13 +131,33 @@ requirements are summarized in below table: ------------+--------+--------+-------- AVX | 2.19 | 2.09 | 3.0 AVX2 | 2.22 | 2.10 | 3.1 - AVX512 | 2.25 | 2.11.8 | 3.6 + ADCX/ADOX | 2.23 | 2.10 | 3.3 + AVX512 | 2.25 | 2.11.8 | see NOTES + AVX512IFMA | 2.26 | 2.11.8 | see NOTES + VAES | n/a | n/a | -B is a macro returning the first word of the vector. +=head1 NOTES + +Even though AVX512 support was implemented in llvm 3.6, compilation of +assembly modules apparently requires explicit -march flag. But then +compiler generates processor-specific code, which in turn contradicts +the mere idea of run-time switch execution facilitated by the variable +in question. Till the limitation is lifted, it's possible to work around +the problem by making build procedure use following script: + + #!/bin/sh + exec clang -no-integrated-as "$@" + +instead of real clang. In which case it doesn't matter which clang +version is used, as it is GNU assembler version that will be checked. + +=head1 RETURN VALUES + +Not available. =head1 COPYRIGHT -Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2004-2018 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 diff --git a/doc/crypto/OPENSSL_init_crypto.pod b/doc/man3/OPENSSL_init_crypto.pod similarity index 95% rename from doc/crypto/OPENSSL_init_crypto.pod rename to doc/man3/OPENSSL_init_crypto.pod index f0b3c8aa..ce7497e1 100644 --- a/doc/crypto/OPENSSL_init_crypto.pod +++ b/doc/man3/OPENSSL_init_crypto.pod @@ -2,7 +2,7 @@ =head1 NAME -OPENSSL_init_new, OPENSSL_INIT_set_config_appname, OPENSSL_INIT_free, +OPENSSL_INIT_new, OPENSSL_INIT_set_config_appname, OPENSSL_INIT_free, OPENSSL_init_crypto, OPENSSL_cleanup, OPENSSL_atexit, OPENSSL_thread_stop - OpenSSL initialisation and deinitialisation functions @@ -16,7 +16,7 @@ initialisation and deinitialisation functions int OPENSSL_atexit(void (*handler)(void)); void OPENSSL_thread_stop(void); - OPENSSL_INIT_SETTINGS *OPENSSL_init_new(void); + OPENSSL_INIT_SETTINGS *OPENSSL_INIT_new(void); int OPENSSL_INIT_set_config_appname(OPENSSL_INIT_SETTINGS *init, const char* name); void OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS *init); @@ -96,7 +96,7 @@ B will be ignored. With this option an OpenSSL configuration file will be automatically loaded and used by calling OPENSSL_config(). This is not a default option. -See the description of OPENSSL_init_new(), below. +See the description of OPENSSL_INIT_new(), below. =item OPENSSL_INIT_NO_LOAD_CONFIG @@ -150,6 +150,11 @@ With this option the library will automatically load and initialise all the built in engines listed above with the exception of the openssl and dasync engines. This not a default option. +=item OPENSSL_INIT_ATFORK + +With this option the library will register its fork handlers. +See OPENSSL_fork_prepare(3) for details. + =back Multiple options may be combined together in a single call to @@ -192,7 +197,7 @@ described in the NOTES section below. The B flag will load a default configuration file. To specify a different file, an B must be created and used. The routines -OPENSSL_init_new() and OPENSSL_INIT_set_config_appname() can be used to +OPENSSL_INIT_new() and OPENSSL_INIT_set_config_appname() can be used to allocate the object and set the application name, and then the object can be released with OPENSSL_INIT_free() when done. @@ -230,7 +235,7 @@ L =head1 HISTORY The OPENSSL_init_crypto(), OPENSSL_cleanup(), OPENSSL_atexit(), -OPENSSL_thread_stop(), OPENSSL_init_new(), OPENSSL_INIT_set_config_appname() +OPENSSL_thread_stop(), OPENSSL_INIT_new(), OPENSSL_INIT_set_config_appname() and OPENSSL_INIT_free() functions were added in OpenSSL 1.1.0. =head1 COPYRIGHT diff --git a/doc/ssl/OPENSSL_init_ssl.pod b/doc/man3/OPENSSL_init_ssl.pod similarity index 100% rename from doc/ssl/OPENSSL_init_ssl.pod rename to doc/man3/OPENSSL_init_ssl.pod diff --git a/doc/crypto/OPENSSL_instrument_bus.pod b/doc/man3/OPENSSL_instrument_bus.pod similarity index 92% rename from doc/crypto/OPENSSL_instrument_bus.pod rename to doc/man3/OPENSSL_instrument_bus.pod index 14072610..744153ec 100644 --- a/doc/crypto/OPENSSL_instrument_bus.pod +++ b/doc/man3/OPENSSL_instrument_bus.pod @@ -16,7 +16,7 @@ OPENSSL_instrument_bus, OPENSSL_instrument_bus2 - instrument references to memor It was empirically found that timings of references to primary memory are subject to irregular, apparently non-deterministic variations. The subroutines in question instrument these references for purposes of -gathering entropy for random number generator. In order to make it +gathering randomness for random number generator. In order to make it bus-bound a 'flush cache line' instruction is used between probes. In addition probes are added to B elements in atomic or interlocked manner, which should contribute additional noise on @@ -32,7 +32,7 @@ periods when probe values appeared deterministic. The subroutine performs at most B probes in attempt to fill the B, with B value of 0 meaning "as many as it takes." -=head1 RETURN VALUE +=head1 RETURN VALUES Return value of 0 indicates that CPU is not capable of performing the benchmark, either because oscillator counter or 'flush cache line' is @@ -43,7 +43,7 @@ Otherwise number of recorded values is returned. =head1 COPYRIGHT -Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2011-2018 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 diff --git a/doc/crypto/OPENSSL_load_builtin_modules.pod b/doc/man3/OPENSSL_load_builtin_modules.pod similarity index 90% rename from doc/crypto/OPENSSL_load_builtin_modules.pod rename to doc/man3/OPENSSL_load_builtin_modules.pod index 112718a6..bf0dc413 100644 --- a/doc/crypto/OPENSSL_load_builtin_modules.pod +++ b/doc/man3/OPENSSL_load_builtin_modules.pod @@ -10,7 +10,7 @@ OPENSSL_load_builtin_modules, ASN1_add_oid_module, ENGINE_add_conf_module - add void OPENSSL_load_builtin_modules(void); void ASN1_add_oid_module(void); - ENGINE_add_conf_module(); + void ENGINE_add_conf_module(void); =head1 DESCRIPTION @@ -36,17 +36,17 @@ configuration modules instead of adding modules selectively: otherwise functionality may be missing from the application if an when new modules are added. -=head1 RETURN VALUE +=head1 RETURN VALUES None of the functions return a value. =head1 SEE ALSO -L, L +L, L =head1 COPYRIGHT -Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2004-2018 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 diff --git a/doc/crypto/OPENSSL_malloc.pod b/doc/man3/OPENSSL_malloc.pod similarity index 78% rename from doc/crypto/OPENSSL_malloc.pod rename to doc/man3/OPENSSL_malloc.pod index 2104f431..2d48ae2e 100644 --- a/doc/crypto/OPENSSL_malloc.pod +++ b/doc/man3/OPENSSL_malloc.pod @@ -14,8 +14,12 @@ OPENSSL_mem_debug_push, OPENSSL_mem_debug_pop, CRYPTO_mem_debug_push, CRYPTO_mem_debug_pop, CRYPTO_clear_realloc, CRYPTO_clear_free, CRYPTO_get_mem_functions, CRYPTO_set_mem_functions, +CRYPTO_get_alloc_counts, CRYPTO_set_mem_debug, CRYPTO_mem_ctrl, -CRYPTO_mem_leaks, CRYPTO_mem_leaks_fp - Memory allocation functions +CRYPTO_mem_leaks, CRYPTO_mem_leaks_fp, CRYPTO_mem_leaks_cb, +OPENSSL_MALLOC_FAILURES, +OPENSSL_MALLOC_FD +- Memory allocation functions =head1 SYNOPSIS @@ -46,7 +50,8 @@ CRYPTO_mem_leaks, CRYPTO_mem_leaks_fp - Memory allocation functions void CRYPTO_free(void *str, const char *, int) char *CRYPTO_strdup(const char *p, const char *file, int line) char *CRYPTO_strndup(const char *p, size_t num, const char *file, int line) - void *CRYPTO_clear_realloc(void *p, size_t old_len, size_t num, const char *file, int line) + void *CRYPTO_clear_realloc(void *p, size_t old_len, size_t num, + const char *file, int line) void CRYPTO_clear_free(void *str, size_t num, const char *, int) void CRYPTO_get_mem_functions( @@ -58,8 +63,13 @@ CRYPTO_mem_leaks, CRYPTO_mem_leaks_fp - Memory allocation functions void *(*r)(void *, size_t, const char *, int), void (*f)(void *, const char *, int)) + void CRYPTO_get_alloc_counts(int *m, int *r, int *f) + int CRYPTO_set_mem_debug(int onoff) + env OPENSSL_MALLOC_FAILURES=... + env OPENSSL_MALLOC_FD=... + int CRYPTO_mem_ctrl(int mode); int OPENSSL_mem_debug_push(const char *info) @@ -70,6 +80,8 @@ CRYPTO_mem_leaks, CRYPTO_mem_leaks_fp - Memory allocation functions void CRYPTO_mem_leaks(BIO *b); void CRYPTO_mem_leaks_fp(FILE *fp); + void CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u), + void *u); =head1 DESCRIPTION @@ -139,7 +151,6 @@ CRYPTO_set_mem_debug() turns this tracking on and off. In order to have any effect, is must be called before any of the allocation functions (e.g., CRYPTO_malloc()) are called, and is therefore normally one of the first lines of main() in an application. - CRYPTO_mem_ctrl() provides fine-grained control of memory leak tracking. To enable tracking call CRYPTO_mem_ctrl() with a B argument of the B. @@ -160,6 +171,45 @@ CRYPTO_mem_leaks_fp() will report all "leaked" memory, writing it to the specified BIO B or FILE B. These functions return 1 if there are no leaks, 0 if there are leaks and -1 if an error occurred. +CRYPTO_mem_leaks_cb() does the same as CRYPTO_mem_leaks(), but instead +of writing to a given BIO, the callback function is called for each +output string with the string, length, and userdata B as the callback +parameters. + +If the library is built with the C option, then one +function, CRYPTO_get_alloc_counts(), and two additional environment +variables, B and B, +are available. + +The function CRYPTO_get_alloc_counts() fills in the number of times +each of CRYPTO_malloc(), CRYPTO_realloc(), and CRYPTO_free() have been +called, into the values pointed to by B, B, and B, +respectively. If a pointer is NULL, then the corresponding count is not stored. + +The variable +B controls how often allocations should fail. +It is a set of fields separated by semicolons, which each field is a count +(defaulting to zero) and an optional atsign and percentage (defaulting +to 100). If the count is zero, then it lasts forever. For example, +C<100;@25> or C<100@0;0@25> means the first 100 allocations pass, then all +other allocations (until the program exits or crashes) have a 25% chance of +failing. + +If the variable B is parsed as a positive integer, then +it is taken as an open file descriptor, and a record of all allocations is +written to that descriptor. If an allocation will fail, and the platform +supports it, then a backtrace will be written to the descriptor. This can +be useful because a malloc may fail but not be checked, and problems will +only occur later. The following example in classic shell syntax shows how +to use this (will not work on all platforms): + + OPENSSL_MALLOC_FAILURES='200;@10' + export OPENSSL_MALLOC_FAILURES + OPENSSL_MALLOC_FD=3 + export OPENSSL_MALLOC_FD + ...app invocation... 3>/tmp/log$$ + + =head1 RETURN VALUES OPENSSL_malloc_init(), OPENSSL_free(), OPENSSL_clear_free() diff --git a/doc/crypto/OPENSSL_secure_malloc.pod b/doc/man3/OPENSSL_secure_malloc.pod similarity index 91% rename from doc/crypto/OPENSSL_secure_malloc.pod rename to doc/man3/OPENSSL_secure_malloc.pod index 3f27d76d..5a01c824 100644 --- a/doc/crypto/OPENSSL_secure_malloc.pod +++ b/doc/man3/OPENSSL_secure_malloc.pod @@ -5,9 +5,9 @@ CRYPTO_secure_malloc_init, CRYPTO_secure_malloc_initialized, CRYPTO_secure_malloc_done, OPENSSL_secure_malloc, CRYPTO_secure_malloc, OPENSSL_secure_zalloc, CRYPTO_secure_zalloc, OPENSSL_secure_free, -OPENSSL_secure_clear_free, CRYPTO_secure_free, CRYPTO_secure_clear_free, -OPENSSL_secure_actual_size, OPENSSL_secure_allocated, CRYPTO_secure_used -- secure heap storage +CRYPTO_secure_free, OPENSSL_secure_clear_free, +CRYPTO_secure_clear_free, OPENSSL_secure_actual_size, +CRYPTO_secure_used - secure heap storage =head1 SYNOPSIS @@ -32,7 +32,6 @@ OPENSSL_secure_actual_size, OPENSSL_secure_allocated, CRYPTO_secure_used void CRYPTO_secure_clear_free(void *ptr, size_t num, const char *, int); size_t OPENSSL_secure_actual_size(const void *ptr); - int OPENSSL_secure_allocated(const void *ptr); size_t CRYPTO_secure_used(); @@ -81,8 +80,12 @@ It exists for consistency with OPENSSL_secure_malloc() , and is a macro that expands to CRYPTO_secure_free() and adds the C<__FILE__> and C<__LINE__> parameters.. -OPENSSL_secure_allocated() tells whether or not a pointer is within -the secure heap. +OPENSSL_secure_clear_free() is similar to OPENSSL_secure_free() except +that it has an additional C parameter which is used to clear +the memory if it was not allocated from the secure heap. +If CRYPTO_secure_malloc_init() is not called, this is equivalent to +calling OPENSSL_clear_free(). + OPENSSL_secure_actual_size() tells the actual size allocated to the pointer; implementations may allocate more space than initially requested, in order to "round up" and reduce secure heap fragmentation. diff --git a/doc/man3/OSSL_STORE_INFO.pod b/doc/man3/OSSL_STORE_INFO.pod new file mode 100644 index 00000000..20d41ac5 --- /dev/null +++ b/doc/man3/OSSL_STORE_INFO.pod @@ -0,0 +1,204 @@ +=pod + +=head1 NAME + +OSSL_STORE_INFO, OSSL_STORE_INFO_get_type, OSSL_STORE_INFO_get0_NAME, +OSSL_STORE_INFO_get0_NAME_description, OSSL_STORE_INFO_get0_PARAMS, +OSSL_STORE_INFO_get0_PKEY, OSSL_STORE_INFO_get0_CERT, OSSL_STORE_INFO_get0_CRL, +OSSL_STORE_INFO_get1_NAME, OSSL_STORE_INFO_get1_NAME_description, +OSSL_STORE_INFO_get1_PARAMS, OSSL_STORE_INFO_get1_PKEY, +OSSL_STORE_INFO_get1_CERT, +OSSL_STORE_INFO_get1_CRL, OSSL_STORE_INFO_type_string, OSSL_STORE_INFO_free, +OSSL_STORE_INFO_new_NAME, OSSL_STORE_INFO_set0_NAME_description, +OSSL_STORE_INFO_new_PARAMS, OSSL_STORE_INFO_new_PKEY, OSSL_STORE_INFO_new_CERT, +OSSL_STORE_INFO_new_CRL - Functions to manipulate OSSL_STORE_INFO objects + +=head1 SYNOPSIS + + #include + + typedef struct ossl_store_info_st OSSL_STORE_INFO; + + int OSSL_STORE_INFO_get_type(const OSSL_STORE_INFO *store_info); + const char *OSSL_STORE_INFO_get0_NAME(const OSSL_STORE_INFO *store_info); + char *OSSL_STORE_INFO_get1_NAME(const OSSL_STORE_INFO *store_info); + const char *OSSL_STORE_INFO_get0_NAME_description(const OSSL_STORE_INFO + *store_info); + char *OSSL_STORE_INFO_get1_NAME_description(const OSSL_STORE_INFO *store_info); + EVP_PKEY *OSSL_STORE_INFO_get0_PARAMS(const OSSL_STORE_INFO *store_info); + EVP_PKEY *OSSL_STORE_INFO_get1_PARAMS(const OSSL_STORE_INFO *store_info); + EVP_PKEY *OSSL_STORE_INFO_get0_PKEY(const OSSL_STORE_INFO *store_info); + EVP_PKEY *OSSL_STORE_INFO_get1_PKEY(const OSSL_STORE_INFO *store_info); + X509 *OSSL_STORE_INFO_get0_CERT(const OSSL_STORE_INFO *store_info); + X509 *OSSL_STORE_INFO_get1_CERT(const OSSL_STORE_INFO *store_info); + X509_CRL *OSSL_STORE_INFO_get0_CRL(const OSSL_STORE_INFO *store_info); + X509_CRL *OSSL_STORE_INFO_get1_CRL(const OSSL_STORE_INFO *store_info); + + const char *OSSL_STORE_INFO_type_string(int type); + + void OSSL_STORE_INFO_free(OSSL_STORE_INFO *store_info); + + OSSL_STORE_INFO *OSSL_STORE_INFO_new_NAME(char *name); + int OSSL_STORE_INFO_set0_NAME_description(OSSL_STORE_INFO *info, char *desc); + OSSL_STORE_INFO *OSSL_STORE_INFO_new_PARAMS(DSA *dsa_params); + OSSL_STORE_INFO *OSSL_STORE_INFO_new_PKEY(EVP_PKEY *pkey); + OSSL_STORE_INFO *OSSL_STORE_INFO_new_CERT(X509 *x509); + OSSL_STORE_INFO *OSSL_STORE_INFO_new_CRL(X509_CRL *crl); + +=head1 DESCRIPTION + +These functions are primarily useful for applications to retrieve +supported objects from B objects and for scheme specific +loaders to create B holders. + +=head2 Types + +B is an opaque type that's just an intermediary holder for +the objects that have been retrieved by OSSL_STORE_load() and similar +functions. +Supported OpenSSL type object can be extracted using one of +STORE_INFO_get0_TYPE(). +The life time of this extracted object is as long as the life time of +the B it was extracted from, so care should be taken not +to free the latter too early. +As an alternative, STORE_INFO_get1_TYPE() extracts a duplicate (or the +same object with its reference count increased), which can be used +after the containing B has been freed. +The object returned by STORE_INFO_get1_TYPE() must be freed separately +by the caller. +See L for more information on the types that are +supported. + +=head2 Functions + +OSSL_STORE_INFO_get_type() takes a B and returns the STORE +type number for the object inside. +STORE_INFO_get_type_string() takes a STORE type number and returns a +short string describing it. + +OSSL_STORE_INFO_get0_NAME(), OSSL_STORE_INFO_get0_NAME_description(), +OSSL_STORE_INFO_get0_PARAMS(), OSSL_STORE_INFO_get0_PKEY(), +OSSL_STORE_INFO_get0_CERT() and OSSL_STORE_INFO_get0_CRL() all take a +B and return the held object of the appropriate OpenSSL +type provided that's what's held. + +OSSL_STORE_INFO_get1_NAME(), OSSL_STORE_INFO_get1_NAME_description(), +OSSL_STORE_INFO_get1_PARAMS(), OSSL_STORE_INFO_get1_PKEY(), +OSSL_STORE_INFO_get1_CERT() and OSSL_STORE_INFO_get1_CRL() all take a +B and return a duplicate of the held object of the +appropriate OpenSSL type provided that's what's held. + +OSSL_STORE_INFO_free() frees a B and its contained type. + +OSSL_STORE_INFO_new_NAME() , OSSL_STORE_INFO_new_PARAMS(), +OSSL_STORE_INFO_new_PKEY(), OSSL_STORE_INFO_new_CERT() and +OSSL_STORE_INFO_new_CRL() create a B +object to hold the given input object. +Additionally, for B` objects, +OSSL_STORE_INFO_set0_NAME_description() can be used to add an extra +description. +This description is meant to be human readable and should be used for +information printout. + +=head1 SUPPORTED OBJECTS + +Currently supported object types are: + +=over 4 + +=item OSSL_STORE_INFO_NAME + +A name is exactly that, a name. +It's like a name in a directory, but formatted as a complete URI. +For example, the path in URI C could include a file +named C, and in that case, the returned B +object would have the URI C, which can be +used by the application to get the objects in that file. +This can be applied to all schemes that can somehow support a listing +of object URIs. + +For C URIs that are used without the explicit scheme, the +returned name will be the path of each object, so if C was +given and that path has the file C, the name +C will be returned. + +The returned URI is considered canonical and must be unique and permanent +for the storage where the object (or collection of objects) resides. +Each loader is responsible for ensuring that it only returns canonical +URIs. +However, it's possible that certain schemes allow an object (or collection +thereof) to be reached with alternative URIs; just because one URI is +canonical doesn't mean that other variants can't be used. + +At the discretion of the loader that was used to get these names, an +extra description may be attached as well. + +=item OSSL_STORE_INFO_PARAMS + +Key parameters. + +=item OSSL_STORE_INFO_PKEY + +A private/public key of some sort. + +=item OSSL_STORE_INFO_CERT + +An X.509 certificate. + +=item OSSL_STORE_INFO_CRL + +A X.509 certificate revocation list. + +=back + +=head1 RETURN VALUES + +OSSL_STORE_INFO_get_type() returns the STORE type number of the given +B. +There is no error value. + +OSSL_STORE_INFO_get0_NAME(), OSSL_STORE_INFO_get0_NAME_description(), +OSSL_STORE_INFO_get0_PARAMS(), OSSL_STORE_INFO_get0_PKEY(), +OSSL_STORE_INFO_get0_CERT() and OSSL_STORE_INFO_get0_CRL() all return +a pointer to the OpenSSL object on success, NULL otherwise. + +OSSL_STORE_INFO_get0_NAME(), OSSL_STORE_INFO_get0_NAME_description(), +OSSL_STORE_INFO_get0_PARAMS(), OSSL_STORE_INFO_get0_PKEY(), +OSSL_STORE_INFO_get0_CERT() and OSSL_STORE_INFO_get0_CRL() all return +a pointer to a duplicate of the OpenSSL object on success, NULL otherwise. + +OSSL_STORE_INFO_type_string() returns a string on success, or B on +failure. + +OSSL_STORE_INFO_new_NAME(), OSSL_STORE_INFO_new_PARAMS(), +OSSL_STORE_INFO_new_PKEY(), OSSL_STORE_INFO_new_CERT() and +OSSL_STORE_INFO_new_CRL() return a B +pointer on success, or B on failure. + +OSSL_STORE_INFO_set0_NAME_description() returns 1 on success, or 0 on +failure. + +=head1 SEE ALSO + +L, L, L + +=head1 HISTORY + +OSSL_STORE_INFO(), OSSL_STORE_INFO_get_type(), OSSL_STORE_INFO_get0_NAME(), +OSSL_STORE_INFO_get0_PARAMS(), OSSL_STORE_INFO_get0_PKEY(), +OSSL_STORE_INFO_get0_CERT(), OSSL_STORE_INFO_get0_CRL(), +OSSL_STORE_INFO_type_string(), OSSL_STORE_INFO_free(), OSSL_STORE_INFO_new_NAME(), +OSSL_STORE_INFO_new_PARAMS(), OSSL_STORE_INFO_new_PKEY(), +OSSL_STORE_INFO_new_CERT() and OSSL_STORE_INFO_new_CRL() +were added to OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2016-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 +L. + +=cut diff --git a/doc/man3/OSSL_STORE_LOADER.pod b/doc/man3/OSSL_STORE_LOADER.pod new file mode 100644 index 00000000..e6e520ec --- /dev/null +++ b/doc/man3/OSSL_STORE_LOADER.pod @@ -0,0 +1,264 @@ +=pod + +=head1 NAME + +OSSL_STORE_LOADER, OSSL_STORE_LOADER_CTX, OSSL_STORE_LOADER_new, +OSSL_STORE_LOADER_get0_engine, OSSL_STORE_LOADER_get0_scheme, +OSSL_STORE_LOADER_set_open, OSSL_STORE_LOADER_set_ctrl, +OSSL_STORE_LOADER_set_expect, OSSL_STORE_LOADER_set_find, +OSSL_STORE_LOADER_set_load, OSSL_STORE_LOADER_set_eof, +OSSL_STORE_LOADER_set_error, OSSL_STORE_LOADER_set_close, +OSSL_STORE_LOADER_free, OSSL_STORE_register_loader, +OSSL_STORE_unregister_loader, OSSL_STORE_open_fn, OSSL_STORE_ctrl_fn, +OSSL_STORE_expect_fn, OSSL_STORE_find_fn, +OSSL_STORE_load_fn, OSSL_STORE_eof_fn, OSSL_STORE_error_fn, +OSSL_STORE_close_fn - Types and functions to manipulate, register and +unregister STORE loaders for different URI schemes + +=head1 SYNOPSIS + + #include + + typedef struct ossl_store_loader_st OSSL_STORE_LOADER; + + OSSL_STORE_LOADER *OSSL_STORE_LOADER_new(ENGINE *e, const char *scheme); + const ENGINE *OSSL_STORE_LOADER_get0_engine(const OSSL_STORE_LOADER + *store_loader); + const char *OSSL_STORE_LOADER_get0_scheme(const OSSL_STORE_LOADER + *store_loader); + + /* struct ossl_store_loader_ctx_st is defined differently by each loader */ + typedef struct ossl_store_loader_ctx_st OSSL_STORE_LOADER_CTX; + + typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_open_fn)(const char *uri, + const UI_METHOD *ui_method, + void *ui_data); + int OSSL_STORE_LOADER_set_open(OSSL_STORE_LOADER *store_loader, + OSSL_STORE_open_fn store_open_function); + typedef int (*OSSL_STORE_ctrl_fn)(OSSL_STORE_LOADER_CTX *ctx, int cmd, + va_list args); + int OSSL_STORE_LOADER_set_ctrl(OSSL_STORE_LOADER *store_loader, + OSSL_STORE_ctrl_fn store_ctrl_function); + typedef int (*OSSL_STORE_expect_fn)(OSSL_STORE_LOADER_CTX *ctx, int expected); + int OSSL_STORE_LOADER_set_expect(OSSL_STORE_LOADER *loader, + OSSL_STORE_expect_fn expect_function); + typedef int (*OSSL_STORE_find_fn)(OSSL_STORE_LOADER_CTX *ctx, + OSSL_STORE_SEARCH *criteria); + int OSSL_STORE_LOADER_set_find(OSSL_STORE_LOADER *loader, + OSSL_STORE_find_fn find_function); + typedef OSSL_STORE_INFO *(*OSSL_STORE_load_fn)(OSSL_STORE_LOADER_CTX *ctx, + UI_METHOD *ui_method, + void *ui_data); + int OSSL_STORE_LOADER_set_load(OSSL_STORE_LOADER *store_loader, + OSSL_STORE_load_fn store_load_function); + typedef int (*OSSL_STORE_eof_fn)(OSSL_STORE_LOADER_CTX *ctx); + int OSSL_STORE_LOADER_set_eof(OSSL_STORE_LOADER *store_loader, + OSSL_STORE_eof_fn store_eof_function); + typedef int (*OSSL_STORE_error_fn)(OSSL_STORE_LOADER_CTX *ctx); + int OSSL_STORE_LOADER_set_error(OSSL_STORE_LOADER *store_loader, + OSSL_STORE_error_fn store_error_function); + typedef int (*OSSL_STORE_close_fn)(OSSL_STORE_LOADER_CTX *ctx); + int OSSL_STORE_LOADER_set_close(OSSL_STORE_LOADER *store_loader, + OSSL_STORE_close_fn store_close_function); + void OSSL_STORE_LOADER_free(OSSL_STORE_LOADER *store_loader); + + int OSSL_STORE_register_loader(OSSL_STORE_LOADER *loader); + OSSL_STORE_LOADER *OSSL_STORE_unregister_loader(const char *scheme); + +=head1 DESCRIPTION + +These functions help applications and engines to create loaders for +schemes they support. + +=head2 Types + +B is the type to hold a loader. +It contains a scheme and the functions needed to implement +OSSL_STORE_open(), OSSL_STORE_load(), OSSL_STORE_eof(), OSSL_STORE_error() and +OSSL_STORE_close() for this scheme. + +B is a type template, to be defined by each loader +using B. + +B, B, B, +B, B, B, +and B +are the function pointer types used within a STORE loader. +The functions pointed at define the functionality of the given loader. + +=over 4 + +=item B + +This function takes a URI and is expected to interpret it in the best +manner possible according to the scheme the loader implements, it also +takes a B and associated data, to be used any time +something needs to be prompted for. +Furthermore, this function is expected to initialize what needs to be +initialized, to create a privata data store (B, see +above), and to return it. +If something goes wrong, this function is expected to return NULL. + +=item B + +This function takes a B pointer, a command number +B and a B B and is used to manipulate loader +specific parameters. + +=begin comment + +Globally known command numbers are documented in L, +along with what B are expected with each of them. + +=end comment + +Loader specific command numbers must begin at B. +Any number below that is reserved for future globally known command +numbers. + +This function is expected to return 1 on success, 0 on error. + +=item B + +This function takes a B pointer and a B +identity B, and is used to tell the loader what object type is +expected. +B may be zero to signify that no specific object type is expected. + +This function is expected to return 1 on success, 0 on error. + +=item B + +This function takes a B pointer and a +B search criterion, and is used to tell the loader what +to search for. + +When called with the loader context being B, this function is expected +to return 1 if the loader supports the criterion, otherwise 0. + +When called with the loader context being something other than B, this +function is expected to return 1 on success, 0 on error. + +=item B + +This function takes a B pointer and a B +with associated data. +It's expected to load the next available data, mold it into a data +structure that can be wrapped in a B using one of the +L functions. +If no more data is available or an error occurs, this function is +expected to return NULL. +The B and B functions must indicate if +it was in fact the end of data or if an error occurred. + +Note that this function retrieves I data item only. + +=item B + +This function takes a B pointer and is expected to +return 1 to indicate that the end of available data has been reached. +It is otherwise expected to return 0. + +=item B + +This function takes a B pointer and is expected to +return 1 to indicate that an error occured in a previous call to the +B function. +It is otherwise expected to return 0. + +=item B + +This function takes a B pointer and is expected to +close or shut down what needs to be closed, and finally free the +contents of the B pointer. +It returns 1 on success and 0 on error. + +=back + +=head2 Functions + +OSSL_STORE_LOADER_new() creates a new B. +It takes an B B and a string B. +B must I be set. +Both B and B are used as is and must therefore be alive as +long as the created loader is. + +OSSL_STORE_LOADER_get0_engine() returns the engine of the B. +OSSL_STORE_LOADER_get0_scheme() returns the scheme of the B. + +OSSL_STORE_LOADER_set_open() sets the opener function for the +B. + +OSSL_STORE_LOADER_set_ctrl() sets the control function for the +B. + +OSSL_STORE_LOADER_set_expect() sets the expect function for the +B. + +OSSL_STORE_LOADER_set_load() sets the loader function for the +B. + +OSSL_STORE_LOADER_set_eof() sets the end of file checker function for the +B. + +OSSL_STORE_LOADER_set_close() sets the closing function for the +B. + +OSSL_STORE_LOADER_free() frees the given B. + +OSSL_STORE_register_loader() register the given B and thereby +makes it available for use with OSSL_STORE_open(), OSSL_STORE_load(), +OSSL_STORE_eof() and OSSL_STORE_close(). + +OSSL_STORE_unregister_loader() unregister the store loader for the given +B. + +=head1 NOTES + +The B scheme has built in support. + +=head1 RETURN VALUES + +The functions with the types B, B, +B, +B, B and B have the +same return values as OSSL_STORE_open(), OSSL_STORE_ctrl(), OSSL_STORE_expect(), +OSSL_STORE_load(), OSSL_STORE_eof() and OSSL_STORE_close(), respectively. + +OSSL_STORE_LOADER_new() returns a pointer to a B on success, +or B on failure. + +OSSL_STORE_LOADER_set_open(), OSSL_STORE_LOADER_set_ctrl(), +OSSL_STORE_LOADER_set_load(), OSSL_STORE_LOADER_set_eof() and +OSSL_STORE_LOADER_set_close() return 1 on success, or 0 on failure. + +OSSL_STORE_register_loader() returns 1 on success, or 0 on failure. + +OSSL_STORE_unregister_loader() returns the unregistered loader on success, +or B on failure. + +=head1 SEE ALSO + +L, L + +=head1 HISTORY + +OSSL_STORE_LOADER(), OSSL_STORE_LOADER_CTX(), OSSL_STORE_LOADER_new(), +OSSL_STORE_LOADER_set0_scheme(), OSSL_STORE_LOADER_set_open(), +OSSL_STORE_LOADER_set_ctrl(), OSSL_STORE_LOADER_set_load(), +OSSL_STORE_LOADER_set_eof(), OSSL_STORE_LOADER_set_close(), +OSSL_STORE_LOADER_free(), OSSL_STORE_register_loader(), +OSSL_STORE_unregister_loader(), OSSL_STORE_open_fn(), OSSL_STORE_ctrl_fn(), +OSSL_STORE_load_fn(), OSSL_STORE_eof_fn() and OSSL_STORE_close_fn() +were added to OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2016-2018 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 +L. + +=cut diff --git a/doc/man3/OSSL_STORE_SEARCH.pod b/doc/man3/OSSL_STORE_SEARCH.pod new file mode 100644 index 00000000..411664d4 --- /dev/null +++ b/doc/man3/OSSL_STORE_SEARCH.pod @@ -0,0 +1,193 @@ +=pod + +=head1 NAME + +OSSL_STORE_SEARCH, +OSSL_STORE_SEARCH_by_name, +OSSL_STORE_SEARCH_by_issuer_serial, +OSSL_STORE_SEARCH_by_key_fingerprint, +OSSL_STORE_SEARCH_by_alias, +OSSL_STORE_SEARCH_free, +OSSL_STORE_SEARCH_get_type, +OSSL_STORE_SEARCH_get0_name, +OSSL_STORE_SEARCH_get0_serial, +OSSL_STORE_SEARCH_get0_bytes, +OSSL_STORE_SEARCH_get0_string, +OSSL_STORE_SEARCH_get0_digest +- Type and functions to create OSSL_STORE search criteria + +=head1 SYNOPSIS + + #include + + typedef struct ossl_store_search_st OSSL_STORE_SEARCH; + + OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_name(X509_NAME *name); + OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_issuer_serial(X509_NAME *name, + const ASN1_INTEGER + *serial); + OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_key_fingerprint(const EVP_MD *digest, + const unsigned char + *bytes, int len); + OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_alias(const char *alias); + + void OSSL_STORE_SEARCH_free(OSSL_STORE_SEARCH *search); + + int OSSL_STORE_SEARCH_get_type(const OSSL_STORE_SEARCH *criterion); + X509_NAME *OSSL_STORE_SEARCH_get0_name(OSSL_STORE_SEARCH *criterion); + const ASN1_INTEGER *OSSL_STORE_SEARCH_get0_serial(const OSSL_STORE_SEARCH + *criterion); + const unsigned char *OSSL_STORE_SEARCH_get0_bytes(const OSSL_STORE_SEARCH + *criterion, size_t *length); + const char *OSSL_STORE_SEARCH_get0_string(const OSSL_STORE_SEARCH *criterion); + const EVP_MD *OSSL_STORE_SEARCH_get0_digest(const OSSL_STORE_SEARCH + *criterion); + +=head1 DESCRIPTION + +These functions are use to specify search criteria to help search for specific +objects through other names than just the URI that's given to OSSL_STORE_open(). +For example, this can be useful for an application that has received a URI +and then wants to add on search criteria in a uniform and supported manner. + +=head2 Types + +B is an opaque type that holds the constructed search +criterion, and that can be given to an OSSL_STORE context with +OSSL_STORE_find(). + +The calling application owns the allocation of an B at all +times, and should therefore be careful not to deallocate it before +OSSL_STORE_close() has been called for the OSSL_STORE context it was given +to. + +=head2 Application Functions + +OSSL_STORE_SEARCH_by_name(), +OSSL_STORE_SEARCH_by_issuer_serial(), +OSSL_STORE_SEARCH_by_key_fingerprint(), +and OSSL_STORE_SEARCH_by_alias() +are used to create an B from a subject name, an issuer name +and serial number pair, a key fingerprint, and an alias (for example a friendly +name). +The parameters that are provided are not copied, only referred to in a +criterion, so they must have at least the same life time as the created +B. + +OSSL_STORE_SEARCH_free() is used to free the B. + +=head2 Loader Functions + +OSSL_STORE_SEARCH_get_type() returns the criterion type for the given +B. + +OSSL_STORE_SEARCH_get0_name(), OSSL_STORE_SEARCH_get0_serial(), +OSSL_STORE_SEARCH_get0_bytes(), OSSL_STORE_SEARCH_get0_string(), +and OSSL_STORE_SEARCH_get0_digest() +are used to retrieve different data from a B, as +available for each type. +For more information, see L below. + +=head1 SUPPORTED CRITERION TYPES + +Currently supported criterion types are: + +=over 4 + +=item OSSL_STORE_SEARCH_BY_NAME + +This criterion supports a search by exact match of subject name. +The subject name itself is a B pointer. +A criterion of this type is created with OSSL_STORE_SEARCH_by_name(), +and the actual subject name is retrieved with OSSL_STORE_SEARCH_get0_name(). + +=item OSSL_STORE_SEARCH_BY_ISSUER_SERIAL + +This criterion supports a search by exact match of both issuer name and serial +number. +The issuer name itself is a B pointer, and the serial number is +a B pointer. +A criterion of this type is created with OSSL_STORE_SEARCH_by_issuer_serial() +and the actual issuer name and serial number are retrieved with +OSSL_STORE_SEARCH_get0_name() and OSSL_STORE_SEARCH_get0_serial(). + +=item OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT + +This criterion supports a search by exact match of key fingerprint. +The key fingerprint in itself is a string of bytes and its length, as +well as the algorithm that was used to compute the fingerprint. +The digest may be left unspecified (NULL), and in that case, the +loader has to decide on a default digest and compare fingerprints +accordingly. +A criterion of this type is created with OSSL_STORE_SEARCH_by_key_fingerprint() +and the actual fingerprint and its length can be retrieved with +OSSL_STORE_SEARCH_get0_bytes(). +The digest can be retreived with OSSL_STORE_SEARCH_get0_digest(). + +=item OSSL_STORE_SEARCH_BY_ALIAS + +This criterion supports a search by match of an alias of some kind. +The alias in itself is a simple C string. +A criterion of this type is created with OSSL_STORE_SEARCH_by_alias() +and the actual alias is retrieved with OSSL_STORE_SEARCH_get0_string(). + +=back + +=head1 RETURN VALUES + +OSSL_STORE_SEARCH_by_name(), +OSSL_STORE_SEARCH_by_issuer_serial(), +OSSL_STORE_SEARCH_by_key_fingerprint(), +and OSSL_STORE_SEARCH_by_alias() +return a B pointer on success, or B on failure. + +OSSL_STORE_SEARCH_get_type() returns the criterion type of the given +B. +There is no error value. + +OSSL_STORE_SEARCH_get0_name() returns a B pointer on success, +or B when the given B was of a different type. + +OSSL_STORE_SEARCH_get0_serial() returns a B pointer on success, +or B when the given B was of a different type. + +OSSL_STORE_SEARCH_get0_bytes() returns a B pointer and +sets B<*length> to the strings length on success, or B when the given +B was of a different type. + +OSSL_STORE_SEARCH_get0_string() returns a B pointer on success, +or B when the given B was of a different type. + +OSSL_STORE_SEARCH_get0_digest() returns a B pointer. +B is a valid value and means that the store loader default will +be used when applicable. + +=head1 SEE ALSO + +L, L, L + +=head1 HISTORY + +B, +OSSL_STORE_SEARCH_by_name(), +OSSL_STORE_SEARCH_by_issuer_serial(), +OSSL_STORE_SEARCH_by_key_fingerprint(), +OSSL_STORE_SEARCH_by_alias(), +OSSL_STORE_SEARCH_free(), +OSSL_STORE_SEARCH_get_type(), +OSSL_STORE_SEARCH_get0_name(), +OSSL_STORE_SEARCH_get0_serial(), +OSSL_STORE_SEARCH_get0_bytes(), +and OSSL_STORE_SEARCH_get0_string() +were added to OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2018 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 +L. + +=cut diff --git a/doc/man3/OSSL_STORE_expect.pod b/doc/man3/OSSL_STORE_expect.pod new file mode 100644 index 00000000..ab0e8784 --- /dev/null +++ b/doc/man3/OSSL_STORE_expect.pod @@ -0,0 +1,79 @@ +=pod + +=head1 NAME + +OSSL_STORE_expect, +OSSL_STORE_supports_search, +OSSL_STORE_find +- Specify what object type is expected + +=head1 SYNOPSIS + + #include + + int OSSL_STORE_expect(OSSL_STORE_CTX *ctx, int expected_type); + + int OSSL_STORE_supports_search(OSSL_STORE_CTX *ctx, int criterion_type); + + int OSSL_STORE_find(OSSL_STORE_CTX *ctx, OSSL_STORE_SEARCH *search); + +=head1 DESCRIPTION + +OSSL_STORE_expect() helps applications filter what OSSL_STORE_load() returns +by specifying a B type. +For example, if C contains several different objects +and only the certificates are interesting, the application can simply say +that it expects the type B. +All known object types (see L) +except for B are supported. + +OSSL_STORE_find() helps applications specify a criterion for a more fine +grained search of objects. + +OSSL_STORE_supports_search() checks if the loader of the given OSSL_STORE +context supports the given search type. +See L for information on the +supported search criterion types. + +OSSL_STORE_expect() and OSSL_STORE_find I be called before the first +OSSL_STORE_load() of a given session, or they will fail. + +=head1 NOTES + +If a more elaborate filter is required by the application, a better choice +would be to use a post-processing function. +See L for more information. + +However, some loaders may take advantage of the knowledge of an expected type +to make object retrieval more efficient, so if a single type is expected, this +method is usually preferable. + +=head1 RETURN VALUES + +OSSL_STORE_expect() returns 1 on success, or 0 on failure. + +OSSL_STORE_supports_search() returns 1 if the criterion is supported, or 0 +otherwise. + +OSSL_STORE_find() returns 1 on success, or 0 on failure. + +=head1 SEE ALSO + +L, L, L, +L + +=head1 HISTORY + +OSSL_STORE_expect(), OSSL_STORE_supports_search() and OSSL_STORE_find() +were added to OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2018 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 +L. + +=cut diff --git a/doc/man3/OSSL_STORE_open.pod b/doc/man3/OSSL_STORE_open.pod new file mode 100644 index 00000000..3a05a880 --- /dev/null +++ b/doc/man3/OSSL_STORE_open.pod @@ -0,0 +1,152 @@ +=pod + +=head1 NAME + +OSSL_STORE_CTX, OSSL_STORE_post_process_info_fn, OSSL_STORE_open, +OSSL_STORE_ctrl, OSSL_STORE_load, OSSL_STORE_eof, OSSL_STORE_error, +OSSL_STORE_close - Types and functions to read objects from a URI + +=head1 SYNOPSIS + + #include + + typedef struct ossl_store_ctx_st OSSL_STORE_CTX; + + typedef OSSL_STORE_INFO *(*OSSL_STORE_post_process_info_fn)(OSSL_STORE_INFO *, + void *); + + OSSL_STORE_CTX *OSSL_STORE_open(const char *uri, const UI_METHOD *ui_method, + void *ui_data, + OSSL_STORE_post_process_info_fn post_process, + void *post_process_data); + int OSSL_STORE_ctrl(OSSL_STORE_CTX *ctx, int cmd, ... /* args */); + OSSL_STORE_INFO *OSSL_STORE_load(OSSL_STORE_CTX *ctx); + int OSSL_STORE_eof(OSSL_STORE_CTX *ctx); + int OSSL_STORE_error(OSSL_STORE_CTX *ctx); + int OSSL_STORE_close(OSSL_STORE_CTX *ctx); + +=head1 DESCRIPTION + +These functions help the application to fetch supported objects (see +L for information on which those are) +from a given URI (see L for more information on +the supported URI schemes). +The general method to do so is to "open" the URI using OSSL_STORE_open(), +read each available and supported object using OSSL_STORE_load() as long as +OSSL_STORE_eof() hasn't been reached, and finish it off with OSSL_STORE_close(). + +The retrieved information is stored in a B, which is further +described in L. + +=head2 Types + +B is a context variable that holds all the internal +information for OSSL_STORE_open(), OSSL_STORE_load(), OSSL_STORE_eof() and +OSSL_STORE_close() to work together. + +=head2 Functions + +OSSL_STORE_open() takes a uri or path B, password UI method +B with associated data B, and post processing +callback B with associated data B, +opens a channel to the data located at that URI and returns a +B with all necessary internal information. +The given B and B will be reused by all +functions that use B when interaction is needed. +The given B and B will be reused by +OSSL_STORE_load() to manipulate or drop the value to be returned. +The B function drops values by returning B, which +will cause OSSL_STORE_load() to start its process over with loading +the next object, until B returns something other than +B, or the end of data is reached as indicated by OSSL_STORE_eof(). + +OSSL_STORE_ctrl() takes a B, and command number B and +more arguments not specified here. +The available loader specific command numbers and arguments they each +take depends on the loader that's used and is documented together with +that loader. + +There are also global controls available: + +=over 4 + +=item B + +Controls if the loader should attempt to use secure memory for any +allocated B and its contents. +This control expects one argument, a pointer to an B that is expected to +have the value 1 (yes) or 0 (no). +Any other value is an error. + +=back + +OSSL_STORE_load() takes a B, tries to load the next available +object and return it wrapped with B. + +OSSL_STORE_eof() takes a B and checks if we've reached the end +of data. + +OSSL_STORE_error() takes a B and checks if an error occured in +the last OSSL_STORE_load() call. +Note that it may still be meaningful to try and load more objects, unless +OSSL_STORE_eof() shows that the end of data has been reached. + +OSSL_STORE_close() takes a B, closes the channel that was opened +by OSSL_STORE_open() and frees all other information that was stored in the +B, as well as the B itself. + +=head1 SUPPORTED SCHEMES + +The basic supported scheme is B. +Any other scheme can be added dynamically, using +OSSL_STORE_register_loader(). + +=head1 NOTES + +A string without a scheme prefix (that is, a non-URI string) is +implicitly interpreted as using the F scheme. + +There are some tools that can be used together with +OSSL_STORE_open() to determine if any failure is caused by an unparsable +URI, or if it's a different error (such as memory allocation +failures); if the URI was parsable but the scheme unregistered, the +top error will have the reason C. + +=head1 RETURN VALUES + +OSSL_STORE_open() returns a pointer to a B on success, or +B on failure. + +OSSL_STORE_load() returns a pointer to a B on success, or +B on error or when end of data is reached. +Use OSSL_STORE_error() and OSSL_STORE_eof() to determine the meaning of a +returned B. + +OSSL_STORE_eof() returns 1 if the end of data has been reached, otherwise +0. + +OSSL_STORE_error() returns 1 if an error occured in a OSSL_STORE_load() call, +otherwise 0. + +OSSL_STORE_ctrl() and OSSL_STORE_close() returns 1 on success, or 0 on failure. + +=head1 SEE ALSO + +L, L, L + +=head1 HISTORY + +OSSL_STORE_CTX(), OSSL_STORE_post_process_info_fn(), OSSL_STORE_open(), +OSSL_STORE_ctrl(), OSSL_STORE_load(), OSSL_STORE_eof() and OSSL_STORE_close() +were added to OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2016-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 +L. + +=cut diff --git a/doc/man3/OpenSSL_add_all_algorithms.pod b/doc/man3/OpenSSL_add_all_algorithms.pod new file mode 100644 index 00000000..0c086d12 --- /dev/null +++ b/doc/man3/OpenSSL_add_all_algorithms.pod @@ -0,0 +1,63 @@ +=pod + +=head1 NAME + +OpenSSL_add_all_algorithms, OpenSSL_add_all_ciphers, OpenSSL_add_all_digests, EVP_cleanup - +add algorithms to internal table + +=head1 SYNOPSIS + + #include + +Deprecated: + + # if OPENSSL_API_COMPAT < 0x10100000L + void OpenSSL_add_all_algorithms(void); + void OpenSSL_add_all_ciphers(void); + void OpenSSL_add_all_digests(void); + + void EVP_cleanup(void) +# endif + +=head1 DESCRIPTION + +OpenSSL keeps an internal table of digest algorithms and ciphers. It uses +this table to lookup ciphers via functions such as EVP_get_cipher_byname(). + +OpenSSL_add_all_digests() adds all digest algorithms to the table. + +OpenSSL_add_all_algorithms() adds all algorithms to the table (digests and +ciphers). + +OpenSSL_add_all_ciphers() adds all encryption algorithms to the table including +password based encryption algorithms. + +In versions prior to 1.1.0 EVP_cleanup() removed all ciphers and digests from +the table. It no longer has any effect in OpenSSL 1.1.0. + +=head1 RETURN VALUES + +None of the functions return a value. + +=head1 SEE ALSO + +L, L, +L + +=head1 HISTORY + +The OpenSSL_add_all_algorithms(), OpenSSL_add_all_ciphers(), +OpenSSL_add_all_digests(), and EVP_cleanup(), functions +were deprecated in OpenSSL 1.1.0 by OPENSSL_init_crypto() and should +not be used. + +=head1 COPYRIGHT + +Copyright 2000-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 +L. + +=cut diff --git a/doc/man3/PEM_bytes_read_bio.pod b/doc/man3/PEM_bytes_read_bio.pod new file mode 100644 index 00000000..d16ccd8c --- /dev/null +++ b/doc/man3/PEM_bytes_read_bio.pod @@ -0,0 +1,81 @@ +=pod + +=head1 NAME + +PEM_bytes_read_bio, PEM_bytes_read_bio_secmem - read a PEM-encoded data structure from a BIO + +=head1 SYNOPSIS + + #include + + int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm, + const char *name, BIO *bp, pem_password_cb *cb, + void *u); + int PEM_bytes_read_bio_secmem(unsigned char **pdata, long *plen, char **pnm, + const char *name, BIO *bp, pem_password_cb *cb, + void *u); + +=head1 DESCRIPTION + +PEM_bytes_read_bio() reads PEM-formatted (RFC 1421) data from the BIO +I for the data type given in I (RSA PRIVATE KEY, CERTIFICATE, +etc.). If multiple PEM-encoded data structures are present in the same +stream, PEM_bytes_read_bio() will skip non-matching data types and +continue reading. Non-PEM data present in the stream may cause an +error. + +The PEM header may indicate that the following data is encrypted; if so, +the data will be decrypted, waiting on user input to supply a passphrase +if needed. The password callback I and rock I are used to obtain +the decryption passphrase, if applicable. + +Some data types have compatibility aliases, such as a file containing +X509 CERTIFICATE matching a request for the deprecated type CERTIFICATE. +The actual type indicated by the file is returned in I<*pnm> if I is +non-NULL. The caller must free the storage pointed to by I<*pnm>. + +The returned data is the DER-encoded form of the requested type, in +I<*pdata> with length I<*plen>. The caller must free the storage pointed +to by I<*pdata>. + +PEM_bytes_read_bio_secmem() is similar to PEM_bytes_read_bio(), but uses +memory from the secure heap for its temporary buffers and the storage +returned in I<*pdata> and I<*pnm>. Accordingly, the caller must use +OPENSSL_secure_free() to free that storage. + +=head1 NOTES + +PEM_bytes_read_bio_secmem() only enforces that the secure heap is used for +storage allocated within the PEM processing stack. The BIO stack from +which input is read may also use temporary buffers, which are not necessarily +allocated from the secure heap. In cases where it is desirable to ensure +that the contents of the PEM file only appears in memory from the secure heap, +care is needed in generating the BIO passed as I. In particular, the +use of BIO_s_file() indicates the use of the operating system stdio +functionality, which includes buffering as a feature; BIO_s_fd() is likely +to be more appropriate in such cases. + +=head1 RETURN VALUES + +PEM_bytes_read_bio() and PEM_bytes_read_bio_secmem() return 1 for success or +0 for failure. + +=head1 SEE ALSO + +L, +L + +=head1 HISTORY + +PEM_bytes_read_bio_secmem() was introduced in OpenSSL 1.1.1 + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/crypto/PEM_read.pod b/doc/man3/PEM_read.pod similarity index 100% rename from doc/crypto/PEM_read.pod rename to doc/man3/PEM_read.pod diff --git a/doc/crypto/PEM_read_CMS.pod b/doc/man3/PEM_read_CMS.pod similarity index 100% rename from doc/crypto/PEM_read_CMS.pod rename to doc/man3/PEM_read_CMS.pod index 649c8089..65a114d6 100644 --- a/doc/crypto/PEM_read_CMS.pod +++ b/doc/man3/PEM_read_CMS.pod @@ -38,10 +38,10 @@ PEM_write_SSL_SESSION, PEM_write_bio_SSL_SESSION - PEM object encoding routines -=for comment generic - =head1 SYNOPSIS +=for comment generic + #include DECLARE_PEM_rw(name, TYPE) diff --git a/doc/crypto/PEM_read_bio_PrivateKey.pod b/doc/man3/PEM_read_bio_PrivateKey.pod similarity index 96% rename from doc/crypto/PEM_read_bio_PrivateKey.pod rename to doc/man3/PEM_read_bio_PrivateKey.pod index 6b3006ef..4ff5b2d3 100644 --- a/doc/crypto/PEM_read_bio_PrivateKey.pod +++ b/doc/man3/PEM_read_bio_PrivateKey.pod @@ -161,17 +161,18 @@ For more details about the meaning of arguments see the B section. Each operation has four functions associated with it. For -clarity the term "B functions" will be used to collectively -refer to the PEM_read_bio_foobar(), PEM_read_foobar(), -PEM_write_bio_foobar() and PEM_write_foobar() functions. +brevity the term "B functions" will be used below to collectively +refer to the PEM_read_bio_TYPE(), PEM_read_TYPE(), +PEM_write_bio_TYPE(), and PEM_write_TYPE() functions. The B functions read or write a private key in PEM format using an EVP_PKEY structure. The write routines use PKCS#8 private key format and are equivalent to PEM_write_bio_PKCS8PrivateKey().The read functions transparently handle traditional and PKCS#8 format encrypted and unencrypted keys. -PEM_write_bio_PrivateKey_traditional() writes out a private key in legacy -"traditional" format. +PEM_write_bio_PrivateKey_traditional() writes out a private key in the +"traditional" format with a simple private key marker and should only +be used for compatibility with legacy programs. PEM_write_bio_PKCS8PrivateKey() and PEM_write_PKCS8PrivateKey() write a private key in an EVP_PKEY structure in PKCS#8 EncryptedPrivateKeyInfo format using @@ -305,44 +306,41 @@ most of them are set to 0 or NULL. Read a certificate in PEM format from a BIO: X509 *x; + x = PEM_read_bio_X509(bp, NULL, 0, NULL); - if (x == NULL) { + if (x == NULL) /* Error */ - } Alternative method: X509 *x = NULL; - if (!PEM_read_bio_X509(bp, &x, 0, NULL)) { + + if (!PEM_read_bio_X509(bp, &x, 0, NULL)) /* Error */ - } Write a certificate to a BIO: - if (!PEM_write_bio_X509(bp, x)) { + if (!PEM_write_bio_X509(bp, x)) /* Error */ - } Write a private key (using traditional format) to a BIO using triple DES encryption, the pass phrase is prompted for: - if (!PEM_write_bio_PrivateKey(bp, key, EVP_des_ede3_cbc(), NULL, 0, 0, NULL)) { + if (!PEM_write_bio_PrivateKey(bp, key, EVP_des_ede3_cbc(), NULL, 0, 0, NULL)) /* Error */ - } Write a private key (using PKCS#8 format) to a BIO using triple DES encryption, using the pass phrase "hello": - if (!PEM_write_bio_PKCS8PrivateKey(bp, key, EVP_des_ede3_cbc(), NULL, 0, 0, "hello")) { + if (!PEM_write_bio_PKCS8PrivateKey(bp, key, EVP_des_ede3_cbc(), + NULL, 0, 0, "hello")) /* Error */ - } Read a private key from a BIO using a pass phrase callback: key = PEM_read_bio_PrivateKey(bp, NULL, pass_cb, "My Private Key"); - if (key == NULL) { + if (key == NULL) /* Error */ - } Skeleton pass phrase callback: @@ -382,6 +380,7 @@ A frequent cause of problems is attempting to use the PEM routines like this: X509 *x; + PEM_read_bio_X509(bp, &x, 0, NULL); this is a bug because an attempt will be made to reuse the data at B @@ -432,9 +431,8 @@ The pseudo code to derive the key would look similar to: memcpy(iv, HexToBin("3F17F5316E2BAC89"), niv); rc = EVP_BytesToKey(cipher, md, iv /*salt*/, pword, plen, 1, key, NULL /*iv*/); - if (rc != nkey) { + if (rc != nkey) /* Error */ - } /* On success, use key and iv to initialize the cipher */ @@ -452,7 +450,7 @@ where B already contains a valid certificate, may not work, whereas: is guaranteed to work. -=head1 RETURN CODES +=head1 RETURN VALUES The read routines return either a pointer to the structure read or NULL if an error occurred. @@ -462,7 +460,7 @@ The write routines return 1 for success or 0 for failure. =head1 HISTORY The old Netscape certificate sequences were no longer documented -in OpenSSL 1.1; applications should use the PKCS7 standard instead +in OpenSSL 1.1.0; applications should use the PKCS7 standard instead as they will be formally deprecated in a future releases. =head1 SEE ALSO @@ -471,7 +469,7 @@ L, L =head1 COPYRIGHT -Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2001-2018 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 diff --git a/doc/man3/PEM_read_bio_ex.pod b/doc/man3/PEM_read_bio_ex.pod new file mode 100644 index 00000000..e171bff2 --- /dev/null +++ b/doc/man3/PEM_read_bio_ex.pod @@ -0,0 +1,70 @@ +=pod + +=head1 NAME + +PEM_read_bio_ex, PEM_FLAG_SECURE, PEM_FLAG_EAY_COMPATIBLE, +PEM_FLAG_ONLY_B64 - read PEM format files with custom processing + +=head1 SYNOPSIS + + #include + + #define PEM_FLAG_SECURE 0x1 + #define PEM_FLAG_EAY_COMPATIBLE 0x2 + #define PEM_FLAG_ONLY_B64 0x4 + int PEM_read_bio_ex(BIO *in, char **name, char **header, + unsigned char **data, long *len, unsigned int flags); + +=head1 DESCRIPTION + +PEM_read_bio_ex() reads in PEM formatted data from an input BIO, outputting +the name of the type of contained data, the header information regarding +the possibly encrypted data, and the binary data payload (after base64 decoding). +It should generally only be used to implement PEM_read_bio_-family functions +for specific data types or other usage, but is exposed to allow greater flexibility +over how processing is performed, if needed. + +If PEM_FLAG_SECURE is set, the intermediate buffers used to read in lines of +input are allocated from the secure heap. + +If PEM_FLAG_EAY_COMPATIBLE is set, a simple algorithm is used to remove whitespace +and control characters from the end of each line, so as to be compatible with +the historical behavior of PEM_read_bio(). + +If PEM_FLAG_ONLY_B64 is set, all characters are required to be valid base64 +characters (or newlines); non-base64 characters are treated as end of input. + +If neither PEM_FLAG_EAY_COMPATIBLE or PEM_FLAG_ONLY_B64 is set, control characters +are ignored. + +If both PEM_FLAG_EAY_COMPATIBLE and PEM_FLAG_ONLY_B64 are set, an error is returned; +these options are not compatible with each other. + +=head1 NOTES + +The caller must release the storage allocated for *name, *header, and *data. +If PEM_FLAG_SECURE was set, use OPENSSL_secure_free(); otherwise, +OPENSSL_free() is used. + +=head1 RETURN VALUES + +PEM_read_bio_ex() returns 1 for success or 0 for failure. + +=head1 SEE ALSO + +L + +=head1 HISTORY + +PEM_read_bio_ex() was added in OpenSSL 1.1.1. + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/crypto/PEM_write_bio_CMS_stream.pod b/doc/man3/PEM_write_bio_CMS_stream.pod similarity index 100% rename from doc/crypto/PEM_write_bio_CMS_stream.pod rename to doc/man3/PEM_write_bio_CMS_stream.pod diff --git a/doc/crypto/PEM_write_bio_PKCS7_stream.pod b/doc/man3/PEM_write_bio_PKCS7_stream.pod similarity index 100% rename from doc/crypto/PEM_write_bio_PKCS7_stream.pod rename to doc/man3/PEM_write_bio_PKCS7_stream.pod diff --git a/doc/crypto/PKCS12_create.pod b/doc/man3/PKCS12_create.pod similarity index 94% rename from doc/crypto/PKCS12_create.pod rename to doc/man3/PKCS12_create.pod index 0a43b96c..37b53be8 100644 --- a/doc/crypto/PKCS12_create.pod +++ b/doc/man3/PKCS12_create.pod @@ -60,13 +60,17 @@ should be used. B can be set to -1 and the MAC will then be omitted entirely. +=head1 RETURN VALUES + +PKCS12_create() returns a valid B structure or NULL if an error occurred. + =head1 SEE ALSO L =head1 COPYRIGHT -Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2002-2018 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 diff --git a/doc/man3/PKCS12_newpass.pod b/doc/man3/PKCS12_newpass.pod new file mode 100644 index 00000000..58207f5e --- /dev/null +++ b/doc/man3/PKCS12_newpass.pod @@ -0,0 +1,116 @@ +=pod + +=head1 NAME + +PKCS12_newpass - change the password of a PKCS12 structure + +=head1 SYNOPSIS + + #include + + int PKCS12_newpass(PKCS12 *p12, const char *oldpass, const char *newpass); + +=head1 DESCRIPTION + +PKCS12_newpass() changes the password of a PKCS12 structure. + +B is a pointer to a PKCS12 structure. B is the existing password +and B is the new password. + +=head1 NOTES + +Each of B and B is independently interpreted as a string in +the UTF-8 encoding. If it is not valid UTF-8, it is assumed to be ISO8859-1 +instead. + +In particular, this means that passwords in the locale character set +(or code page on Windows) must potentially be converted to UTF-8 before +use. This may include passwords from local text files, or input from +the terminal or command line. Refer to the documentation of +L, for example. + +=head1 RETURN VALUES + +PKCS12_newpass() returns 1 on success or 0 on failure. Applications can +retrieve the most recent error from PKCS12_newpass() with ERR_get_error(). + +=head1 EXAMPLE + +This example loads a PKCS#12 file, changes its password and writes out +the result to a new file. + + #include + #include + #include + #include + #include + + int main(int argc, char **argv) + { + FILE *fp; + PKCS12 *p12; + + if (argc != 5) { + fprintf(stderr, "Usage: pkread p12file password newpass opfile\n"); + return 1; + } + if ((fp = fopen(argv[1], "rb")) == NULL) { + fprintf(stderr, "Error opening file %s\n", argv[1]); + return 1; + } + p12 = d2i_PKCS12_fp(fp, NULL); + fclose(fp); + if (p12 == NULL) { + fprintf(stderr, "Error reading PKCS#12 file\n"); + ERR_print_errors_fp(stderr); + return 1; + } + if (PKCS12_newpass(p12, argv[2], argv[3]) == 0) { + fprintf(stderr, "Error changing password\n"); + ERR_print_errors_fp(stderr); + PKCS12_free(p12); + return 1; + } + if ((fp = fopen(argv[4], "wb")) == NULL) { + fprintf(stderr, "Error opening file %s\n", argv[4]); + PKCS12_free(p12); + return 1; + } + i2d_PKCS12_fp(fp, p12); + PKCS12_free(p12); + fclose(fp); + return 0; + } + + +=head1 NOTES + +If the PKCS#12 structure does not have a password, then you must use the empty +string "" for B. Using NULL for B will result in a +PKCS12_newpass() failure. + +If the wrong password is used for B then the function will fail, +with a MAC verification error. In rare cases the PKCS12 structure does not +contain a MAC: in this case it will usually fail with a decryption padding +error. + +=head1 BUGS + +The password format is a NULL terminated ASCII string which is converted to +Unicode form internally. As a result some passwords cannot be supplied to +this function. + +=head1 SEE ALSO + +L, L + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/crypto/PKCS12_parse.pod b/doc/man3/PKCS12_parse.pod similarity index 100% rename from doc/crypto/PKCS12_parse.pod rename to doc/man3/PKCS12_parse.pod diff --git a/doc/crypto/PKCS5_PBKDF2_HMAC.pod b/doc/man3/PKCS5_PBKDF2_HMAC.pod similarity index 91% rename from doc/crypto/PKCS5_PBKDF2_HMAC.pod rename to doc/man3/PKCS5_PBKDF2_HMAC.pod index 5cc2caa5..e5d1689e 100644 --- a/doc/crypto/PKCS5_PBKDF2_HMAC.pod +++ b/doc/man3/PKCS5_PBKDF2_HMAC.pod @@ -13,9 +13,9 @@ PKCS5_PBKDF2_HMAC, PKCS5_PBKDF2_HMAC_SHA1 - password based derivation routines w const EVP_MD *digest, int keylen, unsigned char *out); -int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen, - const unsigned char *salt, int saltlen, int iter, - int keylen, unsigned char *out); + int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen, + const unsigned char *salt, int saltlen, int iter, + int keylen, unsigned char *out); =head1 DESCRIPTION @@ -58,7 +58,7 @@ PKCS5_PBKDF2_HMAC() and PBKCS5_PBKDF2_HMAC_SHA1() return 1 on success or 0 on er =head1 SEE ALSO -L, L, +L, L, L =head1 COPYRIGHT diff --git a/doc/crypto/PKCS7_decrypt.pod b/doc/man3/PKCS7_decrypt.pod similarity index 100% rename from doc/crypto/PKCS7_decrypt.pod rename to doc/man3/PKCS7_decrypt.pod diff --git a/doc/crypto/PKCS7_encrypt.pod b/doc/man3/PKCS7_encrypt.pod similarity index 98% rename from doc/crypto/PKCS7_encrypt.pod rename to doc/man3/PKCS7_encrypt.pod index 4e1afc91..9895a1f7 100644 --- a/doc/crypto/PKCS7_encrypt.pod +++ b/doc/man3/PKCS7_encrypt.pod @@ -8,7 +8,8 @@ PKCS7_encrypt - create a PKCS#7 envelopedData structure #include - PKCS7 *PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, const EVP_CIPHER *cipher, int flags); + PKCS7 *PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, const EVP_CIPHER *cipher, + int flags); =head1 DESCRIPTION diff --git a/doc/crypto/PKCS7_sign.pod b/doc/man3/PKCS7_sign.pod similarity index 98% rename from doc/crypto/PKCS7_sign.pod rename to doc/man3/PKCS7_sign.pod index f319f664..c1df5f19 100644 --- a/doc/crypto/PKCS7_sign.pod +++ b/doc/man3/PKCS7_sign.pod @@ -8,7 +8,8 @@ PKCS7_sign - create a PKCS#7 signedData structure #include - PKCS7 *PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, BIO *data, int flags); + PKCS7 *PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, + BIO *data, int flags); =head1 DESCRIPTION @@ -65,7 +66,6 @@ way data can be signed in a single pass. If the B flag is set a partial B structure is output to which additional signers and capabilities can be added before finalization. - =head1 NOTES If the flag B is set the returned B structure is B diff --git a/doc/crypto/PKCS7_sign_add_signer.pod b/doc/man3/PKCS7_sign_add_signer.pod similarity index 97% rename from doc/crypto/PKCS7_sign_add_signer.pod rename to doc/man3/PKCS7_sign_add_signer.pod index 88fef771..2bc6c40b 100644 --- a/doc/crypto/PKCS7_sign_add_signer.pod +++ b/doc/man3/PKCS7_sign_add_signer.pod @@ -8,7 +8,8 @@ PKCS7_sign_add_signer - add a signer PKCS7 signed data structure #include - PKCS7_SIGNER_INFO *PKCS7_sign_add_signer(PKCS7 *p7, X509 *signcert, EVP_PKEY *pkey, const EVP_MD *md, int flags); + PKCS7_SIGNER_INFO *PKCS7_sign_add_signer(PKCS7 *p7, X509 *signcert, + EVP_PKEY *pkey, const EVP_MD *md, int flags); =head1 DESCRIPTION diff --git a/doc/crypto/PKCS7_verify.pod b/doc/man3/PKCS7_verify.pod similarity index 98% rename from doc/crypto/PKCS7_verify.pod rename to doc/man3/PKCS7_verify.pod index c34808ec..ebcdde07 100644 --- a/doc/crypto/PKCS7_verify.pod +++ b/doc/man3/PKCS7_verify.pod @@ -8,7 +8,8 @@ PKCS7_verify, PKCS7_get0_signers - verify a PKCS#7 signedData structure #include - int PKCS7_verify(PKCS7 *p7, STACK_OF(X509) *certs, X509_STORE *store, BIO *indata, BIO *out, int flags); + int PKCS7_verify(PKCS7 *p7, STACK_OF(X509) *certs, X509_STORE *store, + BIO *indata, BIO *out, int flags); STACK_OF(X509) *PKCS7_get0_signers(PKCS7 *p7, STACK_OF(X509) *certs, int flags); diff --git a/doc/man3/RAND_add.pod b/doc/man3/RAND_add.pod new file mode 100644 index 00000000..62048e67 --- /dev/null +++ b/doc/man3/RAND_add.pod @@ -0,0 +1,157 @@ +=pod + +=head1 NAME + +RAND_add, RAND_poll, RAND_seed, RAND_status, RAND_event, RAND_screen +- add randomness to the PRNG or get its status + +=head1 SYNOPSIS + + #include + + int RAND_status(void); + int RAND_poll(); + + void RAND_add(const void *buf, int num, double randomness); + void RAND_seed(const void *buf, int num); + +Deprecated: + + #if OPENSSL_API_COMPAT < 0x10100000L + int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam); + void RAND_screen(void); + #endif + +=head1 DESCRIPTION + +Random numbers are a vital part of cryptography, including key generation, +creating salts, etc., and software-based +generators must be "seeded" with external randomness before they can be +used as a cryptographically-secure pseudo-random number generator (CSPRNG). +The availability of common hardware with special instructions and +modern operating systems, which may use items such as interrupt jitter +and network packet timings, can be reasonable sources of seeding material. + +RAND_status() indicates whether or not the CSPRNG has been sufficiently +seeded. If not, functions such as RAND_bytes(3) will fail. + +RAND_poll() uses the system's capabilities to seed the CSPRNG using +random input obtained from polling various trusted entropy sources. +The default choice of the entropy source can be modified at build time +using the --with-rand-seed configure option, see also the B section. +A summary of the configure options can be displayed with the OpenSSL +L command. + +RAND_add() mixes the B bytes at B into the PRNG state. +The B argument is an estimate of how much randomness is +contained in +B, in bytes, and should be a number between zero and B. +Details about sources of randomness and how to estimate their randomness +can be found in the literature; for example NIST SP 800-90B. +The content of B cannot be recovered from subsequent CSPRNG output. +This function will not normally be needed, as RAND_poll() should have been +configured to do the appropriate seeding for the local platform. +Applications that need to keep random state in an external file should +use L. + +RAND_seed() is equivalent to RAND_add() with B set to B. + +RAND_event() and RAND_screen() are equivalent to RAND_poll(). + +=head1 RETURN VALUES + +RAND_status() returns 1 if the CSPRNG has been seeded +with enough data, 0 otherwise. + +RAND_poll() returns 1 if it generated seed data, 0 otherwise. + +RAND_event() returns RAND_status(). + +The other functions do not return values. + +=head1 NOTES + +The new OpenSSL DRBG has some peculiarities which need to be taken +into account when it is selected as the default OpenSSL CSPRNG, i.e., +when RAND_get_rand_method() == RAND_OpenSSL(). +This applies in particular to the way reseeding is done by the DRBG: + +=over 2 + +=item * + +The DRBG seeds itself automatically, pulling random input from trusted +entropy sources. +Automatic reseeding occurs after a predefined number of generate requests. +The selection of the trusted entropy sources is configured at build +time using the --with-rand-seed option. + +=item * + +The DRBG distinguishes two different types of random input: +'entropy', which comes from a trusted source, and 'additional input', +which can optionally be added by the user and is considered untrusted. + +=back + +Automatic seeding can be disabled using the --with-rand-seed=none option. + +=head2 DRBG with automatic seeding enabled + +Calling RAND_poll() or RAND_add() is not necessary, because the DRBG +polls the entropy source automatically. +However, both calls are permitted, and do reseed the RNG. + +RAND_add() can be used to add both kinds of random input, depending on the +value of the B argument: + +=over 4 + +=item randomness == 0: + +The random bytes are mixed as additional input into the current state of +the DRBG. +Mixing in additional input is not considered a full reseeding, hence the +reseed counter is not reset. + + +=item randomness > 0: + +The random bytes are used as entropy input for a full reseeding +(resp. reinstantiation) if the DRBG is instantiated +(resp. uninstantiated or in an error state). +A reseeding requires 16 bytes (128 bits) of randomness. +It is possible to provide less randomness than required. +In this case the missing randomness will be obtained by pulling random input +from the trusted entropy sources. + +=back + +=head2 DRBG with automatic seeding disabled (--with-rand-seed=none) + +Calling RAND_poll() will always fail. + +RAND_add() needs to be called for initial seeding and periodic reseeding. +At least 16 bytes (128 bits) of randomness have to be provided, otherwise +the (re-)seeding of the DRBG will fail. + +=head1 HISTORY + +RAND_event() and RAND_screen() were deprecated in OpenSSL 1.1.0 and should +not be used. + +=head1 SEE ALSO + +L, L, +L + +=head1 COPYRIGHT + +Copyright 2000-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 +L. + +=cut diff --git a/doc/man3/RAND_bytes.pod b/doc/man3/RAND_bytes.pod new file mode 100644 index 00000000..c3e6aef3 --- /dev/null +++ b/doc/man3/RAND_bytes.pod @@ -0,0 +1,56 @@ +=pod + +=head1 NAME + +RAND_bytes, RAND_priv_bytes, RAND_pseudo_bytes - generate random data + +=head1 SYNOPSIS + + #include + + int RAND_bytes(unsigned char *buf, int num); + int RAND_priv_bytes(unsigned char *buf, int num); + +Deprecated: + + #if OPENSSL_API_COMPAT < 0x10100000L + int RAND_pseudo_bytes(unsigned char *buf, int num); + #endif + +=head1 DESCRIPTION + +RAND_bytes() puts B cryptographically strong pseudo-random bytes +into B. An error occurs if the PRNG has not been seeded with +enough randomness to ensure an unpredictable byte sequence. + +RAND_priv_bytes() has the same semantics as RAND_bytes(). It is intended to +be used for generating long-term private keys. If using the default +RAND_METHOD, this function uses a separate instance of the PRNG so that +a compromise of the global generator will not affect such key generation. + +=head1 RETURN VALUES + +RAND_bytes() nad RAND_priv_bytes() +return 1 on success, -1 if not supported by the current +RAND method, or 0 on other failure. The error code can be +obtained by L. + +=head1 HISTORY + +RAND_pseudo_bytes() was deprecated in OpenSSL 1.1.0; use RAND_bytes() instead. + +=head1 SEE ALSO + +L, L, +L + +=head1 COPYRIGHT + +Copyright 2000-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 +L. + +=cut diff --git a/doc/man3/RAND_cleanup.pod b/doc/man3/RAND_cleanup.pod new file mode 100644 index 00000000..03a0798f --- /dev/null +++ b/doc/man3/RAND_cleanup.pod @@ -0,0 +1,40 @@ +=pod + +=head1 NAME + +RAND_cleanup - erase the PRNG state + +=head1 SYNOPSIS + + #include + + #if OPENSSL_API_COMPAT < 0x10100000L + void RAND_cleanup(void) + #endif + +=head1 DESCRIPTION + +Prior to OpenSSL 1.1.0, RAND_cleanup() released all resources used by +the PRNG. As of version 1.1.0, it does nothing and should not be called, +since no explicit initialisation or de-initialisation is necessary. See +L. + +=head1 RETURN VALUES + +RAND_cleanup() returns no value. + +=head1 HISTORY + +RAND_cleanup() was deprecated in OpenSSL 1.1.0; do not use it. +See L + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/man3/RAND_egd.pod b/doc/man3/RAND_egd.pod new file mode 100644 index 00000000..ebbaf303 --- /dev/null +++ b/doc/man3/RAND_egd.pod @@ -0,0 +1,59 @@ +=pod + +=head1 NAME + +RAND_egd, RAND_egd_bytes, RAND_query_egd_bytes - query entropy gathering daemon + +=head1 SYNOPSIS + + #include + + int RAND_egd_bytes(const char *path, int num); + int RAND_egd(const char *path); + + int RAND_query_egd_bytes(const char *path, unsigned char *buf, int num); + +=head1 DESCRIPTION + +On older platforms without a good source of randomness such as C, +it is possible to query an Entropy Gathering Daemon (EGD) over a local +socket to obtain randomness and seed the OpenSSL RNG. +The protocol used is defined by the EGDs available at +L or L. + +RAND_egd_bytes() requests B bytes of randomness from an EGD at the +specified socket B, and passes the data it receives into RAND_add(). +RAND_egd() is equivalent to RAND_egd_bytes() with B set to 255. + +RAND_query_egd_bytes() requests B bytes of randomness from an EGD at +the specified socket B, where B must be less than 256. +If B is B, it is equivalent to RAND_egd_bytes(). +If B is not B, then the data is copied to the buffer and +RAND_add() is not called. + +OpenSSL can be configured at build time to try to use the EGD for seeding +automatically. + +=head1 RETURN VALUES + +RAND_egd() and RAND_egd_bytes() return the number of bytes read from the +daemon on success, or -1 if the connection failed or the daemon did not +return enough data to fully seed the PRNG. + +RAND_query_egd_bytes() returns the number of bytes read from the daemon on +success, or -1 if the connection failed. + +=head1 SEE ALSO + +L, L + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/man3/RAND_load_file.pod b/doc/man3/RAND_load_file.pod new file mode 100644 index 00000000..2fe932fd --- /dev/null +++ b/doc/man3/RAND_load_file.pod @@ -0,0 +1,89 @@ +=pod + +=head1 NAME + +RAND_load_file, RAND_write_file, RAND_file_name - PRNG seed file + +=head1 SYNOPSIS + + #include + + int RAND_load_file(const char *filename, long max_bytes); + + int RAND_write_file(const char *filename); + + const char *RAND_file_name(char *buf, size_t num); + +=head1 DESCRIPTION + +RAND_load_file() reads a number of bytes from file B and +adds them to the PRNG. If B is non-negative, +up to B are read; +if B is -1, the complete file is read. +Do not load the same file multiple times unless its contents have +been updated by RAND_write_file() between reads. +Also, note that B should be adequately protected so that an +attacker cannot replace or examine the contents. + +RAND_write_file() writes a number of random bytes (currently 128) to +file B which can be used to initialize the PRNG by calling +RAND_load_file() in a later session. + +RAND_file_name() generates a default path for the random seed +file. B points to a buffer of size B in which to store the +filename. + +On all systems, if the environment variable B is set, its +value will be used as the seed file name. +Otherwise, the file is called C<.rnd>, found in platform dependent locations: + +=over 4 + +=item On Windows (in order of preference) + + %HOME%, %USERPROFILE%, %SYSTEMROOT%, C:\ + +=item On VMS + + SYS$LOGIN: + +=item On all other systems + + $HOME + +=back + +If C<$HOME> (on non-Windows and non-VMS system) is not set either, or +B is too small for the path name, an error occurs. + +=head1 RETURN VALUES + +RAND_load_file() returns the number of bytes read or -1 on error. + +RAND_write_file() returns the number of bytes written, or -1 if the +bytes written were generated without appropriate seeding. + +RAND_file_name() returns a pointer to B on success, and NULL on +error. + +=head1 SEE ALSO + +L, L + +=head1 HISTORY + +A comment in the source since at least OpenSSL 1.0.2 said that +RAND_load_file() and RAND_write_file() were only intended for regular files, +and not really device special files such as C. This was +poorly enforced before OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2000-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 +L. + +=cut diff --git a/doc/man3/RAND_set_rand_method.pod b/doc/man3/RAND_set_rand_method.pod new file mode 100644 index 00000000..70c1b23c --- /dev/null +++ b/doc/man3/RAND_set_rand_method.pod @@ -0,0 +1,68 @@ +=pod + +=head1 NAME + +RAND_set_rand_method, RAND_get_rand_method, RAND_OpenSSL - select RAND method + +=head1 SYNOPSIS + + #include + + RAND_METHOD *RAND_OpenSSL(void); + + void RAND_set_rand_method(const RAND_METHOD *meth); + + const RAND_METHOD *RAND_get_rand_method(void); + +=head1 DESCRIPTION + +A B specifies the functions that OpenSSL uses for random number +generation. + +Initially, the default B is the OpenSSL internal implementation, +as returned by RAND_OpenSSL(). +This implementation ensures that the PRNG state is unique for each thread. + +If an B is loaded that provides the RAND API, however, it will +be used instead of the method returned by RAND_OpenSSL(). + +RAND_set_rand_method() makes B the method for PRNG use. If an +ENGINE was providing the method, it will be released first. + +RAND_get_rand_method() returns a pointer to the current B. + +=head1 THE RAND_METHOD STRUCTURE + + typedef struct rand_meth_st { + void (*seed)(const void *buf, int num); + int (*bytes)(unsigned char *buf, int num); + void (*cleanup)(void); + void (*add)(const void *buf, int num, int randomness); + int (*pseudorand)(unsigned char *buf, int num); + int (*status)(void); + } RAND_METHOD; + +The fields point to functions that are used by, in order, +RAND_seed(), RAND_bytes(), internal RAND cleanup, RAND_add(), RAND_pseudo_rand() +and RAND_status(). +Each pointer may be NULL if the function is not implemented. + +=head1 RETURN VALUES + +RAND_set_rand_method() returns no value. RAND_get_rand_method() and +RAND_OpenSSL() return pointers to the respective methods. + +=head1 SEE ALSO + +L, L + +=head1 COPYRIGHT + +Copyright 2000-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 +L. + +=cut diff --git a/doc/crypto/RC4_set_key.pod b/doc/man3/RC4_set_key.pod similarity index 100% rename from doc/crypto/RC4_set_key.pod rename to doc/man3/RC4_set_key.pod diff --git a/doc/crypto/RIPEMD160_Init.pod b/doc/man3/RIPEMD160_Init.pod similarity index 87% rename from doc/crypto/RIPEMD160_Init.pod rename to doc/man3/RIPEMD160_Init.pod index a372e32c..77ac4fbc 100644 --- a/doc/crypto/RIPEMD160_Init.pod +++ b/doc/man3/RIPEMD160_Init.pod @@ -10,11 +10,10 @@ RIPEMD-160 hash function #include unsigned char *RIPEMD160(const unsigned char *d, unsigned long n, - unsigned char *md); + unsigned char *md); int RIPEMD160_Init(RIPEMD160_CTX *c); - int RIPEMD160_Update(RIPEMD_CTX *c, const void *data, - unsigned long len); + int RIPEMD160_Update(RIPEMD_CTX *c, const void *data, unsigned long len); int RIPEMD160_Final(unsigned char *md, RIPEMD160_CTX *c); =head1 DESCRIPTION @@ -54,7 +53,7 @@ functions directly. =head1 CONFORMING TO -ISO/IEC 10118-3 (draft) (??) +ISO/IEC 10118-3:2016 Dedicated Hash-Function 1 (RIPEMD-160). =head1 SEE ALSO @@ -62,7 +61,7 @@ L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/crypto/RSA_blinding_on.pod b/doc/man3/RSA_blinding_on.pod similarity index 100% rename from doc/crypto/RSA_blinding_on.pod rename to doc/man3/RSA_blinding_on.pod diff --git a/doc/crypto/RSA_check_key.pod b/doc/man3/RSA_check_key.pod similarity index 96% rename from doc/crypto/RSA_check_key.pod rename to doc/man3/RSA_check_key.pod index d8689f4a..8080b1a4 100644 --- a/doc/crypto/RSA_check_key.pod +++ b/doc/man3/RSA_check_key.pod @@ -33,7 +33,7 @@ manner as L. RSA_check_key() is equivalent to RSA_check_key_ex() with a NULL B. -=head1 RETURN VALUE +=head1 RETURN VALUES RSA_check_key_ex() and RSA_check_key() return 1 if B is a valid RSA key, and 0 otherwise. @@ -74,7 +74,7 @@ RSA_check_key_ex() appeared after OpenSSL 1.0.2. =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-2018 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 diff --git a/doc/man3/RSA_generate_key.pod b/doc/man3/RSA_generate_key.pod new file mode 100644 index 00000000..fb3d86ca --- /dev/null +++ b/doc/man3/RSA_generate_key.pod @@ -0,0 +1,107 @@ +=pod + +=head1 NAME + +RSA_generate_key_ex, RSA_generate_key, +RSA_generate_multi_prime_key - generate RSA key pair + +=head1 SYNOPSIS + + #include + + int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); + int RSA_generate_multi_prime_key(RSA *rsa, int bits, int primes, BIGNUM *e, BN_GENCB *cb); + +Deprecated: + + #if OPENSSL_API_COMPAT < 0x00908000L + RSA *RSA_generate_key(int num, unsigned long e, + void (*callback)(int, int, void *), void *cb_arg); + #endif + +=head1 DESCRIPTION + +RSA_generate_key_ex() generates a 2-prime RSA key pair and stores it in the +B structure provided in B. The pseudo-random number generator must +be seeded prior to calling RSA_generate_key_ex(). + +RSA_generate_multi_prime_key() generates a multi-prime RSA key pair and stores +it in the B structure provided in B. The number of primes is given by +the B parameter. The pseudo-random number generator must be seeded prior +to calling RSA_generate_multi_prime_key(). + +The modulus size will be of length B, the number of primes to form the +modulus will be B, and the public exponent will be B. Key sizes +with B E 1024 should be considered insecure. The exponent is an odd +number, typically 3, 17 or 65537. + +In order to maintain adequate security level, the maximum number of permitted +B depends on modulus bit length: + + <1024 | >=1024 | >=4096 | >=8192 + ------+--------+--------+------- + 2 | 3 | 4 | 5 + +A callback function may be used to provide feedback about the +progress of the key generation. If B is not B, it +will be called as follows using the BN_GENCB_call() function +described on the L page. + +RSA_generate_prime() is similar to RSA_generate_prime_ex() but +expects an old-style callback function; see +L for information on the old-style callback. + +=over 2 + +=item * + +While a random prime number is generated, it is called as +described in L. + +=item * + +When the n-th randomly generated prime is rejected as not +suitable for the key, B is called. + +=item * + +When a random p has been found with p-1 relatively prime to B, +it is called as B. + +=back + +The process is then repeated for prime q and other primes (if any) +with B where B indicates the i-th prime. + +=head1 RETURN VALUES + +RSA_generate_multi_prime_key() returns 1 on success or 0 on error. +RSA_generate_key_ex() returns 1 on success or 0 on error. +The error codes can be obtained by L. + +RSA_generate_key() returns a pointer to the RSA structure or +B if the key generation fails. + +=head1 BUGS + +B is used with two different meanings. + +=head1 SEE ALSO + +L, L, L + +=head1 HISTORY + +RSA_generate_key() was deprecated in OpenSSL 0.9.8; use +RSA_generate_key_ex() intsead. + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/man3/RSA_get0_key.pod b/doc/man3/RSA_get0_key.pod new file mode 100644 index 00000000..6e6576e7 --- /dev/null +++ b/doc/man3/RSA_get0_key.pod @@ -0,0 +1,155 @@ +=pod + +=head1 NAME + +RSA_set0_key, RSA_set0_factors, RSA_set0_crt_params, RSA_get0_key, +RSA_get0_factors, RSA_get0_crt_params, RSA_clear_flags, +RSA_test_flags, RSA_set_flags, RSA_get0_engine, RSA_get_multi_prime_extra_count, +RSA_get0_multi_prime_factors, RSA_get0_multi_prime_crt_params, +RSA_set0_multi_prime_params, RSA_get_version +- Routines for getting and setting data in an RSA object + +=head1 SYNOPSIS + + #include + + int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d); + int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q); + int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp); + void RSA_get0_key(const RSA *r, + const BIGNUM **n, const BIGNUM **e, const BIGNUM **d); + void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q); + void RSA_get0_crt_params(const RSA *r, + const BIGNUM **dmp1, const BIGNUM **dmq1, + const BIGNUM **iqmp); + void RSA_clear_flags(RSA *r, int flags); + int RSA_test_flags(const RSA *r, int flags); + void RSA_set_flags(RSA *r, int flags); + ENGINE *RSA_get0_engine(RSA *r); + int RSA_get_multi_prime_extra_count(const RSA *r); + int RSA_get0_multi_prime_factors(const RSA *r, const BIGNUM *primes[]); + int RSA_get0_multi_prime_crt_params(const RSA *r, const BIGNUM *exps[], + const BIGNUM *coeffs[]); + int RSA_set0_multi_prime_params(RSA *r, BIGNUM *primes[], BIGNUM *exps[], + BIGNUM *coeffs[], int pnum); + int RSA_get_version(RSA *r); + +=head1 DESCRIPTION + +An RSA object contains the components for the public and private key, +B, B, B, B

, B, B, B and B. B is +the modulus common to both public and private key, B is the public +exponent and B is the private exponent. B

, B, B, +B and B are the factors for the second representation of a +private key (see PKCS#1 section 3 Key Types), where B

and B are +the first and second factor of B and B, B and B +are the exponents and coefficient for CRT calculations. + +For multi-prime RSA (defined in RFC 8017), there are also one or more +'triplet' in an RSA object. A triplet contains three members, B, B +and B. B is the additional prime besides B

and B. B and +B are the exponent and coefficient for CRT calculations. + +The B, B and B parameters can be obtained by calling +RSA_get0_key(). If they have not been set yet, then B<*n>, B<*e> and +B<*d> will be set to NULL. Otherwise, they are set to pointers to +their respective values. These point directly to the internal +representations of the values and therefore should not be freed +by the caller. + +The B, B and B parameter values can be set by calling +RSA_set0_key() and passing the new values for B, B and B as +parameters to the function. The values B and B must be non-NULL +the first time this function is called on a given RSA object. The +value B may be NULL. On subsequent calls any of these values may be +NULL which means the corresponding RSA field is left untouched. +Calling this function transfers the memory management of the values to +the RSA object, and therefore the values that have been passed in +should not be freed by the caller after this function has been called. + +In a similar fashion, the B

and B parameters can be obtained and +set with RSA_get0_factors() and RSA_set0_factors(), and the B, +B and B parameters can be obtained and set with +RSA_get0_crt_params() and RSA_set0_crt_params(). + +For RSA_get0_key(), RSA_get0_factors(), and RSA_get0_crt_params(), +NULL value BIGNUM ** output parameters are permitted. The functions +ignore NULL parameters but return values for other, non-NULL, parameters. + +For multi-prime RSA, RSA_get0_multi_prime_factors() and RSA_get0_multi_prime_params() +can be used to obtain other primes and related CRT parameters. The +return values are stored in an array of B. RSA_set0_multi_prime_params() +sets a collect of multi-prime 'triplet' members (prime, exponent and coefficient) +into an RSA object. + +RSA_set_flags() sets the flags in the B parameter on the RSA +object. Multiple flags can be passed in one go (bitwise ORed together). +Any flags that are already set are left set. RSA_test_flags() tests to +see whether the flags passed in the B parameter are currently +set in the RSA object. Multiple flags can be tested in one go. All +flags that are currently set are returned, or zero if none of the +flags are set. RSA_clear_flags() clears the specified flags within the +RSA object. + +RSA_get0_engine() returns a handle to the ENGINE that has been set for +this RSA object, or NULL if no such ENGINE has been set. + +RSA_get_version() returns the version of an RSA object B. + +=head1 NOTES + +Values retrieved with RSA_get0_key() are owned by the RSA object used +in the call and may therefore I be passed to RSA_set0_key(). If +needed, duplicate the received value using BN_dup() and pass the +duplicate. The same applies to RSA_get0_factors() and RSA_set0_factors() +as well as RSA_get0_crt_params() and RSA_set0_crt_params(). + +The caller should obtain the size by calling RSA_get_multi_prime_extra_count() +in advance and allocate sufficient buffer to store the return values before +calling RSA_get0_multi_prime_factors() and RSA_get0_multi_prime_params(). + +RSA_set0_multi_prime_params() always clears the original multi-prime +triplets in RSA object B and assign the new set of triplets into it. + +=head1 RETURN VALUES + +RSA_set0_key(), RSA_set0_factors(), RSA_set0_crt_params() and +RSA_set0_multi_prime_params() return 1 on success or 0 on failure. + +RSA_get0_multi_prime_factors() and RSA_get0_multi_prime_crt_params() return +1 on success or 0 on failure. + +RSA_get_multi_prime_extra_count() returns two less than the number of primes +in use, which is 0 for traditional RSA and the number of extra primes for +multi-prime RSA. + +RSA_get_version() returns B for multi-prime RSA and +B for normal two-prime RSA, as defined in RFC 8017. + +RSA_test_flags() returns the current state of the flags in the RSA object. + +RSA_get0_engine() returns the ENGINE set for the RSA object or NULL if no +ENGINE has been set. + +=head1 SEE ALSO + +L, L + +=head1 HISTORY + +RSA_get_multi_prime_extra_count(), RSA_get0_multi_prime_factors(), +RSA_get0_multi_prime_crt_params(), RSA_set0_multi_prime_params(), +and RSA_get_version() functions were added in OpenSSL 1.1.1. + +Other functions described here were added in OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2016-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 +L. + +=cut diff --git a/doc/man3/RSA_meth_new.pod b/doc/man3/RSA_meth_new.pod new file mode 100644 index 00000000..fde1a41e --- /dev/null +++ b/doc/man3/RSA_meth_new.pod @@ -0,0 +1,262 @@ +=pod + +=head1 NAME + +RSA_meth_get0_app_data, RSA_meth_set0_app_data, +RSA_meth_new, RSA_meth_free, RSA_meth_dup, RSA_meth_get0_name, +RSA_meth_set1_name, RSA_meth_get_flags, RSA_meth_set_flags, +RSA_meth_get_pub_enc, +RSA_meth_set_pub_enc, RSA_meth_get_pub_dec, RSA_meth_set_pub_dec, +RSA_meth_get_priv_enc, RSA_meth_set_priv_enc, RSA_meth_get_priv_dec, +RSA_meth_set_priv_dec, RSA_meth_get_mod_exp, RSA_meth_set_mod_exp, +RSA_meth_get_bn_mod_exp, RSA_meth_set_bn_mod_exp, RSA_meth_get_init, +RSA_meth_set_init, RSA_meth_get_finish, RSA_meth_set_finish, +RSA_meth_get_sign, RSA_meth_set_sign, RSA_meth_get_verify, +RSA_meth_set_verify, RSA_meth_get_keygen, RSA_meth_set_keygen, +RSA_meth_get_multi_prime_keygen, RSA_meth_set_multi_prime_keygen +- Routines to build up RSA methods + +=head1 SYNOPSIS + + #include + + RSA_METHOD *RSA_meth_new(const char *name, int flags); + void RSA_meth_free(RSA_METHOD *meth); + + RSA_METHOD *RSA_meth_dup(const RSA_METHOD *meth); + + const char *RSA_meth_get0_name(const RSA_METHOD *meth); + int RSA_meth_set1_name(RSA_METHOD *meth, const char *name); + + int RSA_meth_get_flags(RSA_METHOD *meth); + int RSA_meth_set_flags(RSA_METHOD *meth, int flags); + + void *RSA_meth_get0_app_data(const RSA_METHOD *meth); + int RSA_meth_set0_app_data(RSA_METHOD *meth, void *app_data); + + int (*RSA_meth_get_pub_enc(const RSA_METHOD *meth))(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); + int RSA_meth_set_pub_enc(RSA_METHOD *rsa, + int (*pub_enc)(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, + int padding)); + + int (*RSA_meth_get_pub_dec(const RSA_METHOD *meth)) + (int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding); + int RSA_meth_set_pub_dec(RSA_METHOD *rsa, + int (*pub_dec)(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, + int padding)); + + int (*RSA_meth_get_priv_enc(const RSA_METHOD *meth))(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, + int padding); + int RSA_meth_set_priv_enc(RSA_METHOD *rsa, + int (*priv_enc)(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding)); + + int (*RSA_meth_get_priv_dec(const RSA_METHOD *meth))(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, + int padding); + int RSA_meth_set_priv_dec(RSA_METHOD *rsa, + int (*priv_dec)(int flen, const unsigned char *from, + unsigned char *to, RSA *rsa, int padding)); + + /* Can be null */ + int (*RSA_meth_get_mod_exp(const RSA_METHOD *meth))(BIGNUM *r0, const BIGNUM *I, + RSA *rsa, BN_CTX *ctx); + int RSA_meth_set_mod_exp(RSA_METHOD *rsa, + int (*mod_exp)(BIGNUM *r0, const BIGNUM *I, RSA *rsa, + BN_CTX *ctx)); + + /* Can be null */ + int (*RSA_meth_get_bn_mod_exp(const RSA_METHOD *meth))(BIGNUM *r, const BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *m_ctx); + int RSA_meth_set_bn_mod_exp(RSA_METHOD *rsa, + int (*bn_mod_exp)(BIGNUM *r, const BIGNUM *a, + const BIGNUM *p, const BIGNUM *m, + BN_CTX *ctx, BN_MONT_CTX *m_ctx)); + + /* called at new */ + int (*RSA_meth_get_init(const RSA_METHOD *meth) (RSA *rsa); + int RSA_meth_set_init(RSA_METHOD *rsa, int (*init (RSA *rsa)); + + /* called at free */ + int (*RSA_meth_get_finish(const RSA_METHOD *meth))(RSA *rsa); + int RSA_meth_set_finish(RSA_METHOD *rsa, int (*finish)(RSA *rsa)); + + int (*RSA_meth_get_sign(const RSA_METHOD *meth))(int type, const unsigned char *m, + unsigned int m_length, + unsigned char *sigret, + unsigned int *siglen, const RSA *rsa); + int RSA_meth_set_sign(RSA_METHOD *rsa, + int (*sign)(int type, const unsigned char *m, + unsigned int m_length, unsigned char *sigret, + unsigned int *siglen, const RSA *rsa)); + + int (*RSA_meth_get_verify(const RSA_METHOD *meth))(int dtype, const unsigned char *m, + unsigned int m_length, + const unsigned char *sigbuf, + unsigned int siglen, const RSA *rsa); + int RSA_meth_set_verify(RSA_METHOD *rsa, + int (*verify)(int dtype, const unsigned char *m, + unsigned int m_length, + const unsigned char *sigbuf, + unsigned int siglen, const RSA *rsa)); + + int (*RSA_meth_get_keygen(const RSA_METHOD *meth))(RSA *rsa, int bits, BIGNUM *e, + BN_GENCB *cb); + int RSA_meth_set_keygen(RSA_METHOD *rsa, + int (*keygen)(RSA *rsa, int bits, BIGNUM *e, + BN_GENCB *cb)); + + int (*RSA_meth_get_multi_prime_keygen(const RSA_METHOD *meth))(RSA *rsa, int bits, + int primes, BIGNUM *e, + BN_GENCB *cb); + + int RSA_meth_set_multi_prime_keygen(RSA_METHOD *meth, + int (*keygen) (RSA *rsa, int bits, + int primes, BIGNUM *e, + BN_GENCB *cb)); + +=head1 DESCRIPTION + +The B type is a structure used for the provision of custom +RSA implementations. It provides a set of functions used by OpenSSL +for the implementation of the various RSA capabilities. See the L +page for more information. + +RSA_meth_new() creates a new B structure. It should be +given a unique B and a set of B. The B should be a +NULL terminated string, which will be duplicated and stored in the +B object. It is the callers responsibility to free the +original string. The flags will be used during the construction of a +new B object based on this B. Any new B object +will have those flags set by default. + +RSA_meth_dup() creates a duplicate copy of the B object +passed as a parameter. This might be useful for creating a new +B based on an existing one, but with some differences. + +RSA_meth_free() destroys an B structure and frees up any +memory associated with it. + +RSA_meth_get0_name() will return a pointer to the name of this +RSA_METHOD. This is a pointer to the internal name string and so +should not be freed by the caller. RSA_meth_set1_name() sets the name +of the RSA_METHOD to B. The string is duplicated and the copy is +stored in the RSA_METHOD structure, so the caller remains responsible +for freeing the memory associated with the name. + +RSA_meth_get_flags() returns the current value of the flags associated +with this RSA_METHOD. RSA_meth_set_flags() provides the ability to set +these flags. + +The functions RSA_meth_get0_app_data() and RSA_meth_set0_app_data() +provide the ability to associate implementation specific data with the +RSA_METHOD. It is the application's responsibility to free this data +before the RSA_METHOD is freed via a call to RSA_meth_free(). + +RSA_meth_get_sign() and RSA_meth_set_sign() get and set the function +used for creating an RSA signature respectively. This function will be +called in response to the application calling RSA_sign(). The +parameters for the function have the same meaning as for RSA_sign(). + +RSA_meth_get_verify() and RSA_meth_set_verify() get and set the +function used for verifying an RSA signature respectively. This +function will be called in response to the application calling +RSA_verify(). The parameters for the function have the same meaning as +for RSA_verify(). + +RSA_meth_get_mod_exp() and RSA_meth_set_mod_exp() get and set the +function used for CRT computations. + +RSA_meth_get_bn_mod_exp() and RSA_meth_set_bn_mod_exp() get and set +the function used for CRT computations, specifically the following +value: + + r = a ^ p mod m + +Both the mod_exp() and bn_mod_exp() functions are called by the +default OpenSSL method during encryption, decryption, signing and +verification. + +RSA_meth_get_init() and RSA_meth_set_init() get and set the function +used for creating a new RSA instance respectively. This function will +be called in response to the application calling RSA_new() (if the +current default RSA_METHOD is this one) or RSA_new_method(). The +RSA_new() and RSA_new_method() functions will allocate the memory for +the new RSA object, and a pointer to this newly allocated structure +will be passed as a parameter to the function. This function may be +NULL. + +RSA_meth_get_finish() and RSA_meth_set_finish() get and set the +function used for destroying an instance of an RSA object respectively. +This function will be called in response to the application calling +RSA_free(). A pointer to the RSA to be destroyed is passed as a +parameter. The destroy function should be used for RSA implementation +specific clean up. The memory for the RSA itself should not be freed +by this function. This function may be NULL. + +RSA_meth_get_keygen() and RSA_meth_set_keygen() get and set the +function used for generating a new RSA key pair respectively. This +function will be called in response to the application calling +RSA_generate_key_ex(). The parameter for the function has the same +meaning as for RSA_generate_key_ex(). + +RSA_meth_get_multi_prime_keygen() and RSA_meth_set_multi_prime_keygen() get +and set the function used for generating a new multi-prime RSA key pair +respectively. This function will be called in response to the application calling +RSA_generate_multi_prime_key(). The parameter for the function has the same +meaning as for RSA_generate_multi_prime_key(). + +RSA_meth_get_pub_enc(), RSA_meth_set_pub_enc(), +RSA_meth_get_pub_dec(), RSA_meth_set_pub_dec(), +RSA_meth_get_priv_enc(), RSA_meth_set_priv_enc(), +RSA_meth_get_priv_dec(), RSA_meth_set_priv_dec() get and set the +functions used for public and private key encryption and decryption. +These functions will be called in response to the application calling +RSA_public_encrypt(), RSA_private_decrypt(), RSA_private_encrypt() and +RSA_public_decrypt() and take the same parameters as those. + + +=head1 RETURN VALUES + +RSA_meth_new() and RSA_meth_dup() return the newly allocated +RSA_METHOD object or NULL on failure. + +RSA_meth_get0_name() and RSA_meth_get_flags() return the name and +flags associated with the RSA_METHOD respectively. + +All other RSA_meth_get_*() functions return the appropriate function +pointer that has been set in the RSA_METHOD, or NULL if no such +pointer has yet been set. + +RSA_meth_set1_name and all RSA_meth_set_*() functions return 1 on +success or 0 on failure. + +=head1 SEE ALSO + +L, L, L, +L, L, L, +L + +=head1 HISTORY + +RSA_meth_get_multi_prime_keygen() and RSA_meth_set_multi_prime_keygen() were +added in OpenSSL 1.1.1. + +Other functions described here were added in OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2016-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 +L. + +=cut diff --git a/doc/crypto/RSA_new.pod b/doc/man3/RSA_new.pod similarity index 98% rename from doc/crypto/RSA_new.pod rename to doc/man3/RSA_new.pod index 33179207..d57fe826 100644 --- a/doc/crypto/RSA_new.pod +++ b/doc/man3/RSA_new.pod @@ -8,7 +8,7 @@ RSA_new, RSA_free - allocate and free RSA objects #include - RSA * RSA_new(void); + RSA *RSA_new(void); void RSA_free(RSA *rsa); diff --git a/doc/crypto/RSA_padding_add_PKCS1_type_1.pod b/doc/man3/RSA_padding_add_PKCS1_type_1.pod similarity index 82% rename from doc/crypto/RSA_padding_add_PKCS1_type_1.pod rename to doc/man3/RSA_padding_add_PKCS1_type_1.pod index 5b53eb9e..93911cac 100644 --- a/doc/crypto/RSA_padding_add_PKCS1_type_1.pod +++ b/doc/man3/RSA_padding_add_PKCS1_type_1.pod @@ -14,34 +14,35 @@ padding #include int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen, - unsigned char *f, int fl); + unsigned char *f, int fl); int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen, - unsigned char *f, int fl, int rsa_len); + unsigned char *f, int fl, int rsa_len); int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen, - unsigned char *f, int fl); + unsigned char *f, int fl); int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen, - unsigned char *f, int fl, int rsa_len); + unsigned char *f, int fl, int rsa_len); int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen, - unsigned char *f, int fl, unsigned char *p, int pl); + unsigned char *f, int fl, unsigned char *p, int pl); int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen, - unsigned char *f, int fl, int rsa_len, unsigned char *p, int pl); + unsigned char *f, int fl, int rsa_len, + unsigned char *p, int pl); int RSA_padding_add_SSLv23(unsigned char *to, int tlen, - unsigned char *f, int fl); + unsigned char *f, int fl); int RSA_padding_check_SSLv23(unsigned char *to, int tlen, - unsigned char *f, int fl, int rsa_len); + unsigned char *f, int fl, int rsa_len); int RSA_padding_add_none(unsigned char *to, int tlen, - unsigned char *f, int fl); + unsigned char *f, int fl); int RSA_padding_check_none(unsigned char *to, int tlen, - unsigned char *f, int fl, int rsa_len); + unsigned char *f, int fl, int rsa_len); =head1 DESCRIPTION diff --git a/doc/crypto/RSA_print.pod b/doc/man3/RSA_print.pod similarity index 100% rename from doc/crypto/RSA_print.pod rename to doc/man3/RSA_print.pod diff --git a/doc/crypto/RSA_private_encrypt.pod b/doc/man3/RSA_private_encrypt.pod similarity index 88% rename from doc/crypto/RSA_private_encrypt.pod rename to doc/man3/RSA_private_encrypt.pod index 1eb7a0ad..060a9000 100644 --- a/doc/crypto/RSA_private_encrypt.pod +++ b/doc/man3/RSA_private_encrypt.pod @@ -8,11 +8,11 @@ RSA_private_encrypt, RSA_public_decrypt - low level signature operations #include - int RSA_private_encrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); + int RSA_private_encrypt(int flen, unsigned char *from, + unsigned char *to, RSA *rsa, int padding); - int RSA_public_decrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); + int RSA_public_decrypt(int flen, unsigned char *from, + unsigned char *to, RSA *rsa, int padding); =head1 DESCRIPTION diff --git a/doc/crypto/RSA_public_encrypt.pod b/doc/man3/RSA_public_encrypt.pod similarity index 89% rename from doc/crypto/RSA_public_encrypt.pod rename to doc/man3/RSA_public_encrypt.pod index b1dd50d7..91c176e2 100644 --- a/doc/crypto/RSA_public_encrypt.pod +++ b/doc/man3/RSA_public_encrypt.pod @@ -8,11 +8,11 @@ RSA_public_encrypt, RSA_private_decrypt - RSA public key cryptography #include - int RSA_public_encrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); + int RSA_public_encrypt(int flen, unsigned char *from, + unsigned char *to, RSA *rsa, int padding); - int RSA_private_decrypt(int flen, const unsigned char *from, - unsigned char *to, RSA *rsa, int padding); + int RSA_private_decrypt(int flen, unsigned char *from, + unsigned char *to, RSA *rsa, int padding); =head1 DESCRIPTION @@ -80,7 +80,7 @@ SSL, PKCS #1 v2.0 =head1 SEE ALSO -L, L, +L, L, L =head1 COPYRIGHT diff --git a/doc/crypto/RSA_set_method.pod b/doc/man3/RSA_set_method.pod similarity index 78% rename from doc/crypto/RSA_set_method.pod rename to doc/man3/RSA_set_method.pod index 668ad7a1..4bb63962 100644 --- a/doc/crypto/RSA_set_method.pod +++ b/doc/man3/RSA_set_method.pod @@ -81,56 +81,56 @@ the default method is used. typedef struct rsa_meth_st { /* name of the implementation */ - const char *name; + const char *name; /* encrypt */ - int (*rsa_pub_enc)(int flen, unsigned char *from, - unsigned char *to, RSA *rsa, int padding); + int (*rsa_pub_enc)(int flen, unsigned char *from, + unsigned char *to, RSA *rsa, int padding); /* verify arbitrary data */ - int (*rsa_pub_dec)(int flen, unsigned char *from, - unsigned char *to, RSA *rsa, int padding); + int (*rsa_pub_dec)(int flen, unsigned char *from, + unsigned char *to, RSA *rsa, int padding); /* sign arbitrary data */ - int (*rsa_priv_enc)(int flen, unsigned char *from, - unsigned char *to, RSA *rsa, int padding); + int (*rsa_priv_enc)(int flen, unsigned char *from, + unsigned char *to, RSA *rsa, int padding); /* decrypt */ - int (*rsa_priv_dec)(int flen, unsigned char *from, - unsigned char *to, RSA *rsa, int padding); + int (*rsa_priv_dec)(int flen, unsigned char *from, + unsigned char *to, RSA *rsa, int padding); - /* compute r0 = r0 ^ I mod rsa->n (May be NULL for some - implementations) */ - int (*rsa_mod_exp)(BIGNUM *r0, BIGNUM *I, RSA *rsa); + /* compute r0 = r0 ^ I mod rsa->n (May be NULL for some implementations) */ + int (*rsa_mod_exp)(BIGNUM *r0, BIGNUM *I, RSA *rsa); /* compute r = a ^ p mod m (May be NULL for some implementations) */ - int (*bn_mod_exp)(BIGNUM *r, BIGNUM *a, const BIGNUM *p, - const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); + int (*bn_mod_exp)(BIGNUM *r, BIGNUM *a, const BIGNUM *p, + const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); /* called at RSA_new */ - int (*init)(RSA *rsa); + int (*init)(RSA *rsa); /* called at RSA_free */ - int (*finish)(RSA *rsa); + int (*finish)(RSA *rsa); - /* RSA_FLAG_EXT_PKEY - rsa_mod_exp is called for private key + /* + * RSA_FLAG_EXT_PKEY - rsa_mod_exp is called for private key * operations, even if p,q,dmp1,dmq1,iqmp * are NULL * RSA_METHOD_FLAG_NO_CHECK - don't check pub/private match */ - int flags; + int flags; - char *app_data; /* ?? */ + char *app_data; /* ?? */ - int (*rsa_sign)(int type, - const unsigned char *m, unsigned int m_length, - unsigned char *sigret, unsigned int *siglen, const RSA *rsa); - int (*rsa_verify)(int dtype, - const unsigned char *m, unsigned int m_length, - const unsigned char *sigbuf, unsigned int siglen, - const RSA *rsa); + int (*rsa_sign)(int type, + const unsigned char *m, unsigned int m_length, + unsigned char *sigret, unsigned int *siglen, const RSA *rsa); + int (*rsa_verify)(int dtype, + const unsigned char *m, unsigned int m_length, + const unsigned char *sigbuf, unsigned int siglen, + const RSA *rsa); /* keygen. If NULL builtin RSA key generation will be used */ - int (*rsa_keygen)(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); + int (*rsa_keygen)(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb); } RSA_METHOD; @@ -172,7 +172,7 @@ L =head1 HISTORY The RSA_null_method(), which was a partial attempt to avoid patent issues, -was replaced to always return NULL in OpenSSL 1.1.0f. +was replaced to always return NULL in OpenSSL 1.1.1. =head1 COPYRIGHT diff --git a/doc/crypto/RSA_sign.pod b/doc/man3/RSA_sign.pod similarity index 92% rename from doc/crypto/RSA_sign.pod rename to doc/man3/RSA_sign.pod index fbb38d81..310abd49 100644 --- a/doc/crypto/RSA_sign.pod +++ b/doc/man3/RSA_sign.pod @@ -9,10 +9,10 @@ RSA_sign, RSA_verify - RSA signatures #include int RSA_sign(int type, const unsigned char *m, unsigned int m_len, - unsigned char *sigret, unsigned int *siglen, RSA *rsa); + unsigned char *sigret, unsigned int *siglen, RSA *rsa); int RSA_verify(int type, const unsigned char *m, unsigned int m_len, - unsigned char *sigbuf, unsigned int siglen, RSA *rsa); + unsigned char *sigbuf, unsigned int siglen, RSA *rsa); =head1 DESCRIPTION diff --git a/doc/crypto/RSA_sign_ASN1_OCTET_STRING.pod b/doc/man3/RSA_sign_ASN1_OCTET_STRING.pod similarity index 83% rename from doc/crypto/RSA_sign_ASN1_OCTET_STRING.pod rename to doc/man3/RSA_sign_ASN1_OCTET_STRING.pod index 16303c9f..f577e153 100644 --- a/doc/crypto/RSA_sign_ASN1_OCTET_STRING.pod +++ b/doc/man3/RSA_sign_ASN1_OCTET_STRING.pod @@ -9,12 +9,12 @@ RSA_sign_ASN1_OCTET_STRING, RSA_verify_ASN1_OCTET_STRING - RSA signatures #include int RSA_sign_ASN1_OCTET_STRING(int dummy, unsigned char *m, - unsigned int m_len, unsigned char *sigret, unsigned int *siglen, - RSA *rsa); + unsigned int m_len, unsigned char *sigret, + unsigned int *siglen, RSA *rsa); int RSA_verify_ASN1_OCTET_STRING(int dummy, unsigned char *m, - unsigned int m_len, unsigned char *sigbuf, unsigned int siglen, - RSA *rsa); + unsigned int m_len, unsigned char *sigbuf, + unsigned int siglen, RSA *rsa); =head1 DESCRIPTION @@ -48,7 +48,7 @@ These functions serve no recognizable purpose. =head1 SEE ALSO L, -L, L, +L, L, L =head1 COPYRIGHT diff --git a/doc/man3/RSA_size.pod b/doc/man3/RSA_size.pod new file mode 100644 index 00000000..02262007 --- /dev/null +++ b/doc/man3/RSA_size.pod @@ -0,0 +1,55 @@ +=pod + +=head1 NAME + +RSA_size, RSA_bits, RSA_security_bits - get RSA modulus size or security bits + +=head1 SYNOPSIS + + #include + + int RSA_size(const RSA *rsa); + + int RSA_bits(const RSA *rsa); + + int RSA_security_bits(const RSA *rsa) + +=head1 DESCRIPTION + +RSA_size() returns the RSA modulus size in bytes. It can be used to +determine how much memory must be allocated for an RSA encrypted +value. + +RSA_bits() returns the number of significant bits. + +B and Bn> must not be B. + +RSA_security_bits() returns the number of security bits of the given B +key. See L. + +=head1 RETURN VALUES + +RSA_size() returns the size of modulus in bytes. + +DSA_bits() returns the number of bits in the key. + +RSA_security_bits() returns the number of security bits. + +=head1 SEE ALSO + +L + +=head1 HISTORY + +RSA_bits() was added in OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/crypto/SCT_new.pod b/doc/man3/SCT_new.pod similarity index 80% rename from doc/crypto/SCT_new.pod rename to doc/man3/SCT_new.pod index fb395a51..8da7f6ad 100644 --- a/doc/crypto/SCT_new.pod +++ b/doc/man3/SCT_new.pod @@ -18,21 +18,21 @@ SCT_get_source, SCT_set_source #include typedef enum { - CT_LOG_ENTRY_TYPE_NOT_SET = -1, - CT_LOG_ENTRY_TYPE_X509 = 0, - CT_LOG_ENTRY_TYPE_PRECERT = 1 + CT_LOG_ENTRY_TYPE_NOT_SET = -1, + CT_LOG_ENTRY_TYPE_X509 = 0, + CT_LOG_ENTRY_TYPE_PRECERT = 1 } ct_log_entry_type_t; typedef enum { - SCT_VERSION_NOT_SET = -1, - SCT_VERSION_V1 = 0 + SCT_VERSION_NOT_SET = -1, + SCT_VERSION_V1 = 0 } sct_version_t; typedef enum { - SCT_SOURCE_UNKNOWN, - SCT_SOURCE_TLS_EXTENSION, - SCT_SOURCE_X509V3_EXTENSION, - SCT_SOURCE_OCSP_STAPLED_RESPONSE + SCT_SOURCE_UNKNOWN, + SCT_SOURCE_TLS_EXTENSION, + SCT_SOURCE_X509V3_EXTENSION, + SCT_SOURCE_OCSP_STAPLED_RESPONSE } sct_source_t; SCT *SCT_new(void); @@ -84,31 +84,45 @@ An internal representation of an SCT can be created in one of two ways. The first option is to create a blank SCT, using SCT_new(), and then populate it using: -=over 4 +=over 2 -=item * SCT_set_version() to set the SCT version. +=item * + +SCT_set_version() to set the SCT version. Only SCT_VERSION_V1 is currently supported. -=item * SCT_set_log_entry_type() to set the type of certificate the SCT was issued for: +=item * + +SCT_set_log_entry_type() to set the type of certificate the SCT was issued for: B for a normal certificate. B for a pre-certificate. -=item * SCT_set0_log_id() or SCT_set1_log_id() to set the LogID of the CT log that the SCT came from. +=item * + +SCT_set0_log_id() or SCT_set1_log_id() to set the LogID of the CT log that the SCT came from. The former takes ownership, whereas the latter makes a copy. See RFC 6962, Section 3.2 for the definition of LogID. -=item * SCT_set_timestamp() to set the time the SCT was issued (epoch time in milliseconds). +=item * -=item * SCT_set_signature_nid() to set the NID of the signature. +SCT_set_timestamp() to set the time the SCT was issued (epoch time in milliseconds). -=item * SCT_set0_signature() or SCT_set1_signature() to set the raw signature value. +=item * + +SCT_set_signature_nid() to set the NID of the signature. + +=item * + +SCT_set0_signature() or SCT_set1_signature() to set the raw signature value. The former takes ownership, whereas the latter makes a copy. -=item * SCT_set0_extensions() or B to provide SCT extensions. +=item * + +SCT_set0_extensions() or B to provide SCT extensions. The former takes ownership, whereas the latter makes a copy. @@ -117,22 +131,33 @@ The former takes ownership, whereas the latter makes a copy. Alternatively, the SCT can be pre-populated from the following data using SCT_new_from_base64(): -=over 4 +=over 2 -=item * The SCT version (only SCT_VERSION_V1 is currently supported). +=item * -=item * The LogID (see RFC 6962, Section 3.2), base64 encoded. +The SCT version (only SCT_VERSION_V1 is currently supported). -=item * The type of certificate the SCT was issued for: +=item * +The LogID (see RFC 6962, Section 3.2), base64 encoded. + +=item * + +The type of certificate the SCT was issued for: B for a normal certificate. B for a pre-certificate. -=item * The time that the SCT was issued (epoch time in milliseconds). +=item * -=item * The SCT extensions, base64 encoded. +The time that the SCT was issued (epoch time in milliseconds). -=item * The SCT signature, base64 encoded. +=item * + +The SCT extensions, base64 encoded. + +=item * + +The SCT signature, base64 encoded. =back diff --git a/doc/crypto/SCT_print.pod b/doc/man3/SCT_print.pod similarity index 87% rename from doc/crypto/SCT_print.pod rename to doc/man3/SCT_print.pod index 88ad43ec..2b9913d4 100644 --- a/doc/crypto/SCT_print.pod +++ b/doc/man3/SCT_print.pod @@ -29,10 +29,15 @@ SCT_validation_status_string() will return the validation status of an SCT as a human-readable string. Call SCT_validate() or SCT_LIST_validate() beforehand in order to set the validation status of an SCT first. +=head1 RETURN VALUES + +SCT_validation_status_string() returns a null-terminated string representing +the validation status of an B object. + =head1 SEE ALSO -L, -L, +L, +L, L, L @@ -42,7 +47,7 @@ These functions were added in OpenSSL 1.1.0. =head1 COPYRIGHT -Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2016-2018 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 diff --git a/doc/crypto/SCT_validate.pod b/doc/man3/SCT_validate.pod similarity index 87% rename from doc/crypto/SCT_validate.pod rename to doc/man3/SCT_validate.pod index 3c03e972..fa7e2a8b 100644 --- a/doc/crypto/SCT_validate.pod +++ b/doc/man3/SCT_validate.pod @@ -10,12 +10,12 @@ checks Signed Certificate Timestamps (SCTs) are valid #include typedef enum { - SCT_VALIDATION_STATUS_NOT_SET, - SCT_VALIDATION_STATUS_UNKNOWN_LOG, - SCT_VALIDATION_STATUS_VALID, - SCT_VALIDATION_STATUS_INVALID, - SCT_VALIDATION_STATUS_UNVERIFIED, - SCT_VALIDATION_STATUS_UNKNOWN_VERSION + SCT_VALIDATION_STATUS_NOT_SET, + SCT_VALIDATION_STATUS_UNKNOWN_LOG, + SCT_VALIDATION_STATUS_VALID, + SCT_VALIDATION_STATUS_INVALID, + SCT_VALIDATION_STATUS_UNVERIFIED, + SCT_VALIDATION_STATUS_UNKNOWN_VERSION } sct_validation_status_t; int SCT_validate(SCT *sct, const CT_POLICY_EVAL_CTX *ctx); @@ -31,20 +31,26 @@ SCT_get_validation_status(). A CT_POLICY_EVAL_CTX must be provided that specifies: -=over 4 +=over 2 -=item * The certificate the SCT was issued for. +=item * + +The certificate the SCT was issued for. Failure to provide the certificate will result in the validation status being SCT_VALIDATION_STATUS_UNVERIFIED. -=item * The issuer of that certificate. +=item * + +The issuer of that certificate. This is only required if the SCT was issued for a pre-certificate (see RFC 6962). If it is required but not provided, the validation status will be SCT_VALIDATION_STATUS_UNVERIFIED. -=item * A CTLOG_STORE that contains the CT log that issued this SCT. +=item * + +A CTLOG_STORE that contains the CT log that issued this SCT. If the SCT was issued by a log that is not in this CTLOG_STORE, the validation status will be SCT_VALIDATION_STATUS_UNKNOWN_LOG. diff --git a/doc/crypto/SHA256_Init.pod b/doc/man3/SHA256_Init.pod similarity index 94% rename from doc/crypto/SHA256_Init.pod rename to doc/man3/SHA256_Init.pod index f3565bb2..6a8f2fa0 100644 --- a/doc/crypto/SHA256_Init.pod +++ b/doc/man3/SHA256_Init.pod @@ -15,31 +15,31 @@ SHA512_Final - Secure Hash Algorithm int SHA1_Update(SHA_CTX *c, const void *data, size_t len); int SHA1_Final(unsigned char *md, SHA_CTX *c); unsigned char *SHA1(const unsigned char *d, size_t n, - unsigned char *md); + unsigned char *md); int SHA224_Init(SHA256_CTX *c); int SHA224_Update(SHA256_CTX *c, const void *data, size_t len); int SHA224_Final(unsigned char *md, SHA256_CTX *c); unsigned char *SHA224(const unsigned char *d, size_t n, - unsigned char *md); + unsigned char *md); int SHA256_Init(SHA256_CTX *c); int SHA256_Update(SHA256_CTX *c, const void *data, size_t len); int SHA256_Final(unsigned char *md, SHA256_CTX *c); unsigned char *SHA256(const unsigned char *d, size_t n, - unsigned char *md); + unsigned char *md); int SHA384_Init(SHA512_CTX *c); int SHA384_Update(SHA512_CTX *c, const void *data, size_t len); int SHA384_Final(unsigned char *md, SHA512_CTX *c); unsigned char *SHA384(const unsigned char *d, size_t n, - unsigned char *md); + unsigned char *md); int SHA512_Init(SHA512_CTX *c); int SHA512_Update(SHA512_CTX *c, const void *data, size_t len); int SHA512_Final(unsigned char *md, SHA512_CTX *c); unsigned char *SHA512(const unsigned char *d, size_t n, - unsigned char *md); + unsigned char *md); =head1 DESCRIPTION diff --git a/doc/crypto/SMIME_read_CMS.pod b/doc/man3/SMIME_read_CMS.pod similarity index 96% rename from doc/crypto/SMIME_read_CMS.pod rename to doc/man3/SMIME_read_CMS.pod index efde0bda..800e4aa2 100644 --- a/doc/crypto/SMIME_read_CMS.pod +++ b/doc/man3/SMIME_read_CMS.pod @@ -58,9 +58,9 @@ if an error occurred. The error can be obtained from ERR_get_error(3). =head1 SEE ALSO -L, L +L, L, L, L, -L, L +L, L, L =head1 COPYRIGHT diff --git a/doc/crypto/SMIME_read_PKCS7.pod b/doc/man3/SMIME_read_PKCS7.pod similarity index 100% rename from doc/crypto/SMIME_read_PKCS7.pod rename to doc/man3/SMIME_read_PKCS7.pod diff --git a/doc/crypto/SMIME_write_CMS.pod b/doc/man3/SMIME_write_CMS.pod similarity index 100% rename from doc/crypto/SMIME_write_CMS.pod rename to doc/man3/SMIME_write_CMS.pod diff --git a/doc/crypto/SMIME_write_PKCS7.pod b/doc/man3/SMIME_write_PKCS7.pod similarity index 100% rename from doc/crypto/SMIME_write_PKCS7.pod rename to doc/man3/SMIME_write_PKCS7.pod diff --git a/doc/man3/SSL_CIPHER_get_name.pod b/doc/man3/SSL_CIPHER_get_name.pod new file mode 100644 index 00000000..af59b589 --- /dev/null +++ b/doc/man3/SSL_CIPHER_get_name.pod @@ -0,0 +1,210 @@ +=pod + +=head1 NAME + +SSL_CIPHER_get_name, +SSL_CIPHER_standard_name, +OPENSSL_cipher_name, +SSL_CIPHER_get_bits, +SSL_CIPHER_get_version, +SSL_CIPHER_description, +SSL_CIPHER_get_cipher_nid, +SSL_CIPHER_get_digest_nid, +SSL_CIPHER_get_handshake_digest, +SSL_CIPHER_get_kx_nid, +SSL_CIPHER_get_auth_nid, +SSL_CIPHER_is_aead, +SSL_CIPHER_find, +SSL_CIPHER_get_id, +SSL_CIPHER_get_protocol_id +- get SSL_CIPHER properties + +=head1 SYNOPSIS + + #include + + const char *SSL_CIPHER_get_name(const SSL_CIPHER *cipher); + const char *SSL_CIPHER_standard_name(const SSL_CIPHER *cipher); + const char *OPENSSL_cipher_name(const char *stdname); + int SSL_CIPHER_get_bits(const SSL_CIPHER *cipher, int *alg_bits); + char *SSL_CIPHER_get_version(const SSL_CIPHER *cipher); + char *SSL_CIPHER_description(const SSL_CIPHER *cipher, char *buf, int size); + int SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *c); + int SSL_CIPHER_get_digest_nid(const SSL_CIPHER *c); + const EVP_MD *SSL_CIPHER_get_handshake_digest(const SSL_CIPHER *c); + int SSL_CIPHER_get_kx_nid(const SSL_CIPHER *c); + int SSL_CIPHER_get_auth_nid(const SSL_CIPHER *c); + int SSL_CIPHER_is_aead(const SSL_CIPHER *c); + const SSL_CIPHER *SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr); + uint32_t SSL_CIPHER_get_id(const SSL_CIPHER *c); + uint32_t SSL_CIPHER_get_protocol_id(const SSL_CIPHER *c); + +=head1 DESCRIPTION + +SSL_CIPHER_get_name() returns a pointer to the name of B. If the +B is NULL, it returns "(NONE)". + +SSL_CIPHER_standard_name() returns a pointer to the standard RFC name of +B. If the B is NULL, it returns "(NONE)". If the B +has no standard name, it returns B. If B was defined in both +SSLv3 and TLS, it returns the TLS name. + +OPENSSL_cipher_name() returns a pointer to the OpenSSL name of B. +If the B is NULL, or B has no corresponding OpenSSL name, +it returns "(NONE)". Where both exist, B should be the TLS name rather +than the SSLv3 name. + +SSL_CIPHER_get_bits() returns the number of secret bits used for B. +If B is NULL, 0 is returned. + +SSL_CIPHER_get_version() returns string which indicates the SSL/TLS protocol +version that first defined the cipher. It returns "(NONE)" if B is NULL. + +SSL_CIPHER_get_cipher_nid() returns the cipher NID corresponding to B. +If there is no cipher (e.g. for cipher suites with no encryption) then +B is returned. + +SSL_CIPHER_get_digest_nid() returns the digest NID corresponding to the MAC +used by B during record encryption/decryption. If there is no digest (e.g. +for AEAD cipher suites) then B is returned. + +SSL_CIPHER_get_handshake_digest() returns an EVP_MD for the digest used during +the SSL/TLS handshake when using the SSL_CIPHER B. Note that this may be +different to the digest used to calculate the MAC for encrypted records. + +SSL_CIPHER_get_kx_nid() returns the key exchange NID corresponding to the method +used by B. If there is no key exchange, then B is returned. +If any appropriate key exchange algorithm can be used (as in the case of TLS 1.3 +cipher suites) B is returned. Examples (not comprehensive): + + NID_kx_rsa + NID_kx_ecdhe + NID_kx_dhe + NID_kx_psk + +SSL_CIPHER_get_auth_nid() returns the authentication NID corresponding to the method +used by B. If there is no authentication, then B is returned. +If any appropriate authentication algorithm can be used (as in the case of +TLS 1.3 cipher suites) B is returned. Examples (not comprehensive): + + NID_auth_rsa + NID_auth_ecdsa + NID_auth_psk + +SSL_CIPHER_is_aead() returns 1 if the cipher B is AEAD (e.g. GCM or +ChaCha20/Poly1305), and 0 if it is not AEAD. + +SSL_CIPHER_find() returns a B structure which has the cipher ID stored +in B. The B parameter is a two element array of B, which stores the +two-byte TLS cipher ID (as allocated by IANA) in network byte order. This parameter +is usually retrieved from a TLS packet by using functions like +L. SSL_CIPHER_find() returns NULL if an +error occurs or the indicated cipher is not found. + +SSL_CIPHER_get_id() returns the OpenSSL-specific ID of the given cipher B. That ID is +not the same as the IANA-specific ID. + +SSL_CIPHER_get_protocol_id() returns the two-byte ID used in the TLS protocol of the given +cipher B. + +SSL_CIPHER_description() returns a textual description of the cipher used +into the buffer B of length B provided. If B is provided, it +must be at least 128 bytes, otherwise a buffer will be allocated using +OPENSSL_malloc(). If the provided buffer is too small, or the allocation fails, +B is returned. + +The string returned by SSL_CIPHER_description() consists of several fields +separated by whitespace: + +=over 4 + +=item + +Textual representation of the cipher name. + +=item + +Protocol version, such as B, when the cipher was first defined. + +=item Kx= + +Key exchange method such as B, B, etc. + +=item Au= + +Authentication method such as B, B, etc.. None is the +representation of anonymous ciphers. + +=item Enc= + +Encryption method, with number of secret bits, such as B. + +=item Mac= + +Message digest, such as B. + +=back + +Some examples for the output of SSL_CIPHER_description(): + + ECDHE-RSA-AES256-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD + RSA-PSK-AES256-CBC-SHA384 TLSv1.0 Kx=RSAPSK Au=RSA Enc=AES(256) Mac=SHA384 + +=head1 RETURN VALUES + +SSL_CIPHER_get_name(), SSL_CIPHER_standard_name(), OPENSSL_cipher_name(), +SSL_CIPHER_get_version() and SSL_CIPHER_description() return the corresponding +value in a null-terminated string for a specific cipher or "(NONE)" +if the cipher is not found. + +SSL_CIPHER_get_bits() returns a positive integer representing the number of +secret bits or 0 if an error occurred. + +SSL_CIPHER_get_cipher_nid(), SSL_CIPHER_get_digest_nid(), +SSL_CIPHER_get_kx_nid() and SSL_CIPHER_get_auth_nid() return the NID value or +B if an error occurred. + +SSL_CIPHER_get_handshake_digest() returns a valid B structure or NULL +if an error occurred. + +SSL_CIPHER_is_aead() returns 1 if the cipher is AEAD or 0 otherwise. + +SSL_CIPHER_find() returns a valid B structure or NULL if an error +occurred. + +SSL_CIPHER_get_id() returns a 4-byte integer representing the OpenSSL-specific ID. + +SSL_CIPHER_get_protocol_id() returns a 2-byte integer representing the TLS +protocol-specific ID. + +=head1 HISTORY + +SSL_CIPHER_get_version() was updated to always return the correct protocol +string in OpenSSL 1.1.0. + +SSL_CIPHER_description() was changed to return B on error, +rather than a fixed string, in OpenSSL 1.1.0. + +SSL_CIPHER_get_handshake_digest() was added in OpenSSL 1.1.1. + +SSL_CIPHER_standard_name() was globally available in OpenSSL 1.1.1. Before +OpenSSL 1.1.1, tracing (B argument to Configure) was +required to enable this function. + +OPENSSL_cipher_name() was added in OpenSSL 1.1.1. + +=head1 SEE ALSO + +L, L, +L, L + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/ssl/SSL_COMP_add_compression_method.pod b/doc/man3/SSL_COMP_add_compression_method.pod similarity index 83% rename from doc/ssl/SSL_COMP_add_compression_method.pod rename to doc/man3/SSL_COMP_add_compression_method.pod index 15929df3..1dc8eb14 100644 --- a/doc/ssl/SSL_COMP_add_compression_method.pod +++ b/doc/man3/SSL_COMP_add_compression_method.pod @@ -35,12 +35,8 @@ SSL_COMP_get0_name() returns the name of the compression method B. SSL_COMP_get_id() returns the id of the compression method B. -In versions of OpenSSL prior to 1.1.0 SSL_COMP_free_compression_methods() freed -the internal table of compression methods that were built internally, and -possibly augmented by adding SSL_COMP_add_compression_method(). However this is -now unnecessary from version 1.1.0. No explicit initialisation or -de-initialisation is necessary. See L and -L. From OpenSSL 1.1.0 calling this function does nothing. +SSL_COMP_free_compression_methods() releases any resources acquired to +maintain the internal table of compression methods. =head1 NOTES @@ -66,12 +62,6 @@ of compression methods supported on a per connection basis. If enabled during compilation, the OpenSSL library will have the COMP_zlib() compression method available. -=head1 WARNINGS - -Once the identities of the compression methods for the TLS protocol have -been standardized, the compression API will most likely be changed. Using -it in the current state is not recommended. - =head1 RETURN VALUES SSL_COMP_add_compression_method() may return the following values: @@ -97,11 +87,12 @@ SSL_COMP_get_id() returns the name of the compression method or -1 on error. =head1 SEE ALSO -L +L =head1 HISTORY -SSL_COMP_free_compression_methods() was deprecated in OpenSSL 1.1.0. +SSL_COMP_free_compression_methods() was deprecated in OpenSSL 1.1.0; +do not use it. SSL_COMP_get0_name() and SSL_comp_get_id() were added in OpenSSL 1.1.0d. =head1 COPYRIGHT diff --git a/doc/ssl/SSL_CONF_CTX_new.pod b/doc/man3/SSL_CONF_CTX_new.pod similarity index 100% rename from doc/ssl/SSL_CONF_CTX_new.pod rename to doc/man3/SSL_CONF_CTX_new.pod diff --git a/doc/ssl/SSL_CONF_CTX_set1_prefix.pod b/doc/man3/SSL_CONF_CTX_set1_prefix.pod similarity index 99% rename from doc/ssl/SSL_CONF_CTX_set1_prefix.pod rename to doc/man3/SSL_CONF_CTX_set1_prefix.pod index da9e5802..d9864702 100644 --- a/doc/ssl/SSL_CONF_CTX_set1_prefix.pod +++ b/doc/man3/SSL_CONF_CTX_set1_prefix.pod @@ -17,7 +17,7 @@ to B. If B is B it is restored to the default value. =head1 NOTES -Command prefixes alter the commands recognised by subsequent SSL_CTX_cmd() +Command prefixes alter the commands recognised by subsequent SSL_CONF_cmd() calls. For example for files, if the prefix "SSL" is set then command names such as "SSLProtocol", "SSLOptions" etc. are recognised instead of "Protocol" and "Options". Similarly for command lines if the prefix is "--ssl-" then diff --git a/doc/ssl/SSL_CONF_CTX_set_flags.pod b/doc/man3/SSL_CONF_CTX_set_flags.pod similarity index 97% rename from doc/ssl/SSL_CONF_CTX_set_flags.pod rename to doc/man3/SSL_CONF_CTX_set_flags.pod index efd8da3b..766d9846 100644 --- a/doc/ssl/SSL_CONF_CTX_set_flags.pod +++ b/doc/man3/SSL_CONF_CTX_set_flags.pod @@ -2,7 +2,7 @@ =head1 NAME -SSL_CONF_CTX_set_flags, SSL_CONF_CTX_clear_flags - Set of clear SSL configuration context flags +SSL_CONF_CTX_set_flags, SSL_CONF_CTX_clear_flags - Set or clear SSL configuration context flags =head1 SYNOPSIS diff --git a/doc/ssl/SSL_CONF_CTX_set_ssl_ctx.pod b/doc/man3/SSL_CONF_CTX_set_ssl_ctx.pod similarity index 100% rename from doc/ssl/SSL_CONF_CTX_set_ssl_ctx.pod rename to doc/man3/SSL_CONF_CTX_set_ssl_ctx.pod diff --git a/doc/ssl/SSL_CONF_cmd.pod b/doc/man3/SSL_CONF_cmd.pod similarity index 75% rename from doc/ssl/SSL_CONF_cmd.pod rename to doc/man3/SSL_CONF_cmd.pod index a28e2183..b4392f48 100644 --- a/doc/ssl/SSL_CONF_cmd.pod +++ b/doc/man3/SSL_CONF_cmd.pod @@ -2,7 +2,7 @@ =head1 NAME -SSL_CONF_cmd_value_type, SSL_CONF_finish, +SSL_CONF_cmd_value_type, SSL_CONF_cmd - send configuration command =head1 SYNOPSIS @@ -11,7 +11,6 @@ SSL_CONF_cmd - send configuration command int SSL_CONF_cmd(SSL_CONF_CTX *cctx, const char *cmd, const char *value); int SSL_CONF_cmd_value_type(SSL_CONF_CTX *cctx, const char *cmd); - int SSL_CONF_finish(SSL_CONF_CTX *cctx); =head1 DESCRIPTION @@ -22,10 +21,6 @@ framework for command line options or configuration files. SSL_CONF_cmd_value_type() returns the type of value that B refers to. -The function SSL_CONF_finish() must be called after all configuration -operations have been completed. It is used to finalise any operations -or to process defaults. - =head1 SUPPORTED COMMAND LINE COMMANDS Currently supported B names for command lines (i.e. when the @@ -62,16 +57,25 @@ If a server does not request a certificate this option has no effect. The syntax of B is identical to B<-sigalgs>. If not set then the value set for B<-sigalgs> will be used instead. +=item B<-groups> + +This sets the supported groups. For clients, the groups are +sent using the supported groups extension. For servers, it is used +to determine which group to use. This setting affects groups used for both +signatures and key exchange, if applicable. It also affects the preferred +key_share sent by a client in a TLSv1.3 compatible connection. + +The B argument is a colon separated list of groups. The group can be +either the B name (e.g. B), some other commonly used name where +applicable (e.g. B) or an OpenSSL OID name (e.g B). Group +names are case sensitive. The list should be in order of preference with the +most preferred group first. The first listed group will be the one used for a +key_share by a TLSv1.3 client. + =item B<-curves> -This sets the supported elliptic curves. For clients the curves are -sent using the supported curves extension. For servers it is used -to determine which curve to use. This setting affects curves used for both -signatures and key exchange, if applicable. +This is a synonym for the "-groups" command. -The B argument is a colon separated list of curves. The curve can be -either the B name (e.g. B) or an OpenSSL OID name (e.g -B). Curve names are case sensitive. =item B<-named_curve> @@ -110,6 +114,12 @@ Attempts to use the file B as the set of temporary DH parameters for the appropriate context. This option is only supported if certificate operations are permitted. +=item B<-record_padding> + +Attempts to pad TLS 1.3 records so that they are a multiple of B in +length on send. A B of 0 or 1 turns off padding. Otherwise, the +B must be >1 or <=16384. + =item B<-no_renegotiation> Disables all attempts at renegotiation in TLSv1.2 and earlier, same as setting @@ -126,12 +136,13 @@ if specified. To restrict the supported protocol versions use these commands rather than the deprecated alternative commands below. -=item B<-no_ssl3>, B<-no_tls1>, B<-no_tls1_1>, B<-no_tls1_2> +=item B<-no_ssl3>, B<-no_tls1>, B<-no_tls1_1>, B<-no_tls1_2>, B<-no_tls1_3> -Disables protocol support for SSLv3, TLSv1.0, TLSv1.1 or TLSv1.2 by setting the -corresponding options B, B, B -and B respectively. -These options are deprecated, instead use B<-min_protocol> and B<-max_protocol>. +Disables protocol support for SSLv3, TLSv1.0, TLSv1.1, TLSv1.2 or TLSv1.3 by +setting the corresponding options B, B, +B, B and B +respectively. These options are deprecated, instead use B<-min_protocol> and +B<-max_protocol>. =item B<-bugs> @@ -160,6 +171,13 @@ Use server and not client preference order when determining which cipher suite, signature algorithm or elliptic curve to use for an incoming connection. Equivalent to B. Only used by servers. +=item B<-prioritize_chacha> + +Prioritize ChaCha ciphers when the client has a ChaCha20 cipher at the top of +its preference list. This usually indicates a client without AES hardware +acceleration (e.g. mobile) is in use. Equivalent to B. +Only used by servers. Requires B<-serverpref>. + =item B<-no_resumption_on_reneg> set SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION flag. Only used by servers. @@ -175,6 +193,11 @@ permits or prohibits the use of unsafe legacy renegotiation for OpenSSL clients only. Equivalent to setting or clearing B. Set by default. +=item B<-allow_no_dhe_kex> + +In TLSv1.3 allow a non-(ec)dhe based key exchange mode on resumption. This means +that there will be no forward secrecy for the resumed session. + =item B<-strict> enables strict mode protocol handling. Equivalent to setting @@ -221,6 +244,14 @@ These options indicate a file or directory used for building certificate chains or verifying certificate chains. These options are only supported if certificate operations are permitted. +=item B + +This option indicates a file containing a set of certificates in PEM form. +The subject names of the certificates are sent to the peer in the +B extension for TLS 1.3 (in ClientHello or +CertificateRequest) or in a certificate request for previous versions or +TLS. + =item B Attempts to use the file B in the "serverinfo" extension using the @@ -232,6 +263,12 @@ Attempts to use the file B as the set of temporary DH parameters for the appropriate context. This option is only supported if certificate operations are permitted. +=item B + +Attempts to pad TLS 1.3 records so that they are a multiple of B in +length on send. A B of 0 or 1 turns off padding. Otherwise, the +B must be >1 or <=16384. + =item B Disables all attempts at renegotiation in TLSv1.2 and earlier, same as setting @@ -262,16 +299,24 @@ used to determine which signature algorithm to with the client certificate. The syntax of B is identical to B. If not set then the value set for B will be used instead. +=item B + +This sets the supported groups. For clients, the groups are +sent using the supported groups extension. For servers, it is used +to determine which group to use. This setting affects groups used for both +signatures and key exchange, if applicable. It also affects the preferred +key_share sent by a client in a TLSv1.3 compatible connection. + +The B argument is a colon separated list of groups. The group can be +either the B name (e.g. B), some other commonly used name where +applicable (e.g. B) or an OpenSSL OID name (e.g B). Group +names are case sensitive. The list should be in order of preference with the +most preferred group first. The first listed group will be the one used for a +key_share by a TLSv1.3 client. + =item B -This sets the supported elliptic curves. For clients the curves are -sent using the supported curves extension. For servers it is used -to determine which curve to use. This setting affects curves used for both -signatures and key exchange, if applicable. - -The B argument is a colon separated list of curves. The curve can be -either the B name (e.g. B) or an OpenSSL OID name (e.g -B). Curve names are case sensitive. +This is a synonym for the "Groups" command. =item B @@ -344,24 +389,43 @@ B: enable various bug workarounds. Same as B. B: enable single use DH keys, set by default. Inverse of B. Only used by servers. -B enable single use ECDH keys, set by default. Inverse of +B: enable single use ECDH keys, set by default. Inverse of B. Only used by servers. -B use server and not client preference order when +B: use server and not client preference order when determining which cipher suite, signature algorithm or elliptic curve to use for an incoming connection. Equivalent to B. Only used by servers. -B set +B: prioritizes ChaCha ciphers when the client has a +ChaCha20 cipher at the top of its preference list. This usually indicates +a mobile client is in use. Equivalent to B. +Only used by servers. + +B: set B flag. Only used by servers. -B permits the use of unsafe legacy renegotiation. +B: permits the use of unsafe legacy renegotiation. Equivalent to B. -B permits the use of unsafe legacy renegotiation +B: permits the use of unsafe legacy renegotiation for OpenSSL clients only. Equivalent to B. Set by default. +B: use encrypt-then-mac extension, enabled by +default. Inverse of B: that is, +B<-EncryptThenMac> is the same as setting B. + +B: In TLSv1.3 allow a non-(ec)dhe based key exchange mode on +resumption. This means that there will be no forward secrecy for the resumed +session. Equivalent to B. + +B: If set then dummy Change Cipher Spec (CCS) messages are sent +in TLSv1.3. This has the effect of making TLSv1.3 look more like TLSv1.2 so that +middleboxes that do not understand TLSv1.3 will not drop the connection. This +option is set by default. A future version of OpenSSL may not set this by +default. Equivalent to B. + =item B The B argument is a comma separated list of flags to set. @@ -377,6 +441,18 @@ occurs if the client does not present a certificate. Servers only. B requests a certificate from a client only on the initial connection: not when renegotiating. Servers only. +B configures the connection to support requests but does +not require a certificate from the client post-handshake. A certificate will +not be requested during the initial handshake. The server application must +provide a mechanism to request a certificate post-handshake. Servers only. +TLSv1.3 only. + +B configures the connection to support requests and +requires a certificate from the client post-handshake: an error occurs if the +client does not present a certificate. A certificate will not be requested +during the initial handshake. The server application must provide a mechanism +to request a certificate post-handshake. Servers only. TLSv1.3 only. + =item B, B A file or directory of certificates in PEM format whose names are used as the @@ -433,22 +509,22 @@ however the call sequence is: SSLv3 is B disabled and attempt to override this by the user are ignored. -By checking the return code of SSL_CTX_cmd() it is possible to query if a -given B is recognised, this is useful if SSL_CTX_cmd() values are +By checking the return code of SSL_CONF_cmd() it is possible to query if a +given B is recognised, this is useful if SSL_CONF_cmd() values are mixed with additional application specific operations. -For example an application might call SSL_CTX_cmd() and if it returns +For example an application might call SSL_CONF_cmd() and if it returns -2 (unrecognised command) continue with processing of application specific commands. -Applications can also use SSL_CTX_cmd() to process command lines though the -utility function SSL_CTX_cmd_argv() is normally used instead. One way +Applications can also use SSL_CONF_cmd() to process command lines though the +utility function SSL_CONF_cmd_argv() is normally used instead. One way to do this is to set the prefix to an appropriate value using SSL_CONF_CTX_set1_prefix(), pass the current argument to B and the following argument to B (which may be NULL). In this case if the return value is positive then it is used to skip that -number of arguments as they have been processed by SSL_CTX_cmd(). If -2 is +number of arguments as they have been processed by SSL_CONF_cmd(). If -2 is returned then B is not recognised and application specific arguments can be checked instead. If -3 is returned a required argument is missing and an error is indicated. If 0 is returned some other error occurred and @@ -527,8 +603,6 @@ error occurred attempting to perform the operation: for example due to an error in the syntax of B in this case the error queue may provide additional information. -SSL_CONF_finish() returns 1 for success and 0 for failure. - =head1 SEE ALSO L, @@ -551,6 +625,8 @@ B. B and B where added in OpenSSL 1.1.0. +B and B were added in OpenSSL 1.1.1. + =head1 COPYRIGHT Copyright 2012-2018 The OpenSSL Project Authors. All Rights Reserved. diff --git a/doc/ssl/SSL_CONF_cmd_argv.pod b/doc/man3/SSL_CONF_cmd_argv.pod similarity index 96% rename from doc/ssl/SSL_CONF_cmd_argv.pod rename to doc/man3/SSL_CONF_cmd_argv.pod index 15529a59..567fa5a5 100644 --- a/doc/ssl/SSL_CONF_cmd_argv.pod +++ b/doc/man3/SSL_CONF_cmd_argv.pod @@ -15,7 +15,7 @@ SSL_CONF_cmd_argv - SSL configuration command line processing The function SSL_CONF_cmd_argv() processes at most two command line arguments from B and B. The values of B and B are updated to reflect the number of command options processed. The B -argument can be set to B is it is not used. +argument can be set to B if it is not used. =head1 RETURN VALUES diff --git a/doc/ssl/SSL_CTX_add1_chain_cert.pod b/doc/man3/SSL_CTX_add1_chain_cert.pod similarity index 97% rename from doc/ssl/SSL_CTX_add1_chain_cert.pod rename to doc/man3/SSL_CTX_add1_chain_cert.pod index 1f0418b2..24730024 100644 --- a/doc/ssl/SSL_CTX_add1_chain_cert.pod +++ b/doc/man3/SSL_CTX_add1_chain_cert.pod @@ -86,7 +86,7 @@ used to iterate over all certificates in an B structure. SSL_set_current_cert() also supports the option B. If B is a server and has sent a certificate to a connected client this option sets that certificate to the current certificate and returns 1. -If the negotiated ciphersuite is anonymous (and thus no certificate will +If the negotiated cipher suite is anonymous (and thus no certificate will be sent) 2 is returned and the current certificate is unchanged. If B is not a server or a certificate has not been sent 0 is returned and the current certificate is unchanged. @@ -129,7 +129,7 @@ using SSL_CTX_add_extra_chain_cert() will be used. =head1 RETURN VALUES SSL_set_current_cert() with B return 1 for success, 2 if -no server certificate is used because the ciphersuites is anonymous and 0 +no server certificate is used because the cipher suites is anonymous and 0 for failure. SSL_CTX_build_cert_chain() and SSL_build_cert_chain() return 1 for success diff --git a/doc/ssl/SSL_CTX_add_extra_chain_cert.pod b/doc/man3/SSL_CTX_add_extra_chain_cert.pod similarity index 99% rename from doc/ssl/SSL_CTX_add_extra_chain_cert.pod rename to doc/man3/SSL_CTX_add_extra_chain_cert.pod index e2783de9..05d17f8b 100644 --- a/doc/ssl/SSL_CTX_add_extra_chain_cert.pod +++ b/doc/man3/SSL_CTX_add_extra_chain_cert.pod @@ -53,7 +53,7 @@ reason for failure. =head1 SEE ALSO -L, +L, L, L, L diff --git a/doc/ssl/SSL_CTX_add_session.pod b/doc/man3/SSL_CTX_add_session.pod similarity index 77% rename from doc/ssl/SSL_CTX_add_session.pod rename to doc/man3/SSL_CTX_add_session.pod index dbdd9f0c..d8b115bb 100644 --- a/doc/ssl/SSL_CTX_add_session.pod +++ b/doc/man3/SSL_CTX_add_session.pod @@ -2,17 +2,15 @@ =head1 NAME -SSL_CTX_add_session, SSL_add_session, SSL_CTX_remove_session, SSL_remove_session - manipulate session cache +SSL_CTX_add_session, SSL_CTX_remove_session - manipulate session cache =head1 SYNOPSIS #include int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c); - int SSL_add_session(SSL_CTX *ctx, SSL_SESSION *c); int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c); - int SSL_remove_session(SSL_CTX *ctx, SSL_SESSION *c); =head1 DESCRIPTION @@ -21,11 +19,8 @@ reference count for session B is incremented by 1. If a session with the same session id already exists, the old session is removed by calling L. -SSL_CTX_remove_session() removes the session B from the context B. -L is called once for B. - -SSL_add_session() and SSL_remove_session() are synonyms for their -SSL_CTX_*() counterparts. +SSL_CTX_remove_session() removes the session B from the context B and +marks it as non-resumable. L is called once for B. =head1 NOTES @@ -54,19 +49,19 @@ The following values are returned by all functions: =item Z<>0 - The operation failed. In case of the add operation, it was tried to add - the same (identical) session twice. In case of the remove operation, the - session was not found in the cache. +The operation failed. In case of the add operation, it was tried to add +the same (identical) session twice. In case of the remove operation, the +session was not found in the cache. =item Z<>1 - The operation succeeded. +The operation succeeded. =back =head1 SEE ALSO -L, +L, L, L diff --git a/doc/ssl/SSL_CTX_config.pod b/doc/man3/SSL_CTX_config.pod similarity index 93% rename from doc/ssl/SSL_CTX_config.pod rename to doc/man3/SSL_CTX_config.pod index ec744ad0..5b2aed76 100644 --- a/doc/ssl/SSL_CTX_config.pod +++ b/doc/man3/SSL_CTX_config.pod @@ -25,7 +25,7 @@ can also be achieved: an application can support configuration features in newer versions of OpenSSL automatically. A configuration file must have been previously loaded, for example using -CONF_modules_load_file(). See L for details of the configuration +CONF_modules_load_file(). See L for details of the configuration file syntax. =head1 RETURN VALUES @@ -45,11 +45,9 @@ If the file "config.cnf" contains the following: ssl_conf = ssl_sect [ssl_sect] - server = server_section [server_section] - RSA.Certificate = server-rsa.pem ECDSA.Certificate = server-ecdsa.pem Ciphers = ALL:!RC4 @@ -57,8 +55,8 @@ If the file "config.cnf" contains the following: An application could call: if (CONF_modules_load_file("config.cnf", "testapp", 0) <= 0) { - fprintf(stderr, "Error processing config file\n"); - goto err; + fprintf(stderr, "Error processing config file\n"); + goto err; } ctx = SSL_CTX_new(TLS_server_method()); @@ -73,7 +71,7 @@ the need for any additional application code. =head1 SEE ALSO -L, +L, L, L diff --git a/doc/ssl/SSL_CTX_ctrl.pod b/doc/man3/SSL_CTX_ctrl.pod similarity index 99% rename from doc/ssl/SSL_CTX_ctrl.pod rename to doc/man3/SSL_CTX_ctrl.pod index e8386a59..55fb015e 100644 --- a/doc/ssl/SSL_CTX_ctrl.pod +++ b/doc/man3/SSL_CTX_ctrl.pod @@ -29,7 +29,7 @@ supplied via the B parameter. =head1 SEE ALSO -L +L =head1 COPYRIGHT diff --git a/doc/man3/SSL_CTX_dane_enable.pod b/doc/man3/SSL_CTX_dane_enable.pod new file mode 100644 index 00000000..d767bb29 --- /dev/null +++ b/doc/man3/SSL_CTX_dane_enable.pod @@ -0,0 +1,382 @@ +=pod + +=head1 NAME + +SSL_CTX_dane_enable, SSL_CTX_dane_mtype_set, SSL_dane_enable, +SSL_dane_tlsa_add, SSL_get0_dane_authority, SSL_get0_dane_tlsa, +SSL_CTX_dane_set_flags, SSL_CTX_dane_clear_flags, +SSL_dane_set_flags, SSL_dane_clear_flags +- enable DANE TLS authentication of the remote TLS server in the local +TLS client + +=head1 SYNOPSIS + + #include + + int SSL_CTX_dane_enable(SSL_CTX *ctx); + int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md, + uint8_t mtype, uint8_t ord); + int SSL_dane_enable(SSL *s, const char *basedomain); + int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector, + uint8_t mtype, unsigned const char *data, size_t dlen); + int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki); + int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector, + uint8_t *mtype, unsigned const char **data, + size_t *dlen); + unsigned long SSL_CTX_dane_set_flags(SSL_CTX *ctx, unsigned long flags); + unsigned long SSL_CTX_dane_clear_flags(SSL_CTX *ctx, unsigned long flags); + unsigned long SSL_dane_set_flags(SSL *ssl, unsigned long flags); + unsigned long SSL_dane_clear_flags(SSL *ssl, unsigned long flags); + +=head1 DESCRIPTION + +These functions implement support for DANE TLSA (RFC6698 and RFC7671) +peer authentication. + +SSL_CTX_dane_enable() must be called first to initialize the shared state +required for DANE support. +Individual connections associated with the context can then enable +per-connection DANE support as appropriate. +DANE authentication is implemented in the L function, and +applications that override L via +L are responsible to authenticate the peer +chain in whatever manner they see fit. + +SSL_CTX_dane_mtype_set() may then be called zero or more times to adjust the +supported digest algorithms. +This must be done before any SSL handles are created for the context. + +The B argument specifies a DANE TLSA matching type and the B +argument specifies the associated digest algorithm handle. +The B argument specifies a strength ordinal. +Algorithms with a larger strength ordinal are considered more secure. +Strength ordinals are used to implement RFC7671 digest algorithm agility. +Specifying a B digest algorithm for a matching type disables +support for that matching type. +Matching type Full(0) cannot be modified or disabled. + +By default, matching type C (see RFC7218 for definitions +of the DANE TLSA parameter acronyms) is mapped to C +with a strength ordinal of C<1> and matching type C +is mapped to C with a strength ordinal of C<2>. + +SSL_dane_enable() must be called before the SSL handshake is initiated with +L if (and only if) you want to enable DANE for that connection. +(The connection must be associated with a DANE-enabled SSL context). +The B argument specifies the RFC7671 TLSA base domain, +which will be the primary peer reference identifier for certificate +name checks. +Additional server names can be specified via L. +The B is used as the default SNI hint if none has yet been +specified via L. + +SSL_dane_tlsa_add() may then be called one or more times, to load each of the +TLSA records that apply to the remote TLS peer. +(This too must be done prior to the beginning of the SSL handshake). +The arguments specify the fields of the TLSA record. +The B field is provided in binary (wire RDATA) form, not the hexadecimal +ASCII presentation form, with an explicit length passed via B. +The library takes a copy of the B buffer contents and the caller may +free the original B buffer when convenient. +A return value of 0 indicates that "unusable" TLSA records (with invalid or +unsupported parameters) were provided. +A negative return value indicates an internal error in processing the record. + +The caller is expected to check the return value of each SSL_dane_tlsa_add() +call and take appropriate action if none are usable or an internal error +is encountered in processing some records. + +If no TLSA records are added successfully, DANE authentication is not enabled, +and authentication will be based on any configured traditional trust-anchors; +authentication success in this case does not mean that the peer was +DANE-authenticated. + +SSL_get0_dane_authority() can be used to get more detailed information about +the matched DANE trust-anchor after successful connection completion. +The return value is negative if DANE verification failed (or was not enabled), +0 if an EE TLSA record directly matched the leaf certificate, or a positive +number indicating the depth at which a TA record matched an issuer certificate. +The complete verified chain can be retrieved via L. +The return value is an index into this verified chain, rather than the list of +certificates sent by the peer as returned by L. + +If the B argument is not B and a TLSA record matched a chain +certificate, a pointer to the matching certificate is returned via B. +The returned address is a short-term internal reference to the certificate and +must not be freed by the application. +Applications that want to retain access to the certificate can call +L to obtain a long-term reference which must then be freed via +L once no longer needed. + +If no TLSA records directly matched any elements of the certificate chain, but +a DANE-TA(2) SPKI(1) Full(0) record provided the public key that signed an +element of the chain, then that key is returned via B argument (if not +NULL). +In this case the return value is the depth of the top-most element of the +validated certificate chain. +As with B this is a short-term internal reference, and +L and L can be used to acquire and +release long-term references respectively. + +SSL_get0_dane_tlsa() can be used to retrieve the fields of the TLSA record that +matched the peer certificate chain. +The return value indicates the match depth or failure to match just as with +SSL_get0_dane_authority(). +When the return value is non-negative, the storage pointed to by the B, +B, B and B parameters is updated to the corresponding +TLSA record fields. +The B field is in binary wire form, and is therefore not NUL-terminated, +its length is returned via the B parameter. +If any of these parameters is NULL, the corresponding field is not returned. +The B parameter is set to a short-term internal-copy of the associated +data field and must not be freed by the application. +Applications that need long-term access to this field need to copy the content. + +SSL_CTX_dane_set_flags() and SSL_dane_set_flags() can be used to enable +optional DANE verification features. +SSL_CTX_dane_clear_flags() and SSL_dane_clear_flags() can be used to disable +the same features. +The B argument is a bitmask of the features to enable or disable. +The B set for an B context are copied to each B handle +associated with that context at the time the handle is created. +Subsequent changes in the context's B have no effect on the B set +for the handle. + +At present, the only available option is B +which can be used to disable server name checks when authenticating via +DANE-EE(3) TLSA records. +For some applications, primarily web browsers, it is not safe to disable name +checks due to "unknown key share" attacks, in which a malicious server can +convince a client that a connection to a victim server is instead a secure +connection to the malicious server. +The malicious server may then be able to violate cross-origin scripting +restrictions. +Thus, despite the text of RFC7671, name checks are by default enabled for +DANE-EE(3) TLSA records, and can be disabled in applications where it is safe +to do so. +In particular, SMTP and XMPP clients should set this option as SRV and MX +records already make it possible for a remote domain to redirect client +connections to any server of its choice, and in any case SMTP and XMPP clients +do not execute scripts downloaded from remote servers. + +=head1 RETURN VALUES + +The functions SSL_CTX_dane_enable(), SSL_CTX_dane_mtype_set(), +SSL_dane_enable() and SSL_dane_tlsa_add() return a positive value on success. +Negative return values indicate resource problems (out of memory, etc.) in the +SSL library, while a return value of B<0> indicates incorrect usage or invalid +input, such as an unsupported TLSA record certificate usage, selector or +matching type. +Invalid input also includes malformed data, either a digest length that does +not match the digest algorithm, or a C (binary ASN.1 DER form) +certificate or a public key that fails to parse. + +The functions SSL_get0_dane_authority() and SSL_get0_dane_tlsa() return a +negative value when DANE authentication failed or was not enabled, a +non-negative value indicates the chain depth at which the TLSA record matched a +chain certificate, or the depth of the top-most certificate, when the TLSA +record is a full public key that is its signer. + +The functions SSL_CTX_dane_set_flags(), SSL_CTX_dane_clear_flags(), +SSL_dane_set_flags() and SSL_dane_clear_flags() return the B in effect +before they were called. + +=head1 EXAMPLE + +Suppose "smtp.example.com" is the MX host of the domain "example.com", and has +DNSSEC-validated TLSA records. +The calls below will perform DANE authentication and arrange to match either +the MX hostname or the destination domain name in the SMTP server certificate. +Wildcards are supported, but must match the entire label. +The actual name matched in the certificate (which might be a wildcard) is +retrieved, and must be copied by the application if it is to be retained beyond +the lifetime of the SSL connection. + + SSL_CTX *ctx; + SSL *ssl; + int (*verify_cb)(int ok, X509_STORE_CTX *sctx) = NULL; + int num_usable = 0; + const char *nexthop_domain = "example.com"; + const char *dane_tlsa_domain = "smtp.example.com"; + uint8_t usage, selector, mtype; + + if ((ctx = SSL_CTX_new(TLS_client_method())) == NULL) + /* error */ + if (SSL_CTX_dane_enable(ctx) <= 0) + /* error */ + if ((ssl = SSL_new(ctx)) == NULL) + /* error */ + if (SSL_dane_enable(ssl, dane_tlsa_domain) <= 0) + /* error */ + + /* + * For many applications it is safe to skip DANE-EE(3) namechecks. Do not + * disable the checks unless "unknown key share" attacks pose no risk for + * your application. + */ + SSL_dane_set_flags(ssl, DANE_FLAG_NO_DANE_EE_NAMECHECKS); + + if (!SSL_add1_host(ssl, nexthop_domain)) + /* error */ + SSL_set_hostflags(ssl, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + + for (... each TLSA record ...) { + unsigned char *data; + size_t len; + int ret; + + /* set usage, selector, mtype, data, len */ + + /* + * Opportunistic DANE TLS clients support only DANE-TA(2) or DANE-EE(3). + * They treat all other certificate usages, and in particular PKIX-TA(0) + * and PKIX-EE(1), as unusable. + */ + switch (usage) { + default: + case 0: /* PKIX-TA(0) */ + case 1: /* PKIX-EE(1) */ + continue; + case 2: /* DANE-TA(2) */ + case 3: /* DANE-EE(3) */ + break; + } + + ret = SSL_dane_tlsa_add(ssl, usage, selector, mtype, data, len); + /* free data as appropriate */ + + if (ret < 0) + /* handle SSL library internal error */ + else if (ret == 0) + /* handle unusable TLSA record */ + else + ++num_usable; + } + + /* + * At this point, the verification mode is still the default SSL_VERIFY_NONE. + * Opportunistic DANE clients use unauthenticated TLS when all TLSA records + * are unusable, so continue the handshake even if authentication fails. + */ + if (num_usable == 0) { + /* Log all records unusable? */ + + /* Optionally set verify_cb to a suitable non-NULL callback. */ + SSL_set_verify(ssl, SSL_VERIFY_NONE, verify_cb); + } else { + /* At least one usable record. We expect to verify the peer */ + + /* Optionally set verify_cb to a suitable non-NULL callback. */ + + /* + * Below we elect to fail the handshake when peer verification fails. + * Alternatively, use the permissive SSL_VERIFY_NONE verification mode, + * complete the handshake, check the verification status, and if not + * verified disconnect gracefully at the application layer, especially if + * application protocol supports informing the server that authentication + * failed. + */ + SSL_set_verify(ssl, SSL_VERIFY_PEER, verify_cb); + } + + /* + * Load any saved session for resumption, making sure that the previous + * session applied the same security and authentication requirements that + * would be expected of a fresh connection. + */ + + /* Perform SSL_connect() handshake and handle errors here */ + + if (SSL_session_reused(ssl)) { + if (SSL_get_verify_result(ssl) == X509_V_OK) { + /* + * Resumed session was originally verified, this connection is + * authenticated. + */ + } else { + /* + * Resumed session was not originally verified, this connection is not + * authenticated. + */ + } + } else if (SSL_get_verify_result(ssl) == X509_V_OK) { + const char *peername = SSL_get0_peername(ssl); + EVP_PKEY *mspki = NULL; + + int depth = SSL_get0_dane_authority(ssl, NULL, &mspki); + if (depth >= 0) { + (void) SSL_get0_dane_tlsa(ssl, &usage, &selector, &mtype, NULL, NULL); + printf("DANE TLSA %d %d %d %s at depth %d\n", usage, selector, mtype, + (mspki != NULL) ? "TA public key verified certificate" : + depth ? "matched TA certificate" : "matched EE certificate", + depth); + } + if (peername != NULL) { + /* Name checks were in scope and matched the peername */ + printf("Verified peername: %s\n", peername); + } + } else { + /* + * Not authenticated, presumably all TLSA rrs unusable, but possibly a + * callback suppressed connection termination despite the presence of + * usable TLSA RRs none of which matched. Do whatever is appropriate for + * fresh unauthenticated connections. + */ + } + +=head1 NOTES + +It is expected that the majority of clients employing DANE TLS will be doing +"opportunistic DANE TLS" in the sense of RFC7672 and RFC7435. +That is, they will use DANE authentication when DNSSEC-validated TLSA records +are published for a given peer, and otherwise will use unauthenticated TLS or +even cleartext. + +Such applications should generally treat any TLSA records published by the peer +with usages PKIX-TA(0) and PKIX-EE(1) as "unusable", and should not include +them among the TLSA records used to authenticate peer connections. +In addition, some TLSA records with supported usages may be "unusable" as a +result of invalid or unsupported parameters. + +When a peer has TLSA records, but none are "usable", an opportunistic +application must avoid cleartext, but cannot authenticate the peer, +and so should generally proceed with an unauthenticated connection. +Opportunistic applications need to note the return value of each +call to SSL_dane_tlsa_add(), and if all return 0 (due to invalid +or unsupported parameters) disable peer authentication by calling +L with B equal to B. + +=head1 SEE ALSO + +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L + +=head1 HISTORY + +These functions were first added to OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2016-2018 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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_flush_sessions.pod b/doc/man3/SSL_CTX_flush_sessions.pod similarity index 81% rename from doc/ssl/SSL_CTX_flush_sessions.pod rename to doc/man3/SSL_CTX_flush_sessions.pod index 7639451c..c2f01064 100644 --- a/doc/ssl/SSL_CTX_flush_sessions.pod +++ b/doc/man3/SSL_CTX_flush_sessions.pod @@ -2,29 +2,26 @@ =head1 NAME -SSL_CTX_flush_sessions, SSL_flush_sessions - remove expired sessions +SSL_CTX_flush_sessions - remove expired sessions =head1 SYNOPSIS #include void SSL_CTX_flush_sessions(SSL_CTX *ctx, long tm); - void SSL_flush_sessions(SSL_CTX *ctx, long tm); =head1 DESCRIPTION SSL_CTX_flush_sessions() causes a run through the session cache of B to remove sessions expired at time B. -SSL_flush_sessions() is a synonym for SSL_CTX_flush_sessions(). - =head1 NOTES If enabled, the internal session cache will collect all sessions established up to the specified maximum number (see SSL_CTX_sess_set_cache_size()). As sessions will not be reused ones they are expired, they should be removed from the cache to save resources. This can either be done - automatically whenever 255 new sessions were established (see +automatically whenever 255 new sessions were established (see L) or manually by calling SSL_CTX_flush_sessions(). @@ -37,16 +34,20 @@ cache. When a session is found and removed, the remove_session_cb is however called to synchronize with the external cache (see L). +=head1 RETURN VALUES + +SSL_CTX_flush_sessions() does not return a value. + =head1 SEE ALSO -L, +L, L, L, L =head1 COPYRIGHT -Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2001-2018 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 diff --git a/doc/ssl/SSL_CTX_free.pod b/doc/man3/SSL_CTX_free.pod similarity index 97% rename from doc/ssl/SSL_CTX_free.pod rename to doc/man3/SSL_CTX_free.pod index e5cc1aab..6b7bf1a8 100644 --- a/doc/ssl/SSL_CTX_free.pod +++ b/doc/man3/SSL_CTX_free.pod @@ -36,7 +36,7 @@ SSL_CTX_free() does not provide diagnostic information. =head1 SEE ALSO -L, L, +L, L, L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_CTX_get0_param.pod b/doc/man3/SSL_CTX_get0_param.pod similarity index 100% rename from doc/ssl/SSL_CTX_get0_param.pod rename to doc/man3/SSL_CTX_get0_param.pod diff --git a/doc/ssl/SSL_CTX_get_verify_mode.pod b/doc/man3/SSL_CTX_get_verify_mode.pod similarity index 98% rename from doc/ssl/SSL_CTX_get_verify_mode.pod rename to doc/man3/SSL_CTX_get_verify_mode.pod index bd100344..5f6da9d4 100644 --- a/doc/ssl/SSL_CTX_get_verify_mode.pod +++ b/doc/man3/SSL_CTX_get_verify_mode.pod @@ -45,7 +45,7 @@ See DESCRIPTION =head1 SEE ALSO -L, L +L, L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_CTX_has_client_custom_ext.pod b/doc/man3/SSL_CTX_has_client_custom_ext.pod similarity index 98% rename from doc/ssl/SSL_CTX_has_client_custom_ext.pod rename to doc/man3/SSL_CTX_has_client_custom_ext.pod index d9e9a066..b220c5e7 100644 --- a/doc/ssl/SSL_CTX_has_client_custom_ext.pod +++ b/doc/man3/SSL_CTX_has_client_custom_ext.pod @@ -22,7 +22,7 @@ Returns 1 if a handler has been set, 0 otherwise. =head1 SEE ALSO -L, +L, L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_CTX_load_verify_locations.pod b/doc/man3/SSL_CTX_load_verify_locations.pod similarity index 99% rename from doc/ssl/SSL_CTX_load_verify_locations.pod rename to doc/man3/SSL_CTX_load_verify_locations.pod index 59d11e03..a96aafed 100644 --- a/doc/ssl/SSL_CTX_load_verify_locations.pod +++ b/doc/man3/SSL_CTX_load_verify_locations.pod @@ -108,7 +108,7 @@ ca1.pem ca2.pem ca3.pem: #!/bin/sh rm CAfile.pem for i in ca1.pem ca2.pem ca3.pem ; do - openssl x509 -in $i -text >> CAfile.pem + openssl x509 -in $i -text >> CAfile.pem done Prepare the directory /some/where/certs containing several CA certificates @@ -141,7 +141,7 @@ missing default location is still treated as a success. =head1 SEE ALSO -L, +L, L, L, L, diff --git a/doc/ssl/SSL_CTX_new.pod b/doc/man3/SSL_CTX_new.pod similarity index 93% rename from doc/ssl/SSL_CTX_new.pod rename to doc/man3/SSL_CTX_new.pod index 7b35bdda..4bcbccaf 100644 --- a/doc/ssl/SSL_CTX_new.pod +++ b/doc/man3/SSL_CTX_new.pod @@ -156,12 +156,12 @@ and be able to negotiate with all possible clients, but to only allow newer protocols like TLS 1.0, TLS 1.1 or TLS 1.2. The list of protocols available can also be limited using the -B, B, B and -B options of the L or -L functions, but this approach is not recommended. -Clients should avoid creating "holes" in the set of protocols they support. -When disabling a protocol, make sure that you also disable either all previous -or all subsequent protocol versions. +B, B, B, +B and B options of the +L or L functions, but this approach +is not recommended. Clients should avoid creating "holes" in the set of +protocols they support. When disabling a protocol, make sure that you also +disable either all previous or all subsequent protocol versions. In clients, when a protocol version is disabled without disabling I previous protocol versions, the effect is to also disable all subsequent protocol versions. @@ -204,7 +204,7 @@ All version-specific methods were deprecated in OpenSSL 1.1.0. =head1 SEE ALSO L, L, L, -L, L, L +L, L, L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_CTX_sess_number.pod b/doc/man3/SSL_CTX_sess_number.pod similarity index 93% rename from doc/ssl/SSL_CTX_sess_number.pod rename to doc/man3/SSL_CTX_sess_number.pod index 049c04c4..a96c8dd7 100644 --- a/doc/ssl/SSL_CTX_sess_number.pod +++ b/doc/man3/SSL_CTX_sess_number.pod @@ -32,7 +32,7 @@ client mode. SSL_CTX_sess_connect_good() returns the number of successfully established SSL/TLS sessions in client mode. -SSL_CTX_sess_connect_renegotiate() returns the number of start renegotiations +SSL_CTX_sess_connect_renegotiate() returns the number of started renegotiations in client mode. SSL_CTX_sess_accept() returns the number of started SSL/TLS handshakes in @@ -41,7 +41,7 @@ server mode. SSL_CTX_sess_accept_good() returns the number of successfully established SSL/TLS sessions in server mode. -SSL_CTX_sess_accept_renegotiate() returns the number of start renegotiations +SSL_CTX_sess_accept_renegotiate() returns the number of started renegotiations in server mode. SSL_CTX_sess_hits() returns the number of successfully reused sessions. @@ -69,7 +69,7 @@ The functions return the values indicated in the DESCRIPTION section. =head1 SEE ALSO -L, L, +L, L, L L diff --git a/doc/ssl/SSL_CTX_sess_set_cache_size.pod b/doc/man3/SSL_CTX_sess_set_cache_size.pod similarity index 99% rename from doc/ssl/SSL_CTX_sess_set_cache_size.pod rename to doc/man3/SSL_CTX_sess_set_cache_size.pod index 5aef10bd..6a1c140e 100644 --- a/doc/ssl/SSL_CTX_sess_set_cache_size.pod +++ b/doc/man3/SSL_CTX_sess_set_cache_size.pod @@ -45,7 +45,7 @@ SSL_CTX_sess_get_cache_size() returns the currently valid size. =head1 SEE ALSO -L, +L, L, L, L diff --git a/doc/man3/SSL_CTX_sess_set_get_cb.pod b/doc/man3/SSL_CTX_sess_set_get_cb.pod new file mode 100644 index 00000000..c66164eb --- /dev/null +++ b/doc/man3/SSL_CTX_sess_set_get_cb.pod @@ -0,0 +1,114 @@ +=pod + +=head1 NAME + +SSL_CTX_sess_set_new_cb, SSL_CTX_sess_set_remove_cb, SSL_CTX_sess_set_get_cb, SSL_CTX_sess_get_new_cb, SSL_CTX_sess_get_remove_cb, SSL_CTX_sess_get_get_cb - provide callback functions for server side external session caching + +=head1 SYNOPSIS + + #include + + void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx, + int (*new_session_cb)(SSL *, SSL_SESSION *)); + void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx, + void (*remove_session_cb)(SSL_CTX *ctx, + SSL_SESSION *)); + void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, + SSL_SESSION (*get_session_cb)(SSL *, + const unsigned char *, + int, int *)); + + int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(struct ssl_st *ssl, + SSL_SESSION *sess); + void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(struct ssl_ctx_st *ctx, + SSL_SESSION *sess); + SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(struct ssl_st *ssl, + const unsigned char *data, + int len, int *copy); + +=head1 DESCRIPTION + +SSL_CTX_sess_set_new_cb() sets the callback function, which is automatically +called whenever a new session was negotiated. + +SSL_CTX_sess_set_remove_cb() sets the callback function, which is +automatically called whenever a session is removed by the SSL engine, +because it is considered faulty or the session has become obsolete because +of exceeding the timeout value. + +SSL_CTX_sess_set_get_cb() sets the callback function which is called, +whenever a SSL/TLS client proposed to resume a session but the session +could not be found in the internal session cache (see +L). +(SSL/TLS server only.) + +SSL_CTX_sess_get_new_cb(), SSL_CTX_sess_get_remove_cb(), and +SSL_CTX_sess_get_get_cb() allow to retrieve the function pointers of the +provided callback functions. If a callback function has not been set, +the NULL pointer is returned. + +=head1 NOTES + +In order to allow external session caching, synchronization with the internal +session cache is realized via callback functions. Inside these callback +functions, session can be saved to disk or put into a database using the +L interface. + +The new_session_cb() is called, whenever a new session has been negotiated +and session caching is enabled (see +L). +The new_session_cb() is passed the B connection and the ssl session +B. If the callback returns B<0>, the session will be immediately +removed again. Note that in TLSv1.3, sessions are established after the main +handshake has completed. The server decides when to send the client the session +information and this may occur some time after the end of the handshake (or not +at all). This means that applications should expect the new_session_cb() +function to be invoked during the handshake (for <= TLSv1.2) or after the +handshake (for TLSv1.3). It is also possible in TLSv1.3 for multiple sessions to +be established with a single connection. In these case the new_session_cb() +function will be invoked multiple times. + +In TLSv1.3 it is recommended that each SSL_SESSION object is only used for +resumption once. One way of enforcing that is for applications to call +L after a session has been used. + +The remove_session_cb() is called, whenever the SSL engine removes a session +from the internal cache. This happens when the session is removed because +it is expired or when a connection was not shutdown cleanly. It also happens +for all sessions in the internal session cache when +L is called. The remove_session_cb() is passed +the B and the ssl session B. It does not provide any feedback. + +The get_session_cb() is only called on SSL/TLS servers with the session id +proposed by the client. The get_session_cb() is always called, also when +session caching was disabled. The get_session_cb() is passed the +B connection, the session id of length B at the memory location +B. With the parameter B the callback can require the +SSL engine to increment the reference count of the SSL_SESSION object, +Normally the reference count is not incremented and therefore the +session must not be explicitly freed with +L. + +=head1 RETURN VALUES + +SSL_CTX_sess_get_new_cb(), SSL_CTX_sess_get_remove_cb() and SSL_CTX_sess_get_get_cb() +return different callback function pointers respectively. + +=head1 SEE ALSO + +L, L, +L, +L, +L, +L + +=head1 COPYRIGHT + +Copyright 2001-2018 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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_sessions.pod b/doc/man3/SSL_CTX_sessions.pod similarity index 76% rename from doc/ssl/SSL_CTX_sessions.pod rename to doc/man3/SSL_CTX_sessions.pod index bc4a55e1..41c0777c 100644 --- a/doc/ssl/SSL_CTX_sessions.pod +++ b/doc/man3/SSL_CTX_sessions.pod @@ -18,22 +18,26 @@ internal session cache for B. =head1 NOTES The sessions in the internal session cache are kept in an -L type database. It is possible to directly +L type database. It is possible to directly access this database e.g. for searching. In parallel, the sessions form a linked list which is maintained separately from the -L operations, so that the database must not be +L operations, so that the database must not be modified directly but by using the L family of functions. +=head1 RETURN VALUES + +SSL_CTX_sessions() returns a pointer to the lhash of B. + =head1 SEE ALSO -L, L, +L, L, L, L =head1 COPYRIGHT -Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2001-2018 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 diff --git a/doc/man3/SSL_CTX_set0_CA_list.pod b/doc/man3/SSL_CTX_set0_CA_list.pod new file mode 100644 index 00000000..0f8b7da7 --- /dev/null +++ b/doc/man3/SSL_CTX_set0_CA_list.pod @@ -0,0 +1,92 @@ +=pod + +=head1 NAME + +SSL_set0_CA_list, SSL_CTX_set0_CA_list, SSL_get0_CA_list, +SSL_CTX_get0_CA_list, SSL_add1_CA_list, SSL_CTX_add1_CA_list, +SSL_get0_peer_CA_list - get or set CA list + +=head1 SYNOPSIS + + #include + + void SSL_CTX_set0_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list); + void SSL_set0_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list); + const STACK_OF(X509_NAME) *SSL_CTX_get0_CA_list(const SSL_CTX *ctx); + const STACK_OF(X509_NAME) *SSL_get0_CA_list(const SSL *s); + int SSL_CTX_add1_CA_list(SSL_CTX *ctx, const X509 *x); + int SSL_add1_CA_list(SSL *ssl, const X509 *x); + + const STACK_OF(X509_NAME) *SSL_get0_peer_CA_list(const SSL *s); + +=head1 DESCRIPTION + +SSL_CTX_set0_CA_list() sets the list of CAs to be sent to the peer to +B. Ownership of B is transferred to B and +it should not be freed by the caller. + +SSL_set0_CA_list() sets the list of CAs to be sent to the peer to B +overriding any list set in the parent B of B. Ownership of +B is transferred to B and it should not be freed by the caller. + +SSL_CTX_get0_CA_list() retrieves any previously set list of CAs set for +B. + +SSL_CTX_get0_CA_list() retrieves any previously set list of CAs set for +B or if none are set the list from the parent B is retrieved. + +SSL_CTX_add1_CA_list() appends the CA subject name extracted from B to the +list of CAs sent to peer for B. + +SSL_add1_CA_list() appends the CA subject name extracted from B to the +list of CAs sent to the peer for B, overriding the setting in the parent +B. + +SSL_get0_peer_CA_list() retrieves the list of CA names (if any) the peer +has sent. + +=head1 NOTES + +These functions are generalised versions of the client authentication +CA list functions such as L. + +For TLS versions before 1.3 the list of CA names is only sent from the server +to client when requesting a client certificate. So any list of CA names set +is never sent from client to server and the list of CA names retrieved by +SSL_get0_peer_CA_list() is always B. + +For TLS 1.3 the list of CA names is sent using the B +extension and will be sent by a client (in the ClientHello message) or by +a server (when requesting a certificate). + +=head1 RETURN VALUES + +SSL_CTX_set0_CA_list() and SSL_set0_CA_list() do not return a value. + +SSL_CTX_get0_CA_list() and SSL_get0_CA_list() return a stack of CA names +or B is no CA names are set. + +SSL_CTX_add1_CA_list() and SSL_add1_CA_list() return 1 for success and 0 +for failure. + +SSL_get0_peer_CA_list() returns a stack of CA names sent by the peer or +B or an empty stack if no list was sent. + +=head1 SEE ALSO + +L, +L, +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/man3/SSL_CTX_set1_curves.pod b/doc/man3/SSL_CTX_set1_curves.pod new file mode 100644 index 00000000..a250f20c --- /dev/null +++ b/doc/man3/SSL_CTX_set1_curves.pod @@ -0,0 +1,109 @@ +=pod + +=head1 NAME + +SSL_CTX_set1_groups, SSL_CTX_set1_groups_list, SSL_set1_groups, +SSL_set1_groups_list, SSL_get1_groups, SSL_get_shared_group, +SSL_CTX_set1_curves, SSL_CTX_set1_curves_list, SSL_set1_curves, +SSL_set1_curves_list, SSL_get1_curves, SSL_get_shared_curve +- EC supported curve functions + +=head1 SYNOPSIS + + #include + + int SSL_CTX_set1_groups(SSL_CTX *ctx, int *glist, int glistlen); + int SSL_CTX_set1_groups_list(SSL_CTX *ctx, char *list); + + int SSL_set1_groups(SSL *ssl, int *glist, int glistlen); + int SSL_set1_groups_list(SSL *ssl, char *list); + + int SSL_get1_groups(SSL *ssl, int *groups); + int SSL_get_shared_group(SSL *s, int n); + + int SSL_CTX_set1_curves(SSL_CTX *ctx, int *clist, int clistlen); + int SSL_CTX_set1_curves_list(SSL_CTX *ctx, char *list); + + int SSL_set1_curves(SSL *ssl, int *clist, int clistlen); + int SSL_set1_curves_list(SSL *ssl, char *list); + + int SSL_get1_curves(SSL *ssl, int *curves); + int SSL_get_shared_curve(SSL *s, int n); + +=head1 DESCRIPTION + +SSL_CTX_set1_groups() sets the supported groups for B to B +groups in the array B. The array consist of all NIDs of groups in +preference order. For a TLS client the groups are used directly in the +supported groups extension. For a TLS server the groups are used to +determine the set of shared groups. + +SSL_CTX_set1_groups_list() sets the supported groups for B to +string B. The string is a colon separated list of group NIDs or +names, for example "P-521:P-384:P-256". + +SSL_set1_groups() and SSL_set1_groups_list() are similar except they set +supported groups for the SSL structure B. + +SSL_get1_groups() returns the set of supported groups sent by a client +in the supported groups extension. It returns the total number of +supported groups. The B parameter can be B to simply +return the number of groups for memory allocation purposes. The +B array is in the form of a set of group NIDs in preference +order. It can return zero if the client did not send a supported groups +extension. + +SSL_get_shared_group() returns shared group B for a server-side +SSL B. If B is -1 then the total number of shared groups is +returned, which may be zero. Other than for diagnostic purposes, +most applications will only be interested in the first shared group +so B is normally set to zero. If the value B is out of range, +NID_undef is returned. + +All these functions are implemented as macros. + +The curve functions are synonyms for the equivalently named group functions and +are identical in every respect. They exist because, prior to TLS1.3, there was +only the concept of supported curves. In TLS1.3 this was renamed to supported +groups, and extended to include Diffie Hellman groups. The group functions +should be used in preference. + +=head1 NOTES + +If an application wishes to make use of several of these functions for +configuration purposes either on a command line or in a file it should +consider using the SSL_CONF interface instead of manually parsing options. + +=head1 RETURN VALUES + +SSL_CTX_set1_groups(), SSL_CTX_set1_groups_list(), SSL_set1_groups() and +SSL_set1_groups_list(), return 1 for success and 0 for failure. + +SSL_get1_groups() returns the number of groups, which may be zero. + +SSL_get_shared_group() returns the NID of shared group B or NID_undef if there +is no shared group B; or the total number of shared groups if B +is -1. + +When called on a client B, SSL_get_shared_group() has no meaning and +returns -1. + +=head1 SEE ALSO + +L + +=head1 HISTORY + +The curve functions were first added to OpenSSL 1.0.2. The equivalent group +functions were first added to OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2013-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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_set1_sigalgs.pod b/doc/man3/SSL_CTX_set1_sigalgs.pod similarity index 82% rename from doc/ssl/SSL_CTX_set1_sigalgs.pod rename to doc/man3/SSL_CTX_set1_sigalgs.pod index e9073b99..93d5320d 100644 --- a/doc/ssl/SSL_CTX_set1_sigalgs.pod +++ b/doc/man3/SSL_CTX_set1_sigalgs.pod @@ -30,8 +30,10 @@ algorithms. SSL_CTX_set1_sigalgs_list() and SSL_set1_sigalgs_list() set the supported signature algorithms for B or B. The B parameter -must be a null terminated string consisting or a colon separated list of -public key algorithms and digests separated by B<+>. +must be a null terminated string consisting of a colon separated list of +elements, where each element is either a combination of a public key +algorithm and a digest separated by B<+>, or a TLS 1.3-style named +SignatureScheme such as rsa_pss_pss_sha256. SSL_CTX_set1_client_sigalgs(), SSL_set1_client_sigalgs(), SSL_CTX_set1_client_sigalgs_list() and SSL_set1_client_sigalgs_list() set @@ -70,11 +72,14 @@ prohibits them (for example SHA1 if the security level is 4 or more). Currently the NID_md5, NID_sha1, NID_sha224, NID_sha256, NID_sha384 and NID_sha512 digest NIDs are supported and the public key algorithm NIDs -EVP_PKEY_RSA, EVP_PKEY_DSA and EVP_PKEY_EC. +EVP_PKEY_RSA, EVP_PKEY_RSA_PSS, EVP_PKEY_DSA and EVP_PKEY_EC. The short or long name values for digests can be used in a string (for example "MD5", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512") and -the public key algorithm strings "RSA", "DSA" or "ECDSA". +the public key algorithm strings "RSA", "RSA-PSS", "DSA" or "ECDSA". + +The TLS 1.3 signature scheme names (such as "rsa_pss_pss_sha256") can also +be used with the B<_list> forms of the API. The use of MD5 as a digest is strongly discouraged due to security weaknesses. @@ -83,14 +88,14 @@ The use of MD5 as a digest is strongly discouraged due to security weaknesses. Set supported signature algorithms to SHA256 with ECDSA and SHA256 with RSA using an array: - const int slist[] = {NID_sha256, EVP_PKEY_EC, NID_sha256, EVP_PKEY_RSA}; + const int slist[] = {NID_sha256, EVP_PKEY_EC, NID_sha256, EVP_PKEY_RSA}; - SSL_CTX_set1_sigalgs(ctx, slist, 4); + SSL_CTX_set1_sigalgs(ctx, slist, 4); Set supported signature algorithms to SHA256 with ECDSA and SHA256 with RSA using a string: - SSL_CTX_set1_sigalgs_list(ctx, "ECDSA+SHA256:RSA+SHA256"); + SSL_CTX_set1_sigalgs_list(ctx, "ECDSA+SHA256:RSA+SHA256"); =head1 RETURN VALUES @@ -98,12 +103,12 @@ All these functions return 1 for success and 0 for failure. =head1 SEE ALSO -L, L, +L, L, L =head1 COPYRIGHT -Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2015-2018 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 diff --git a/doc/ssl/SSL_CTX_set1_verify_cert_store.pod b/doc/man3/SSL_CTX_set1_verify_cert_store.pod similarity index 100% rename from doc/ssl/SSL_CTX_set1_verify_cert_store.pod rename to doc/man3/SSL_CTX_set1_verify_cert_store.pod diff --git a/doc/ssl/SSL_CTX_set_alpn_select_cb.pod b/doc/man3/SSL_CTX_set_alpn_select_cb.pod similarity index 100% rename from doc/ssl/SSL_CTX_set_alpn_select_cb.pod rename to doc/man3/SSL_CTX_set_alpn_select_cb.pod diff --git a/doc/ssl/SSL_CTX_set_cert_cb.pod b/doc/man3/SSL_CTX_set_cert_cb.pod similarity index 92% rename from doc/ssl/SSL_CTX_set_cert_cb.pod rename to doc/man3/SSL_CTX_set_cert_cb.pod index eaa7a4e3..fbe4f2ac 100644 --- a/doc/ssl/SSL_CTX_set_cert_cb.pod +++ b/doc/man3/SSL_CTX_set_cert_cb.pod @@ -8,7 +8,8 @@ SSL_CTX_set_cert_cb, SSL_set_cert_cb - handle certificate callback function #include - void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cert_cb)(SSL *ssl, void *arg), void *arg); + void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cert_cb)(SSL *ssl, void *arg), + void *arg); void SSL_set_cert_cb(SSL *s, int (*cert_cb)(SSL *ssl, void *arg), void *arg); int (*cert_cb)(SSL *ssl, void *arg); @@ -58,16 +59,20 @@ Normal server sanity checks are performed on any certificates set by the callback. So if an EC chain is set for a curve the client does not support it will B be used. +=head1 RETURN VALUES + +SSL_CTX_set_cert_cb() and SSL_set_cert_cb() do not return values. + =head1 SEE ALSO -L, L, +L, L, L, L, L, L =head1 COPYRIGHT -Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2014-2018 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 diff --git a/doc/man3/SSL_CTX_set_cert_store.pod b/doc/man3/SSL_CTX_set_cert_store.pod new file mode 100644 index 00000000..f1a54a69 --- /dev/null +++ b/doc/man3/SSL_CTX_set_cert_store.pod @@ -0,0 +1,89 @@ +=pod + +=head1 NAME + +SSL_CTX_set_cert_store, SSL_CTX_set1_cert_store, SSL_CTX_get_cert_store - manipulate X509 certificate verification storage + +=head1 SYNOPSIS + + #include + + void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store); + void SSL_CTX_set1_cert_store(SSL_CTX *ctx, X509_STORE *store); + X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx); + +=head1 DESCRIPTION + +SSL_CTX_set_cert_store() sets/replaces the certificate verification storage +of B to/with B. If another X509_STORE object is currently +set in B, it will be X509_STORE_free()ed. + +SSL_CTX_set1_cert_store() sets/replaces the certificate verification storage +of B to/with B. The B's reference count is incremented. +If another X509_STORE object is currently set in B, it will be X509_STORE_free()ed. + +SSL_CTX_get_cert_store() returns a pointer to the current certificate +verification storage. + +=head1 NOTES + +In order to verify the certificates presented by the peer, trusted CA +certificates must be accessed. These CA certificates are made available +via lookup methods, handled inside the X509_STORE. From the X509_STORE +the X509_STORE_CTX used when verifying certificates is created. + +Typically the trusted certificate store is handled indirectly via using +L. +Using the SSL_CTX_set_cert_store() and SSL_CTX_get_cert_store() functions +it is possible to manipulate the X509_STORE object beyond the +L +call. + +Currently no detailed documentation on how to use the X509_STORE +object is available. Not all members of the X509_STORE are used when +the verification takes place. So will e.g. the verify_callback() be +overridden with the verify_callback() set via the +L family of functions. +This document must therefore be updated when documentation about the +X509_STORE object and its handling becomes available. + +SSL_CTX_set_cert_store() does not increment the B's reference +count, so it should not be used to assign an X509_STORE that is owned +by another SSL_CTX. + +To share X509_STOREs between two SSL_CTXs, use SSL_CTX_get_cert_store() +to get the X509_STORE from the first SSL_CTX, and then use +SSL_CTX_set1_cert_store() to assign to the second SSL_CTX and +increment the reference count of the X509_STORE. + +=head1 RESTRICTIONS + +The X509_STORE structure used by an SSL_CTX is used for verifying peer +certificates and building certificate chains, it is also shared by +every child SSL structure. Applications wanting finer control can use +functions such as SSL_CTX_set1_verify_cert_store() instead. + +=head1 RETURN VALUES + +SSL_CTX_set_cert_store() does not return diagnostic output. + +SSL_CTX_set1_cert_store() does not return diagnostic output. + +SSL_CTX_get_cert_store() returns the current setting. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +Copyright 2001-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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_set_cert_verify_callback.pod b/doc/man3/SSL_CTX_set_cert_verify_callback.pod similarity index 87% rename from doc/ssl/SSL_CTX_set_cert_verify_callback.pod rename to doc/man3/SSL_CTX_set_cert_verify_callback.pod index af303f25..6a9c2389 100644 --- a/doc/ssl/SSL_CTX_set_cert_verify_callback.pod +++ b/doc/man3/SSL_CTX_set_cert_verify_callback.pod @@ -8,7 +8,9 @@ SSL_CTX_set_cert_verify_callback - set peer certificate verification procedure #include - void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx, int (*callback)(X509_STORE_CTX *, void *), void *arg); + void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx, + int (*callback)(X509_STORE_CTX *, void *), + void *arg); =head1 DESCRIPTION @@ -40,6 +42,10 @@ about the detailed result of the verification procedure! Within I, I has access to the I function set using L. +=head1 RETURN VALUES + +SSL_CTX_set_cert_verify_callback() does not return a value. + =head1 WARNINGS Do not mix the verification callback described in this function with the @@ -58,13 +64,13 @@ SSL_CTX_set_cert_verify_callback() does not provide diagnostic information. =head1 SEE ALSO -L, L, +L, L, L, L =head1 COPYRIGHT -Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2001-2018 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 diff --git a/doc/ssl/SSL_CTX_set_cipher_list.pod b/doc/man3/SSL_CTX_set_cipher_list.pod similarity index 98% rename from doc/ssl/SSL_CTX_set_cipher_list.pod rename to doc/man3/SSL_CTX_set_cipher_list.pod index 4e66917b..714bb3a8 100644 --- a/doc/ssl/SSL_CTX_set_cipher_list.pod +++ b/doc/man3/SSL_CTX_set_cipher_list.pod @@ -57,7 +57,7 @@ could be selected and 0 on complete failure. =head1 SEE ALSO -L, L, +L, L, L, L, L diff --git a/doc/ssl/SSL_CTX_set_client_CA_list.pod b/doc/man3/SSL_CTX_set_client_CA_list.pod similarity index 97% rename from doc/ssl/SSL_CTX_set_client_CA_list.pod rename to doc/man3/SSL_CTX_set_client_CA_list.pod index 0252e7b5..76fd65e6 100644 --- a/doc/ssl/SSL_CTX_set_client_CA_list.pod +++ b/doc/man3/SSL_CTX_set_client_CA_list.pod @@ -82,11 +82,11 @@ The operation succeeded. Scan all certificates in B and list them as acceptable CAs: - SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile)); + SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile)); =head1 SEE ALSO -L, +L, L, L, L diff --git a/doc/ssl/SSL_CTX_set_client_cert_cb.pod b/doc/man3/SSL_CTX_set_client_cert_cb.pod similarity index 89% rename from doc/ssl/SSL_CTX_set_client_cert_cb.pod rename to doc/man3/SSL_CTX_set_client_cert_cb.pod index aed7d4f0..0dd147f9 100644 --- a/doc/ssl/SSL_CTX_set_client_cert_cb.pod +++ b/doc/man3/SSL_CTX_set_client_cert_cb.pod @@ -8,8 +8,11 @@ SSL_CTX_set_client_cert_cb, SSL_CTX_get_client_cert_cb - handle client certifica #include - void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, int (*client_cert_cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey)); - int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL *ssl, X509 **x509, EVP_PKEY **pkey); + void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, + int (*client_cert_cb)(SSL *ssl, X509 **x509, + EVP_PKEY **pkey)); + int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL *ssl, X509 **x509, + EVP_PKEY **pkey); int (*client_cert_cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey); =head1 DESCRIPTION @@ -60,6 +63,11 @@ object. It will not be reset by calling L. If the callback returns no certificate, the OpenSSL library will not send a certificate. +=head1 RETURN VALUES + +SSL_CTX_get_client_cert_cb() returns function pointer of client_cert_cb() or +NULL if the callback is not set. + =head1 BUGS The client_cert_cb() cannot return a complete certificate chain, it can @@ -86,14 +94,14 @@ and create a new one to return to the previous state. =head1 SEE ALSO -L, L, +L, L, L, L, L, L =head1 COPYRIGHT -Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2002-2018 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 diff --git a/doc/man3/SSL_CTX_set_client_hello_cb.pod b/doc/man3/SSL_CTX_set_client_hello_cb.pod new file mode 100644 index 00000000..6824b5b8 --- /dev/null +++ b/doc/man3/SSL_CTX_set_client_hello_cb.pod @@ -0,0 +1,130 @@ +=pod + +=head1 NAME + +SSL_CTX_set_client_hello_cb, SSL_client_hello_cb_fn, SSL_client_hello_isv2, SSL_client_hello_get0_legacy_version, SSL_client_hello_get0_random, SSL_client_hello_get0_session_id, SSL_client_hello_get0_ciphers, SSL_client_hello_get0_compression_methods, SSL_client_hello_get1_extensions_present, SSL_client_hello_get0_ext - callback functions for early server-side ClientHello processing + +=head1 SYNOPSIS + + typedef int (*SSL_client_hello_cb_fn)(SSL *s, int *al, void *arg); + void SSL_CTX_set_client_hello_cb(SSL_CTX *c, SSL_client_hello_cb_fn *f, + void *arg); + int SSL_client_hello_isv2(SSL *s); + unsigned int SSL_client_hello_get0_legacy_version(SSL *s); + size_t SSL_client_hello_get0_random(SSL *s, const unsigned char **out); + size_t SSL_client_hello_get0_session_id(SSL *s, const unsigned char **out); + size_t SSL_client_hello_get0_ciphers(SSL *s, const unsigned char **out); + size_t SSL_client_hello_get0_compression_methods(SSL *s, + const unsigned char **out); + int SSL_client_hello_get1_extensions_present(SSL *s, int **out, + size_t *outlen); + int SSL_client_hello_get0_ext(SSL *s, int type, const unsigned char **out, + size_t *outlen); + +=head1 DESCRIPTION + +SSL_CTX_set_client_hello_cb() sets the callback function, which is automatically +called during the early stages of ClientHello processing on the server. +The argument supplied when setting the callback is passed back to the +callback at runtime. A callback that returns failure (0) will cause the +connection to terminate, and callbacks returning failure should indicate +what alert value is to be sent in the B parameter. A callback may +also return a negative value to suspend the handshake, and the handshake +function will return immediately. L will return +SSL_ERROR_WANT_CLIENT_HELLO_CB to indicate that the handshake was suspended. +It is the job of the ClientHello callback to store information about the state +of the last call if needed to continue. On the next call into the handshake +function, the ClientHello callback will be called again, and, if it returns +success, normal handshake processing will continue from that point. + +SSL_client_hello_isv2() indicates whether the ClientHello was carried in a +SSLv2 record and is in the SSLv2 format. The SSLv2 format has substantial +differences from the normal SSLv3 format, including using three bytes per +cipher suite, and not allowing extensions. Additionally, the SSLv2 format +'challenge' field is exposed via SSL_client_hello_get0_random(), padded to +SSL3_RANDOM_SIZE bytes with zeros if needed. For SSLv2 format ClientHellos, +SSL_client_hello_get0_compression_methods() returns a dummy list that only includes +the null compression method, since the SSLv2 format does not include a +mechanism by which to negotiate compression. + +SSL_client_hello_get0_random(), SSL_client_hello_get0_session_id(), +SSL_client_hello_get0_ciphers(), and +SSL_client_hello_get0_compression_methods() provide access to the corresponding +ClientHello fields, returning the field length and optionally setting an out +pointer to the octets of that field. + +Similarly, SSL_client_hello_get0_ext() provides access to individual extensions +from the ClientHello on a per-extension basis. For the provided wire +protocol extension type value, the extension value and length are returned +in the output parameters (if present). + +SSL_client_hello_get1_extensions_present() can be used prior to +SSL_client_hello_get0_ext(), to determine which extensions are present in the +ClientHello before querying for them. The B and B parameters are +both required, and on success the caller must release the storage allocated for +B<*out> using OPENSSL_free(). The contents of B<*out> is an array of integers +holding the numerical value of the TLS extension types in the order they appear +in the ClientHello. B<*outlen> contains the number of elements in the array. + +=head1 NOTES + +The ClientHello callback provides a vast window of possibilities for application +code to affect the TLS handshake. A primary use of the callback is to +allow the server to examine the server name indication extension provided +by the client in order to select an appropriate certificate to present, +and make other configuration adjustments relevant to that server name +and its configuration. Such configuration changes can include swapping out +the associated SSL_CTX pointer, modifying the server's list of permitted TLS +versions, changing the server's cipher list in response to the client's +cipher list, etc. + +It is also recommended that applications utilize a ClientHello callback and +not use a servername callback, in order to avoid unexpected behavior that +occurs due to the relative order of processing between things like session +resumption and the historical servername callback. + +The SSL_client_hello_* family of functions may only be called from code executing +within a ClientHello callback. + +=head1 RETURN VALUES + +The application's supplied ClientHello callback returns +SSL_CLIENT_HELLO_SUCCESS on success, SSL_CLIENT_HELLO_ERROR on failure, and +SSL_CLIENT_HELLO_RETRY to suspend processing. + +SSL_client_hello_isv2() returns 1 for SSLv2-format ClientHellos and 0 otherwise. + +SSL_client_hello_get0_random(), SSL_client_hello_get0_session_id(), +SSL_client_hello_get0_ciphers(), and +SSL_client_hello_get0_compression_methods() return the length of the +corresponding ClientHello fields. If zero is returned, the output pointer +should not be assumed to be valid. + +SSL_client_hello_get0_ext() returns 1 if the extension of type 'type' is present, and +0 otherwise. + +SSL_client_hello_get1_extensions_present() returns 1 on success and 0 on failure. + +=head1 SEE ALSO + +L, L, +L + +=head1 HISTORY + +The SSL ClientHello callback, SSL_client_hello_isv2(), +SSL_client_hello_get0_random(), SSL_client_hello_get0_session_id(), +SSL_client_hello_get0_ciphers(), SSL_client_hello_get0_compression_methods(), +SSL_client_hello_get0_ext(), and SSL_client_hello_get1_extensions_present() +were added in OpenSSL 1.1.1. + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_set_ct_validation_callback.pod b/doc/man3/SSL_CTX_set_ct_validation_callback.pod similarity index 99% rename from doc/ssl/SSL_CTX_set_ct_validation_callback.pod rename to doc/man3/SSL_CTX_set_ct_validation_callback.pod index afa45dc9..a0a8028f 100644 --- a/doc/ssl/SSL_CTX_set_ct_validation_callback.pod +++ b/doc/man3/SSL_CTX_set_ct_validation_callback.pod @@ -78,7 +78,7 @@ If no callback is set, SCTs will not be requested and Certificate Transparency validation will not occur. No callback will be invoked when the peer presents no certificate, e.g. by -employing an anonymous (aNULL) ciphersuite. +employing an anonymous (aNULL) cipher suite. In that case the handshake continues as it would had no callback been requested. Callbacks are also not invoked when the peer certificate chain is invalid or diff --git a/doc/ssl/SSL_CTX_set_ctlog_list_file.pod b/doc/man3/SSL_CTX_set_ctlog_list_file.pod similarity index 99% rename from doc/ssl/SSL_CTX_set_ctlog_list_file.pod rename to doc/man3/SSL_CTX_set_ctlog_list_file.pod index 4a2fa946..275831ab 100644 --- a/doc/ssl/SSL_CTX_set_ctlog_list_file.pod +++ b/doc/man3/SSL_CTX_set_ctlog_list_file.pod @@ -37,7 +37,7 @@ the case of an error, the log list may have been partially loaded. =head1 SEE ALSO -L, +L, L, L diff --git a/doc/ssl/SSL_CTX_set_default_passwd_cb.pod b/doc/man3/SSL_CTX_set_default_passwd_cb.pod similarity index 97% rename from doc/ssl/SSL_CTX_set_default_passwd_cb.pod rename to doc/man3/SSL_CTX_set_default_passwd_cb.pod index 21969061..c7bdc9b9 100644 --- a/doc/ssl/SSL_CTX_set_default_passwd_cb.pod +++ b/doc/man3/SSL_CTX_set_default_passwd_cb.pod @@ -85,9 +85,9 @@ truncated. int my_cb(char *buf, int size, int rwflag, void *u) { - strncpy(buf, (char *)u, size); - buf[size - 1] = '\0'; - return strlen(buf); + strncpy(buf, (char *)u, size); + buf[size - 1] = '\0'; + return strlen(buf); } =head1 HISTORY @@ -98,7 +98,7 @@ first added to OpenSSL 1.1.0 =head1 SEE ALSO -L, +L, L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_CTX_set_ex_data.pod b/doc/man3/SSL_CTX_set_ex_data.pod similarity index 100% rename from doc/ssl/SSL_CTX_set_ex_data.pod rename to doc/man3/SSL_CTX_set_ex_data.pod diff --git a/doc/ssl/SSL_CTX_set_generate_session_id.pod b/doc/man3/SSL_CTX_set_generate_session_id.pod similarity index 84% rename from doc/ssl/SSL_CTX_set_generate_session_id.pod rename to doc/man3/SSL_CTX_set_generate_session_id.pod index 1b1171fe..2bee351a 100644 --- a/doc/ssl/SSL_CTX_set_generate_session_id.pod +++ b/doc/man3/SSL_CTX_set_generate_session_id.pod @@ -91,28 +91,27 @@ server id given, and will fill the rest with pseudo random bytes: #define MAX_SESSION_ID_ATTEMPTS 10 static int generate_session_id(const SSL *ssl, unsigned char *id, - unsigned int *id_len) + unsigned int *id_len) { - unsigned int count = 0; - do { - RAND_pseudo_bytes(id, *id_len); - /* - * 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; - } + unsigned int count = 0; + + do { + RAND_pseudo_bytes(id, *id_len); + /* + * 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; + } =head1 RETURN VALUES diff --git a/doc/ssl/SSL_CTX_set_info_callback.pod b/doc/man3/SSL_CTX_set_info_callback.pod similarity index 76% rename from doc/ssl/SSL_CTX_set_info_callback.pod rename to doc/man3/SSL_CTX_set_info_callback.pod index f36f217e..f4d91283 100644 --- a/doc/ssl/SSL_CTX_set_info_callback.pod +++ b/doc/man3/SSL_CTX_set_info_callback.pod @@ -110,44 +110,38 @@ The following example callback function prints state strings, information about alerts being handled and error messages to the B BIO. void apps_ssl_info_callback(SSL *s, int where, int ret) - { - const char *str; - int w; + { + const char *str; + int w = where & ~SSL_ST_MASK; - w = where & ~SSL_ST_MASK; + if (w & SSL_ST_CONNECT) + str = "SSL_connect"; + else if (w & SSL_ST_ACCEPT) + str = "SSL_accept"; + else + str = "undefined"; - if (w & SSL_ST_CONNECT) str = "SSL_connect"; - else if (w & SSL_ST_ACCEPT) str = "SSL_accept"; - else str = "undefined"; - - if (where & SSL_CB_LOOP) - { - BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s)); - } - else if (where & SSL_CB_ALERT) - { - str = (where & SSL_CB_READ) ? "read" : "write"; - BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n", - str, - SSL_alert_type_string_long(ret), - SSL_alert_desc_string_long(ret)); - } - else if (where & SSL_CB_EXIT) - { - if (ret == 0) - BIO_printf(bio_err, "%s:failed in %s\n", - str, SSL_state_string_long(s)); - else if (ret < 0) - { - BIO_printf(bio_err, "%s:error in %s\n", - str, SSL_state_string_long(s)); - } - } - } + if (where & SSL_CB_LOOP) { + BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s)); + } else if (where & SSL_CB_ALERT) { + str = (where & SSL_CB_READ) ? "read" : "write"; + BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n", str, + SSL_alert_type_string_long(ret), + SSL_alert_desc_string_long(ret)); + } else if (where & SSL_CB_EXIT) { + if (ret == 0) { + BIO_printf(bio_err, "%s:failed in %s\n", + str, SSL_state_string_long(s)); + } else if (ret < 0) { + BIO_printf(bio_err, "%s:error in %s\n", + str, SSL_state_string_long(s)); + } + } + } =head1 SEE ALSO -L, L, +L, L, L =head1 COPYRIGHT diff --git a/doc/man3/SSL_CTX_set_keylog_callback.pod b/doc/man3/SSL_CTX_set_keylog_callback.pod new file mode 100644 index 00000000..9e0127f9 --- /dev/null +++ b/doc/man3/SSL_CTX_set_keylog_callback.pod @@ -0,0 +1,52 @@ +=pod + +=head1 NAME + +SSL_CTX_set_keylog_callback, SSL_CTX_get_keylog_callback, +SSL_CTX_keylog_cb_func - logging TLS key material + +=head1 SYNOPSIS + + #include + + typedef void (*SSL_CTX_keylog_cb_func)(const SSL *ssl, const char *line); + + void SSL_CTX_set_keylog_callback(SSL_CTX *ctx, SSL_CTX_keylog_cb_func cb); + SSL_CTX_keylog_cb_func SSL_CTX_get_keylog_callback(const SSL_CTX *ctx); + +=head1 DESCRIPTION + +SSL_CTX_set_keylog_callback() sets the TLS key logging callback. This callback +is called whenever TLS key material is generated or received, in order to allow +applications to store this keying material for debugging purposes. + +SSL_CTX_get_keylog_callback() retrieves the previously set TLS key logging +callback. If no callback has been set, this will return NULL. When there is no +key logging callback, or if SSL_CTX_set_keylog_callback is called with NULL as +the value of cb, no logging of key material will be done. + +The key logging callback is called with two items: the B object associated +with the connection, and B, a string containing the key material in the +format used by NSS for its B debugging output. To recreate that +file, the key logging callback should log B, followed by a newline. +B will always be a NULL-terminated string. + +=head1 RETURN VALUES + +SSL_CTX_get_keylog_callback() returns a pointer to B or +NULL if the callback is not set. + +=head1 SEE ALSO + +L + +=head1 COPYRIGHT + +Copyright 2016-2018 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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_set_max_cert_list.pod b/doc/man3/SSL_CTX_set_max_cert_list.pod similarity index 99% rename from doc/ssl/SSL_CTX_set_max_cert_list.pod rename to doc/man3/SSL_CTX_set_max_cert_list.pod index 482751e7..01936c58 100644 --- a/doc/ssl/SSL_CTX_set_max_cert_list.pod +++ b/doc/man3/SSL_CTX_set_max_cert_list.pod @@ -67,7 +67,7 @@ set value. =head1 SEE ALSO -L, L, +L, L, L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_CTX_set_min_proto_version.pod b/doc/man3/SSL_CTX_set_min_proto_version.pod similarity index 95% rename from doc/ssl/SSL_CTX_set_min_proto_version.pod rename to doc/man3/SSL_CTX_set_min_proto_version.pod index ff080e48..45866588 100644 --- a/doc/ssl/SSL_CTX_set_min_proto_version.pod +++ b/doc/man3/SSL_CTX_set_min_proto_version.pod @@ -39,8 +39,8 @@ Getters return 0 in case B or B have been configured to automatically use the lowest or highest version supported by the library. Currently supported versions are B, B, -B, B for TLS and B, -B for DTLS. +B, B, B for TLS and +B, B for DTLS. =head1 RETURN VALUES diff --git a/doc/man3/SSL_CTX_set_mode.pod b/doc/man3/SSL_CTX_set_mode.pod new file mode 100644 index 00000000..e83b5918 --- /dev/null +++ b/doc/man3/SSL_CTX_set_mode.pod @@ -0,0 +1,116 @@ +=pod + +=head1 NAME + +SSL_CTX_set_mode, SSL_set_mode, SSL_CTX_get_mode, SSL_get_mode - manipulate SSL engine mode + +=head1 SYNOPSIS + + #include + + long SSL_CTX_set_mode(SSL_CTX *ctx, long mode); + long SSL_set_mode(SSL *ssl, long mode); + + long SSL_CTX_get_mode(SSL_CTX *ctx); + long SSL_get_mode(SSL *ssl); + +=head1 DESCRIPTION + +SSL_CTX_set_mode() adds the mode set via bitmask in B to B. +Options already set before are not cleared. + +SSL_set_mode() adds the mode set via bitmask in B to B. +Options already set before are not cleared. + +SSL_CTX_get_mode() returns the mode set for B. + +SSL_get_mode() returns the mode set for B. + +=head1 NOTES + +The following mode changes are available: + +=over 4 + +=item SSL_MODE_ENABLE_PARTIAL_WRITE + +Allow SSL_write_ex(..., n, &r) to return with 0 < r < n (i.e. report success +when just a single record has been written). This works in a similar way for +SSL_write(). When not set (the default), SSL_write_ex() or SSL_write() will only +report success once the complete chunk was written. Once SSL_write_ex() or +SSL_write() returns successful, B bytes have been written and the next call +to SSL_write_ex() or SSL_write() must only send the n-r bytes left, imitating +the behaviour of write(). + +=item SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER + +Make it possible to retry SSL_write_ex() or SSL_write() with changed buffer +location (the buffer contents must stay the same). This is not the default to +avoid the misconception that non-blocking SSL_write() behaves like +non-blocking write(). + +=item SSL_MODE_AUTO_RETRY + +Never bother the application with retries if the transport is blocking. +If a renegotiation take place during normal operation, a +L, L, L or L would +return with a failure and indicate the need to retry with SSL_ERROR_WANT_READ. +In a non-blocking environment applications must be prepared to handle +incomplete read/write operations. +In a blocking environment, applications are not always prepared to +deal with read/write operations returning without success report. The +flag SSL_MODE_AUTO_RETRY will cause read/write operations to only +return after the handshake and successful completion. + +=item SSL_MODE_RELEASE_BUFFERS + +When we no longer need a read buffer or a write buffer for a given SSL, +then release the memory we were using to hold it. +Using this flag can +save around 34k per idle SSL connection. +This flag has no effect on SSL v2 connections, or on DTLS connections. + +=item SSL_MODE_SEND_FALLBACK_SCSV + +Send TLS_FALLBACK_SCSV in the ClientHello. +To be set only by applications that reconnect with a downgraded protocol +version; see draft-ietf-tls-downgrade-scsv-00 for details. + +DO NOT ENABLE THIS if your application attempts a normal handshake. +Only use this in explicit fallback retries, following the guidance +in draft-ietf-tls-downgrade-scsv-00. + +=item SSL_MODE_ASYNC + +Enable asynchronous processing. TLS I/O operations may indicate a retry with +SSL_ERROR_WANT_ASYNC with this mode set if an asynchronous capable engine is +used to perform cryptographic operations. See L. + +=back + +=head1 RETURN VALUES + +SSL_CTX_set_mode() and SSL_set_mode() return the new mode bitmask +after adding B. + +SSL_CTX_get_mode() and SSL_get_mode() return the current bitmask. + +=head1 SEE ALSO + +L, L, L, L or +L, L + +=head1 HISTORY + +SSL_MODE_ASYNC was first added to OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2001-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 +L. + +=cut diff --git a/doc/man3/SSL_CTX_set_msg_callback.pod b/doc/man3/SSL_CTX_set_msg_callback.pod new file mode 100644 index 00000000..bbc78b64 --- /dev/null +++ b/doc/man3/SSL_CTX_set_msg_callback.pod @@ -0,0 +1,143 @@ +=pod + +=head1 NAME + +SSL_CTX_set_msg_callback, +SSL_CTX_set_msg_callback_arg, +SSL_set_msg_callback, +SSL_set_msg_callback_arg +- install callback for observing protocol messages + +=head1 SYNOPSIS + + #include + + 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)); + void SSL_CTX_set_msg_callback_arg(SSL_CTX *ctx, void *arg); + + 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)); + void SSL_set_msg_callback_arg(SSL *ssl, void *arg); + +=head1 DESCRIPTION + +SSL_CTX_set_msg_callback() or SSL_set_msg_callback() can be used to +define a message callback function I for observing all SSL/TLS +protocol messages (such as handshake messages) that are received or +sent, as well as other events that occur during processing. +SSL_CTX_set_msg_callback_arg() and SSL_set_msg_callback_arg() +can be used to set argument I to the callback function, which is +available for arbitrary application use. + +SSL_CTX_set_msg_callback() and SSL_CTX_set_msg_callback_arg() specify +default settings that will be copied to new B objects by +L. SSL_set_msg_callback() and +SSL_set_msg_callback_arg() modify the actual settings of an B +object. Using a B pointer for I disables the message callback. + +When I is called by the SSL/TLS library the function arguments have the +following meaning: + +=over 4 + +=item I + +This flag is B<0> when a protocol message has been received and B<1> +when a protocol message has been sent. + +=item I + +The protocol version according to which the protocol message is +interpreted by the library such as B, B etc. +This is set to 0 for the SSL3_RT_HEADER pseudo content type (see NOTES below). + +=item I + +This is one of the content type values defined in the protocol specification +(B, B, B; but never +B because the callback will only be called for protocol +messages). Alternatively it may be a "pseudo" content type. These pseudo +content types are used to signal some other event in the processing of data (see +NOTES below). + +=item I, I + +I points to a buffer containing the protocol message or other data (in the +case of pseudo content types), which consists of I bytes. The buffer is no +longer valid after the callback function has returned. + +=item I + +The B object that received or sent the message. + +=item I + +The user-defined argument optionally defined by +SSL_CTX_set_msg_callback_arg() or SSL_set_msg_callback_arg(). + +=back + +=head1 NOTES + +Protocol messages are passed to the callback function after decryption +and fragment collection where applicable. (Thus record boundaries are +not visible.) + +If processing a received protocol message results in an error, +the callback function may not be called. For example, the callback +function will never see messages that are considered too large to be +processed. + +Due to automatic protocol version negotiation, I is not +necessarily the protocol version used by the sender of the message: If +a TLS 1.0 ClientHello message is received by an SSL 3.0-only server, +I will be B. + +Pseudo content type values may be sent at various points during the processing +of data. The following pseudo content types are currently defined: + +=over 4 + +=item B + +Used when a record is sent or received. The B contains the record header +bytes only. + +=item B + +Used when an encrypted TLSv1.3 record is sent or received. In encrypted TLSv1.3 +records the content type in the record header is always +SSL3_RT_APPLICATION_DATA. The real content type for the record is contained in +an "inner" content type. B contains the encoded "inner" content type byte. + +=back + +=head1 RETURN VALUES + +SSL_CTX_set_msg_callback(), SSL_CTX_set_msg_callback_arg(), SSL_set_msg_callback() +and SSL_set_msg_callback_arg() do not return values. + +=head1 SEE ALSO + +L, L + +=head1 HISTORY + +The pseudo content type B was added in OpenSSL +1.1.1. + +=head1 COPYRIGHT + +Copyright 2001-2018 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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_set_options.pod b/doc/man3/SSL_CTX_set_options.pod similarity index 81% rename from doc/ssl/SSL_CTX_set_options.pod rename to doc/man3/SSL_CTX_set_options.pod index 241aeb3c..0d510773 100644 --- a/doc/ssl/SSL_CTX_set_options.pod +++ b/doc/man3/SSL_CTX_set_options.pod @@ -62,27 +62,11 @@ The following B options are available: =over 4 -=item SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG - -... - -=item SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER - -... - =item SSL_OP_SAFARI_ECDHE_ECDSA_BUG Don't prefer ECDHE-ECDSA ciphers when the client appears to be Safari on OS X. OS X 10.8..10.8.3 has broken support for ECDHE-ECDSA ciphers. -=item SSL_OP_SSLEAY_080_CLIENT_DH_BUG - -... - -=item SSL_OP_TLS_D5_BUG - -... - =item SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS Disables a countermeasure against a SSL 3.0/TLS 1.0 protocol @@ -98,7 +82,8 @@ implementations. =item SSL_OP_ALL -All of the above bug workarounds. +All of the above bug workarounds plus B as +mentioned below. =back @@ -122,22 +107,6 @@ only understands up to SSLv3. In this case the client must still use the same SSLv3.1=TLSv1 announcement. Some clients step down to SSLv3 with respect to the server's answer and violate the version rollback protection.) -=item SSL_OP_SINGLE_DH_USE - -Always create a new key when using temporary/ephemeral DH parameters -(see L). -This option must be used to prevent small subgroup attacks, when -the DH parameters were not generated using "strong" primes -(e.g. when using DSA-parameters, see L). -If "strong" primes were used, it is not strictly necessary to generate -a new DH key during each handshake but it is also recommended. -B should therefore be enabled whenever -temporary/ephemeral DH parameters are used. - -=item SSL_OP_EPHEMERAL_RSA - -This option is no longer implemented and is treated as no op. - =item SSL_OP_CIPHER_SERVER_PREFERENCE When choosing a cipher, use the server's preferences instead of the client @@ -145,19 +114,10 @@ preferences. When not set, the SSL server will always follow the clients preferences. When set, the SSL/TLS server will choose following its own preferences. -=item SSL_OP_PKCS1_CHECK_1 - -... - -=item SSL_OP_PKCS1_CHECK_2 - -... - - =item SSL_OP_NO_SSLv3, SSL_OP_NO_TLSv1, SSL_OP_NO_TLSv1_1, -SSL_OP_NO_TLSv1_2, SSL_OP_NO_DTLSv1, SSL_OP_NO_DTLSv1_2 +SSL_OP_NO_TLSv1_2, SSL_OP_NO_TLSv1_3, SSL_OP_NO_DTLSv1, SSL_OP_NO_DTLSv1_2 -These options turn off the SSLv3, TLSv1, TLSv1.1 or TLSv1.2 protocol +These options turn off the SSLv3, TLSv1, TLSv1.1, TLSv1.2 or TLSv1.3 protocol versions with TLS or the DTLSv1, DTLSv1.2 versions with DTLS, respectively. As of OpenSSL 1.1.0, these options are deprecated, use @@ -170,6 +130,19 @@ When performing renegotiation as a server, always start a new session (i.e., session resumption requests are only accepted in the initial handshake). This option is not needed for clients. +=item SSL_OP_NO_COMPRESSION + +Do not use compression even if it is supported. + +=item SSL_OP_NO_QUERY_MTU + +Do not query the MTU. Only affects DTLS connections. + +=item SSL_OP_COOKIE_EXCHANGE + +Turn on Cookie Exchange as described in RFC4347 Section 4.2.1. Only affects +DTLS connections. + =item SSL_OP_NO_TICKET Normally clients and servers will, where possible, transparently make use @@ -202,6 +175,64 @@ propose, and servers will not accept the extension. Disable all renegotiation in TLSv1.2 and earlier. Do not send HelloRequest messages, and ignore renegotiation requests via ClientHello. +=item SSL_OP_ALLOW_NO_DHE_KEX + +In TLSv1.3 allow a non-(ec)dhe based key exchange mode on resumption. This means +that there will be no forward secrecy for the resumed session. + +=item SSL_OP_PRIORITIZE_CHACHA + +When SSL_OP_CIPHER_SERVER_PREFERENCE is set, temporarily reprioritize +ChaCha20-Poly1305 ciphers to the top of the server cipher list if a +ChaCha20-Poly1305 cipher is at the top of the client cipher list. This helps +those clients (e.g. mobile) use ChaCha20-Poly1305 if that cipher is anywhere +in the server cipher list; but still allows other clients to use AES and other +ciphers. Requires B. + +=item SSL_OP_ENABLE_MIDDLEBOX_COMPAT + +If set then dummy Change Cipher Spec (CCS) messages are sent in TLSv1.3. This +has the effect of making TLSv1.3 look more like TLSv1.2 so that middleboxes that +do not understand TLSv1.3 will not drop the connection. Regardless of whether +this option is set or not CCS messages received from the peer will always be +ignored in TLSv1.3. This option is set by default. To switch it off use +SSL_clear_options(). A future version of OpenSSL may not set this by default. + +=back + +The following options no longer have any effect but their identifiers are +retained for compatibility purposes: + +=over 4 + +=item SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG + +=item SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER + +=item SSL_OP_SSLEAY_080_CLIENT_DH_BUG + +=item SSL_OP_TLS_D5_BUG + +=item SSL_OP_TLS_BLOCK_PADDING_BUG + +=item SSL_OP_MSIE_SSLV2_RSA_PADDING + +=item SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG + +=item SSL_OP_MICROSOFT_SESS_ID_BUG + +=item SSL_OP_NETSCAPE_CHALLENGE_BUG + +=item SSL_OP_PKCS1_CHECK_1 + +=item SSL_OP_PKCS1_CHECK_2 + +=item SSL_OP_SINGLE_DH_USE + +=item SSL_OP_SINGLE_ECDH_USE + +=item SSL_OP_EPHEMERAL_RSA + =back =head1 SECURE RENEGOTIATION @@ -283,7 +314,7 @@ secure renegotiation and 0 if it does not. =head1 SEE ALSO -L, L, L, +L, L, L, L, L, L @@ -293,7 +324,8 @@ L The attempt to always try to use secure renegotiation was added in Openssl 0.9.8m. -B was added in OpenSSL 1.1.0h. +B and B were added in +OpenSSL 1.1.1. =head1 COPYRIGHT diff --git a/doc/man3/SSL_CTX_set_psk_client_callback.pod b/doc/man3/SSL_CTX_set_psk_client_callback.pod new file mode 100644 index 00000000..e771072f --- /dev/null +++ b/doc/man3/SSL_CTX_set_psk_client_callback.pod @@ -0,0 +1,156 @@ +=pod + +=head1 NAME + +SSL_psk_client_cb_func, +SSL_psk_use_session_cb_func, +SSL_CTX_set_psk_client_callback, +SSL_set_psk_client_callback, +SSL_CTX_set_psk_use_session_callback, +SSL_set_psk_use_session_callback +- set PSK client callback + +=head1 SYNOPSIS + + #include + + typedef unsigned int (*SSL_psk_client_cb_func)(SSL *ssl, + const char *hint, + char *identity, + unsigned int max_identity_len, + unsigned char *psk, + unsigned int max_psk_len); + typedef int (*SSL_psk_use_session_cb_func)(SSL *ssl, const EVP_MD *md, + const unsigned char **id, + size_t *idlen, + SSL_SESSION **sess); + + void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, SSL_psk_client_cb_func cb); + void SSL_set_psk_client_callback(SSL *ssl, SSL_psk_client_cb_func cb); + + void SSL_CTX_set_psk_use_session_callback(SSL_CTX *ctx, + SSL_psk_use_session_cb_func cb); + void SSL_set_psk_use_session_callback(SSL *s, SSL_psk_use_session_cb_func cb); + +=head1 DESCRIPTION + +TLSv1.3 Pre-Shared Keys (PSKs) and PSKs for TLSv1.2 and below are not +compatible. + +A client application wishing to use PSK ciphersuites for TLSv1.2 and below must +provide a callback function. This function will be called when the client is +sending the ClientKeyExchange message to the server. + +The purpose of the callback function is to select the PSK identity and +the pre-shared key to use during the connection setup phase. + +The callback is set using functions SSL_CTX_set_psk_client_callback() +or SSL_set_psk_client_callback(). The callback function is given the +connection in parameter B, a B-terminated PSK identity hint +sent by the server in parameter B, a buffer B of +length B bytes where the resulting +B-terminated identity is to be stored, and a buffer B of +length B bytes where the resulting pre-shared key is to +be stored. + +A client application wishing to use TLSv1.3 PSKs must set a different callback +using either SSL_CTX_set_psk_use_session_callback() or +SSL_set_psk_use_session_callback() as appropriate. + +The callback function is given a pointer to the SSL connection in B. + +The first time the callback is called for a connection the B parameter is +NULL. In some circumstances the callback will be called a second time. In that +case the server will have specified a ciphersuite to use already and the PSK +must be compatible with the digest for that ciphersuite. The digest will be +given in B. The PSK returned by the callback is allowed to be different +between the first and second time it is called. + +On successful completion the callback must store a pointer to an identifier for +the PSK in B<*id>. The identifier length in bytes should be stored in B<*idlen>. +The memory pointed to by B<*id> remains owned by the application and should +be freed by it as required at any point after the handshake is complete. + +Additionally the callback should store a pointer to an SSL_SESSION object in +B<*sess>. This is used as the basis for the PSK, and should, at a minimum, have +the following fields set: + +=over 4 + +=item The master key + +This can be set via a call to L. + +=item A ciphersuite + +Only the handshake digest associated with the ciphersuite is relevant for the +PSK (the server may go on to negotiate any ciphersuite which is compatible with +the digest). The application can use any TLSv1.3 ciphersuite. If B is +not NULL the handshake digest for the ciphersuite should be the same. +The ciphersuite can be set via a call to . The +handshake digest of an SSL_CIPHER object can be checked using +. + +=item The protocol version + +This can be set via a call to L and should +be TLS1_3_VERSION. + +=back + +Additionally the maximum early data value should be set via a call to +L if the PSK will be used for sending early +data. + +Alternatively an SSL_SESSION created from a previous non-PSK handshake may also +be used as the basis for a PSK. + +Ownership of the SSL_SESSION object is passed to the OpenSSL library and so it +should not be freed by the application. + +It is also possible for the callback to succeed but not supply a PSK. In this +case no PSK will be sent to the server but the handshake will continue. To do +this the callback should return successfully and ensure that B<*sess> is +NULL. The contents of B<*id> and B<*idlen> will be ignored. + +=head1 NOTES + +Note that parameter B given to the callback may be B. + +A connection established via a TLSv1.3 PSK will appear as if session resumption +has occurred so that L will return true. + +=head1 RETURN VALUES + +Return values from the B callback are interpreted as +follows: + +On success (callback found a PSK identity and a pre-shared key to use) +the length (> 0) of B in bytes is returned. + +Otherwise or on errors the callback should return 0. In this case +the connection setup fails. + +The SSL_psk_use_session_cb_func callback should return 1 on success or 0 on +failure. In the event of failure the connection setup fails. + +=head1 SEE ALSO + +L, +L + +=head1 HISTORY + +SSL_CTX_set_psk_use_session_callback() and SSL_set_psk_use_session_callback() +were added in OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2006-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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_set_quiet_shutdown.pod b/doc/man3/SSL_CTX_set_quiet_shutdown.pod similarity index 98% rename from doc/ssl/SSL_CTX_set_quiet_shutdown.pod rename to doc/man3/SSL_CTX_set_quiet_shutdown.pod index d39d747c..99922eb5 100644 --- a/doc/ssl/SSL_CTX_set_quiet_shutdown.pod +++ b/doc/man3/SSL_CTX_set_quiet_shutdown.pod @@ -56,7 +56,7 @@ setting. =head1 SEE ALSO -L, L, +L, L, L, L, L, L diff --git a/doc/ssl/SSL_CTX_set_read_ahead.pod b/doc/man3/SSL_CTX_set_read_ahead.pod similarity index 98% rename from doc/ssl/SSL_CTX_set_read_ahead.pod rename to doc/man3/SSL_CTX_set_read_ahead.pod index bea83900..3a96ce3c 100644 --- a/doc/ssl/SSL_CTX_set_read_ahead.pod +++ b/doc/man3/SSL_CTX_set_read_ahead.pod @@ -46,7 +46,7 @@ and non zero otherwise. =head1 SEE ALSO -L, L +L, L =head1 COPYRIGHT diff --git a/doc/man3/SSL_CTX_set_record_padding_callback.pod b/doc/man3/SSL_CTX_set_record_padding_callback.pod new file mode 100644 index 00000000..d0b2e30f --- /dev/null +++ b/doc/man3/SSL_CTX_set_record_padding_callback.pod @@ -0,0 +1,96 @@ +=pod + +=head1 NAME + +SSL_CTX_set_record_padding_callback, +SSL_set_record_padding_callback, +SSL_CTX_set_record_padding_callback_arg, +SSL_set_record_padding_callback_arg, +SSL_CTX_get_record_padding_callback_arg, +SSL_get_record_padding_callback_arg, +SSL_CTX_set_block_padding, +SSL_set_block_padding - install callback to specify TLS 1.3 record padding + +=head1 SYNOPSIS + + #include + + void SSL_CTX_set_record_padding_callback(SSL_CTX *ctx, size_t (*cb)(SSL *s, int type, size_t len, void *arg)); + void SSL_set_record_padding_callback(SSL *ssl, size_t (*cb)(SSL *s, int type, size_t len, void *arg)); + + void SSL_CTX_set_record_padding_callback_arg(SSL_CTX *ctx, void *arg); + void *SSL_CTX_get_record_padding_callback_arg(SSL_CTX *ctx); + + void SSL_set_record_padding_callback_arg(SSL *ssl, void *arg); + void *SSL_get_record_padding_callback_arg(SSL *ssl); + + int SSL_CTX_set_block_padding(SSL_CTX *ctx, size_t block_size); + int SSL_set_block_padding(SSL *ssl, size_t block_size); + +=head1 DESCRIPTION + +SSL_CTX_set_record_padding_callback() or SSL_set_record_padding_callback() +can be used to assign a callback function I to specify the padding +for TLS 1.3 records. The value set in B is copied to a new SSL by SSL_new(). + +SSL_CTX_set_record_padding_callback_arg() and SSL_set_record_padding_callback_arg() +assign a value B that is passed to the callback when it is invoked. The value +set in B is copied to a new SSL by SSL_new(). + +SSL_CTX_get_record_padding_callback_arg() and SSL_get_record_padding_callback_arg() +retrieve the B value that is passed to the callback. + +SSL_CTX_set_block_padding() and SSL_set_block_padding() pads the record to a multiple +of the B. A B of 0 or 1 disables block padding. The limit of +B is SSL3_RT_MAX_PLAIN_LENGTH. + +The callback is invoked for every record before encryption. +The B parameter is the TLS record type that is being processed; may be +one of SSL3_RT_APPLICATION_DATA, SSL3_RT_HANDSHAKE, or SSL3_RT_ALERT. +The B parameter is the current plaintext length of the record before encryption. +The B parameter is the value set via SSL_CTX_set_record_padding_callback_arg() +or SSL_set_record_padding_callback_arg(). + +=head1 RETURN VALUES + +The SSL_CTX_get_record_padding_callback_arg() and SSL_get_record_padding_callback_arg() +functions return the B value assigned in the corresponding set functions. + +The SSL_CTX_set_block_padding() and SSL_set_block_padding() functions return 1 on success +or 0 if B is too large. + +The B returns the number of padding bytes to add to the record. A return of 0 +indicates no padding will be added. A return value that causes the record to +exceed the maximum record size (SSL3_RT_MAX_PLAIN_LENGTH) will pad out to the +maximum record size. + +=head1 NOTES + +The default behavior is to add no padding to the record. + +A user-supplied padding callback function will override the behavior set by +SSL_set_block_padding() or SSL_CTX_set_block_padding(). Setting the user-supplied +callback to NULL will restore the configured block padding behavior. + +These functions only apply to TLS 1.3 records being written. + +Padding bytes are not added in constant-time. + +=head1 SEE ALSO + +L, L + +=head1 HISTORY + +The record padding API was added for TLS 1.3 support in OpenSSL 1.1.1. + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/man3/SSL_CTX_set_security_level.pod b/doc/man3/SSL_CTX_set_security_level.pod new file mode 100644 index 00000000..8baaaffe --- /dev/null +++ b/doc/man3/SSL_CTX_set_security_level.pod @@ -0,0 +1,190 @@ +=pod + +=head1 NAME + +SSL_CTX_set_security_level, SSL_set_security_level, SSL_CTX_get_security_level, SSL_get_security_level, SSL_CTX_set_security_callback, SSL_set_security_callback, SSL_CTX_get_security_callback, SSL_get_security_callback, SSL_CTX_set0_security_ex_data, SSL_set0_security_ex_data, SSL_CTX_get0_security_ex_data, SSL_get0_security_ex_data - SSL/TLS security framework + +=head1 SYNOPSIS + + #include + + void SSL_CTX_set_security_level(SSL_CTX *ctx, int level); + void SSL_set_security_level(SSL *s, int level); + + int SSL_CTX_get_security_level(const SSL_CTX *ctx); + int SSL_get_security_level(const SSL *s); + + void SSL_CTX_set_security_callback(SSL_CTX *ctx, + int (*cb)(SSL *s, SSL_CTX *ctx, int op, + int bits, int nid, + void *other, void *ex)); + + void SSL_set_security_callback(SSL *s, int (*cb)(SSL *s, SSL_CTX *ctx, int op, + int bits, int nid, + void *other, void *ex)); + + int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx))(SSL *s, SSL_CTX *ctx, int op, + int bits, int nid, void *other, + void *ex); + int (*SSL_get_security_callback(const SSL *s))(SSL *s, SSL_CTX *ctx, int op, + int bits, int nid, void *other, + void *ex); + + void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex); + void SSL_set0_security_ex_data(SSL *s, void *ex); + + void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx); + void *SSL_get0_security_ex_data(const SSL *s); + +=head1 DESCRIPTION + +The functions SSL_CTX_set_security_level() and SSL_set_security_level() set +the security level to B. If not set the library default security level +is used. + +The functions SSL_CTX_get_security_level() and SSL_get_security_level() +retrieve the current security level. + +SSL_CTX_set_security_callback(), SSL_set_security_callback(), +SSL_CTX_get_security_callback() and SSL_get_security_callback() get or set +the security callback associated with B or B. If not set a default +security callback is used. The meaning of the parameters and the behaviour +of the default callbacks is described below. + +SSL_CTX_set0_security_ex_data(), SSL_set0_security_ex_data(), +SSL_CTX_get0_security_ex_data() and SSL_get0_security_ex_data() set the +extra data pointer passed to the B parameter of the callback. This +value is passed to the callback verbatim and can be set to any convenient +application specific value. + +=head1 DEFAULT CALLBACK BEHAVIOUR + +If an application doesn't set its own security callback the default +callback is used. It is intended to provide sane defaults. The meaning +of each level is described below. + +=over 4 + +=item B + +Everything is permitted. This retains compatibility with previous versions of +OpenSSL. + +=item B + +The security level corresponds to a minimum of 80 bits of security. Any +parameters offering below 80 bits of security are excluded. As a result RSA, +DSA and DH keys shorter than 1024 bits and ECC keys shorter than 160 bits +are prohibited. All export cipher suites are prohibited since they all offer +less than 80 bits of security. SSL version 2 is prohibited. Any cipher suite +using MD5 for the MAC is also prohibited. + +=item B + +Security level set to 112 bits of security. As a result RSA, DSA and DH keys +shorter than 2048 bits and ECC keys shorter than 224 bits are prohibited. +In addition to the level 1 exclusions any cipher suite using RC4 is also +prohibited. SSL version 3 is also not allowed. Compression is disabled. + +=item B + +Security level set to 128 bits of security. As a result RSA, DSA and DH keys +shorter than 3072 bits and ECC keys shorter than 256 bits are prohibited. +In addition to the level 2 exclusions cipher suites not offering forward +secrecy are prohibited. TLS versions below 1.1 are not permitted. Session +tickets are disabled. + +=item B + +Security level set to 192 bits of security. As a result RSA, DSA and +DH keys shorter than 7680 bits and ECC keys shorter than 384 bits are +prohibited. Cipher suites using SHA1 for the MAC are prohibited. TLS +versions below 1.2 are not permitted. + +=item B + +Security level set to 256 bits of security. As a result RSA, DSA and DH keys +shorter than 15360 bits and ECC keys shorter than 512 bits are prohibited. + +=back + +=head1 APPLICATION DEFINED SECURITY CALLBACKS + +I + +=head1 NOTES + +B at this time setting the security level higher than 1 for +general internet use is likely to cause B interoperability +issues and is not recommended. This is because the B algorithm +is very widely used in certificates and will be rejected at levels +higher than 1 because it only offers 80 bits of security. + +The default security level can be configured when OpenSSL is compiled by +setting B<-DOPENSSL_TLS_SECURITY_LEVEL=level>. If not set then 1 is used. + +The security framework disables or reject parameters inconsistent with the +set security level. In the past this was difficult as applications had to set +a number of distinct parameters (supported ciphers, supported curves supported +signature algorithms) to achieve this end and some cases (DH parameter size +for example) could not be checked at all. + +By setting an appropriate security level much of this complexity can be +avoided. + +The bits of security limits affect all relevant parameters including +cipher suite encryption algorithms, supported ECC curves, supported +signature algorithms, DH parameter sizes, certificate key sizes and +signature algorithms. This limit applies no matter what other custom +settings an application has set: so if the cipher suite is set to B +then only cipher suites consistent with the security level are permissible. + +See SP800-57 for how the security limits are related to individual +algorithms. + +Some security levels require large key sizes for non-ECC public key +algorithms which can severely degrade performance. For example 256 bits +of security requires the use of RSA keys of at least 15360 bits in size. + +Some restrictions can be gracefully handled: for example cipher suites +offering insufficient security are not sent by the client and will not +be selected by the server. Other restrictions such as the peer certificate +key size or the DH parameter size will abort the handshake with a fatal +alert. + +Attempts to set certificates or parameters with insufficient security are +also blocked. For example trying to set a certificate using a 512 bit RSA +key using SSL_CTX_use_certificate() at level 1. Applications which do not +check the return values for errors will misbehave: for example it might +appear that a certificate is not set at all because it had been rejected. + +=head1 RETURN VALUES + +SSL_CTX_set_security_level() and SSL_set_security_level() do not return values. + +SSL_CTX_get_security_level() and SSL_get_security_level() return a integer that +represents the security level with B or B, respectively. + +SSL_CTX_set_security_callback() and SSL_set_security_callback() do not return +values. + +SSL_CTX_get_security_callback() and SSL_get_security_callback() return the pointer +to the security callback or NULL if the callback is not set. + +SSL_CTX_get0_security_ex_data() and SSL_get0_security_ex_data() return the extra +data pointer or NULL if the ex data is not set. + +=head1 HISTORY + +These functions were first added to OpenSSL 1.1.0 + +=head1 COPYRIGHT + +Copyright 2014-2018 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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_set_session_cache_mode.pod b/doc/man3/SSL_CTX_set_session_cache_mode.pod similarity index 99% rename from doc/ssl/SSL_CTX_set_session_cache_mode.pod rename to doc/man3/SSL_CTX_set_session_cache_mode.pod index b2370768..18c9783f 100644 --- a/doc/ssl/SSL_CTX_set_session_cache_mode.pod +++ b/doc/man3/SSL_CTX_set_session_cache_mode.pod @@ -119,7 +119,7 @@ SSL_CTX_get_session_cache_mode() returns the currently set cache mode. =head1 SEE ALSO -L, L, +L, L, L, L, L, diff --git a/doc/ssl/SSL_CTX_set_session_id_context.pod b/doc/man3/SSL_CTX_set_session_id_context.pod similarity index 99% rename from doc/ssl/SSL_CTX_set_session_id_context.pod rename to doc/man3/SSL_CTX_set_session_id_context.pod index a873b038..d8323509 100644 --- a/doc/ssl/SSL_CTX_set_session_id_context.pod +++ b/doc/man3/SSL_CTX_set_session_id_context.pod @@ -78,7 +78,7 @@ The operation succeeded. =head1 SEE ALSO -L +L =head1 COPYRIGHT diff --git a/doc/man3/SSL_CTX_set_split_send_fragment.pod b/doc/man3/SSL_CTX_set_split_send_fragment.pod new file mode 100644 index 00000000..ef5e7cda --- /dev/null +++ b/doc/man3/SSL_CTX_set_split_send_fragment.pod @@ -0,0 +1,188 @@ +=pod + +=head1 NAME + +SSL_CTX_set_max_send_fragment, SSL_set_max_send_fragment, +SSL_CTX_set_split_send_fragment, SSL_set_split_send_fragment, +SSL_CTX_set_max_pipelines, SSL_set_max_pipelines, +SSL_CTX_set_default_read_buffer_len, SSL_set_default_read_buffer_len, +SSL_CTX_set_tlsext_max_fragment_length, +SSL_set_tlsext_max_fragment_length, +SSL_SESSION_get_max_fragment_length - Control fragment size settings and pipelining operations + +=head1 SYNOPSIS + + #include + + long SSL_CTX_set_max_send_fragment(SSL_CTX *ctx, long); + long SSL_set_max_send_fragment(SSL *ssl, long m); + + long SSL_CTX_set_max_pipelines(SSL_CTX *ctx, long m); + long SSL_set_max_pipelines(SSL_CTX *ssl, long m); + + long SSL_CTX_set_split_send_fragment(SSL_CTX *ctx, long m); + long SSL_set_split_send_fragment(SSL *ssl, long m); + + void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len); + void SSL_set_default_read_buffer_len(SSL *s, size_t len); + + int SSL_CTX_set_tlsext_max_fragment_length(SSL_CTX *ctx, uint8_t mode); + int SSL_set_tlsext_max_fragment_length(SSL *ssl, uint8_t mode); + uint8_t SSL_SESSION_get_max_fragment_length(SSL_SESSION *session); + +=head1 DESCRIPTION + +Some engines are able to process multiple simultaneous crypto operations. This +capability could be utilised to parallelise the processing of a single +connection. For example a single write can be split into multiple records and +each one encrypted independently and in parallel. Note: this will only work in +TLS1.1+. There is no support in SSLv3, TLSv1.0 or DTLS (any version). This +capability is known as "pipelining" within OpenSSL. + +In order to benefit from the pipelining capability. You need to have an engine +that provides ciphers that support this. The OpenSSL "dasync" engine provides +AES128-SHA based ciphers that have this capability. However these are for +development and test purposes only. + +SSL_CTX_set_max_send_fragment() and SSL_set_max_send_fragment() set the +B parameter for SSL_CTX and SSL objects respectively. This +value restricts the amount of plaintext bytes that will be sent in any one +SSL/TLS record. By default its value is SSL3_RT_MAX_PLAIN_LENGTH (16384). These +functions will only accept a value in the range 512 - SSL3_RT_MAX_PLAIN_LENGTH. + +SSL_CTX_set_max_pipelines() and SSL_set_max_pipelines() set the maximum number +of pipelines that will be used at any one time. This value applies to both +"read" pipelining and "write" pipelining. By default only one pipeline will be +used (i.e. normal non-parallel operation). The number of pipelines set must be +in the range 1 - SSL_MAX_PIPELINES (32). Setting this to a value > 1 will also +automatically turn on "read_ahead" (see L). This is +explained further below. OpenSSL will only every use more than one pipeline if +a cipher suite is negotiated that uses a pipeline capable cipher provided by an +engine. + +Pipelining operates slightly differently for reading encrypted data compared to +writing encrypted data. SSL_CTX_set_split_send_fragment() and +SSL_set_split_send_fragment() define how data is split up into pipelines when +writing encrypted data. The number of pipelines used will be determined by the +amount of data provided to the SSL_write_ex() or SSL_write() call divided by +B. + +For example if B is set to 2000 and B is 4 +then: + +SSL_write/SSL_write_ex called with 0-2000 bytes == 1 pipeline used + +SSL_write/SSL_write_ex called with 2001-4000 bytes == 2 pipelines used + +SSL_write/SSL_write_ex called with 4001-6000 bytes == 3 pipelines used + +SSL_write/SSL_write_ex called with 6001+ bytes == 4 pipelines used + +B must always be less than or equal to +B. By default it is set to be equal to B. +This will mean that the same number of records will always be created as would +have been created in the non-parallel case, although the data will be +apportioned differently. In the parallel case data will be spread equally +between the pipelines. + +Read pipelining is controlled in a slightly different way than with write +pipelining. While reading we are constrained by the number of records that the +peer (and the network) can provide to us in one go. The more records we can get +in one go the more opportunity we have to parallelise the processing. As noted +above when setting B to a value greater than one, B +is automatically set. The B parameter causes OpenSSL to attempt to +read as much data into the read buffer as the network can provide and will fit +into the buffer. Without this set data is read into the read buffer one record +at a time. The more data that can be read, the more opportunity there is for +parallelising the processing at the cost of increased memory overhead per +connection. Setting B can impact the behaviour of the SSL_pending() +function (see L). + +The SSL_CTX_set_default_read_buffer_len() and SSL_set_default_read_buffer_len() +functions control the size of the read buffer that will be used. The B +parameter sets the size of the buffer. The value will only be used if it is +greater than the default that would have been used anyway. The normal default +value depends on a number of factors but it will be at least +SSL3_RT_MAX_PLAIN_LENGTH + SSL3_RT_MAX_ENCRYPTED_OVERHEAD (16704) bytes. + +SSL_CTX_set_tlsext_max_fragment_length() sets the default maximum fragment +length negotiation mode via value B to B. +This setting affects only SSL instances created after this function is called. +It affects the client-side as only its side may initiate this extension use. + +SSL_set_tlsext_max_fragment_length() sets the maximum fragment length +negotiation mode via value B to B. +This setting will be used during a handshake when extensions are exchanged +between client and server. +So it only affects SSL sessions created after this function is called. +It affects the client-side as only its side may initiate this extension use. + +SSL_SESSION_get_max_fragment_length() gets the maximum fragment length +negotiated in B. + +=head1 RETURN VALUES + +All non-void functions return 1 on success and 0 on failure. + +=head1 NOTES + +The Maximum Fragment Length extension support is optional on the server side. +If the server does not support this extension then +SSL_SESSION_get_max_fragment_length() will return: +TLSEXT_max_fragment_length_DISABLED. + +The following modes are available: + +=over 4 + +=item TLSEXT_max_fragment_length_DISABLED + +Disables Maximum Fragment Length Negotiation (default). + +=item TLSEXT_max_fragment_length_512 + +Sets Maximum Fragment Length to 512 bytes. + +=item TLSEXT_max_fragment_length_1024 + +Sets Maximum Fragment Length to 1024. + +=item TLSEXT_max_fragment_length_2048 + +Sets Maximum Fragment Length to 2048. + +=item TLSEXT_max_fragment_length_4096 + +Sets Maximum Fragment Length to 4096. + +=back + +With the exception of SSL_CTX_set_default_read_buffer_len() +SSL_set_default_read_buffer_len(), SSL_CTX_set_tlsext_max_fragment_length(), +SSL_set_tlsext_max_fragment_length() and SSL_SESSION_get_max_fragment_length() +all these functions are implemented using macros. + +=head1 HISTORY + +The SSL_CTX_set_max_pipelines(), SSL_set_max_pipelines(), +SSL_CTX_set_split_send_fragment(), SSL_set_split_send_fragment(), +SSL_CTX_set_default_read_buffer_len() and SSL_set_default_read_buffer_len() +functions were added in OpenSSL 1.1.0. + +SSL_CTX_set_tlsext_max_fragment_length(), SSL_set_tlsext_max_fragment_length() +and SSL_SESSION_get_max_fragment_length() were added in OpenSSL 1.1.1. + +=head1 SEE ALSO + +L, L + +=head1 COPYRIGHT + +Copyright 2016-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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_set_ssl_version.pod b/doc/man3/SSL_CTX_set_ssl_version.pod similarity index 98% rename from doc/ssl/SSL_CTX_set_ssl_version.pod rename to doc/man3/SSL_CTX_set_ssl_version.pod index 22c0370b..901c057f 100644 --- a/doc/ssl/SSL_CTX_set_ssl_version.pod +++ b/doc/man3/SSL_CTX_set_ssl_version.pod @@ -55,7 +55,7 @@ The operation succeeded. =head1 SEE ALSO L, L, -L, L, +L, L, L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_CTX_set_timeout.pod b/doc/man3/SSL_CTX_set_timeout.pod similarity index 99% rename from doc/ssl/SSL_CTX_set_timeout.pod rename to doc/man3/SSL_CTX_set_timeout.pod index 470efdfc..c32585e4 100644 --- a/doc/ssl/SSL_CTX_set_timeout.pod +++ b/doc/man3/SSL_CTX_set_timeout.pod @@ -50,7 +50,7 @@ SSL_CTX_get_timeout() returns the currently set timeout value. =head1 SEE ALSO -L, +L, L, L, L, diff --git a/doc/man3/SSL_CTX_set_tlsext_servername_callback.pod b/doc/man3/SSL_CTX_set_tlsext_servername_callback.pod new file mode 100644 index 00000000..b1fb5ab7 --- /dev/null +++ b/doc/man3/SSL_CTX_set_tlsext_servername_callback.pod @@ -0,0 +1,77 @@ +=pod + +=head1 NAME + +SSL_CTX_set_tlsext_servername_callback, SSL_CTX_set_tlsext_servername_arg, +SSL_get_servername_type, SSL_get_servername, +SSL_set_tlsext_host_name - handle server name indication (SNI) + +=head1 SYNOPSIS + + #include + + long SSL_CTX_set_tlsext_servername_callback(SSL_CTX *ctx, + int (*cb)(SSL *, int *, void *)); + long SSL_CTX_set_tlsext_servername_arg(SSL_CTX *ctx, void *arg); + + const char *SSL_get_servername(const SSL *s, const int type); + int SSL_get_servername_type(const SSL *s); + + int SSL_set_tlsext_host_name(const SSL *s, const char *name); + +=head1 DESCRIPTION + +The functionality provided by the servername callback is superseded by the +ClientHello callback, which can be set using SSL_CTX_set_client_hello_cb(). +The servername callback is retained for historical compatibility. + +SSL_CTX_set_tlsext_servername_callback() sets the application callback B +used by a server to perform any actions or configuration required based on +the servername extension received in the incoming connection. When B +is NULL, SNI is not used. The B value is a pointer which is passed to +the application callback. + +SSL_CTX_set_tlsext_servername_arg() sets a context-specific argument to be +passed into the callback for this B. + +SSL_get_servername() returns a servername extension value of the specified +type if provided in the Client Hello or NULL. + +SSL_get_servername_type() returns the servername type or -1 if no servername +is present. Currently the only supported type (defined in RFC3546) is +B. + +SSL_set_tlsext_host_name() sets the server name indication ClientHello extension +to contain the value B. The type of server name indication extension is set +to B (defined in RFC3546). + +=head1 NOTES + +Several callbacks are executed during ClientHello processing, including +the ClientHello, ALPN, and servername callbacks. The ClientHello callback is +executed first, then the servername callback, followed by the ALPN callback. + +The SSL_set_tlsext_host_name() function should only be called on SSL objects +that will act as clients; otherwise the configured B will be ignored. + +=head1 RETURN VALUES + +SSL_CTX_set_tlsext_servername_callback() and +SSL_CTX_set_tlsext_servername_arg() both always return 1 indicating success. +SSL_set_tlsext_host_name() returns 1 on success, 0 in case of error. + +=head1 SEE ALSO + +L, L, +L, L + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_set_tlsext_status_cb.pod b/doc/man3/SSL_CTX_set_tlsext_status_cb.pod similarity index 95% rename from doc/ssl/SSL_CTX_set_tlsext_status_cb.pod rename to doc/man3/SSL_CTX_set_tlsext_status_cb.pod index c12ff0e5..d6c04ece 100644 --- a/doc/ssl/SSL_CTX_set_tlsext_status_cb.pod +++ b/doc/man3/SSL_CTX_set_tlsext_status_cb.pod @@ -18,10 +18,8 @@ SSL_set_tlsext_status_ocsp_resp #include - long SSL_CTX_set_tlsext_status_cb(SSL_CTX *ctx, - int (*callback)(SSL *, void *)); - long SSL_CTX_get_tlsext_status_cb(SSL_CTX *ctx, - int (**callback)(SSL *, void *)); + long SSL_CTX_set_tlsext_status_cb(SSL_CTX *ctx, int (*callback)(SSL *, void *)); + long SSL_CTX_get_tlsext_status_cb(SSL_CTX *ctx, int (**callback)(SSL *, void *)); long SSL_CTX_set_tlsext_status_arg(SSL_CTX *ctx, void *arg); long SSL_CTX_get_tlsext_status_arg(SSL_CTX *ctx, void **arg); diff --git a/doc/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod b/doc/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod new file mode 100644 index 00000000..3cf0717d --- /dev/null +++ b/doc/man3/SSL_CTX_set_tlsext_ticket_key_cb.pod @@ -0,0 +1,200 @@ +=pod + +=head1 NAME + +SSL_CTX_set_tlsext_ticket_key_cb - set a callback for session ticket processing + +=head1 SYNOPSIS + + #include + + long SSL_CTX_set_tlsext_ticket_key_cb(SSL_CTX sslctx, + int (*cb)(SSL *s, unsigned char key_name[16], + unsigned char iv[EVP_MAX_IV_LENGTH], + EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)); + +=head1 DESCRIPTION + +SSL_CTX_set_tlsext_ticket_key_cb() sets a callback function I for handling +session tickets for the ssl context I. Session tickets, defined in +RFC5077 provide an enhanced session resumption capability where the server +implementation is not required to maintain per session state. It only applies +to TLS and there is no SSLv3 implementation. + +The callback function I will be called for every client instigated TLS +session when session ticket extension is presented in the TLS hello +message. It is the responsibility of this function to create or retrieve the +cryptographic parameters and to maintain their state. + +The OpenSSL library uses your callback function to help implement a common TLS +ticket construction state according to RFC5077 Section 4 such that per session +state is unnecessary and a small set of cryptographic variables needs to be +maintained by the callback function implementation. + +In order to reuse a session, a TLS client must send the a session ticket +extension to the server. The client can only send exactly one session ticket. +The server, through the callback function, either agrees to reuse the session +ticket information or it starts a full TLS handshake to create a new session +ticket. + +Before the callback function is started I and I have been +initialised with EVP_CIPHER_CTX_init and HMAC_CTX_init respectively. + +For new sessions tickets, when the client doesn't present a session ticket, or +an attempted retrieval of the ticket failed, or a renew option was indicated, +the callback function will be called with I equal to 1. The OpenSSL +library expects that the function will set an arbitrary I, initialize +I, and set the cipher context I and the hash context I. + +The I is 16 characters long and is used as a key identifier. + +The I length is the length of the IV of the corresponding cipher. The +maximum IV length is B bytes defined in B. + +The initialization vector I should be a random value. The cipher context +I should use the initialisation vector I. The cipher context can be +set using L. The hmac context can be set using +L. + +When the client presents a session ticket, the callback function with be called +with I set to 0 indicating that the I function should retrieve a set +of parameters. In this case I and I have already been parsed out of +the session ticket. The OpenSSL library expects that the I will be used +to retrieve a cryptographic parameters and that the cryptographic context +I will be set with the retrieved parameters and the initialization vector +I. using a function like L. The I needs to be +set using L. + +If the I is still valid but a renewal of the ticket is required the +callback function should return 2. The library will call the callback again +with an argument of enc equal to 1 to set the new ticket. + +The return value of the I function is used by OpenSSL to determine what +further processing will occur. The following return values have meaning: + +=over 4 + +=item Z<>2 + +This indicates that the I and I have been set and the session can +continue on those parameters. Additionally it indicates that the session +ticket is in a renewal period and should be replaced. The OpenSSL library will +call I again with an enc argument of 1 to set the new ticket (see RFC5077 +3.3 paragraph 2). + +=item Z<>1 + +This indicates that the I and I have been set and the session can +continue on those parameters. + +=item Z<>0 + +This indicates that it was not possible to set/retrieve a session ticket and +the SSL/TLS session will continue by negotiating a set of cryptographic +parameters or using the alternate SSL/TLS resumption mechanism, session ids. + +If called with enc equal to 0 the library will call the I again to get +a new set of parameters. + +=item less than 0 + +This indicates an error. + +=back + +=head1 NOTES + +Session resumption shortcuts the TLS so that the client certificate +negotiation don't occur. It makes up for this by storing client certificate +an all other negotiated state information encrypted within the ticket. In a +resumed session the applications will have all this state information available +exactly as if a full negotiation had occurred. + +If an attacker can obtain the key used to encrypt a session ticket, they can +obtain the master secret for any ticket using that key and decrypt any traffic +using that session: even if the cipher suite supports forward secrecy. As +a result applications may wish to use multiple keys and avoid using long term +keys stored in files. + +Applications can use longer keys to maintain a consistent level of security. +For example if a cipher suite uses 256 bit ciphers but only a 128 bit ticket key +the overall security is only 128 bits because breaking the ticket key will +enable an attacker to obtain the session keys. + +=head1 EXAMPLES + +Reference Implementation: + + SSL_CTX_set_tlsext_ticket_key_cb(SSL, ssl_tlsext_ticket_key_cb); + ... + + static int ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16], + unsigned char *iv, EVP_CIPHER_CTX *ctx, + HMAC_CTX *hctx, int enc) + { + if (enc) { /* create new session */ + if (RAND_bytes(iv, EVP_MAX_IV_LENGTH)) + return -1; /* insufficient random */ + + key = currentkey(); /* something that you need to implement */ + if (key == NULL) { + /* current key doesn't exist or isn't valid */ + key = createkey(); /* + * Something that you need to implement. + * createkey needs to initialise a name, + * an aes_key, a hmac_key and optionally + * an expire time. + */ + if (key == NULL) /* key couldn't be created */ + return 0; + } + memcpy(key_name, key->name, 16); + + EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key->aes_key, iv); + HMAC_Init_ex(&hctx, key->hmac_key, 16, EVP_sha256(), NULL); + + return 1; + + } else { /* retrieve session */ + key = findkey(name); + + if (key == NULL || key->expire < now()) + return 0; + + HMAC_Init_ex(&hctx, key->hmac_key, 16, EVP_sha256(), NULL); + EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key->aes_key, iv); + + if (key->expire < now() - RENEW_TIME) { + /* + * return 2 - This session will get a new ticket even though the + * current one is still valid. + */ + return 2; + } + return 1; + } + } + +=head1 RETURN VALUES + +returns 0 to indicate the callback function was set. + +=head1 SEE ALSO + +L, L, +L, +L, +L, +L, +L, + +=head1 COPYRIGHT + +Copyright 2014-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 +L. + +=cut diff --git a/doc/crypto/SSL_CTX_set_tlsext_use_srtp.pod b/doc/man3/SSL_CTX_set_tlsext_use_srtp.pod similarity index 100% rename from doc/crypto/SSL_CTX_set_tlsext_use_srtp.pod rename to doc/man3/SSL_CTX_set_tlsext_use_srtp.pod diff --git a/doc/ssl/SSL_CTX_set_tmp_dh_callback.pod b/doc/man3/SSL_CTX_set_tmp_dh_callback.pod similarity index 84% rename from doc/ssl/SSL_CTX_set_tmp_dh_callback.pod rename to doc/man3/SSL_CTX_set_tmp_dh_callback.pod index fbfb8cba..a2ac1c0a 100644 --- a/doc/ssl/SSL_CTX_set_tmp_dh_callback.pod +++ b/doc/man3/SSL_CTX_set_tmp_dh_callback.pod @@ -9,11 +9,13 @@ SSL_CTX_set_tmp_dh_callback, SSL_CTX_set_tmp_dh, SSL_set_tmp_dh_callback, SSL_se #include void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx, - DH *(*tmp_dh_callback)(SSL *ssl, int is_export, int keylength)); + DH *(*tmp_dh_callback)(SSL *ssl, int is_export, + int keylength)); long SSL_CTX_set_tmp_dh(SSL_CTX *ctx, DH *dh); void SSL_set_tmp_dh_callback(SSL *ctx, - DH *(*tmp_dh_callback)(SSL *ssl, int is_export, int keylength)); + DH *(*tmp_dh_callback)(SSL *ssl, int is_export, + int keylength)); long SSL_set_tmp_dh(SSL *ssl, DH *dh) =head1 DESCRIPTION @@ -74,7 +76,7 @@ can supply the DH parameters via a callback function. Previous versions of the callback used B and B parameters to control parameter generation for export and non-export -cipher suites. Modern servers that do not support export ciphersuites +cipher suites. Modern servers that do not support export cipher suites are advised to either use SSL_CTX_set_tmp_dh() or alternatively, use the callback but ignore B and B and simply supply at least 2048-bit parameters in the callback. @@ -84,31 +86,27 @@ supply at least 2048-bit parameters in the callback. Setup DH parameters with a key length of 2048 bits. (Error handling partly left out.) - Command-line parameter generation: +Command-line parameter generation: + $ openssl dhparam -out dh_param_2048.pem 2048 - Code for setting up parameters during server initialization: +Code for setting up parameters during server initialization: - ... SSL_CTX ctx = SSL_CTX_new(); - ... - /* Set up ephemeral DH parameters. */ DH *dh_2048 = NULL; - FILE *paramfile; - paramfile = fopen("dh_param_2048.pem", "r"); + FILE *paramfile = fopen("dh_param_2048.pem", "r"); + if (paramfile) { - dh_2048 = PEM_read_DHparams(paramfile, NULL, NULL, NULL); - fclose(paramfile); + dh_2048 = PEM_read_DHparams(paramfile, NULL, NULL, NULL); + fclose(paramfile); } else { - /* Error. */ - } - if (dh_2048 == NULL) { - /* Error. */ - } - if (SSL_CTX_set_tmp_dh(ctx, dh_2048) != 1) { - /* Error. */ + /* Error. */ } + if (dh_2048 == NULL) + /* Error. */ + if (SSL_CTX_set_tmp_dh(ctx, dh_2048) != 1) + /* Error. */ ... =head1 RETURN VALUES @@ -121,7 +119,7 @@ on failure. Check the error queue to find out the reason of failure. =head1 SEE ALSO -L, L, +L, L, L, L, L diff --git a/doc/man3/SSL_CTX_set_verify.pod b/doc/man3/SSL_CTX_set_verify.pod new file mode 100644 index 00000000..71655479 --- /dev/null +++ b/doc/man3/SSL_CTX_set_verify.pod @@ -0,0 +1,355 @@ +=pod + +=head1 NAME + +SSL_get_ex_data_X509_STORE_CTX_idx, +SSL_CTX_set_verify, SSL_set_verify, +SSL_CTX_set_verify_depth, SSL_set_verify_depth, +SSL_verify_cb, +SSL_verify_client_post_handshake, +SSL_force_post_handshake_auth +- set peer certificate verification parameters + +=head1 SYNOPSIS + + #include + + typedef int (*SSL_verify_cb)(int preverify_ok, X509_STORE_CTX *x509_ctx); + + void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, SSL_verify_cb verify_callback); + void SSL_set_verify(SSL *ssl, int mode, SSL_verify_cb verify_callback); + SSL_get_ex_data_X509_STORE_CTX_idx(void); + + void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth); + void SSL_set_verify_depth(SSL *ssl, int depth); + + int SSL_verify_client_post_handshake(SSL *ssl); + void SSL_force_post_handshake_auth(SSL *ssl); + +=head1 DESCRIPTION + +SSL_CTX_set_verify() sets the verification flags for B to be B and +specifies the B function to be used. If no callback function +shall be specified, the NULL pointer can be used for B. + +SSL_set_verify() sets the verification flags for B to be B and +specifies the B function to be used. If no callback function +shall be specified, the NULL pointer can be used for B. In +this case last B set specifically for this B remains. If +no special B was set before, the default callback for the underlying +B is used, that was valid at the time B was created with +L. Within the callback function, +B can be called to get the data index +of the current SSL object that is doing the verification. + +SSL_CTX_set_verify_depth() sets the maximum B for the certificate chain +verification that shall be allowed for B. + +SSL_set_verify_depth() sets the maximum B for the certificate chain +verification that shall be allowed for B. + +SSL_force_post_handshake_auth() forces the Post-Handshake Authentication +extension to be added to the ClientHello regardless of certificate configuration +at the time of the initial handshake, such that post-handshake authentication +can be requested by the server. A certificate callback will need to be set via +SSL_CTX_set_client_cert_cb() if no certificate is provided at initialization. + +SSL_verify_client_post_handshake() causes a CertificateRequest message to be +sent by a server on the given B connection. The SSL_VERIFY_PEER flag must +be set; the SSL_VERIFY_POST_HANDSHAKE flag is optional. + +=head1 NOTES + +The verification of certificates can be controlled by a set of logically +or'ed B flags: + +=over 4 + +=item SSL_VERIFY_NONE + +B the server will not send a client certificate request to the +client, so the client will not send a certificate. + +B if not using an anonymous cipher (by default disabled), the +server will send a certificate which will be checked. The result of the +certificate verification process can be checked after the TLS/SSL handshake +using the L function. +The handshake will be continued regardless of the verification result. + +=item SSL_VERIFY_PEER + +B the server sends a client certificate request to the client. +The certificate returned (if any) is checked. If the verification process +fails, the TLS/SSL handshake is +immediately terminated with an alert message containing the reason for +the verification failure. +The behaviour can be controlled by the additional +SSL_VERIFY_FAIL_IF_NO_PEER_CERT, SSL_VERIFY_CLIENT_ONCE and +SSL_VERIFY_POST_HANDSHAKE flags. + +B the server certificate is verified. If the verification process +fails, the TLS/SSL handshake is +immediately terminated with an alert message containing the reason for +the verification failure. If no server certificate is sent, because an +anonymous cipher is used, SSL_VERIFY_PEER is ignored. + +=item SSL_VERIFY_FAIL_IF_NO_PEER_CERT + +B if the client did not return a certificate, the TLS/SSL +handshake is immediately terminated with a "handshake failure" alert. +This flag must be used together with SSL_VERIFY_PEER. + +B ignored + +=item SSL_VERIFY_CLIENT_ONCE + +B only request a client certificate once during the +connection. Do not ask for a client certificate again during +renegotiation or post-authentication if a certificate was requested +during the initial handshake. This flag must be used together with +SSL_VERIFY_PEER. + +B ignored + +=item SSL_VERIFY_POST_HANDSHAKE + +B the server will not send a client certificate request +during the initial handshake, but will send the request via +SSL_verify_client_post_handshake(). This allows the SSL_CTX or SSL +to be configured for post-handshake peer verification before the +handshake occurs. This flag must be used together with +SSL_VERIFY_PEER. TLSv1.3 only; no effect on pre-TLSv1.3 connections. + +B ignored + +=back + +If the B is SSL_VERIFY_NONE none of the other flags may be set. + +The actual verification procedure is performed either using the built-in +verification procedure or using another application provided verification +function set with +L. +The following descriptions apply in the case of the built-in procedure. An +application provided procedure also has access to the verify depth information +and the verify_callback() function, but the way this information is used +may be different. + +SSL_CTX_set_verify_depth() and SSL_set_verify_depth() set a limit on the +number of certificates between the end-entity and trust-anchor certificates. +Neither the +end-entity nor the trust-anchor certificates count against B. If the +certificate chain needed to reach a trusted issuer is longer than B, +X509_V_ERR_CERT_CHAIN_TOO_LONG will be issued. +The depth count is "level 0:peer certificate", "level 1: CA certificate", +"level 2: higher level CA certificate", and so on. Setting the maximum +depth to 2 allows the levels 0, 1, 2 and 3 (0 being the end-entity and 3 the +trust-anchor). +The default depth limit is 100, +allowing for the peer certificate, at most 100 intermediate CA certificates and +a final trust anchor certificate. + +The B function is used to control the behaviour when the +SSL_VERIFY_PEER flag is set. It must be supplied by the application and +receives two arguments: B indicates, whether the verification of +the certificate in question was passed (preverify_ok=1) or not +(preverify_ok=0). B is a pointer to the complete context used +for the certificate chain verification. + +The certificate chain is checked starting with the deepest nesting level +(the root CA certificate) and worked upward to the peer's certificate. +At each level signatures and issuer attributes are checked. Whenever +a verification error is found, the error number is stored in B +and B is called with B=0. By applying +X509_CTX_store_* functions B can locate the certificate +in question and perform additional steps (see EXAMPLES). If no error is +found for a certificate, B is called with B=1 +before advancing to the next level. + +The return value of B controls the strategy of the further +verification process. If B returns 0, the verification +process is immediately stopped with "verification failed" state. If +SSL_VERIFY_PEER is set, a verification failure alert is sent to the peer and +the TLS/SSL handshake is terminated. If B returns 1, +the verification process is continued. If B always returns +1, the TLS/SSL handshake will not be terminated with respect to verification +failures and the connection will be established. The calling process can +however retrieve the error code of the last verification error using +L or by maintaining its +own error storage managed by B. + +If no B is specified, the default callback will be used. +Its return value is identical to B, so that any verification +failure will lead to a termination of the TLS/SSL handshake with an +alert message, if SSL_VERIFY_PEER is set. + +After calling SSL_force_post_handshake_auth(), the client will need to add a +certificate or certificate callback to its configuration before it can +successfully authenticate. This must be called before SSL_connect(). + +SSL_verify_client_post_handshake() requires that verify flags have been +previously set, and that a client sent the post-handshake authentication +extension. When the client returns a certificate the verify callback will be +invoked. A write operation must take place for the Certificate Request to be +sent to the client, this can be done with SSL_do_handshake() or SSL_write_ex(). +Only one certificate request may be outstanding at any time. + +When post-handshake authentication occurs, a refreshed NewSessionTicket +message is sent to the client. + +=head1 BUGS + +In client mode, it is not checked whether the SSL_VERIFY_PEER flag +is set, but whether any flags are set. This can lead to +unexpected behaviour if SSL_VERIFY_PEER and other flags are not used as +required. + +=head1 RETURN VALUES + +The SSL*_set_verify*() functions do not provide diagnostic information. + +The SSL_verify_client_post_handshake() function returns 1 if the request +succeeded, and 0 if the request failed. The error stack can be examined +to determine the failure reason. + +=head1 EXAMPLES + +The following code sequence realizes an example B function +that will always continue the TLS/SSL handshake regardless of verification +failure, if wished. The callback realizes a verification depth limit with +more informational output. + +All verification errors are printed; information about the certificate chain +is printed on request. +The example is realized for a server that does allow but not require client +certificates. + +The example makes use of the ex_data technique to store application data +into/retrieve application data from the SSL structure +(see L, +L). + + ... + typedef struct { + int verbose_mode; + int verify_depth; + int always_continue; + } mydata_t; + int mydata_index; + + ... + static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) + { + char buf[256]; + X509 *err_cert; + int err, depth; + SSL *ssl; + mydata_t *mydata; + + err_cert = X509_STORE_CTX_get_current_cert(ctx); + err = X509_STORE_CTX_get_error(ctx); + depth = X509_STORE_CTX_get_error_depth(ctx); + + /* + * Retrieve the pointer to the SSL of the connection currently treated + * and the application specific data stored into the SSL object. + */ + ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); + mydata = SSL_get_ex_data(ssl, mydata_index); + + X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256); + + /* + * Catch a too long certificate chain. The depth limit set using + * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so + * that whenever the "depth>verify_depth" condition is met, we + * have violated the limit and want to log this error condition. + * We must do it here, because the CHAIN_TOO_LONG error would not + * be found explicitly; only errors introduced by cutting off the + * additional certificates would be logged. + */ + if (depth > mydata->verify_depth) { + preverify_ok = 0; + err = X509_V_ERR_CERT_CHAIN_TOO_LONG; + X509_STORE_CTX_set_error(ctx, err); + } + if (!preverify_ok) { + printf("verify error:num=%d:%s:depth=%d:%s\n", err, + X509_verify_cert_error_string(err), depth, buf); + } else if (mydata->verbose_mode) { + printf("depth=%d:%s\n", depth, buf); + } + + /* + * At this point, err contains the last verification error. We can use + * it for something special + */ + if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) { + X509_NAME_oneline(X509_get_issuer_name(err_cert), buf, 256); + printf("issuer= %s\n", buf); + } + + if (mydata->always_continue) + return 1; + else + return preverify_ok; + } + ... + + mydata_t mydata; + + ... + mydata_index = SSL_get_ex_new_index(0, "mydata index", NULL, NULL, NULL); + + ... + SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, + verify_callback); + + /* + * Let the verify_callback catch the verify_depth error so that we get + * an appropriate error in the logfile. + */ + SSL_CTX_set_verify_depth(verify_depth + 1); + + /* + * Set up the SSL specific data into "mydata" and store it into th SSL + * structure. + */ + mydata.verify_depth = verify_depth; ... + SSL_set_ex_data(ssl, mydata_index, &mydata); + + ... + SSL_accept(ssl); /* check of success left out for clarity */ + if (peer = SSL_get_peer_certificate(ssl)) { + if (SSL_get_verify_result(ssl) == X509_V_OK) { + /* The client sent a certificate which verified OK */ + } + } + +=head1 SEE ALSO + +L, L, +L, +L, +L, +L, +L, +L, +L, +L + +=head1 HISTORY + +The SSL_VERIFY_POST_HANDSHAKE option, and the SSL_verify_client_post_handshake() +and SSL_force_post_handshake_auth() functions were added in OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/ssl/SSL_CTX_use_certificate.pod b/doc/man3/SSL_CTX_use_certificate.pod similarity index 98% rename from doc/ssl/SSL_CTX_use_certificate.pod rename to doc/man3/SSL_CTX_use_certificate.pod index c645f580..22420f97 100644 --- a/doc/ssl/SSL_CTX_use_certificate.pod +++ b/doc/man3/SSL_CTX_use_certificate.pod @@ -103,7 +103,7 @@ SSL_use_PrivateKey_ASN1() and SSL_use_RSAPrivateKey_ASN1() add the private key to B. SSL_CTX_use_PrivateKey_file() adds the first private key found in -B to B. The formatting B of the certificate must be specified +B to B. The formatting B of the private key must be specified from the known types SSL_FILETYPE_PEM, SSL_FILETYPE_ASN1. SSL_CTX_use_RSAPrivateKey_file() adds the first private RSA key found in B to B. SSL_use_PrivateKey_file() adds the first private key found @@ -160,7 +160,7 @@ Otherwise check out the error stack to find out the reason. =head1 SEE ALSO -L, L, L, +L, L, L, L, L, L, diff --git a/doc/man3/SSL_CTX_use_psk_identity_hint.pod b/doc/man3/SSL_CTX_use_psk_identity_hint.pod new file mode 100644 index 00000000..d41c0cce --- /dev/null +++ b/doc/man3/SSL_CTX_use_psk_identity_hint.pod @@ -0,0 +1,137 @@ +=pod + +=head1 NAME + +SSL_psk_server_cb_func, +SSL_psk_find_session_cb_func, +SSL_CTX_use_psk_identity_hint, +SSL_use_psk_identity_hint, +SSL_CTX_set_psk_server_callback, +SSL_set_psk_server_callback, +SSL_CTX_set_psk_find_session_callback, +SSL_set_psk_find_session_callback +- set PSK identity hint to use + +=head1 SYNOPSIS + + #include + + typedef unsigned int (*SSL_psk_server_cb_func)(SSL *ssl, + const char *identity, + unsigned char *psk, + unsigned int max_psk_len); + + typedef int (*SSL_psk_find_session_cb_func)(SSL *ssl, + const unsigned char *identity, + size_t identity_len, + SSL_SESSION **sess); + + int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *hint); + int SSL_use_psk_identity_hint(SSL *ssl, const char *hint); + + void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, SSL_psk_server_cb_func cb); + void SSL_set_psk_server_callback(SSL *ssl, SSL_psk_server_cb_func cb); + + void SSL_CTX_set_psk_find_session_callback(SSL_CTX *ctx, + SSL_psk_find_session_cb_func cb); + void SSL_set_psk_find_session_callback(SSL *s, SSL_psk_find_session_cb_func cb); + +=head1 DESCRIPTION + +TLSv1.3 Pre-Shared Keys (PSKs) and PSKs for TLSv1.2 and below are not +compatible. + +Identity hints are not relevant for TLSv1.3. A server application wishing to use +PSK ciphersuites for TLSv1.2 and below may call SSL_CTX_use_psk_identity_hint() +to set the given B-terminated PSK identity hint B for SSL context +object B. SSL_use_psk_identity_hint() sets the given B-terminated PSK +identity hint B for the SSL connection object B. If B is +B the current hint from B or B is deleted. + +In the case where PSK identity hint is B, the server does not send the +ServerKeyExchange message to the client. + +A server application for TLSv1.2 and below must provide a callback function +which is called when the server receives the ClientKeyExchange message from the +client. The purpose of the callback function is to validate the +received PSK identity and to fetch the pre-shared key used during the +connection setup phase. The callback is set using the functions +SSL_CTX_set_psk_server_callback() or SSL_set_psk_server_callback(). The callback +function is given the connection in parameter B, B-terminated PSK +identity sent by the client in parameter B, and a buffer B of +length B bytes where the pre-shared key is to be stored. + +A client application wishing to use TLSv1.3 PSKs must set a different callback +using either SSL_CTX_set_psk_use_session_callback() or +SSL_set_psk_use_session_callback() as appropriate. + +The callback function is given a pointer to the SSL connection in B and +an identity in B of length B. The callback function +should identify an SSL_SESSION object that provides the PSK details and store it +in B<*sess>. The SSL_SESSION object should, as a minimum, set the master key, +the ciphersuite and the protocol version. See +L for details. + +It is also possible for the callback to succeed but not supply a PSK. In this +case no PSK will be used but the handshake will continue. To do this the +callback should return successfully and ensure that B<*sess> is +NULL. + +=head1 NOTES + +A connection established via a TLSv1.3 PSK will appear as if session resumption +has occurred so that L will return true. + +=head1 RETURN VALUES + +B and B return +1 on success, 0 otherwise. + +Return values from the TLSv1.2 and below server callback are interpreted as +follows: + +=over 4 + +=item Z<>0 + +PSK identity was not found. An "unknown_psk_identity" alert message +will be sent and the connection setup fails. + +=item E0 + +PSK identity was found and the server callback has provided the PSK +successfully in parameter B. Return value is the length of +B in bytes. It is an error to return a value greater than +B. + +If the PSK identity was not found but the callback instructs the +protocol to continue anyway, the callback must provide some random +data to B and return the length of the random data, so the +connection will fail with decryption_error before it will be finished +completely. + +=back + +The B callback should return 1 on success or 0 on +failure. In the event of failure the connection setup fails. + +=head1 SEE ALSO + +L, +L + +=head1 HISTORY + +SSL_CTX_set_psk_find_session_callback() and SSL_set_psk_find_session_callback() +were added in OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2006-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 +L. + +=cut diff --git a/doc/man3/SSL_CTX_use_serverinfo.pod b/doc/man3/SSL_CTX_use_serverinfo.pod new file mode 100644 index 00000000..d35a196f --- /dev/null +++ b/doc/man3/SSL_CTX_use_serverinfo.pod @@ -0,0 +1,83 @@ +=pod + +=head1 NAME + +SSL_CTX_use_serverinfo_ex, +SSL_CTX_use_serverinfo, +SSL_CTX_use_serverinfo_file +- use serverinfo extension + +=head1 SYNOPSIS + + #include + + int SSL_CTX_use_serverinfo_ex(SSL_CTX *ctx, unsigned int version, + const unsigned char *serverinfo, + size_t serverinfo_length); + + int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, + size_t serverinfo_length); + + int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file); + +=head1 DESCRIPTION + +These functions load "serverinfo" TLS extensions into the SSL_CTX. A +"serverinfo" extension is returned in response to an empty ClientHello +Extension. + +SSL_CTX_use_serverinfo_ex() loads one or more serverinfo extensions from +a byte array into B. The B parameter specifies the format of the +byte array provided in B<*serverinfo> which is of length B. + +If B is B then the extensions in the array must +consist of a 4-byte context, a 2-byte Extension Type, a 2-byte length, and then +length bytes of extension_data. The context and type values have the same +meaning as for L. If serverinfo is being loaded for +extensions to be added to a Certificate message, then the extension will only +be added for the first certificate in the message (which is always the +end-entity certificate). + +If B is B then the extensions in the array must +consist of a 2-byte Extension Type, a 2-byte length, and then length bytes of +extension_data. The type value has the same meaning as for +L. The following default context value will be used +in this case: + + SSL_EXT_TLS1_2_AND_BELOW_ONLY | SSL_EXT_CLIENT_HELLO + | SSL_EXT_TLS1_2_SERVER_HELLO | SSL_EXT_IGNORE_ON_RESUMPTION + +SSL_CTX_use_serverinfo() does the same thing as SSL_CTX_use_serverinfo_ex() +except that there is no B parameter so a default version of +SSL_SERVERINFOV1 is used instead. + +SSL_CTX_use_serverinfo_file() loads one or more serverinfo extensions from +B into B. The extensions must be in PEM format. Each extension +must be in a format as described above for SSL_CTX_use_serverinfo_ex(). Each +PEM extension name must begin with the phrase "BEGIN SERVERINFOV2 FOR " for +SSL_SERVERINFOV2 data or "BEGIN SERVERINFO FOR " for SSL_SERVERINFOV1 data. + +If more than one certificate (RSA/DSA) is installed using +SSL_CTX_use_certificate(), the serverinfo extension will be loaded into the +last certificate installed. If e.g. the last item was a RSA certificate, the +loaded serverinfo extension data will be loaded for that certificate. To +use the serverinfo extension for multiple certificates, +SSL_CTX_use_serverinfo() needs to be called multiple times, once B +each time a certificate is loaded via a call to SSL_CTX_use_certificate(). + +=head1 RETURN VALUES + +On success, the functions return 1. +On failure, the functions return 0. Check out the error stack to find out +the reason. + +=head1 COPYRIGHT + +Copyright 2013-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 +L. + +=cut diff --git a/doc/ssl/SSL_SESSION_free.pod b/doc/man3/SSL_SESSION_free.pod similarity index 90% rename from doc/ssl/SSL_SESSION_free.pod rename to doc/man3/SSL_SESSION_free.pod index 5bea7850..87a1cab1 100644 --- a/doc/ssl/SSL_SESSION_free.pod +++ b/doc/man3/SSL_SESSION_free.pod @@ -3,6 +3,7 @@ =head1 NAME SSL_SESSION_new, +SSL_SESSION_dup, SSL_SESSION_up_ref, SSL_SESSION_free - create, free and manage SSL_SESSION structures @@ -11,6 +12,7 @@ SSL_SESSION_free - create, free and manage SSL_SESSION structures #include SSL_SESSION *SSL_SESSION_new(void); + SSL_SESSION *SSL_SESSION_dup(SSL_SESSION *src); int SSL_SESSION_up_ref(SSL_SESSION *ses); void SSL_SESSION_free(SSL_SESSION *session); @@ -19,6 +21,9 @@ SSL_SESSION_free - create, free and manage SSL_SESSION structures SSL_SESSION_new() creates a new SSL_SESSION structure and returns a pointer to it. +SSL_SESSION_dup() copies the contents of the SSL_SESSION structure in B +and returns a pointer to it. + SSL_SESSION_up_ref() increments the reference count on the given SSL_SESSION structure. @@ -61,11 +66,15 @@ SSL_SESSION_up_ref returns 1 on success or 0 on error. =head1 SEE ALSO -L, L, +L, L, L, L, L +=head1 HISTORY + +SSL_SESSION_dup() was added in OpenSSL 1.1.1. + =head1 COPYRIGHT Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. diff --git a/doc/man3/SSL_SESSION_get0_cipher.pod b/doc/man3/SSL_SESSION_get0_cipher.pod new file mode 100644 index 00000000..60f66a2d --- /dev/null +++ b/doc/man3/SSL_SESSION_get0_cipher.pod @@ -0,0 +1,58 @@ +=pod + +=head1 NAME + +SSL_SESSION_get0_cipher, +SSL_SESSION_set_cipher +- set and retrieve the SSL cipher associated with a session + +=head1 SYNOPSIS + + #include + + const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSION *s); + int SSL_SESSION_set_cipher(SSL_SESSION *s, const SSL_CIPHER *cipher); + +=head1 DESCRIPTION + +SSL_SESSION_get0_cipher() retrieves the cipher that was used by the +connection when the session was created, or NULL if it cannot be determined. + +The value returned is a pointer to an object maintained within B and +should not be released. + +SSL_SESSION_set_cipher() can be used to set the ciphersuite associated with the +SSL_SESSION B to B. For example, this could be used to set up a +session based PSK (see L). + +=head1 RETURN VALUES + +SSL_SESSION_get0_cipher() returns the SSL_CIPHER associated with the SSL_SESSION +or NULL if it cannot be determined. + +SSL_SESSION_set_cipher() returns 1 on success or 0 on failure. + +=head1 SEE ALSO + +L, +L, +L, +L, +L, +L + +=head1 HISTORY + +SSL_SESSION_get0_cipher() was first added to OpenSSL 1.1.0. +SSL_SESSION_set_cipher() was first added to OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2016-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 +L. + +=cut diff --git a/doc/man3/SSL_SESSION_get0_hostname.pod b/doc/man3/SSL_SESSION_get0_hostname.pod new file mode 100644 index 00000000..c35c8927 --- /dev/null +++ b/doc/man3/SSL_SESSION_get0_hostname.pod @@ -0,0 +1,74 @@ +=pod + +=head1 NAME + +SSL_SESSION_get0_hostname, +SSL_SESSION_set1_hostname, +SSL_SESSION_get0_alpn_selected, +SSL_SESSION_set1_alpn_selected +- get and set SNI and ALPN data ssociated with a session + +=head1 SYNOPSIS + + #include + + const char *SSL_SESSION_get0_hostname(const SSL_SESSION *s); + int SSL_SESSION_set1_hostname(SSL_SESSION *s, const char *hostname); + + void SSL_SESSION_get0_alpn_selected(const SSL_SESSION *s, + const unsigned char **alpn, + size_t *len); + int SSL_SESSION_set1_alpn_selected(SSL_SESSION *s, const unsigned char *alpn, + size_t len); + +=head1 DESCRIPTION + +SSL_SESSION_get0_hostname() retrieves the SNI value that was sent by the +client when the session was created, or NULL if no value was sent. + +The value returned is a pointer to memory maintained within B and +should not be free'd. + +SSL_SESSION_set1_hostname() sets the SNI value for the hostname to a copy of +the string provided in hostname. + +SSL_SESSION_get0_alpn_selected() retrieves the selected ALPN protocol for this +session and its associated length in bytes. The returned value of B<*alpn> is a +pointer to memory maintained within B and should not be free'd. + +SSL_SESSION_set1_alpn_selected() sets the ALPN protocol for this session to the +value in B which should be of length B bytes. A copy of the input +value is made, and the caller retains ownership of the memory pointed to by +B. + +=head1 RETURN VALUES + +SSL_SESSION_get0_hostname() returns either a string or NULL based on if there +is the SNI value sent by client. + +SSL_SESSION_set1_hostname() returns 1 on success or 0 on error. + +SSL_SESSION_set1_alpn_selected() returns 1 on success or 0 on error. + +=head1 SEE ALSO + +L, +L, +L, +L + +=head1 HISTORY + +SSL_SESSION_set1_hostname(), SSL_SESSION_get0_alpn_selected() and +SSL_SESSION_set1_alpn_selected() were added in OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2016-2018 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 +L. + +=cut diff --git a/doc/ssl/SSL_SESSION_get0_id_context.pod b/doc/man3/SSL_SESSION_get0_id_context.pod similarity index 99% rename from doc/ssl/SSL_SESSION_get0_id_context.pod rename to doc/man3/SSL_SESSION_get0_id_context.pod index ee4a256b..69619a72 100644 --- a/doc/ssl/SSL_SESSION_get0_id_context.pod +++ b/doc/man3/SSL_SESSION_get0_id_context.pod @@ -37,7 +37,7 @@ SSL_SESSION_set1_id_context() returns 1 on success or 0 on error. =head1 SEE ALSO -L, +L, L =head1 HISTORY diff --git a/doc/ssl/SSL_SESSION_get0_peer.pod b/doc/man3/SSL_SESSION_get0_peer.pod similarity index 98% rename from doc/ssl/SSL_SESSION_get0_peer.pod rename to doc/man3/SSL_SESSION_get0_peer.pod index a95f8a5b..f6f2a1cd 100644 --- a/doc/ssl/SSL_SESSION_get0_peer.pod +++ b/doc/man3/SSL_SESSION_get0_peer.pod @@ -24,7 +24,7 @@ no peer certificate is available. =head1 SEE ALSO -L +L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_SESSION_get_compress_id.pod b/doc/man3/SSL_SESSION_get_compress_id.pod similarity index 98% rename from doc/ssl/SSL_SESSION_get_compress_id.pod rename to doc/man3/SSL_SESSION_get_compress_id.pod index 5045c537..0bdccb4b 100644 --- a/doc/ssl/SSL_SESSION_get_compress_id.pod +++ b/doc/man3/SSL_SESSION_get_compress_id.pod @@ -25,7 +25,7 @@ none. =head1 SEE ALSO -L +L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_SESSION_get_ex_data.pod b/doc/man3/SSL_SESSION_get_ex_data.pod similarity index 99% rename from doc/ssl/SSL_SESSION_get_ex_data.pod rename to doc/man3/SSL_SESSION_get_ex_data.pod index e922abc5..f44c4e8e 100644 --- a/doc/ssl/SSL_SESSION_get_ex_data.pod +++ b/doc/man3/SSL_SESSION_get_ex_data.pod @@ -32,7 +32,7 @@ failure. NULL may also be a valid value. =head1 SEE ALSO -L, +L, L =head1 COPYRIGHT diff --git a/doc/man3/SSL_SESSION_get_protocol_version.pod b/doc/man3/SSL_SESSION_get_protocol_version.pod new file mode 100644 index 00000000..22e40bd6 --- /dev/null +++ b/doc/man3/SSL_SESSION_get_protocol_version.pod @@ -0,0 +1,56 @@ +=pod + +=head1 NAME + +SSL_SESSION_get_protocol_version, +SSL_SESSION_set_protocol_version +- get and set the session protocol version + +=head1 SYNOPSIS + + #include + + int SSL_SESSION_get_protocol_version(const SSL_SESSION *s); + int SSL_SESSION_set_protocol_version(SSL_SESSION *s, int version); + +=head1 DESCRIPTION + +SSL_SESSION_get_protocol_version() returns the protocol version number used +by session B. + +SSL_SESSION_set_protocol_version() sets the protocol version associated with the +SSL_SESSION object B to the value B. This value should be a version +constant such as B etc. For example, this could be used to set +up a session based PSK (see L). + +=head1 RETURN VALUES + +SSL_SESSION_get_protocol_version() returns a number indicating the protocol +version used for the session; this number matches the constants I +B or B. + +Note that the SSL_SESSION_get_protocol_version() function +does B perform a null check on the provided session B pointer. + +SSL_SESSION_set_protocol_version() returns 1 on success or 0 on failure. + +=head1 SEE ALSO + +L, +L + +=head1 HISTORY + +SSL_SESSION_get_protocol_version() was first added to OpenSSL 1.1.0. +SSL_SESSION_set_protocol_version() was first added to OpenSSL 1.1.1. + +=head1 COPYRIGHT + +Copyright 2001-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 +L. + +=cut diff --git a/doc/ssl/SSL_SESSION_get_time.pod b/doc/man3/SSL_SESSION_get_time.pod similarity index 100% rename from doc/ssl/SSL_SESSION_get_time.pod rename to doc/man3/SSL_SESSION_get_time.pod diff --git a/doc/ssl/SSL_SESSION_has_ticket.pod b/doc/man3/SSL_SESSION_has_ticket.pod similarity index 87% rename from doc/ssl/SSL_SESSION_has_ticket.pod rename to doc/man3/SSL_SESSION_has_ticket.pod index a84440b5..71973823 100644 --- a/doc/ssl/SSL_SESSION_has_ticket.pod +++ b/doc/man3/SSL_SESSION_has_ticket.pod @@ -29,6 +29,12 @@ NULL then a pointer to the ticket is written to B<*tick>. The pointer is only valid while the connection is in use. The session (and hence the ticket pointer) may also become invalid as a result of a call to SSL_CTX_flush_sessions(). +=head1 RETURN VALUES + +SSL_SESSION_has_ticket() returns 1 if session ticket exists or 0 otherwise. + +SSL_SESSION_get_ticket_lifetime_hint() returns the number of seconds. + =head1 SEE ALSO L, @@ -43,7 +49,7 @@ SSL_SESSION_get0_ticket were added in OpenSSL 1.1.0. =head1 COPYRIGHT -Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2015-2018 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 diff --git a/doc/man3/SSL_SESSION_is_resumable.pod b/doc/man3/SSL_SESSION_is_resumable.pod new file mode 100644 index 00000000..729479a9 --- /dev/null +++ b/doc/man3/SSL_SESSION_is_resumable.pod @@ -0,0 +1,44 @@ +=pod + +=head1 NAME + +SSL_SESSION_is_resumable +- determine whether an SSL_SESSION object can be used for resumption + +=head1 SYNOPSIS + + #include + + int SSL_SESSION_is_resumable(const SSL_SESSION *s); + +=head1 DESCRIPTION + +SSL_SESSION_is_resumable() determines whether an SSL_SESSION object can be used +to resume a session or not. Returns 1 if it can or 0 if not. Note that +attempting to resume with a non-resumable session will result in a full +handshake. + +=head1 RETURN VALUES + +SSL_SESSION_is_resumable() returns 1 if the session is resumable or 0 otherwise. + +=head1 SEE ALSO + +L, +L, +L + +=head1 HISTORY + +SSL_SESSION_is_resumable() was first added to OpenSSL 1.1.1 + +=head1 COPYRIGHT + +Copyright 2017-2018 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 +L. + +=cut diff --git a/doc/ssl/SSL_SESSION_print.pod b/doc/man3/SSL_SESSION_print.pod similarity index 99% rename from doc/ssl/SSL_SESSION_print.pod rename to doc/man3/SSL_SESSION_print.pod index 9a44c11c..957411a7 100644 --- a/doc/ssl/SSL_SESSION_print.pod +++ b/doc/man3/SSL_SESSION_print.pod @@ -33,7 +33,7 @@ SSL_SESSION_print(), SSL_SESSION_print_fp() and SSL_SESSION_print_keylog return =head1 SEE ALSO -L +L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_SESSION_set1_id.pod b/doc/man3/SSL_SESSION_set1_id.pod similarity index 93% rename from doc/ssl/SSL_SESSION_set1_id.pod rename to doc/man3/SSL_SESSION_set1_id.pod index 0bd9b834..f0b131d6 100644 --- a/doc/ssl/SSL_SESSION_set1_id.pod +++ b/doc/man3/SSL_SESSION_set1_id.pod @@ -21,7 +21,7 @@ SSL_SESSION_get_id() returns a pointer to the internal session id value for the session B. The length of the id in bytes is stored in B<*len>. The length may be 0. The caller should not free the returned pointer directly. -SSL_SESSION_set1_id() sets the the session ID for the B SSL/TLS session +SSL_SESSION_set1_id() sets the session ID for the B SSL/TLS session to B of length B. =head1 RETURN VALUES @@ -32,7 +32,7 @@ if the supplied session ID length exceeds B. =head1 SEE ALSO -L +L =head1 HISTORY diff --git a/doc/ssl/SSL_accept.pod b/doc/man3/SSL_accept.pod similarity index 98% rename from doc/ssl/SSL_accept.pod rename to doc/man3/SSL_accept.pod index 3248cacf..335655f0 100644 --- a/doc/ssl/SSL_accept.pod +++ b/doc/man3/SSL_accept.pod @@ -65,7 +65,7 @@ to find out the reason. =head1 SEE ALSO L, L, -L, L, L, +L, L, L, L, L, L diff --git a/doc/ssl/SSL_alert_type_string.pod b/doc/man3/SSL_alert_type_string.pod similarity index 99% rename from doc/ssl/SSL_alert_type_string.pod rename to doc/man3/SSL_alert_type_string.pod index 6e2768e8..b88465b1 100644 --- a/doc/ssl/SSL_alert_type_string.pod +++ b/doc/man3/SSL_alert_type_string.pod @@ -228,7 +228,7 @@ Probably B does not contain a correct alert message. =head1 SEE ALSO -L, L +L, L =head1 COPYRIGHT diff --git a/doc/man3/SSL_alloc_buffers.pod b/doc/man3/SSL_alloc_buffers.pod new file mode 100644 index 00000000..94bd0584 --- /dev/null +++ b/doc/man3/SSL_alloc_buffers.pod @@ -0,0 +1,67 @@ +=pod + +=head1 NAME + +SSL_free_buffers, SSL_alloc_buffers - manage SSL structure buffers + +=head1 SYNOPSIS + + #include + + int SSL_free_buffers(SSL *ssl); + int SSL_alloc_buffers(SSL *ssl); + +=head1 DESCRIPTION + +SSL_free_buffers() frees the read and write buffers of the given B. +SSL_alloc_buffers() allocates the read and write buffers of the given B. + +The B mode releases read or write buffers whenever +the buffers have been drained. These functions allow applications to manually +control when buffers are freed and allocated. + +After freeing the buffers, the buffers are automatically reallocated upon a +new read or write. The SSL_alloc_buffers() does not need to be called, but +can be used to make sure the buffers are pre-allocated. This can be used to +avoid allocation during data processing or with CRYPTO_set_mem_functions() +to control where and how buffers are allocated. + +=head1 RETURN VALUES + +The following return values can occur: + +=over 4 + +=item 0 (Failure) + +The SSL_free_buffers() function returns 0 when there is pending data to be +read or written. The SSL_alloc_buffers() function returns 0 when there is +an allocation failure. + +=item 1 (Success) + +The SSL_free_buffers() function returns 1 if the buffers have been freed. This +value is also returned if the buffers had been freed before calling +SSL_free_buffers(). +The SSL_alloc_buffers() function returns 1 if the buffers have been allocated. +This value is also returned if the buffers had been allocated before calling +SSL_alloc_buffers(). + +=back + +=head1 SEE ALSO + +L, L, +L, L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/ssl/SSL_check_chain.pod b/doc/man3/SSL_check_chain.pod similarity index 99% rename from doc/ssl/SSL_check_chain.pod rename to doc/man3/SSL_check_chain.pod index 86919942..28c789e9 100644 --- a/doc/ssl/SSL_check_chain.pod +++ b/doc/man3/SSL_check_chain.pod @@ -80,7 +80,7 @@ for earlier versions of TLS or DTLS. =head1 SEE ALSO L, -L +L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_clear.pod b/doc/man3/SSL_clear.pod similarity index 98% rename from doc/ssl/SSL_clear.pod rename to doc/man3/SSL_clear.pod index ed0ad60c..385e4f6e 100644 --- a/doc/ssl/SSL_clear.pod +++ b/doc/man3/SSL_clear.pod @@ -69,7 +69,7 @@ The SSL_clear() operation was successful. L, L, L, L, -L, L, +L, L, L =head1 COPYRIGHT diff --git a/doc/ssl/SSL_connect.pod b/doc/man3/SSL_connect.pod similarity index 98% rename from doc/ssl/SSL_connect.pod rename to doc/man3/SSL_connect.pod index df198f9b..1f054d67 100644 --- a/doc/ssl/SSL_connect.pod +++ b/doc/man3/SSL_connect.pod @@ -65,7 +65,7 @@ to find out the reason. =head1 SEE ALSO L, L, -L, L, L, +L, L, L, L, L, L diff --git a/doc/ssl/SSL_do_handshake.pod b/doc/man3/SSL_do_handshake.pod similarity index 98% rename from doc/ssl/SSL_do_handshake.pod rename to doc/man3/SSL_do_handshake.pod index ffb71cc0..a1b973f7 100644 --- a/doc/ssl/SSL_do_handshake.pod +++ b/doc/man3/SSL_do_handshake.pod @@ -66,7 +66,7 @@ to find out the reason. =head1 SEE ALSO L, L, -L, L, L, +L, L, L, L =head1 COPYRIGHT diff --git a/doc/man3/SSL_export_keying_material.pod b/doc/man3/SSL_export_keying_material.pod new file mode 100644 index 00000000..0090097d --- /dev/null +++ b/doc/man3/SSL_export_keying_material.pod @@ -0,0 +1,87 @@ +=pod + +=head1 NAME + +SSL_export_keying_material, +SSL_export_keying_material_early +- obtain keying material for application use + +=head1 SYNOPSIS + + #include + + 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); + + int SSL_export_keying_material_early(SSL *s, unsigned char *out, size_t olen, + const char *label, size_t llen, + const unsigned char *context, + size_t contextlen); + +=head1 DESCRIPTION + +During the creation of a TLS or DTLS connection shared keying material is +established between the two endpoints. The functions +SSL_export_keying_material() and SSL_export_keying_material_early() enable an +application to use some of this keying material for its own purposes in +accordance with RFC5705 (for TLSv1.2 and below) or RFCXXXX (for TLSv1.3). +TODO(TLS1.3): Update the RFC number when the RFC is published. + +SSL_export_keying_material() derives keying material using +the F established in the handshake. + +SSL_export_keying_material_early() is only usable with TLSv1.3, and derives +keying material using the F (as defined in the +TLS 1.3 RFC). For the client, the F is only +available when the client attempts to send 0-RTT data. For the server, it is +only available when the server accepts 0-RTT data. + +An application may need to securely establish the context within which this +keying material will be used. For example this may include identifiers for the +application session, application algorithms or parameters, or the lifetime of +the context. The context value is left to the application but must be the same +on both sides of the communication. + +For a given SSL connection B, B bytes of data will be written to +B. The application specific context should be supplied in the location +pointed to by B and should be B bytes long. Provision of +a context is optional. If the context should be omitted entirely then +B should be set to 0. Otherwise it should be any other value. If +B is 0 then the values of B and B are ignored. +Note that in TLSv1.2 and below a zero length context is treated differently from +no context at all, and will result in different keying material being returned. +In TLSv1.3 a zero length context is that same as no context at all and will +result in the same keying material being returned. + +An application specific label should be provided in the location pointed to by +B and B and returns 0 if they have identical encodings and non-zero otherwise. +=head1 RETURN VALUES + +X509_ALGOR_dup() returns a valid B structure or NULL if an error +occurred. + +X509_ALGOR_set0() returns 1 on success or 0 on error. + +X509_ALGOR_get0() and X509_ALGOR_set_md() return no values. + +X509_ALGOR_cmp() returns 0 if the two parameters have identical encodings and +non-zero otherwise. + =head1 COPYRIGHT -Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2002-2018 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 diff --git a/doc/crypto/X509_CRL_get0_by_serial.pod b/doc/man3/X509_CRL_get0_by_serial.pod similarity index 100% rename from doc/crypto/X509_CRL_get0_by_serial.pod rename to doc/man3/X509_CRL_get0_by_serial.pod diff --git a/doc/crypto/X509_EXTENSION_set_object.pod b/doc/man3/X509_EXTENSION_set_object.pod similarity index 100% rename from doc/crypto/X509_EXTENSION_set_object.pod rename to doc/man3/X509_EXTENSION_set_object.pod diff --git a/doc/crypto/X509_LOOKUP_hash_dir.pod b/doc/man3/X509_LOOKUP_hash_dir.pod similarity index 86% rename from doc/crypto/X509_LOOKUP_hash_dir.pod rename to doc/man3/X509_LOOKUP_hash_dir.pod index 5f8dfa93..84d8fb92 100644 --- a/doc/crypto/X509_LOOKUP_hash_dir.pod +++ b/doc/man3/X509_LOOKUP_hash_dir.pod @@ -10,14 +10,14 @@ lookup methods =head1 SYNOPSIS - #include + #include - X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void); - X509_LOOKUP_METHOD *X509_LOOKUP_file(void); + X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void); + X509_LOOKUP_METHOD *X509_LOOKUP_file(void); - int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type); - int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type); - int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type); + int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type); + int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type); + int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type); =head1 DESCRIPTION @@ -111,6 +111,14 @@ Note that the hash algorithm used for subject name hashing changed in OpenSSL OpenSSL includes a L utility which creates symlinks with correct hashed names for all files with .pem suffix in a given directory. +=head1 RETURN VALUES + +X509_LOOKUP_hash_dir() and X509_LOOKUP_file() always return a valid +B structure. + +X509_load_cert_file(), X509_load_crl_file() and X509_load_cert_crl_file() return +the number of loaded objects or 0 on error. + =head1 SEE ALSO L, @@ -120,7 +128,7 @@ L, =head1 COPYRIGHT -Copyright 2015-2017 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2015-2018 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 diff --git a/doc/man3/X509_NAME_ENTRY_get_object.pod b/doc/man3/X509_NAME_ENTRY_get_object.pod new file mode 100644 index 00000000..5de1b88b --- /dev/null +++ b/doc/man3/X509_NAME_ENTRY_get_object.pod @@ -0,0 +1,99 @@ +=pod + +=head1 NAME + +X509_NAME_ENTRY_get_object, X509_NAME_ENTRY_get_data, +X509_NAME_ENTRY_set_object, X509_NAME_ENTRY_set_data, +X509_NAME_ENTRY_create_by_txt, X509_NAME_ENTRY_create_by_NID, +X509_NAME_ENTRY_create_by_OBJ - X509_NAME_ENTRY utility functions + +=head1 SYNOPSIS + + #include + + ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne); + ASN1_STRING *X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne); + + int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj); + int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type, + const unsigned char *bytes, int len); + + X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne, const char *field, + int type, const unsigned char *bytes, + int len); + X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid, + int type, const unsigned char *bytes, + int len); + X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne, + const ASN1_OBJECT *obj, int type, + const unsigned char *bytes, int len); + +=head1 DESCRIPTION + +X509_NAME_ENTRY_get_object() retrieves the field name of B in +and B structure. + +X509_NAME_ENTRY_get_data() retrieves the field value of B in +and B structure. + +X509_NAME_ENTRY_set_object() sets the field name of B to B. + +X509_NAME_ENTRY_set_data() sets the field value of B to string type +B and value determined by B and B. + +X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_NID() +and X509_NAME_ENTRY_create_by_OBJ() create and return an +B structure. + +=head1 NOTES + +X509_NAME_ENTRY_get_object() and X509_NAME_ENTRY_get_data() can be +used to examine an B function as returned by +X509_NAME_get_entry() for example. + +X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_NID(), +and X509_NAME_ENTRY_create_by_OBJ() create and return an + +X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_OBJ(), +X509_NAME_ENTRY_create_by_NID() and X509_NAME_ENTRY_set_data() +are seldom used in practice because B structures +are almost always part of B structures and the +corresponding B functions are typically used to +create and add new entries in a single operation. + +The arguments of these functions support similar options to the similarly +named ones of the corresponding B functions such as +X509_NAME_add_entry_by_txt(). So for example B can be set to +B but in the case of X509_set_data() the field name must be +set first so the relevant field information can be looked up internally. + +=head1 RETURN VALUES + +X509_NAME_ENTRY_get_object() returns a valid B structure if it is +set or NULL if an error occurred. + +X509_NAME_ENTRY_get_data() returns a valid B structure if it is set +or NULL if an error occurred. + +X509_NAME_ENTRY_set_object() and X509_NAME_ENTRY_set_data() return 1 on success +or 0 on error. + +X509_NAME_ENTRY_create_by_txt(), X509_NAME_ENTRY_create_by_NID() and +X509_NAME_ENTRY_create_by_OBJ() return a valid B on success or +NULL if an error occurred. + +=head1 SEE ALSO + +L, L, +L + +=head1 COPYRIGHT + +Copyright 2002-2018 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 +L. + +=cut diff --git a/doc/crypto/X509_NAME_add_entry_by_txt.pod b/doc/man3/X509_NAME_add_entry_by_txt.pod similarity index 87% rename from doc/crypto/X509_NAME_add_entry_by_txt.pod rename to doc/man3/X509_NAME_add_entry_by_txt.pod index 27e5baf8..b48f0908 100644 --- a/doc/crypto/X509_NAME_add_entry_by_txt.pod +++ b/doc/man3/X509_NAME_add_entry_by_txt.pod @@ -9,11 +9,14 @@ X509_NAME_add_entry, X509_NAME_delete_entry - X509_NAME modification functions #include - int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type, const unsigned char *bytes, int len, int loc, int set); + int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type, + const unsigned char *bytes, int len, int loc, int set); - int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type, const unsigned char *bytes, int len, int loc, int set); + int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type, + const unsigned char *bytes, int len, int loc, int set); - int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type, const unsigned char *bytes, int len, int loc, int set); + int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type, + const unsigned char *bytes, int len, int loc, int set); int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne, int loc, int set); @@ -78,18 +81,19 @@ Create an B structure: "C=UK, O=Disorganized Organization, CN=Joe Bloggs" X509_NAME *nm; + nm = X509_NAME_new(); if (nm == NULL) - /* Some error */ + /* Some error */ if (!X509_NAME_add_entry_by_txt(nm, "C", MBSTRING_ASC, - "UK", -1, -1, 0)) - /* Error */ + "UK", -1, -1, 0)) + /* Error */ if (!X509_NAME_add_entry_by_txt(nm, "O", MBSTRING_ASC, - "Disorganized Organization", -1, -1, 0)) - /* Error */ + "Disorganized Organization", -1, -1, 0)) + /* Error */ if (!X509_NAME_add_entry_by_txt(nm, "CN", MBSTRING_ASC, - "Joe Bloggs", -1, -1, 0)) - /* Error */ + "Joe Bloggs", -1, -1, 0)) + /* Error */ =head1 RETURN VALUES diff --git a/doc/crypto/X509_NAME_get0_der.pod b/doc/man3/X509_NAME_get0_der.pod similarity index 100% rename from doc/crypto/X509_NAME_get0_der.pod rename to doc/man3/X509_NAME_get0_der.pod diff --git a/doc/crypto/X509_NAME_get_index_by_NID.pod b/doc/man3/X509_NAME_get_index_by_NID.pod similarity index 88% rename from doc/crypto/X509_NAME_get_index_by_NID.pod rename to doc/man3/X509_NAME_get_index_by_NID.pod index 2d6713ba..5579dabb 100644 --- a/doc/crypto/X509_NAME_get_index_by_NID.pod +++ b/doc/man3/X509_NAME_get_index_by_NID.pod @@ -48,8 +48,9 @@ of space needed in B (excluding the final null) is returned. =head1 NOTES -X509_NAME_get_text_by_NID() and X509_NAME_get_text_by_OBJ() are -legacy functions which have various limitations which make them +X509_NAME_get_text_by_NID() and X509_NAME_get_text_by_OBJ() should be +considered deprecaated because they +have various limitations which make them of minimal use in practice. They can only find the first matching entry and will copy the contents of the field verbatim: this can be highly confusing if the target is a multicharacter string type @@ -75,25 +76,23 @@ Process all entries: int i; X509_NAME_ENTRY *e; - for (i = 0; i < X509_NAME_entry_count(nm); i++) - { - e = X509_NAME_get_entry(nm, i); - /* Do something with e */ - } + for (i = 0; i < X509_NAME_entry_count(nm); i++) { + e = X509_NAME_get_entry(nm, i); + /* Do something with e */ + } Process all commonName entries: int lastpos = -1; X509_NAME_ENTRY *e; - for (;;) - { - lastpos = X509_NAME_get_index_by_NID(nm, NID_commonName, lastpos); - if (lastpos == -1) - break; - e = X509_NAME_get_entry(nm, lastpos); - /* Do something with e */ - } + for (;;) { + lastpos = X509_NAME_get_index_by_NID(nm, NID_commonName, lastpos); + if (lastpos == -1) + break; + e = X509_NAME_get_entry(nm, lastpos); + /* Do something with e */ + } =head1 RETURN VALUES diff --git a/doc/crypto/X509_NAME_print_ex.pod b/doc/man3/X509_NAME_print_ex.pod similarity index 86% rename from doc/crypto/X509_NAME_print_ex.pod rename to doc/man3/X509_NAME_print_ex.pod index 3e9caa88..96be1ac8 100644 --- a/doc/crypto/X509_NAME_print_ex.pod +++ b/doc/man3/X509_NAME_print_ex.pod @@ -11,7 +11,7 @@ X509_NAME_oneline - X509_NAME printing routines int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent, unsigned long flags); int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent, unsigned long flags); - char * X509_NAME_oneline(const X509_NAME *a, char *buf, int size); + char *X509_NAME_oneline(const X509_NAME *a, char *buf, int size); int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase); =head1 DESCRIPTION @@ -35,10 +35,11 @@ characters. Multiple lines are used if the output (including indent) exceeds =head1 NOTES -The functions X509_NAME_oneline() and X509_NAME_print() are legacy functions which +The functions X509_NAME_oneline() and X509_NAME_print() produce a non standard output form, they don't handle multi character fields and -have various quirks and inconsistencies. Their use is strongly discouraged in new -applications. +have various quirks and inconsistencies. +Their use is strongly discouraged in new applications and they could +be deprecated in a future release. Although there are a large number of possible flags for most purposes B, B or B will suffice. @@ -96,13 +97,23 @@ B is a multiline format which is the same as: B uses a format identical to X509_NAME_print(): in fact it calls X509_NAME_print() internally. +=head1 RETURN VALUES + +X509_NAME_oneline() returns a valid string on success or NULL on error. + +X509_NAME_print() returns 1 on success or 0 on error. + +X509_NAME_print_ex() and X509_NAME_print_ex_fp() return 1 on success or 0 on error +if the B is set, which is the same as X509_NAME_print(). Otherwise, +it returns -1 on error or other values on success. + =head1 SEE ALSO L =head1 COPYRIGHT -Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2002-2018 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 diff --git a/doc/crypto/X509_PUBKEY_new.pod b/doc/man3/X509_PUBKEY_new.pod similarity index 100% rename from doc/crypto/X509_PUBKEY_new.pod rename to doc/man3/X509_PUBKEY_new.pod diff --git a/doc/crypto/X509_SIG_get0.pod b/doc/man3/X509_SIG_get0.pod similarity index 86% rename from doc/crypto/X509_SIG_get0.pod rename to doc/man3/X509_SIG_get0.pod index d24eadcd..bbf37230 100644 --- a/doc/crypto/X509_SIG_get0.pod +++ b/doc/man3/X509_SIG_get0.pod @@ -20,13 +20,17 @@ value in B. X509_SIG_getm() is identical to X509_SIG_get0() except the pointers returned are not constant and can be modified: for example to initialise them. +=head1 RETURN VALUES + +X509_SIG_get0() and X509_SIG_getm() return no values. + =head1 SEE ALSO L =head1 COPYRIGHT -Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2002-2018 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 diff --git a/doc/crypto/X509_STORE_CTX_get_error.pod b/doc/man3/X509_STORE_CTX_get_error.pod similarity index 99% rename from doc/crypto/X509_STORE_CTX_get_error.pod rename to doc/man3/X509_STORE_CTX_get_error.pod index 105e051a..f166b083 100644 --- a/doc/crypto/X509_STORE_CTX_get_error.pod +++ b/doc/man3/X509_STORE_CTX_get_error.pod @@ -70,7 +70,7 @@ is B successful the returned chain may be incomplete or invalid. The returned chain persists after the B structure is freed, when it is no longer needed it should be free up using: - sk_X509_pop_free(chain, X509_free); + sk_X509_pop_free(chain, X509_free); X509_verify_cert_error_string() returns a human readable error string for verification error B. diff --git a/doc/crypto/X509_STORE_CTX_new.pod b/doc/man3/X509_STORE_CTX_new.pod similarity index 100% rename from doc/crypto/X509_STORE_CTX_new.pod rename to doc/man3/X509_STORE_CTX_new.pod diff --git a/doc/man3/X509_STORE_CTX_set_verify_cb.pod b/doc/man3/X509_STORE_CTX_set_verify_cb.pod new file mode 100644 index 00000000..5688ab79 --- /dev/null +++ b/doc/man3/X509_STORE_CTX_set_verify_cb.pod @@ -0,0 +1,211 @@ +=pod + +=head1 NAME + +X509_STORE_CTX_get_cleanup, +X509_STORE_CTX_get_lookup_crls, +X509_STORE_CTX_get_lookup_certs, +X509_STORE_CTX_get_check_policy, +X509_STORE_CTX_get_cert_crl, +X509_STORE_CTX_get_check_crl, +X509_STORE_CTX_get_get_crl, +X509_STORE_CTX_get_check_revocation, +X509_STORE_CTX_get_check_issued, +X509_STORE_CTX_get_get_issuer, +X509_STORE_CTX_get_verify_cb, +X509_STORE_CTX_set_verify_cb, +X509_STORE_CTX_verify_cb +- get and set verification callback + +=head1 SYNOPSIS + + #include + + typedef int (*X509_STORE_CTX_verify_cb)(int, X509_STORE_CTX *); + + X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(X509_STORE_CTX *ctx); + + void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx, + X509_STORE_CTX_verify_cb verify_cb); + + X509_STORE_CTX_get_issuer_fn X509_STORE_CTX_get_get_issuer(X509_STORE_CTX *ctx); + X509_STORE_CTX_check_issued_fn X509_STORE_CTX_get_check_issued(X509_STORE_CTX *ctx); + X509_STORE_CTX_check_revocation_fn X509_STORE_CTX_get_check_revocation(X509_STORE_CTX *ctx); + X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(X509_STORE_CTX *ctx); + X509_STORE_CTX_check_crl_fn X509_STORE_CTX_get_check_crl(X509_STORE_CTX *ctx); + X509_STORE_CTX_cert_crl_fn X509_STORE_CTX_get_cert_crl(X509_STORE_CTX *ctx); + X509_STORE_CTX_check_policy_fn X509_STORE_CTX_get_check_policy(X509_STORE_CTX *ctx); + X509_STORE_CTX_lookup_certs_fn X509_STORE_CTX_get_lookup_certs(X509_STORE_CTX *ctx); + X509_STORE_CTX_lookup_crls_fn X509_STORE_CTX_get_lookup_crls(X509_STORE_CTX *ctx); + X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(X509_STORE_CTX *ctx); + +=head1 DESCRIPTION + +X509_STORE_CTX_set_verify_cb() sets the verification callback of B to +B overwriting any existing callback. + +The verification callback can be used to customise the operation of certificate +verification, either by overriding error conditions or logging errors for +debugging purposes. + +However a verification callback is B essential and the default operation +is often sufficient. + +The B parameter to the callback indicates the value the callback should +return to retain the default behaviour. If it is zero then an error condition +is indicated. If it is 1 then no error occurred. If the flag +B is set then B is set to 2 to indicate the +policy checking is complete. + +The B parameter to the callback is the B structure that +is performing the verification operation. A callback can examine this +structure and receive additional information about the error, for example +by calling X509_STORE_CTX_get_current_cert(). Additional application data can +be passed to the callback via the B mechanism. + +X509_STORE_CTX_get_verify_cb() returns the value of the current callback +for the specific B. + +X509_STORE_CTX_get_get_issuer(), +X509_STORE_CTX_get_check_issued(), X509_STORE_CTX_get_check_revocation(), +X509_STORE_CTX_get_get_crl(), X509_STORE_CTX_get_check_crl(), +X509_STORE_CTX_get_cert_crl(), X509_STORE_CTX_get_check_policy(), +X509_STORE_CTX_get_lookup_certs(), X509_STORE_CTX_get_lookup_crls() +and X509_STORE_CTX_get_cleanup() return the function pointers cached +from the corresponding B, please see +L for more information. + + +=head1 WARNING + +In general a verification callback should B unconditionally return 1 in +all circumstances because this will allow verification to succeed no matter +what the error. This effectively removes all security from the application +because B certificate (including untrusted generated ones) will be +accepted. + +=head1 NOTES + +The verification callback can be set and inherited from the parent structure +performing the operation. In some cases (such as S/MIME verification) the +B structure is created and destroyed internally and the +only way to set a custom verification callback is by inheriting it from the +associated B. + +=head1 RETURN VALUES + +X509_STORE_CTX_set_verify_cb() does not return a value. + +=head1 EXAMPLES + +Default callback operation: + + int verify_callback(int ok, X509_STORE_CTX *ctx) { + return ok; + } + +Simple example, suppose a certificate in the chain is expired and we wish +to continue after this error: + + int verify_callback(int ok, X509_STORE_CTX *ctx) { + /* Tolerate certificate expiration */ + if (X509_STORE_CTX_get_error(ctx) == X509_V_ERR_CERT_HAS_EXPIRED) + return 1; + /* Otherwise don't override */ + return ok; + } + +More complex example, we don't wish to continue after B certificate has +expired just one specific case: + + int verify_callback(int ok, X509_STORE_CTX *ctx) + { + int err = X509_STORE_CTX_get_error(ctx); + X509 *err_cert = X509_STORE_CTX_get_current_cert(ctx); + + if (err == X509_V_ERR_CERT_HAS_EXPIRED) { + if (check_is_acceptable_expired_cert(err_cert) + return 1; + } + return ok; + } + +Full featured logging callback. In this case the B is assumed to be +a global logging B, an alternative would to store a BIO in B using +B. + + int verify_callback(int ok, X509_STORE_CTX *ctx) + { + X509 *err_cert; + int err, depth; + + err_cert = X509_STORE_CTX_get_current_cert(ctx); + err = X509_STORE_CTX_get_error(ctx); + depth = X509_STORE_CTX_get_error_depth(ctx); + + BIO_printf(bio_err, "depth=%d ", depth); + if (err_cert) { + X509_NAME_print_ex(bio_err, X509_get_subject_name(err_cert), + 0, XN_FLAG_ONELINE); + BIO_puts(bio_err, "\n"); + } + else + BIO_puts(bio_err, "\n"); + if (!ok) + BIO_printf(bio_err, "verify error:num=%d:%s\n", err, + X509_verify_cert_error_string(err)); + switch (err) { + case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: + BIO_puts(bio_err, "issuer= "); + X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert), + 0, XN_FLAG_ONELINE); + BIO_puts(bio_err, "\n"); + break; + case X509_V_ERR_CERT_NOT_YET_VALID: + case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: + BIO_printf(bio_err, "notBefore="); + ASN1_TIME_print(bio_err, X509_get_notBefore(err_cert)); + BIO_printf(bio_err, "\n"); + break; + case X509_V_ERR_CERT_HAS_EXPIRED: + case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: + BIO_printf(bio_err, "notAfter="); + ASN1_TIME_print(bio_err, X509_get_notAfter(err_cert)); + BIO_printf(bio_err, "\n"); + break; + case X509_V_ERR_NO_EXPLICIT_POLICY: + policies_print(bio_err, ctx); + break; + } + if (err == X509_V_OK && ok == 2) + /* print out policies */ + + BIO_printf(bio_err, "verify return:%d\n", ok); + return(ok); + } + +=head1 SEE ALSO + +L +L +L + +=head1 HISTORY + +X509_STORE_CTX_get_get_issuer(), +X509_STORE_CTX_get_check_issued(), X509_STORE_CTX_get_check_revocation(), +X509_STORE_CTX_get_get_crl(), X509_STORE_CTX_get_check_crl(), +X509_STORE_CTX_get_cert_crl(), X509_STORE_CTX_get_check_policy(), +X509_STORE_CTX_get_lookup_certs(), X509_STORE_CTX_get_lookup_crls() +and X509_STORE_CTX_get_cleanup() were added in OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2009-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 +L. + +=cut diff --git a/doc/crypto/X509_STORE_get0_param.pod b/doc/man3/X509_STORE_get0_param.pod similarity index 100% rename from doc/crypto/X509_STORE_get0_param.pod rename to doc/man3/X509_STORE_get0_param.pod diff --git a/doc/crypto/X509_STORE_new.pod b/doc/man3/X509_STORE_new.pod similarity index 100% rename from doc/crypto/X509_STORE_new.pod rename to doc/man3/X509_STORE_new.pod diff --git a/doc/crypto/X509_STORE_set_verify_cb_func.pod b/doc/man3/X509_STORE_set_verify_cb_func.pod similarity index 100% rename from doc/crypto/X509_STORE_set_verify_cb_func.pod rename to doc/man3/X509_STORE_set_verify_cb_func.pod diff --git a/doc/crypto/X509_VERIFY_PARAM_set_flags.pod b/doc/man3/X509_VERIFY_PARAM_set_flags.pod similarity index 96% rename from doc/crypto/X509_VERIFY_PARAM_set_flags.pod rename to doc/man3/X509_VERIFY_PARAM_set_flags.pod index 5263facf..825f7601 100644 --- a/doc/crypto/X509_VERIFY_PARAM_set_flags.pod +++ b/doc/man3/X509_VERIFY_PARAM_set_flags.pod @@ -37,15 +37,15 @@ X509_VERIFY_PARAM_set1_ip_asc time_t X509_VERIFY_PARAM_get_time(const X509_VERIFY_PARAM *param); int X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param, - ASN1_OBJECT *policy); + ASN1_OBJECT *policy); int X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param, - STACK_OF(ASN1_OBJECT) *policies); + 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); void X509_VERIFY_PARAM_set_auth_level(X509_VERIFY_PARAM *param, - int auth_level); + int auth_level); int X509_VERIFY_PARAM_get_auth_level(const X509_VERIFY_PARAM *param); int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param, @@ -56,7 +56,7 @@ X509_VERIFY_PARAM_set1_ip_asc 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); + 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); @@ -309,8 +309,9 @@ of ORed. =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(). +instead of functions which work in specific structures such as +X509_STORE_CTX_set_flags() which are likely to be deprecated in a future +release. =head1 BUGS @@ -327,11 +328,12 @@ CRLs from the CRL distribution points extension. Enable CRL checking when performing certificate verification during SSL connections associated with an B structure B: - 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); + 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 @@ -344,7 +346,7 @@ L =head1 HISTORY The B flag was added in OpenSSL 1.1.0 -The legacy B flag is deprecated as of +The flag B was deprecated in OpenSSL 1.1.0, and has no effect. =head1 COPYRIGHT diff --git a/doc/crypto/X509_check_ca.pod b/doc/man3/X509_check_ca.pod similarity index 87% rename from doc/crypto/X509_check_ca.pod rename to doc/man3/X509_check_ca.pod index b79efb5b..38f0811d 100644 --- a/doc/crypto/X509_check_ca.pod +++ b/doc/man3/X509_check_ca.pod @@ -6,16 +6,16 @@ X509_check_ca - check if given certificate is CA certificate =head1 SYNOPSIS - #include + #include - int X509_check_ca(X509 *cert); + int X509_check_ca(X509 *cert); =head1 DESCRIPTION This function checks if given certificate is CA certificate (can be used to sign other certificates). -=head1 RETURN VALUE +=head1 RETURN VALUES Function return 0, if it is not CA certificate, 1 if it is proper X509v3 CA certificate with B extension CA:TRUE, @@ -35,7 +35,7 @@ L =head1 COPYRIGHT -Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2015-2018 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 diff --git a/doc/crypto/X509_check_host.pod b/doc/man3/X509_check_host.pod similarity index 98% rename from doc/crypto/X509_check_host.pod rename to doc/man3/X509_check_host.pod index 93848152..7b96b7c8 100644 --- a/doc/crypto/X509_check_host.pod +++ b/doc/man3/X509_check_host.pod @@ -6,7 +6,7 @@ X509_check_host, X509_check_email, X509_check_ip, X509_check_ip_asc - X.509 cert =head1 SYNOPSIS - #include + #include int X509_check_host(X509 *, const char *name, size_t namelen, unsigned int flags, char **peername); @@ -147,7 +147,7 @@ These functions were added in OpenSSL 1.0.2. =head1 COPYRIGHT -Copyright 2012-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2012-2018 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 diff --git a/doc/crypto/X509_check_issued.pod b/doc/man3/X509_check_issued.pod similarity index 92% rename from doc/crypto/X509_check_issued.pod rename to doc/man3/X509_check_issued.pod index 8e4b1117..f9a541ef 100644 --- a/doc/crypto/X509_check_issued.pod +++ b/doc/man3/X509_check_issued.pod @@ -22,7 +22,7 @@ B of I if B present in the I certificate and checks B field of I. -=head1 RETURN VALUE +=head1 RETURN VALUES Function return B if certificate I is issued by I or some B constant to indicate an error. @@ -35,7 +35,7 @@ L =head1 COPYRIGHT -Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2015-2018 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 diff --git a/doc/man3/X509_check_private_key.pod b/doc/man3/X509_check_private_key.pod new file mode 100644 index 00000000..4735dfd5 --- /dev/null +++ b/doc/man3/X509_check_private_key.pod @@ -0,0 +1,54 @@ +=pod + +=head1 NAME + +X509_check_private_key, X509_REQ_check_private_key - check the consistency +of a private key with the public key in an X509 certificate or certificate +request + +=head1 SYNOPSIS + + #include + + int X509_check_private_key(X509 *x, EVP_PKEY *k); + + int X509_REQ_check_private_key(X509_REQ *x, EVP_PKEY *k); + +=head1 DESCRIPTION + +X509_check_private_key() function checks the consistency of private +key B with the public key in B. + +X509_REQ_check_private_key() is equivalent to X509_check_private_key() +except that B represents a certificate request of structure B. + +=head1 RETURN VALUES + +X509_check_private_key() and X509_REQ_check_private_key() return 1 if +the keys match each other, and 0 if not. + +If the key is invalid or an error occurred, the reason code can be +obtained using L. + +=head1 BUGS + +The B functions don't check if B itself is indeed +a private key or not. It merely compares the public materials (e.g. exponent +and modulus of an RSA key) and/or key parameters (e.g. EC params of an EC key) +of a key pair. So if you pass a public key to these functions in B, it will +return success. + +=head1 SEE ALSO + +L + +=head1 COPYRIGHT + +Copyright 2017-2018 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 +L. + +=cut diff --git a/doc/man3/X509_cmp_time.pod b/doc/man3/X509_cmp_time.pod new file mode 100644 index 00000000..911814ed --- /dev/null +++ b/doc/man3/X509_cmp_time.pod @@ -0,0 +1,61 @@ +=pod + +=head1 NAME + +X509_cmp_time, X509_cmp_current_time, X509_time_adj, X509_time_adj_ex +- X509 time functions + +=head1 SYNOPSIS + + int X509_cmp_time(const ASN1_TIME *asn1_time, time_t *in_tm); + int X509_cmp_current_time(const ASN1_TIME *asn1_time); + ASN1_TIME *X509_time_adj(ASN1_TIME *asn1_time, long offset_sec, time_t *in_tm); + ASN1_TIME *X509_time_adj_ex(ASN1_TIME *asn1_time, int offset_day, long + offset_sec, time_t *in_tm); + +=head1 DESCRIPTION + +X509_cmp_time() compares the ASN1_TIME in B with the time +in . X509_cmp_current_time() compares the ASN1_TIME in +B with the current time, expressed as time_t. B +must satisfy the ASN1_TIME format mandated by RFC 5280, i.e., its +format must be either YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ. + +X509_time_adj_ex() sets the ASN1_TIME structure B to the time +B and B after B. + +X509_time_adj() sets the ASN1_TIME structure B to the time +B after B. This method can only handle second +offsets up to the capacity of long, so the newer X509_time_adj_ex() +API should be preferred. + +In both methods, if B is NULL, a new ASN1_TIME structure +is allocated and returned. + +In all methods, if B is NULL, the current time, expressed as +time_t, is used. + +=head1 BUGS + +Unlike many standard comparison functions, X509_cmp_time() and +X509_cmp_current_time() return 0 on error. + +=head1 RETURN VALUES + +X509_cmp_time() and X509_cmp_current_time() return -1 if B +is earlier than, or equal to, B (resp. current time), and 1 +otherwise. These methods return 0 on error. + +X509_time_ad() and X509_time_adj_ex() return a pointer to the updated +ASN1_TIME structure, and NULL on error. + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/crypto/X509_digest.pod b/doc/man3/X509_digest.pod similarity index 98% rename from doc/crypto/X509_digest.pod rename to doc/man3/X509_digest.pod index 3c76c8fd..ee393450 100644 --- a/doc/crypto/X509_digest.pod +++ b/doc/man3/X509_digest.pod @@ -17,7 +17,7 @@ PKCS7_ISSUER_AND_SERIAL_digest unsigned int *len); int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type, unsigned char *md, - unsigned int *len); + unsigned int *len); int X509_pubkey_digest(const X509 *data, const EVP_MD *type, unsigned char *md, unsigned int *len); diff --git a/doc/crypto/X509_dup.pod b/doc/man3/X509_dup.pod similarity index 95% rename from doc/crypto/X509_dup.pod rename to doc/man3/X509_dup.pod index c5d01b28..4f982089 100644 --- a/doc/crypto/X509_dup.pod +++ b/doc/man3/X509_dup.pod @@ -7,6 +7,10 @@ IMPLEMENT_ASN1_FUNCTIONS, ASN1_ITEM, ACCESS_DESCRIPTION_free, ACCESS_DESCRIPTION_new, +ADMISSIONS_free, +ADMISSIONS_new, +ADMISSION_SYNTAX_free, +ADMISSION_SYNTAX_new, ASIdOrRange_free, ASIdOrRange_new, ASIdentifierChoice_free, @@ -75,6 +79,8 @@ ISSUING_DIST_POINT_free, ISSUING_DIST_POINT_new, NAME_CONSTRAINTS_free, NAME_CONSTRAINTS_new, +NAMING_AUTHORITY_free, +NAMING_AUTHORITY_new, NETSCAPE_CERT_SEQUENCE_free, NETSCAPE_CERT_SEQUENCE_new, NETSCAPE_SPKAC_free, @@ -160,6 +166,10 @@ POLICY_CONSTRAINTS_free, POLICY_CONSTRAINTS_new, POLICY_MAPPING_free, POLICY_MAPPING_new, +PROFESSION_INFO_free, +PROFESSION_INFO_new, +PROFESSION_INFOS_free, +PROFESSION_INFOS_new, PROXY_CERT_INFO_EXTENSION_free, PROXY_CERT_INFO_EXTENSION_new, PROXY_POLICY_free, @@ -170,7 +180,8 @@ RSA_OAEP_PARAMS_free, RSA_OAEP_PARAMS_new, RSA_PSS_PARAMS_free, RSA_PSS_PARAMS_new, -SCT_LIST_free, +SCRYPT_PARAMS_free, +SCRYPT_PARAMS_new, SXNETID_free, SXNETID_new, SXNET_free, @@ -235,10 +246,10 @@ X509_VAL_new, X509_dup, - ASN1 object utilities -=for comment generic - =head1 SYNOPSIS +=for comment generic + #include DECLARE_ASN1_FUNCTIONS(type) @@ -293,7 +304,7 @@ TYPE_print_ctx() returns 1 on success or zero on failure. =head1 COPYRIGHT -Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2016-2018 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 diff --git a/doc/crypto/X509_get0_notBefore.pod b/doc/man3/X509_get0_notBefore.pod similarity index 100% rename from doc/crypto/X509_get0_notBefore.pod rename to doc/man3/X509_get0_notBefore.pod diff --git a/doc/man3/X509_get0_signature.pod b/doc/man3/X509_get0_signature.pod new file mode 100644 index 00000000..f63c5a5b --- /dev/null +++ b/doc/man3/X509_get0_signature.pod @@ -0,0 +1,128 @@ +=pod + +=head1 NAME + +X509_get0_signature, X509_get_signature_nid, X509_get0_tbs_sigalg, +X509_REQ_get0_signature, X509_REQ_get_signature_nid, X509_CRL_get0_signature, +X509_CRL_get_signature_nid, X509_get_signature_info, X509_SIG_INFO_get, +X509_SIG_INFO_set - signature information + +=head1 SYNOPSIS + + #include + + void X509_get0_signature(const ASN1_BIT_STRING **psig, + const X509_ALGOR **palg, + const X509 *x); + int X509_get_signature_nid(const X509 *x); + const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x); + + void X509_REQ_get0_signature(const X509_REQ *crl, + const ASN1_BIT_STRING **psig, + const X509_ALGOR **palg); + int X509_REQ_get_signature_nid(const X509_REQ *crl); + + void X509_CRL_get0_signature(const X509_CRL *crl, + const ASN1_BIT_STRING **psig, + const X509_ALGOR **palg); + int X509_CRL_get_signature_nid(const X509_CRL *crl); + + int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits, + uint32_t *flags); + + int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid, + int *secbits, uint32_t *flags); + void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid, + int secbits, uint32_t flags); + +=head1 DESCRIPTION + +X509_get0_signature() sets B<*psig> to the signature of B and B<*palg> +to the signature algorithm of B. The values returned are internal +pointers which B be freed up after the call. + +X509_get0_tbs_sigalg() returns the signature algorithm in the signed +portion of B. + +X509_get_signature_nid() returns the NID corresponding to the signature +algorithm of B. + +X509_REQ_get0_signature(), X509_REQ_get_signature_nid() +X509_CRL_get0_signature() and X509_CRL_get_signature_nid() perform the +same function for certificate requests and CRLs. + +X509_get_signature_info() retrieves information about the signature of +certificate B. The NID of the signing digest is written to B<*mdnid>, +the public key algorithm to B<*pknid>, the effective security bits to +B<*secbits> and flag details to B<*flags>. Any of the parameters can +be set to B if the information is not required. + +X509_SIG_INFO_get() and X509_SIG_INFO_set() get and set information +about a signature in an B structure. They are only +used by implementations of algorithms which need to set custom +signature information: most applications will never need to call +them. + +=head1 NOTES + +These functions provide lower level access to signatures in certificates +where an application wishes to analyse or generate a signature in a form +where X509_sign() et al is not appropriate (for example a non standard +or unsupported format). + +The security bits returned by X509_get_signature_info() refers to information +available from the certificate signature (such as the signing digest). In some +cases the actual security of the signature is less because the signing +key is less secure: for example a certificate signed using SHA-512 and a +1024 bit RSA key. + +=head1 RETURN VALUES + +X509_get_signature_nid(), X509_REQ_get_signature_nid() and +X509_CRL_get_signature_nid() return a NID. + +X509_get0_signature(), X509_REQ_get0_signature() and +X509_CRL_get0_signature() do not return values. + +X509_get_signature_info() returns 1 if the signature information +returned is valid or 0 if the information is not available (e.g. +unknown algorithms or malformed parameters). + +=head1 SEE ALSO + +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L + +=head1 HISTORY + +X509_get0_signature() and X509_get_signature_nid() were first added to +OpenSSL 1.0.2. + +X509_REQ_get0_signature(), X509_REQ_get_signature_nid(), +X509_CRL_get0_signature() and X509_CRL_get_signature_nid() were first added +to OpenSSL 1.1.0. + +=head1 COPYRIGHT + +Copyright 2015-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 +L. + +=cut diff --git a/doc/crypto/X509_get0_uids.pod b/doc/man3/X509_get0_uids.pod similarity index 100% rename from doc/crypto/X509_get0_uids.pod rename to doc/man3/X509_get0_uids.pod diff --git a/doc/crypto/X509_get_extension_flags.pod b/doc/man3/X509_get_extension_flags.pod similarity index 92% rename from doc/crypto/X509_get_extension_flags.pod rename to doc/man3/X509_get_extension_flags.pod index c07ef972..fc4ebbb3 100644 --- a/doc/crypto/X509_get_extension_flags.pod +++ b/doc/man3/X509_get_extension_flags.pod @@ -14,17 +14,17 @@ X509_get_proxy_pathlen - retrieve certificate extension data =head1 SYNOPSIS - #include + #include - long X509_get_pathlen(X509 *x); - uint32_t X509_get_extension_flags(X509 *x); - uint32_t X509_get_key_usage(X509 *x); - uint32_t X509_get_extended_key_usage(X509 *x); - const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x); - const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x); - void X509_set_proxy_flag(X509 *x); - void X509_set_proxy_pathlen(int l); - long X509_get_proxy_pathlen(X509 *x); + long X509_get_pathlen(X509 *x); + uint32_t X509_get_extension_flags(X509 *x); + uint32_t X509_get_key_usage(X509 *x); + uint32_t X509_get_extended_key_usage(X509 *x); + const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x); + const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x); + void X509_set_proxy_flag(X509 *x); + void X509_set_proxy_pathlen(int l); + long X509_get_proxy_pathlen(X509 *x); =head1 DESCRIPTION @@ -144,7 +144,7 @@ If X509_get0_subject_key_id() returns B then the extension may be absent or malformed. Applications can determine the precise reason using X509_get_ext_d2i(). -=head1 RETURN VALUE +=head1 RETURN VALUES X509_get_pathlen() returns the path length value, or -1 if the extension is not present. diff --git a/doc/crypto/X509_get_pubkey.pod b/doc/man3/X509_get_pubkey.pod similarity index 100% rename from doc/crypto/X509_get_pubkey.pod rename to doc/man3/X509_get_pubkey.pod diff --git a/doc/crypto/X509_get_serialNumber.pod b/doc/man3/X509_get_serialNumber.pod similarity index 100% rename from doc/crypto/X509_get_serialNumber.pod rename to doc/man3/X509_get_serialNumber.pod diff --git a/doc/crypto/X509_get_subject_name.pod b/doc/man3/X509_get_subject_name.pod similarity index 97% rename from doc/crypto/X509_get_subject_name.pod rename to doc/man3/X509_get_subject_name.pod index ce36bbf0..2107c1d0 100644 --- a/doc/crypto/X509_get_subject_name.pod +++ b/doc/man3/X509_get_subject_name.pod @@ -37,7 +37,7 @@ X509_get_subject_name() and X509_set_subject_name() except the get and set the issuer name of B. Similarly X509_REQ_get_subject_name(), X509_REQ_set_subject_name(), - X509_CRL_get_issuer() and X509_CRL_set_issuer_name() get or set the subject +X509_CRL_get_issuer() and X509_CRL_set_issuer_name() get or set the subject or issuer names of certificate requests of CRLs respectively. =head1 RETURN VALUES diff --git a/doc/crypto/X509_get_version.pod b/doc/man3/X509_get_version.pod similarity index 100% rename from doc/crypto/X509_get_version.pod rename to doc/man3/X509_get_version.pod diff --git a/doc/crypto/X509_new.pod b/doc/man3/X509_new.pod similarity index 100% rename from doc/crypto/X509_new.pod rename to doc/man3/X509_new.pod diff --git a/doc/crypto/X509_sign.pod b/doc/man3/X509_sign.pod similarity index 100% rename from doc/crypto/X509_sign.pod rename to doc/man3/X509_sign.pod diff --git a/doc/crypto/X509_verify_cert.pod b/doc/man3/X509_verify_cert.pod similarity index 100% rename from doc/crypto/X509_verify_cert.pod rename to doc/man3/X509_verify_cert.pod diff --git a/doc/crypto/X509v3_get_ext_by_NID.pod b/doc/man3/X509v3_get_ext_by_NID.pod similarity index 99% rename from doc/crypto/X509v3_get_ext_by_NID.pod rename to doc/man3/X509v3_get_ext_by_NID.pod index 032f71c4..81c938e9 100644 --- a/doc/crypto/X509v3_get_ext_by_NID.pod +++ b/doc/man3/X509v3_get_ext_by_NID.pod @@ -50,7 +50,7 @@ X509_REVOKED_add_ext - extension stack utility functions X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc); int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos); int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj, - int lastpos); + int lastpos); int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit, int lastpos); X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc); int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc); diff --git a/doc/man3/d2i_DHparams.pod b/doc/man3/d2i_DHparams.pod new file mode 100644 index 00000000..d4e34fe8 --- /dev/null +++ b/doc/man3/d2i_DHparams.pod @@ -0,0 +1,42 @@ +=pod + +=head1 NAME + +d2i_DHparams, i2d_DHparams - PKCS#3 DH parameter functions + +=head1 SYNOPSIS + + #include + + DH *d2i_DHparams(DH **a, unsigned char **pp, long length); + int i2d_DHparams(DH *a, unsigned char **pp); + +=head1 DESCRIPTION + +These functions decode and encode PKCS#3 DH parameters using the +DHparameter structure described in PKCS#3. + +Otherwise these behave in a similar way to d2i_X509() and i2d_X509() +described in the L manual page. + +=head1 RETURN VALUES + +d2i_DHparams() returns a valid B structure or NULL if an error occurred. + +i2d_DHparams() returns the length of encoded data on success or a value which +is less than or equal to 0 on error. + +=head1 SEE ALSO + +L + +=head1 COPYRIGHT + +Copyright 2000-2018 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 +L. + +=cut diff --git a/doc/man3/d2i_PKCS8PrivateKey_bio.pod b/doc/man3/d2i_PKCS8PrivateKey_bio.pod new file mode 100644 index 00000000..cc588dfc --- /dev/null +++ b/doc/man3/d2i_PKCS8PrivateKey_bio.pod @@ -0,0 +1,69 @@ +=pod + +=head1 NAME + +d2i_PKCS8PrivateKey_bio, d2i_PKCS8PrivateKey_fp, +i2d_PKCS8PrivateKey_bio, i2d_PKCS8PrivateKey_fp, +i2d_PKCS8PrivateKey_nid_bio, i2d_PKCS8PrivateKey_nid_fp - PKCS#8 format private key functions + +=head1 SYNOPSIS + + #include + + EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u); + EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u); + + int i2d_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, + char *kstr, int klen, + pem_password_cb *cb, void *u); + + int i2d_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, + char *kstr, int klen, + pem_password_cb *cb, void *u); + + int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, EVP_PKEY *x, int nid, + char *kstr, int klen, + pem_password_cb *cb, void *u); + + int i2d_PKCS8PrivateKey_nid_fp(FILE *fp, EVP_PKEY *x, int nid, + char *kstr, int klen, + pem_password_cb *cb, void *u); + +=head1 DESCRIPTION + +The PKCS#8 functions encode and decode private keys in PKCS#8 format using both +PKCS#5 v1.5 and PKCS#5 v2.0 password based encryption algorithms. + +Other than the use of DER as opposed to PEM these functions are identical to the +corresponding B function as described in L. + +=head1 NOTES + +These functions are currently the only way to store encrypted private keys using DER format. + +Currently all the functions use BIOs or FILE pointers, there are no functions which +work directly on memory: this can be readily worked around by converting the buffers +to memory BIOs, see L for details. + +=head1 RETURN VALUES + +d2i_PKCS8PrivateKey_bio() and d2i_PKCS8PrivateKey_fp() return a valid B +structure or NULL if an error occurred. + +i2d_PKCS8PrivateKey_bio(), i2d_PKCS8PrivateKey_fp(), i2d_PKCS8PrivateKey_nid_bio() +and i2d_PKCS8PrivateKey_nid_fp() return 1 on success or 0 on error. + +=head1 SEE ALSO + +L + +=head1 COPYRIGHT + +Copyright 2002-2018 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 +L. + +=cut diff --git a/doc/crypto/d2i_PrivateKey.pod b/doc/man3/d2i_PrivateKey.pod similarity index 100% rename from doc/crypto/d2i_PrivateKey.pod rename to doc/man3/d2i_PrivateKey.pod diff --git a/doc/ssl/d2i_SSL_SESSION.pod b/doc/man3/d2i_SSL_SESSION.pod similarity index 94% rename from doc/ssl/d2i_SSL_SESSION.pod rename to doc/man3/d2i_SSL_SESSION.pod index d6b17071..68ed302d 100644 --- a/doc/ssl/d2i_SSL_SESSION.pod +++ b/doc/man3/d2i_SSL_SESSION.pod @@ -8,7 +8,8 @@ d2i_SSL_SESSION, i2d_SSL_SESSION - convert SSL_SESSION object from/to ASN1 repre #include - SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp, long length); + SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp, + long length); int i2d_SSL_SESSION(SSL_SESSION *in, unsigned char **pp); =head1 DESCRIPTION @@ -33,7 +34,7 @@ When the session is not valid, B<0> is returned and no operation is performed. =head1 SEE ALSO -L, L, +L, L, L, L diff --git a/doc/crypto/d2i_X509.pod b/doc/man3/d2i_X509.pod similarity index 98% rename from doc/crypto/d2i_X509.pod rename to doc/man3/d2i_X509.pod index 1fbe5cad..80c5c9dd 100644 --- a/doc/crypto/d2i_X509.pod +++ b/doc/man3/d2i_X509.pod @@ -3,6 +3,8 @@ =head1 NAME d2i_ACCESS_DESCRIPTION, +d2i_ADMISSIONS, +d2i_ADMISSION_SYNTAX, d2i_ASIdOrRange, d2i_ASIdentifierChoice, d2i_ASIdentifiers, @@ -71,6 +73,7 @@ d2i_IPAddressFamily, d2i_IPAddressOrRange, d2i_IPAddressRange, d2i_ISSUING_DIST_POINT, +d2i_NAMING_AUTHORITY, d2i_NETSCAPE_CERT_SEQUENCE, d2i_NETSCAPE_SPKAC, d2i_NETSCAPE_SPKI, @@ -120,6 +123,7 @@ d2i_PKCS8_fp, d2i_PKEY_USAGE_PERIOD, d2i_POLICYINFO, d2i_POLICYQUALINFO, +d2i_PROFESSION_INFO, d2i_PROXY_CERT_INFO_EXTENSION, d2i_PROXY_POLICY, d2i_RSAPrivateKey, @@ -133,6 +137,7 @@ d2i_RSA_PSS_PARAMS, d2i_RSA_PUBKEY, d2i_RSA_PUBKEY_bio, d2i_RSA_PUBKEY_fp, +d2i_SCRYPT_PARAMS, d2i_SCT_LIST, d2i_SXNET, d2i_SXNETID, @@ -174,6 +179,8 @@ d2i_X509_REVOKED, d2i_X509_SIG, d2i_X509_VAL, i2d_ACCESS_DESCRIPTION, +i2d_ADMISSIONS, +i2d_ADMISSION_SYNTAX, i2d_ASIdOrRange, i2d_ASIdentifierChoice, i2d_ASIdentifiers, @@ -242,6 +249,7 @@ i2d_IPAddressFamily, i2d_IPAddressOrRange, i2d_IPAddressRange, i2d_ISSUING_DIST_POINT, +i2d_NAMING_AUTHORITY, i2d_NETSCAPE_CERT_SEQUENCE, i2d_NETSCAPE_SPKAC, i2d_NETSCAPE_SPKI, @@ -294,6 +302,7 @@ i2d_PKCS8_fp, i2d_PKEY_USAGE_PERIOD, i2d_POLICYINFO, i2d_POLICYQUALINFO, +i2d_PROFESSION_INFO, i2d_PROXY_CERT_INFO_EXTENSION, i2d_PROXY_POLICY, i2d_PublicKey, @@ -308,6 +317,7 @@ i2d_RSA_PSS_PARAMS, i2d_RSA_PUBKEY, i2d_RSA_PUBKEY_bio, i2d_RSA_PUBKEY_fp, +i2d_SCRYPT_PARAMS, i2d_SCT_LIST, i2d_SXNET, i2d_SXNETID, diff --git a/doc/crypto/i2d_CMS_bio_stream.pod b/doc/man3/i2d_CMS_bio_stream.pod similarity index 100% rename from doc/crypto/i2d_CMS_bio_stream.pod rename to doc/man3/i2d_CMS_bio_stream.pod diff --git a/doc/crypto/i2d_PKCS7_bio_stream.pod b/doc/man3/i2d_PKCS7_bio_stream.pod similarity index 100% rename from doc/crypto/i2d_PKCS7_bio_stream.pod rename to doc/man3/i2d_PKCS7_bio_stream.pod diff --git a/doc/crypto/i2d_re_X509_tbs.pod b/doc/man3/i2d_re_X509_tbs.pod similarity index 88% rename from doc/crypto/i2d_re_X509_tbs.pod rename to doc/man3/i2d_re_X509_tbs.pod index 672c7ab5..98ac4f41 100644 --- a/doc/crypto/i2d_re_X509_tbs.pod +++ b/doc/man3/i2d_re_X509_tbs.pod @@ -48,6 +48,15 @@ the encoding is automatically renewed. Otherwise, the encoding of the TBSCertificate portion of the B can be manually renewed by calling i2d_re_X509_tbs(). +=head1 RETURN VALUES + +d2i_X509_AUX() returns a valid B structure or NULL if an error occurred. + +i2d_X509_AUX() returns the length of encoded data or -1 on error. + +i2d_re_X509_tbs(), i2d_re_X509_CRL_tbs() and i2d_re_X509_REQ_tbs() return the +length of encoded data or 0 on error. + =head1 SEE ALSO L @@ -69,7 +78,7 @@ L =head1 COPYRIGHT -Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2002-2018 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 diff --git a/doc/crypto/o2i_SCT_LIST.pod b/doc/man3/o2i_SCT_LIST.pod similarity index 95% rename from doc/crypto/o2i_SCT_LIST.pod rename to doc/man3/o2i_SCT_LIST.pod index 82922fce..28989387 100644 --- a/doc/crypto/o2i_SCT_LIST.pod +++ b/doc/man3/o2i_SCT_LIST.pod @@ -9,7 +9,8 @@ decode and encode Signed Certificate Timestamp lists in TLS wire format #include - STACK_OF(SCT) *o2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, size_t len); + STACK_OF(SCT) *o2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, + size_t len); int i2o_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp); SCT *o2i_SCT(SCT **psct, const unsigned char **in, size_t len); int i2o_SCT(const SCT *sct, unsigned char **out); @@ -28,7 +29,7 @@ L and L. =head1 SEE ALSO -L, +L, L, L diff --git a/doc/apps/config.pod b/doc/man5/config.pod similarity index 97% rename from doc/apps/config.pod rename to doc/man5/config.pod index 76f282f2..a7cc16b2 100644 --- a/doc/apps/config.pod +++ b/doc/man5/config.pod @@ -1,7 +1,5 @@ =pod -=for comment openssl_manual_section:5 - =head1 NAME config - OpenSSL CONF library configuration files @@ -66,7 +64,9 @@ file. To enable library configuration the default section needs to contain an appropriate line which points to the main configuration section. The default name is B which is used by the B utility. Other -applications may use an alternative name such as B. +applications may use an alternative name such as B. +All library configuration lines appear in the default section at the start +of the configuration file. The configuration section should consist of a set of name value pairs which contain specific module configuration information. The B represents @@ -74,6 +74,7 @@ the name of the I the meaning of the B is module specific: it may, for example, represent a further configuration section containing configuration module specific information. E.g. + # This must be in the default section openssl_conf = openssl_init [openssl_init] @@ -196,17 +197,8 @@ This modules has the name B which points to a section containing algorithm commands. Currently the only algorithm command supported is B whose -value should be a boolean string such as B or B. If the value is -B this attempt to enter FIPS mode. If the call fails or the library is -not FIPS capable then an error occurs. - -For example: - - alg_section = evp_settings - - [evp_settings] - - fips_mode = on +value can only be the boolean string B. If B is set to B, +an error occurs as this library version is not FIPS capable. =head2 SSL Configuration Module diff --git a/doc/apps/x509v3_config.pod b/doc/man5/x509v3_config.pod similarity index 98% rename from doc/apps/x509v3_config.pod rename to doc/man5/x509v3_config.pod index c0742c84..a35b4ccf 100644 --- a/doc/apps/x509v3_config.pod +++ b/doc/man5/x509v3_config.pod @@ -1,7 +1,5 @@ =pod -=for comment openssl_manual_section:5 - =head1 NAME x509v3_config - X509 V3 certificate extension configuration format @@ -207,7 +205,7 @@ certificate (if possible). Example: - issuserAltName = issuer:copy + issuerAltName = issuer:copy =head2 Authority Info Access. @@ -355,6 +353,12 @@ The B option changes the type of the I field. In RFC2459 it can only be of type DisplayText. In RFC3280 IA5String is also permissible. Some software (for example some versions of MSIE) may require ia5org. +ASN1 type of explicitText can be specified by prepending B, +B or B prefix followed by colon. For example: + + [notice] + explicitText="UTF8:Explicit Text Here" + =head2 Policy Constraints This is a multi-valued extension which consisting of the names diff --git a/doc/man7/Ed25519.pod b/doc/man7/Ed25519.pod new file mode 100644 index 00000000..a75164a1 --- /dev/null +++ b/doc/man7/Ed25519.pod @@ -0,0 +1,67 @@ +=pod + +=head1 NAME + +Ed25519 - EVP_PKEY Ed25519 support + +=head1 DESCRIPTION + +The B EVP_PKEY implementation supports key generation, one shot +digest sign and digest verify using PureEdDSA and B (see RFC8032). +It has associated private and public key formats compatible with +draft-ietf-curdle-pkix-04. + +No additional parameters can be set during key generation one shot signing or +verification. In particular, because PureEdDSA is used, when signing or +verifying a digest must B be specified. + +=head1 NOTES + +The PureEdDSA algorithm does not support the streaming mechanism +of other signature algorithms using, for example, EVP_DigestUpdate(). +The message to sign or verify must be passed using the one shot +EVP_DigestSign() asn EVP_DigestVerify() functions. + +When calling EVP_DigestSignInit() or EVP_DigestSignUpdate() the +digest parameter B be set to B. + +Applications wishing to sign certificates (or other structures such as +CRLs or certificate requests) using Ed25519 can either use X509_sign() +or X509_sign_ctx() in the usual way. + +A context for the B algorithm can be obtained by calling: + + EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, NULL); + +=head1 EXAMPLE + +This example generates an B private key and writes it to standard +output in PEM format: + + #include + #include + ... + EVP_PKEY *pkey = NULL; + EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, NULL); + EVP_PKEY_keygen_init(pctx); + EVP_PKEY_keygen(pctx, &pkey); + EVP_PKEY_CTX_free(pctx); + PEM_write_PrivateKey(stdout, pkey, NULL, NULL, 0, NULL, NULL); + +=head1 SEE ALSO + +L, +L, +L, +L, + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/man7/RSA-PSS.pod b/doc/man7/RSA-PSS.pod new file mode 100644 index 00000000..b608561b --- /dev/null +++ b/doc/man7/RSA-PSS.pod @@ -0,0 +1,111 @@ +=pod + +=head1 NAME + +RSA-PSS - EVP_PKEY RSA-PSS algorithm support + +=head1 SYNOPSIS + + #include + + int EVP_PKEY_CTX_set_rsa_pss_keygen_md(EVP_PKEY_CTX *pctx, + const EVP_MD *md); + int EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md(EVP_PKEY_CTX *pctx, + const EVP_MD *md); + int EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(EVP_PKEY_CTX *pctx, + int saltlen); + +=head1 DESCRIPTION + +The B EVP_PKEY implementation is a restricted version of the RSA +algorithm which only supports signing, verification and key generation +using PSS padding modes with optional parameter restrictions. + +It has associated private key and public key formats. + +This algorithm shares several control operations with the B algorithm +but with some restrictions described below. + +=head1 SIGNING AND VERIFICATION + +Signing and verification is similar to the B algorithm except the +padding mode is always PSS. If the key in use has parameter restrictions then +the corresponding signature parameters are set to the restrictions: +for example, if the key can only be used with digest SHA256, MGF1 SHA256 +and minimum salt length 32 then the digest, MGF1 digest and salt length +will be set to SHA256, SHA256 and 32 respectively. + +The macro EVP_PKEY_CTX_set_rsa_padding() is supported but an error is +returned if an attempt is made to set the padding mode to anything other +than B. It is otherwise similar to the B version. + +The EVP_PKEY_CTX_set_rsa_pss_saltlen() macro is used to set the salt length. +If the key has usage restrictions then an error is returned if an attempt is +made to set the salt length below the minimum value. It is otherwise similar +to the B operation except detection of the salt length (using +RSA_PSS_SALTLEN_AUTO is not supported for verification if the key has +usage restrictions. + +The EVP_PKEY_CTX_set_signature_md() and EVP_PKEY_CTX_set_rsa_mgf1_md() macros +are used to set the digest and MGF1 algorithms respectively. If the key has +usage restrictions then an error is returned if an attempt is made to set the +digest to anything other than the restricted value. Otherwise these are +similar to the B versions. + +=head1 KEY GENERATION + +As with RSA key generation the EVP_PKEY_CTX_set_rsa_rsa_keygen_bits() +and EVP_PKEY_CTX_set_rsa_keygen_pubexp() macros are supported for RSA-PSS: +they have exactly the same meaning as for the RSA algorithm. + +Optional parameter restrictions can be specified when generating a PSS key. By +default no parameter restrictions are placed on the generated key. If any +restrictions are set (using the macros described below) then B parameters +are restricted. For example, setting a minimum salt length also restricts the +digest and MGF1 algorithms. If any restrictions are in place then they are +reflected in the corresponding parameters of the public key when (for example) +a certificate request is signed. + +EVP_PKEY_CTX_set_rsa_pss_keygen_md() restricts the digest algorithm the +generated key can use to B. + +EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md() restricts the MGF1 algorithm the +generated key can use to B. + +EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen() restricts the minimum salt length +to B. + +=head1 NOTES + +A context for the B algorithm can be obtained by calling: + + EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA_PSS, NULL); + +The public key format is documented in RFC4055. + +The PKCS#8 private key format used for RSA-PSS keys is similar to the RSA +format except it uses the B OID and the parameters field, if +present, restricts the key parameters in the same way as the public key. + +=head1 RETURN VALUES + +All these functions return 1 for success and 0 or a negative value for failure. +In particular a return value of -2 indicates the operation is not supported by +the public key algorithm. + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/man7/X25519.pod b/doc/man7/X25519.pod new file mode 100644 index 00000000..96522c50 --- /dev/null +++ b/doc/man7/X25519.pod @@ -0,0 +1,58 @@ +=pod + +=head1 NAME + +X25519 - EVP_PKEY X25519 support + +=head1 DESCRIPTION + +The B EVP_PKEY implementation supports key generation and key +derivation using B. It has associated private and public key formats +compatible with draft-ietf-curdle-pkix-03. + +No additional parameters can be set during key generation. + +The peer public key must be set using EVP_PKEY_derive_set_peer() when +performing key derivation. + +=head1 NOTES + +A context for the B algorithm can be obtained by calling: + + EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_X25519, NULL); + +=head1 EXAMPLE + +This example generates an B private key and writes it to standard +output in PEM format: + + #include + #include + ... + EVP_PKEY *pkey = NULL; + EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_X25519, NULL); + EVP_PKEY_keygen_init(pctx); + EVP_PKEY_keygen(pctx, &pkey); + EVP_PKEY_CTX_free(pctx); + PEM_write_PrivateKey(stdout, pkey, NULL, NULL, 0, NULL, NULL); + +The key derivation example in L can be used with +B. + +=head1 SEE ALSO + +L, +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/crypto/bio.pod b/doc/man7/bio.pod similarity index 90% rename from doc/crypto/bio.pod rename to doc/man7/bio.pod index 1e1dd021..45ef2f77 100644 --- a/doc/crypto/bio.pod +++ b/doc/man7/bio.pod @@ -1,15 +1,13 @@ =pod -=for comment openssl_manual_section 7 - =head1 NAME bio - Basic I/O abstraction -=for comment generic - =head1 SYNOPSIS +=for comment generic + #include =head1 DESCRIPTION @@ -46,8 +44,8 @@ and frequently a utility function exists to create and initialize such BIOs. If BIO_free() is called on a BIO chain it will only free one BIO resulting in a memory leak. -Calling BIO_free_all() a single BIO has the same effect as calling BIO_free() -on it other than the discarded return value. +Calling BIO_free_all() on a single BIO has the same effect as calling +BIO_free() on it other than the discarded return value. Normally the B argument is supplied by a function which returns a pointer to a BIO_METHOD. There is a naming convention for such functions: @@ -68,18 +66,17 @@ L, L, L, L, L, L, L, -L, L, +L, L, L, L, L, L, L, L, -L, L, L, L, L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-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 diff --git a/doc/crypto/crypto.pod b/doc/man7/crypto.pod similarity index 96% rename from doc/crypto/crypto.pod rename to doc/man7/crypto.pod index 082f8435..e08c5c8a 100644 --- a/doc/crypto/crypto.pod +++ b/doc/man7/crypto.pod @@ -1,7 +1,5 @@ =pod -=for comment openssl_manual_section:7 - =head1 NAME crypto - OpenSSL cryptographic library @@ -48,7 +46,7 @@ See the individual manual pages for details. =head1 SEE ALSO -L, L +L, L =head1 COPYRIGHT diff --git a/doc/crypto/ct.pod b/doc/man7/ct.pod similarity index 97% rename from doc/crypto/ct.pod rename to doc/man7/ct.pod index 60718b3f..355204d2 100644 --- a/doc/crypto/ct.pod +++ b/doc/man7/ct.pod @@ -1,7 +1,5 @@ =pod -=for comment openssl_manual_section:7 - =head1 NAME ct - Certificate Transparency diff --git a/doc/crypto/des_modes.pod b/doc/man7/des_modes.pod similarity index 98% rename from doc/crypto/des_modes.pod rename to doc/man7/des_modes.pod index d5a3f8d6..f7415d77 100644 --- a/doc/crypto/des_modes.pod +++ b/doc/man7/des_modes.pod @@ -1,7 +1,5 @@ =pod -=for comment openssl_manual_section:7 - =head1 NAME des_modes - the variants of DES and other crypto algorithms of OpenSSL @@ -18,7 +16,7 @@ other things. Normally, this is found as the function I_ecb_encrypt(). -=over 4 +=over 2 =item * @@ -45,7 +43,7 @@ Normally, this is found as the function I_cbc_encrypt(). Be aware that des_cbc_encrypt() is not really DES CBC (it does not update the IV); use des_ncbc_encrypt() instead. -=over 4 +=over 2 =item * @@ -77,7 +75,7 @@ An error will affect the current and the following ciphertext blocks. Normally, this is found as the function I_cfb_encrypt(). -=over 4 +=over 2 =item * @@ -124,8 +122,7 @@ An error will affect the current and the following ciphertext variables. Normally, this is found as the function I_ofb_encrypt(). -=over 4 - +=over 2 =item * @@ -185,7 +182,7 @@ susceptible to a 'known plaintext' attack. Normally, this is found as the function I_ecb3_encrypt(). -=over 4 +=over 2 =item * @@ -220,7 +217,7 @@ ecb mode. Normally, this is found as the function I_ede3_cbc_encrypt(). -=over 4 +=over 2 =item * diff --git a/doc/crypto/evp.pod b/doc/man7/evp.pod similarity index 79% rename from doc/crypto/evp.pod rename to doc/man7/evp.pod index 02051df6..e493dacd 100644 --- a/doc/crypto/evp.pod +++ b/doc/man7/evp.pod @@ -1,7 +1,5 @@ =pod -=for comment openssl_manual_section:7 - =head1 NAME evp - high-level cryptographic functions @@ -15,19 +13,19 @@ evp - high-level cryptographic functions The EVP library provides a high-level interface to cryptographic functions. -LI<...>|EVP_SealInit(3)> and LI<...>|EVP_OpenInit(3)> -provide public key encryption and decryption to implement digital "envelopes". +The LI|EVP_SealInit(3)> and LI|EVP_OpenInit(3)> +functions provide public key encryption and decryption to implement digital "envelopes". -The LI<...>|EVP_DigestSignInit(3)> and -LI<...>|EVP_DigestVerifyInit(3)> functions implement +The LI|EVP_DigestSignInit(3)> and +LI|EVP_DigestVerifyInit(3)> functions implement digital signatures and Message Authentication Codes (MACs). Also see the older -LI<...>|EVP_SignInit(3)> and LI<...>|EVP_VerifyInit(3)> +LI|EVP_SignInit(3)> and LI|EVP_VerifyInit(3)> functions. -Symmetric encryption is available with the LI<...>|EVP_EncryptInit(3)> -functions. The LI<...>|EVP_DigestInit(3)> functions provide message digests. +Symmetric encryption is available with the LI|EVP_EncryptInit(3)> +functions. The LI|EVP_DigestInit(3)> functions provide message digests. -The BI<...> functions provide a high level interface to +The BI functions provide a high level interface to asymmetric algorithms. To create a new EVP_PKEY see L. EVP_PKEYs can be associated with a private key of a particular algorithm by using the functions @@ -63,12 +61,12 @@ based encryption. Careful selection of the parameters will provide a PKCS#5 PBKD implementation. However, new applications should not typically use this (preferring, for example, PBKDF2 from PCKS#5). -The LI<...>|EVP_EncodeInit(3)> and -LI<...>|EVP_EncodeInit(3)> functions implement base 64 encoding +The LI|EVP_EncodeInit(3)> and +LI|EVP_EncodeInit(3)> functions implement base 64 encoding and decoding. All the symmetric algorithms (ciphers), digests and asymmetric algorithms -(public key algorithms) can be replaced by L modules providing alternative +(public key algorithms) can be replaced by ENGINE modules providing alternative implementations. If ENGINE implementations of ciphers or digests are registered as defaults, then the various EVP functions will automatically use those implementations automatically in preference to built in software @@ -102,11 +100,11 @@ L, L, L, L, -L +L =head1 COPYRIGHT -Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. +Copyright 2000-2018 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 diff --git a/doc/man7/ossl_store.pod b/doc/man7/ossl_store.pod new file mode 100644 index 00000000..98cc04f7 --- /dev/null +++ b/doc/man7/ossl_store.pod @@ -0,0 +1,102 @@ +=pod + +=head1 NAME + +ossl_store - Store retrieval functions + +=head1 SYNOPSIS + +=for comment generic + +#include + +=head1 DESCRIPTION + +=head2 General + +A STORE is a layer of functionality to retrieve a number of supported +objects from a repository of any kind, addressable as a file name or +as a URI. + +The functionality supports the pattern "open a channel to the +repository", "loop and retrieve one object at a time", and "finish up +by closing the channel". + +The retrieved objects are returned as a wrapper type B, +from which an OpenSSL type can be retrieved. + +=head2 URI schemes and loaders + +Support for a URI scheme is called a STORE "loader", and can be added +dynamically from the calling application or from a loadable engine. + +=head2 The 'file' scheme + +Support for the 'file' scheme is already built into C. +Since files come in all kinds of formats and content types, the 'file' +scheme has its own layer of functionality called "file handlers", +which are used to try to decode diverse types of file contents. + +In case a file is formatted as PEM, each called file handler receives +the PEM name (everything following any 'C<-----BEGIN >') as well as +possible PEM headers, together with the decoded PEM body. Since PEM +formatted files can contain more than one object, the file handlers +are called upon for each such object. + +If the file isn't determined to be formatted as PEM, the content is +loaded in raw form in its entirety and passed to the available file +handlers as is, with no PEM name or headers. + +Each file handler is expected to handle PEM and non-PEM content as +appropriate. Some may refuse non-PEM content for the sake of +determinism (for example, there are keys out in the wild that are +represented as an ASN.1 OCTET STRING. In raw form, it's not easily +possible to distinguish those from any other data coming as an ASN.1 +OCTET STRING, so such keys would naturally be accepted as PEM files +only). + +=head1 EXAMPLES + +=head2 A generic call + + OSSL_STORE_CTX *ctx = OSSL_STORE_open("file:/foo/bar/data.pem"); + + /* + * OSSL_STORE_eof() simulates file semantics for any repository to signal + * that no more data can be expected + */ + while (!OSSL_STORE_eof(ctx)) { + OSSL_STORE_INFO *info = OSSL_STORE_load(ctx); + + /* + * Do whatever is necessary with the OSSL_STORE_INFO, + * here just one example + */ + switch (OSSL_STORE_INFO_get_type(info)) { + case OSSL_STORE_INFO_X509: + /* Print the X.509 certificate text */ + X509_print_fp(stdout, OSSL_STORE_INFO_get0_CERT(info)); + /* Print the X.509 certificate PEM output */ + PEM_write_X509(stdout, OSSL_STORE_INFO_get0_CERT(info)); + break; + } + } + + OSSL_STORE_close(ctx); + +=head1 SEE ALSO + +L, L, +L, L, +L + +=head1 COPYRIGHT + +Copyright 2016-2018 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 +L. + +=cut diff --git a/doc/man7/scrypt.pod b/doc/man7/scrypt.pod new file mode 100644 index 00000000..4de0c723 --- /dev/null +++ b/doc/man7/scrypt.pod @@ -0,0 +1,158 @@ +=pod + +=head1 NAME + +scrypt - EVP_PKEY scrypt KDF support + +=head1 SYNOPSIS + + #include + + int EVP_PKEY_CTX_set1_pbe_pass(EVP_PKEY_CTX *pctx, unsigned char *pass, + int passlen); + + int EVP_PKEY_CTX_set1_scrypt_salt(EVP_PKEY_CTX *pctx, unsigned char *salt, + int saltlen); + + int EVP_PKEY_CTX_set_scrypt_N(EVP_PKEY_CTX *pctx, uint64_t N); + + int EVP_PKEY_CTX_set_scrypt_r(EVP_PKEY_CTX *pctx, uint64_t r); + + int EVP_PKEY_CTX_set_scrypt_p(EVP_PKEY_CTX *pctx, uint64_t p); + + int EVP_PKEY_CTX_set_scrypt_maxmem_bytes(EVP_PKEY_CTX *pctx, uint64_t maxmem); + +=head1 DESCRIPTION + +The EVP_PKEY_SCRYPT algorithm implements the scrypt password based key +derivation function, as described in RFC 7914. It is memory-hard in the sense +that it deliberately requires a significant amount of RAM for efficient +computation. The intention of this is to render brute forcing of passwords on +systems that lack large amounts of main memory (such as GPUs or ASICs) +computationally infeasible. + +scrypt provides three work factors that can be customized: N, r and p. N, which +has to be a positive power of two, is the general work factor and scales CPU +time in an approximately linear fashion. r is the block size of the internally +used hash function and p is the parallelization factor. Both r and p need to be +greater than zero. The amount of RAM that scrypt requires for its computation +is roughly (128 * N * r * p) bytes. + +In the original paper of Colin Percival ("Stronger Key Derivation via +Sequential Memory-Hard Functions", 2009), the suggested values that give a +computation time of less than 5 seconds on a 2.5 GHz Intel Core 2 Duo are N = +2^20 = 1048576, r = 8, p = 1. Consequently, the required amount of memory for +this computation is roughly 1 GiB. On a more recent CPU (Intel i7-5930K at 3.5 +GHz), this computation takes about 3 seconds. When N, r or p are not specified, +they default to 1048576, 8, and 1, respectively. The default amount of RAM that +may be used by scrypt defaults to 1025 MiB. + +EVP_PKEY_CTX_set1_pbe_pass() sets the B bytes long password. + +EVP_PKEY_CTX_set1_scrypt_salt() sets the B bytes long salt value. + +EVP_PKEY_CTX_set_scrypt_N(), EVP_PKEY_CTX_set_scrypt_r() and +EVP_PKEY_CTX_set_scrypt_p() configure the work factors N, r and p. + +EVP_PKEY_CTX_set_scrypt_maxmem_bytes() sets how much RAM key derivation may +maximally use, given in bytes. If RAM is exceeded because the load factors are +chosen too high, the key derivation will fail. + +=head1 STRING CTRLS + +scrypt also supports string based control operations via +L. +The B can be directly specified using the B parameter "pass" or +given in hex encoding using the "hexpass" parameter. Similarly, the B can +either be specified using the B parameter "salt" or in hex encoding by +using the "hexsalt" parameter. The work factors B, B and B

as well as +B can be set by using the parameters "N", "r", "p" and +"maxmem_bytes", respectively. + +=head1 NOTES + +All these functions are implemented as macros. + +A context for scrypt can be obtained by calling: + + EVP_PKEY_CTX *pctx = EVP_PKEY_new_id(EVP_PKEY_SCRYPT, NULL); + +The output length of an scrypt key derivation is specified via the length +parameter to the L function. + +=head1 RETURN VALUES + +All these functions return 1 for success and 0 or a negative value for failure. +In particular a return value of -2 indicates the operation is not supported by +the public key algorithm. + +=head1 EXAMPLE + +This example derives a 64-byte long test vector using scrypt using the password +"password", salt "NaCl" and N = 1024, r = 8, p = 16. + + EVP_PKEY_CTX *pctx; + unsigned char out[64]; + + size_t outlen = sizeof(out); + pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SCRYPT, NULL); + + if (EVP_PKEY_derive_init(pctx) <= 0) { + error("EVP_PKEY_derive_init"); + } + if (EVP_PKEY_CTX_set1_pbe_pass(pctx, "password", 8) <= 0) { + error("EVP_PKEY_CTX_set1_pbe_pass"); + } + if (EVP_PKEY_CTX_set1_scrypt_salt(pctx, "NaCl", 4) <= 0) { + error("EVP_PKEY_CTX_set1_scrypt_salt"); + } + if (EVP_PKEY_CTX_set_scrypt_N(pctx, 1024) <= 0) { + error("EVP_PKEY_CTX_set_scrypt_N"); + } + if (EVP_PKEY_CTX_set_scrypt_r(pctx, 8) <= 0) { + error("EVP_PKEY_CTX_set_scrypt_r"); + } + if (EVP_PKEY_CTX_set_scrypt_p(pctx, 16) <= 0) { + error("EVP_PKEY_CTX_set_scrypt_p"); + } + if (EVP_PKEY_derive(pctx, out, &outlen) <= 0) { + error("EVP_PKEY_derive"); + } + + { + const unsigned char expected[sizeof(out)] = { + 0xfd, 0xba, 0xbe, 0x1c, 0x9d, 0x34, 0x72, 0x00, + 0x78, 0x56, 0xe7, 0x19, 0x0d, 0x01, 0xe9, 0xfe, + 0x7c, 0x6a, 0xd7, 0xcb, 0xc8, 0x23, 0x78, 0x30, + 0xe7, 0x73, 0x76, 0x63, 0x4b, 0x37, 0x31, 0x62, + 0x2e, 0xaf, 0x30, 0xd9, 0x2e, 0x22, 0xa3, 0x88, + 0x6f, 0xf1, 0x09, 0x27, 0x9d, 0x98, 0x30, 0xda, + 0xc7, 0x27, 0xaf, 0xb9, 0x4a, 0x83, 0xee, 0x6d, + 0x83, 0x60, 0xcb, 0xdf, 0xa2, 0xcc, 0x06, 0x40 + }; + + assert(!memcmp(out, expected, sizeof(out))); + } + + EVP_PKEY_CTX_free(pctx); + +=head1 CONFORMING TO + +RFC 7914 + +=head1 SEE ALSO + +L, +L, +L + +=head1 COPYRIGHT + +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 +L. + +=cut diff --git a/doc/ssl/ssl.pod b/doc/man7/ssl.pod similarity index 96% rename from doc/ssl/ssl.pod rename to doc/man7/ssl.pod index 4d919072..f3604bb1 100644 --- a/doc/ssl/ssl.pod +++ b/doc/man7/ssl.pod @@ -1,7 +1,5 @@ =pod -=for comment openssl_manual_section:7 - =head1 NAME ssl - OpenSSL SSL/TLS library @@ -16,7 +14,7 @@ The OpenSSL B library implements the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols. It provides a rich API which is documented here. -Then an B object is created as a framework to establish +An B object is created as a framework to establish TLS/SSL enabled connections (see L). Various options regarding certificates, algorithms etc. can be set in this object. @@ -27,10 +25,10 @@ L, L or L can be used to associate the network connection with the object. -Then the TLS/SSL handshake is performed using +When the TLS/SSL handshake is performed using L or L respectively. -L and L are +L, L, L and L are used to read and write data on the TLS/SSL connection. L can be used to shut down the TLS/SSL connection. @@ -44,7 +42,7 @@ structures: =item B (SSL Method) -That's a dispatch structure describing the internal B library +This is a dispatch structure describing the internal B library methods/functions which implement the various protocol versions (SSLv3 TLSv1, ...). It's needed to create an B. @@ -52,12 +50,12 @@ TLSv1, ...). It's needed to create an B. This structure holds the algorithm information for a particular cipher which are a core part of the SSL/TLS protocol. The available ciphers are configured -on a B basis and the actually used ones are then part of the +on a B basis and the actual ones used are then part of the B. =item B (SSL Context) -That's the global context structure which is created by a server or client +This is the global context structure which is created by a server or client once per program life-time and which holds mainly default values for the B structures which are later created for the connections. @@ -68,9 +66,9 @@ connection: Bs, client and server certificates, keys, etc. =item B (SSL Connection) -That's the main SSL/TLS structure which is created by a server or client per +This is the main SSL/TLS structure which is created by a server or client per established connection. This actually is the core structure in the SSL API. -Under run-time the application usually deals with this structure which has +At run-time the application usually deals with this structure which has links to mostly all other structures. =back @@ -85,7 +83,7 @@ containing the prototypes for the data structures and functions: =item B -That's the common header file for the SSL/TLS API. Include it into your +This is the common header file for the SSL/TLS API. Include it into your program to make the API of the B library available. It internally includes both more private SSL headers and headers from the B library. Whenever you need hard-core details on the internals of the SSL API, look @@ -103,13 +101,13 @@ Unused. Present for backwards compatibility only. =item B -That's the sub header file dealing with the SSLv3 protocol only. +This is the sub header file dealing with the SSLv3 protocol only. I. =item B -That's the sub header file dealing with the TLSv1 protocol only. +This is the sub header file dealing with the TLSv1 protocol only. I. @@ -328,6 +326,8 @@ protocol context defined in the B structure. =item void B(SSL_CTX *ctx, X509_STORE *cs); +=item void B(SSL_CTX *ctx, X509_STORE *cs); + =item void B(SSL_CTX *ctx, int (*cb)(), char *arg) =item int B(SSL_CTX *ctx, char *str); @@ -825,7 +825,7 @@ L =head1 HISTORY -B, B and B were removed +B, B and B where removed in OpenSSL 1.1.0. The return type of B was changed from void to int in diff --git a/doc/man7/x509.pod b/doc/man7/x509.pod new file mode 100644 index 00000000..065dcb14 --- /dev/null +++ b/doc/man7/x509.pod @@ -0,0 +1,73 @@ +=pod + +=head1 NAME + +x509 - X.509 certificate handling + +=head1 SYNOPSIS + + #include + +=head1 DESCRIPTION + +An X.509 certificate is a structured grouping of information about +an individual, a device, or anything one can imagine. A X.509 CRL +(certificate revocation list) is a tool to help determine if a +certificate is still valid. The exact definition of those can be +found in the X.509 document from ITU-T, or in RFC3280 from PKIX. +In OpenSSL, the type X509 is used to express such a certificate, and +the type X509_CRL is used to express a CRL. + +A related structure is a certificate request, defined in PKCS#10 from +RSA Security, Inc, also reflected in RFC2896. In OpenSSL, the type +X509_REQ is used to express such a certificate request. + +To handle some complex parts of a certificate, there are the types +X509_NAME (to express a certificate name), X509_ATTRIBUTE (to express +a certificate attributes), X509_EXTENSION (to express a certificate +extension) and a few more. + +Finally, there's the supertype X509_INFO, which can contain a CRL, a +certificate and a corresponding private key. + +BI, BI, and BI functions +handle X.509 certificates, with some exceptions, shown below. + +BI, BI, and BI +functions handle X.509 CRLs. + +BI, BI, and BI +functions handle PKCS#10 certificate requests. + +BI functions handle certificate names. + +BI functions handle certificate attributes. + +BI functions handle certificate extensions. + +=head1 SEE ALSO + +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L, +L + +=head1 COPYRIGHT + +Copyright 2003-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 +L. + +=cut diff --git a/doc/openssl-c-indent.el b/doc/openssl-c-indent.el index cca11830..38e7a4f3 100644 --- a/doc/openssl-c-indent.el +++ b/doc/openssl-c-indent.el @@ -2,7 +2,7 @@ ;;; ;;; This definition is for the "CC mode" package, which is the default ;;; mode for editing C source files in Emacs 20, not for the older -;;; c-mode.el (which was the default in less recent release of Emacs 19). +;;; c-mode.el (which was the default in less recent releases of Emacs 19). ;;; ;;; Recommended use is to add this line in your .emacs: ;;; diff --git a/doc/ssl/DTLSv1_listen.pod b/doc/ssl/DTLSv1_listen.pod deleted file mode 100644 index a839d9fe..00000000 --- a/doc/ssl/DTLSv1_listen.pod +++ /dev/null @@ -1,102 +0,0 @@ -=pod - -=head1 NAME - -DTLSv1_listen - listen for incoming DTLS connections - -=head1 SYNOPSIS - - #include - - int DTLSv1_listen(SSL *ssl, BIO_ADDR *peer); - -=head1 DESCRIPTION - -DTLSv1_listen() listens for new incoming DTLS connections. If a ClientHello is -received that does not contain a cookie, then DTLSv1_listen() responds with a -HelloVerifyRequest. If a ClientHello is received with a cookie that is verified -then control is returned to user code to enable the handshake to be completed -(for example by using SSL_accept()). - -=head1 NOTES - -Datagram based protocols can be susceptible to Denial of Service attacks. A -DTLS attacker could, for example, submit a series of handshake initiation -requests that cause the server to allocate state (and possibly perform -cryptographic operations) thus consuming server resources. The attacker could -also (with UDP) quite simply forge the source IP address in such an attack. - -As a counter measure to that DTLS includes a stateless cookie mechanism. The -idea is that when a client attempts to connect to a server it sends a -ClientHello message. The server responds with a HelloVerifyRequest which -contains a unique cookie. The client then resends the ClientHello, but this time -includes the cookie in the message thus proving that the client is capable of -receiving messages sent to that address. All of this can be done by the server -without allocating any state, and thus without consuming expensive resources. - -OpenSSL implements this capability via the DTLSv1_listen() function. The B -parameter should be a newly allocated SSL object with its read and write BIOs -set, in the same way as might be done for a call to SSL_accept(). Typically the -read BIO will be in an "unconnected" state and thus capable of receiving -messages from any peer. - -When a ClientHello is received that contains a cookie that has been verified, -then DTLSv1_listen() will return with the B parameter updated into a state -where the handshake can be continued by a call to (for example) SSL_accept(). -Additionally the B pointed to by B will be filled in with -details of the peer that sent the ClientHello. If the underlying BIO is unable -to obtain the B of the peer (for example because the BIO does not -support this), then B<*peer> will be cleared and the family set to AF_UNSPEC. -Typically user code is expected to "connect" the underlying socket to the peer -and continue the handshake in a connected state. - -Prior to calling DTLSv1_listen() user code must ensure that cookie generation -and verification callbacks have been set up using -SSL_CTX_set_cookie_generate_cb() and SSL_CTX_set_cookie_verify_cb() -respectively. - -Since DTLSv1_listen() operates entirely statelessly whilst processing incoming -ClientHellos it is unable to process fragmented messages (since this would -require the allocation of state). An implication of this is that DTLSv1_listen() -B supports ClientHellos that fit inside a single datagram. - -=head1 RETURN VALUES - -From OpenSSL 1.1.0 a return value of >= 1 indicates success. In this instance -the B value will be filled in and the B object set up ready to -continue the handshake. - -A return value of 0 indicates a non-fatal error. This could (for -example) be because of non-blocking IO, or some invalid message having been -received from a peer. Errors may be placed on the OpenSSL error queue with -further information if appropriate. Typically user code is expected to retry the -call to DTLSv1_listen() in the event of a non-fatal error. Any old errors on the -error queue will be cleared in the subsequent call. - -A return value of <0 indicates a fatal error. This could (for example) be -because of a failure to allocate sufficient memory for the operation. - -Prior to OpenSSL 1.1.0 fatal and non-fatal errors both produce return codes -<= 0 (in typical implementations user code treats all errors as non-fatal), -whilst return codes >0 indicate success. - -=head1 SEE ALSO - -L, L, -L, L - -=head1 HISTORY - -DTLSv1_listen() return codes were clarified in OpenSSL 1.1.0. The type of "peer" -also changed in OpenSSL 1.1.0. - -=head1 COPYRIGHT - -Copyright 2015-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 -L. - -=cut diff --git a/doc/ssl/SSL_CIPHER_get_name.pod b/doc/ssl/SSL_CIPHER_get_name.pod deleted file mode 100644 index b7ee3c84..00000000 --- a/doc/ssl/SSL_CIPHER_get_name.pod +++ /dev/null @@ -1,128 +0,0 @@ -=pod - -=head1 NAME - -SSL_CIPHER_get_cipher_nid, SSL_CIPHER_get_digest_nid, SSL_CIPHER_get_kx_nid, -SSL_CIPHER_get_auth_nid, SSL_CIPHER_is_aead, -SSL_CIPHER_get_name, SSL_CIPHER_get_bits, -SSL_CIPHER_get_version, SSL_CIPHER_description -- get SSL_CIPHER properties - -=head1 SYNOPSIS - - #include - - const char *SSL_CIPHER_get_name(const SSL_CIPHER *cipher); - int SSL_CIPHER_get_bits(const SSL_CIPHER *cipher, int *alg_bits); - char *SSL_CIPHER_get_version(const SSL_CIPHER *cipher); - char *SSL_CIPHER_description(const SSL_CIPHER *cipher, char *buf, int size); - int SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *c); - int SSL_CIPHER_get_digest_nid(const SSL_CIPHER *c); - int SSL_CIPHER_get_kx_nid(const SSL_CIPHER *c); - int SSL_CIPHER_get_auth_nid(const SSL_CIPHER *c); - int SSL_CIPHER_is_aead(const SSL_CIPHER *c); - -=head1 DESCRIPTION - -SSL_CIPHER_get_name() returns a pointer to the name of B. If the -B is NULL, it returns "(NONE)". - -SSL_CIPHER_get_bits() returns the number of secret bits used for B. -If B is NULL, 0 is returned. - -SSL_CIPHER_get_version() returns string which indicates the SSL/TLS protocol -version that first defined the cipher. It returns "(NONE)" if B is NULL. - -SSL_CIPHER_get_cipher_nid() returns the cipher NID corresponding to B. -If there is no cipher (e.g. for ciphersuites with no encryption) then -B is returned. - -SSL_CIPHER_get_digest_nid() returns the digest NID corresponding to the MAC -used by B. If there is no digest (e.g. for AEAD ciphersuites) then -B is returned. - -SSL_CIPHER_get_kx_nid() returns the key exchange NID corresponding to the method -used by B. If there is no key exchange, then B is returned. Examples (not comprehensive): - - NID_kx_rsa - NID_kx_ecdhe - NID_kx_dhe - NID_kx_psk - -SSL_CIPHER_get_auth_nid() returns the authentication NID corresponding to the method -used by B. If there is no authentication, then B is returned. -Examples (not comprehensive): - - NID_auth_rsa - NID_auth_ecdsa - NID_auth_psk - -SSL_CIPHER_is_aead() returns 1 if the cipher B is AEAD (e.g. GCM or -ChaCha20/Poly1305), and 0 if it is not AEAD. - -SSL_CIPHER_description() returns a textual description of the cipher used -into the buffer B of length B provided. If B is provided, it -must be at least 128 bytes, otherwise a buffer will be allocated using -OPENSSL_malloc(). If the provided buffer is too small, or the allocation fails, -B is returned. - -The string returned by SSL_CIPHER_description() consists of several fields -separated by whitespace: - -=over 4 - -=item - -Textual representation of the cipher name. - -=item - -Protocol version, such as B, when the cipher was first defined. - -=item Kx= - -Key exchange method such as B, B, etc. - -=item Au= - -Authentication method such as B, B, etc.. None is the -representation of anonymous ciphers. - -=item Enc= - -Encryption method, with number of secret bits, such as B. - -=item Mac= - -Message digest, such as B. - -=back - -Some examples for the output of SSL_CIPHER_description(): - - ECDHE-RSA-AES256-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA Enc=AESGCM(256) Mac=AEAD - RSA-PSK-AES256-CBC-SHA384 TLSv1.0 Kx=RSAPSK Au=RSA Enc=AES(256) Mac=SHA384 - -=head1 HISTORY - -SSL_CIPHER_get_version() was updated to always return the correct protocol -string in OpenSSL 1.1. - -SSL_CIPHER_description() was changed to return B on error, -rather than a fixed string, in OpenSSL 1.1 - -=head1 SEE ALSO - -L, L, -L, L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_dane_enable.pod b/doc/ssl/SSL_CTX_dane_enable.pod deleted file mode 100644 index cdb6d1bd..00000000 --- a/doc/ssl/SSL_CTX_dane_enable.pod +++ /dev/null @@ -1,384 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_dane_enable, SSL_CTX_dane_mtype_set, SSL_dane_enable, -SSL_dane_tlsa_add, SSL_get0_dane_authority, SSL_get0_dane_tlsa, -SSL_CTX_dane_set_flags, SSL_CTX_dane_clear_flags, -SSL_dane_set_flags, SSL_dane_clear_flags -- enable DANE TLS authentication of the remote TLS server in the local -TLS client - -=head1 SYNOPSIS - - #include - - int SSL_CTX_dane_enable(SSL_CTX *ctx); - int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md, - uint8_t mtype, uint8_t ord); - int SSL_dane_enable(SSL *s, const char *basedomain); - int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector, - uint8_t mtype, unsigned char *data, size_t dlen); - int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki); - int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector, - uint8_t *mtype, unsigned const char **data, - size_t *dlen); - unsigned long SSL_CTX_dane_set_flags(SSL_CTX *ctx, unsigned long flags); - unsigned long SSL_CTX_dane_clear_flags(SSL_CTX *ctx, unsigned long flags); - unsigned long SSL_dane_set_flags(SSL *ssl, unsigned long flags); - unsigned long SSL_dane_clear_flags(SSL *ssl, unsigned long flags); - -=head1 DESCRIPTION - -These functions implement support for DANE TLSA (RFC6698 and RFC7671) -peer authentication. - -SSL_CTX_dane_enable() must be called first to initialize the shared state -required for DANE support. -Individual connections associated with the context can then enable -per-connection DANE support as appropriate. -DANE authentication is implemented in the L function, and -applications that override L via -L are responsible to authenticate the peer -chain in whatever manner they see fit. - -SSL_CTX_dane_mtype_set() may then be called zero or more times to adjust the -supported digest algorithms. -This must be done before any SSL handles are created for the context. - -The B argument specifies a DANE TLSA matching type and the B -argument specifies the associated digest algorithm handle. -The B argument specifies a strength ordinal. -Algorithms with a larger strength ordinal are considered more secure. -Strength ordinals are used to implement RFC7671 digest algorithm agility. -Specifying a B digest algorithm for a matching type disables -support for that matching type. -Matching type Full(0) cannot be modified or disabled. - -By default, matching type C (see RFC7218 for definitions -of the DANE TLSA parameter acronyms) is mapped to C -with a strength ordinal of C<1> and matching type C -is mapped to C with a strength ordinal of C<2>. - -SSL_dane_enable() must be called before the SSL handshake is initiated with -L if (and only if) you want to enable DANE for that connection. -(The connection must be associated with a DANE-enabled SSL context). -The B argument specifies the RFC7671 TLSA base domain, -which will be the primary peer reference identifier for certificate -name checks. -Additional server names can be specified via L. -The B is used as the default SNI hint if none has yet been -specified via L. - -SSL_dane_tlsa_add() may then be called one or more times, to load each of the -TLSA records that apply to the remote TLS peer. -(This too must be done prior to the beginning of the SSL handshake). -The arguments specify the fields of the TLSA record. -The B field is provided in binary (wire RDATA) form, not the hexadecimal -ASCII presentation form, with an explicit length passed via B. -The library takes a copy of the B buffer contents and the caller may -free the original B buffer when convenient. -A return value of 0 indicates that "unusable" TLSA records (with invalid or -unsupported parameters) were provided. -A negative return value indicates an internal error in processing the record. - -The caller is expected to check the return value of each SSL_dane_tlsa_add() -call and take appropriate action if none are usable or an internal error -is encountered in processing some records. - -If no TLSA records are added successfully, DANE authentication is not enabled, -and authentication will be based on any configured traditional trust-anchors; -authentication success in this case does not mean that the peer was -DANE-authenticated. - -SSL_get0_dane_authority() can be used to get more detailed information about -the matched DANE trust-anchor after successful connection completion. -The return value is negative if DANE verification failed (or was not enabled), -0 if an EE TLSA record directly matched the leaf certificate, or a positive -number indicating the depth at which a TA record matched an issuer certificate. -The complete verified chain can be retrieved via L. -The return value is an index into this verified chain, rather than the list of -certificates sent by the peer as returned by L. - -If the B argument is not B and a TLSA record matched a chain -certificate, a pointer to the matching certificate is returned via B. -The returned address is a short-term internal reference to the certificate and -must not be freed by the application. -Applications that want to retain access to the certificate can call -L to obtain a long-term reference which must then be freed via -L once no longer needed. - -If no TLSA records directly matched any elements of the certificate chain, but -a DANE-TA(2) SPKI(1) Full(0) record provided the public key that signed an -element of the chain, then that key is returned via B argument (if not -NULL). -In this case the return value is the depth of the top-most element of the -validated certificate chain. -As with B this is a short-term internal reference, and -L and L can be used to acquire and -release long-term references respectively. - -SSL_get0_dane_tlsa() can be used to retrieve the fields of the TLSA record that -matched the peer certificate chain. -The return value indicates the match depth or failure to match just as with -SSL_get0_dane_authority(). -When the return value is non-negative, the storage pointed to by the B, -B, B and B parameters is updated to the corresponding -TLSA record fields. -The B field is in binary wire form, and is therefore not NUL-terminated, -its length is returned via the B parameter. -If any of these parameters is NULL, the corresponding field is not returned. -The B parameter is set to a short-term internal-copy of the associated -data field and must not be freed by the application. -Applications that need long-term access to this field need to copy the content. - -SSL_CTX_dane_set_flags() and SSL_dane_set_flags() can be used to enable -optional DANE verification features. -SSL_CTX_dane_clear_flags() and SSL_dane_clear_flags() can be used to disable -the same features. -The B argument is a bitmask of the features to enable or disable. -The B set for an B context are copied to each B handle -associated with that context at the time the handle is created. -Subsequent changes in the context's B have no effect on the B set -for the handle. - -At present, the only available option is B -which can be used to disable server name checks when authenticating via -DANE-EE(3) TLSA records. -For some applications, primarily web browsers, it is not safe to disable name -checks due to "unknown key share" attacks, in which a malicious server can -convince a client that a connection to a victim server is instead a secure -connection to the malicious server. -The malicious server may then be able to violate cross-origin scripting -restrictions. -Thus, despite the text of RFC7671, name checks are by default enabled for -DANE-EE(3) TLSA records, and can be disabled in applications where it is safe -to do so. -In particular, SMTP and XMPP clients should set this option as SRV and MX -records already make it possible for a remote domain to redirect client -connections to any server of its choice, and in any case SMTP and XMPP clients -do not execute scripts downloaded from remote servers. - -=head1 RETURN VALUES - -The functions SSL_CTX_dane_enable(), SSL_CTX_dane_mtype_set(), -SSL_dane_enable() and SSL_dane_tlsa_add() return a positive value on success. -Negative return values indicate resource problems (out of memory, etc.) in the -SSL library, while a return value of B<0> indicates incorrect usage or invalid -input, such as an unsupported TLSA record certificate usage, selector or -matching type. -Invalid input also includes malformed data, either a digest length that does -not match the digest algorithm, or a C (binary ASN.1 DER form) -certificate or a public key that fails to parse. - -The functions SSL_get0_dane_authority() and SSL_get0_dane_tlsa() return a -negative value when DANE authentication failed or was not enabled, a -non-negative value indicates the chain depth at which the TLSA record matched a -chain certificate, or the depth of the top-most certificate, when the TLSA -record is a full public key that is its signer. - -The functions SSL_CTX_dane_set_flags(), SSL_CTX_dane_clear_flags(), -SSL_dane_set_flags() and SSL_dane_clear_flags() return the B in effect -before they were called. - -=head1 EXAMPLE - -Suppose "smtp.example.com" is the MX host of the domain "example.com", and has -DNSSEC-validated TLSA records. -The calls below will perform DANE authentication and arrange to match either -the MX hostname or the destination domain name in the SMTP server certificate. -Wildcards are supported, but must match the entire label. -The actual name matched in the certificate (which might be a wildcard) is -retrieved, and must be copied by the application if it is to be retained beyond -the lifetime of the SSL connection. - - SSL_CTX *ctx; - SSL *ssl; - int (*verify_cb)(int ok, X509_STORE_CTX *sctx) = NULL; - int num_usable = 0; - const char *nexthop_domain = "example.com"; - const char *dane_tlsa_domain = "smtp.example.com"; - uint8_t usage, selector, mtype; - - if ((ctx = SSL_CTX_new(TLS_client_method())) == NULL) - /* handle error */ - if (SSL_CTX_dane_enable(ctx) <= 0) - /* handle error */ - - if ((ssl = SSL_new(ctx)) == NULL) - /* handle error */ - - if (SSL_dane_enable(ssl, dane_tlsa_domain) <= 0) - /* handle error */ - - /* - * For many applications it is safe to skip DANE-EE(3) namechecks. Do not - * disable the checks unless "unknown key share" attacks pose no risk for - * your application. - */ - SSL_dane_set_flags(ssl, DANE_FLAG_NO_DANE_EE_NAMECHECKS); - - if (!SSL_add1_host(ssl, nexthop_domain)) - /* handle error */ - SSL_set_hostflags(ssl, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); - - for (... each TLSA record ...) { - unsigned char *data; - size_t len; - int ret; - - /* set usage, selector, mtype, data, len */ - - /* - * Opportunistic DANE TLS clients support only DANE-TA(2) or DANE-EE(3). - * They treat all other certificate usages, and in particular PKIX-TA(0) - * and PKIX-EE(1), as unusable. - */ - switch (usage) { - default: - case 0: /* PKIX-TA(0) */ - case 1: /* PKIX-EE(1) */ - continue; - case 2: /* DANE-TA(2) */ - case 3: /* DANE-EE(3) */ - break; - } - - ret = SSL_dane_tlsa_add(ssl, usage, selector, mtype, data, len); - /* free data as appropriate */ - - if (ret < 0) - /* handle SSL library internal error */ - else if (ret == 0) - /* handle unusable TLSA record */ - else - ++num_usable; - } - - /* - * At this point, the verification mode is still the default SSL_VERIFY_NONE. - * Opportunistic DANE clients use unauthenticated TLS when all TLSA records - * are unusable, so continue the handshake even if authentication fails. - */ - if (num_usable == 0) { - /* Log all records unusable? */ - - /* Optionally set verify_cb to a suitable non-NULL callback. */ - SSL_set_verify(ssl, SSL_VERIFY_NONE, verify_cb); - } else { - /* At least one usable record. We expect to verify the peer */ - - /* Optionally set verify_cb to a suitable non-NULL callback. */ - - /* - * Below we elect to fail the handshake when peer verification fails. - * Alternatively, use the permissive SSL_VERIFY_NONE verification mode, - * complete the handshake, check the verification status, and if not - * verified disconnect gracefully at the application layer, especially if - * application protocol supports informing the server that authentication - * failed. - */ - SSL_set_verify(ssl, SSL_VERIFY_PEER, verify_cb); - } - - /* - * Load any saved session for resumption, making sure that the previous - * session applied the same security and authentication requirements that - * would be expected of a fresh connection. - */ - - /* Perform SSL_connect() handshake and handle errors here */ - - if (SSL_session_reused(ssl)) { - if (SSL_get_verify_result(ssl) == X509_V_OK) { - /* - * Resumed session was originally verified, this connection is - * authenticated. - */ - } else { - /* - * Resumed session was not originally verified, this connection is not - * authenticated. - */ - } - } else if (SSL_get_verify_result(ssl) == X509_V_OK) { - const char *peername = SSL_get0_peername(ssl); - EVP_PKEY *mspki = NULL; - - int depth = SSL_get0_dane_authority(ssl, NULL, &mspki); - if (depth >= 0) { - (void) SSL_get0_dane_tlsa(ssl, &usage, &selector, &mtype, NULL, NULL); - printf("DANE TLSA %d %d %d %s at depth %d\n", usage, selector, mtype, - (mspki != NULL) ? "TA public key verified certificate" : - depth ? "matched TA certificate" : "matched EE certificate", - depth); - } - if (peername != NULL) { - /* Name checks were in scope and matched the peername */ - printf("Verified peername: %s\n", peername); - } - } else { - /* - * Not authenticated, presumably all TLSA rrs unusable, but possibly a - * callback suppressed connection termination despite the presence of - * usable TLSA RRs none of which matched. Do whatever is appropriate for - * fresh unauthenticated connections. - */ - } - -=head1 NOTES - -It is expected that the majority of clients employing DANE TLS will be doing -"opportunistic DANE TLS" in the sense of RFC7672 and RFC7435. -That is, they will use DANE authentication when DNSSEC-validated TLSA records -are published for a given peer, and otherwise will use unauthenticated TLS or -even cleartext. - -Such applications should generally treat any TLSA records published by the peer -with usages PKIX-TA(0) and PKIX-EE(1) as "unusable", and should not include -them among the TLSA records used to authenticate peer connections. -In addition, some TLSA records with supported usages may be "unusable" as a -result of invalid or unsupported parameters. - -When a peer has TLSA records, but none are "usable", an opportunistic -application must avoid cleartext, but cannot authenticate the peer, -and so should generally proceed with an unauthenticated connection. -Opportunistic applications need to note the return value of each -call to SSL_dane_tlsa_add(), and if all return 0 (due to invalid -or unsupported parameters) disable peer authentication by calling -L with B equal to B. - -=head1 SEE ALSO - -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L, -L - -=head1 HISTORY - -These functions were first added to OpenSSL 1.1.0. - -=head1 COPYRIGHT - -Copyright 2016-2018 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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_sess_set_get_cb.pod b/doc/ssl/SSL_CTX_sess_set_get_cb.pod deleted file mode 100644 index d2b0e047..00000000 --- a/doc/ssl/SSL_CTX_sess_set_get_cb.pod +++ /dev/null @@ -1,96 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_sess_set_new_cb, SSL_CTX_sess_set_remove_cb, SSL_CTX_sess_set_get_cb, SSL_CTX_sess_get_new_cb, SSL_CTX_sess_get_remove_cb, SSL_CTX_sess_get_get_cb - provide callback functions for server side external session caching - -=head1 SYNOPSIS - - #include - - void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx, - int (*new_session_cb)(SSL *, SSL_SESSION *)); - void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx, - void (*remove_session_cb)(SSL_CTX *ctx, SSL_SESSION *)); - void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, - SSL_SESSION (*get_session_cb)(SSL *, const unsigned char *, int, int *)); - - int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(struct ssl_st *ssl, SSL_SESSION *sess); - void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(struct ssl_ctx_st *ctx, SSL_SESSION *sess); - SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(struct ssl_st *ssl, const unsigned char *data, int len, int *copy); - - int (*new_session_cb)(struct ssl_st *ssl, SSL_SESSION *sess); - void (*remove_session_cb)(struct ssl_ctx_st *ctx, SSL_SESSION *sess); - SSL_SESSION *(*get_session_cb)(struct ssl_st *ssl, unsigned char *data, - int len, int *copy); - -=head1 DESCRIPTION - -SSL_CTX_sess_set_new_cb() sets the callback function, which is automatically -called whenever a new session was negotiated. - -SSL_CTX_sess_set_remove_cb() sets the callback function, which is -automatically called whenever a session is removed by the SSL engine, -because it is considered faulty or the session has become obsolete because -of exceeding the timeout value. - -SSL_CTX_sess_set_get_cb() sets the callback function which is called, -whenever a SSL/TLS client proposed to resume a session but the session -could not be found in the internal session cache (see -L). -(SSL/TLS server only.) - -SSL_CTX_sess_get_new_cb(), SSL_CTX_sess_get_remove_cb(), and -SSL_CTX_sess_get_get_cb() allow to retrieve the function pointers of the -provided callback functions. If a callback function has not been set, -the NULL pointer is returned. - -=head1 NOTES - -In order to allow external session caching, synchronization with the internal -session cache is realized via callback functions. Inside these callback -functions, session can be saved to disk or put into a database using the -L interface. - -The new_session_cb() is called, whenever a new session has been negotiated -and session caching is enabled (see -L). -The new_session_cb() is passed the B connection and the ssl session -B. If the callback returns B<0>, the session will be immediately -removed again. - -The remove_session_cb() is called, whenever the SSL engine removes a session -from the internal cache. This happens when the session is removed because -it is expired or when a connection was not shutdown cleanly. It also happens -for all sessions in the internal session cache when -L is called. The remove_session_cb() is passed -the B and the ssl session B. It does not provide any feedback. - -The get_session_cb() is only called on SSL/TLS servers with the session id -proposed by the client. The get_session_cb() is always called, also when -session caching was disabled. The get_session_cb() is passed the -B connection, the session id of length B at the memory location -B. With the parameter B the callback can require the -SSL engine to increment the reference count of the SSL_SESSION object, -Normally the reference count is not incremented and therefore the -session must not be explicitly freed with -L. - -=head1 SEE ALSO - -L, L, -L, -L, -L, -L - -=head1 COPYRIGHT - -Copyright 2001-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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_set1_curves.pod b/doc/ssl/SSL_CTX_set1_curves.pod deleted file mode 100644 index b0276c80..00000000 --- a/doc/ssl/SSL_CTX_set1_curves.pod +++ /dev/null @@ -1,90 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_set1_curves, SSL_CTX_set1_curves_list, SSL_set1_curves, -SSL_set1_curves_list, SSL_get1_curves, SSL_get_shared_curve - EC supported curve functions - -=head1 SYNOPSIS - - #include - - int SSL_CTX_set1_curves(SSL_CTX *ctx, int *clist, int clistlen); - int SSL_CTX_set1_curves_list(SSL_CTX *ctx, char *list); - - int SSL_set1_curves(SSL *ssl, int *clist, int clistlen); - int SSL_set1_curves_list(SSL *ssl, char *list); - - int SSL_get1_curves(SSL *ssl, int *curves); - int SSL_get_shared_curve(SSL *s, int n); - -=head1 DESCRIPTION - -SSL_CTX_set1_curves() sets the supported curves for B to B -curves in the array B. The array consist of all NIDs of curves in -preference order. For a TLS client the curves are used directly in the -supported curves extension. For a TLS server the curves are used to -determine the set of shared curves. - -SSL_CTX_set1_curves_list() sets the supported curves for B to -string B. The string is a colon separated list of curve NIDs or -names, for example "P-521:P-384:P-256". - -SSL_set1_curves() and SSL_set1_curves_list() are similar except they set -supported curves for the SSL structure B. - -SSL_get1_curves() returns the set of supported curves sent by a client -in the supported curves extension. It returns the total number of -supported curves. The B parameter can be B to simply -return the number of curves for memory allocation purposes. The -B array is in the form of a set of curve NIDs in preference -order. It can return zero if the client did not send a supported curves -extension. - -SSL_get_shared_curve() returns shared curve B for a server-side -SSL B. If B is -1 then the total number of shared curves is -returned, which may be zero. Other than for diagnostic purposes, -most applications will only be interested in the first shared curve -so B is normally set to zero. If the value B is out of range, -NID_undef is returned. - -All these functions are implemented as macros. - -=head1 NOTES - -If an application wishes to make use of several of these functions for -configuration purposes either on a command line or in a file it should -consider using the SSL_CONF interface instead of manually parsing options. - -=head1 RETURN VALUES - -SSL_CTX_set1_curves(), SSL_CTX_set1_curves_list(), SSL_set1_curves() and -SSL_set1_curves_list(), return 1 for success and 0 for failure. - -SSL_get1_curves() returns the number of curves, which may be zero. - -SSL_get_shared_curve() returns the NID of shared curve B or NID_undef if there -is no shared curve B; or the total number of shared curves if B -is -1. - -When called on a client B, SSL_get_shared_curve() has no meaning and -returns -1. - -=head1 SEE ALSO - -L - -=head1 HISTORY - -These functions were first added to OpenSSL 1.0.2. - -=head1 COPYRIGHT - -Copyright 2013-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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_set_cert_store.pod b/doc/ssl/SSL_CTX_set_cert_store.pod deleted file mode 100644 index 7f7a794b..00000000 --- a/doc/ssl/SSL_CTX_set_cert_store.pod +++ /dev/null @@ -1,73 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_set_cert_store, SSL_CTX_get_cert_store - manipulate X509 certificate verification storage - -=head1 SYNOPSIS - - #include - - void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store); - X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx); - -=head1 DESCRIPTION - -SSL_CTX_set_cert_store() sets/replaces the certificate verification storage -of B to/with B. If another X509_STORE object is currently -set in B, it will be X509_STORE_free()ed. - -SSL_CTX_get_cert_store() returns a pointer to the current certificate -verification storage. - -=head1 NOTES - -In order to verify the certificates presented by the peer, trusted CA -certificates must be accessed. These CA certificates are made available -via lookup methods, handled inside the X509_STORE. From the X509_STORE -the X509_STORE_CTX used when verifying certificates is created. - -Typically the trusted certificate store is handled indirectly via using -L. -Using the SSL_CTX_set_cert_store() and SSL_CTX_get_cert_store() functions -it is possible to manipulate the X509_STORE object beyond the -L -call. - -Currently no detailed documentation on how to use the X509_STORE -object is available. Not all members of the X509_STORE are used when -the verification takes place. So will e.g. the verify_callback() be -overridden with the verify_callback() set via the -L family of functions. -This document must therefore be updated when documentation about the -X509_STORE object and its handling becomes available. - -=head1 RESTRICTIONS - -The X509_STORE structure used by an SSL_CTX is used for verifying peer -certificates and building certificate chains, it is also shared by -every child SSL structure. Applications wanting finer control can use -functions such as SSL_CTX_set1_verify_cert_store() instead. - -=head1 RETURN VALUES - -SSL_CTX_set_cert_store() does not return diagnostic output. - -SSL_CTX_get_cert_store() returns the current setting. - -=head1 SEE ALSO - -L, -L, -L - -=head1 COPYRIGHT - -Copyright 2001-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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_set_mode.pod b/doc/ssl/SSL_CTX_set_mode.pod deleted file mode 100644 index 1b3e783a..00000000 --- a/doc/ssl/SSL_CTX_set_mode.pod +++ /dev/null @@ -1,114 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_set_mode, SSL_set_mode, SSL_CTX_get_mode, SSL_get_mode - manipulate SSL engine mode - -=head1 SYNOPSIS - - #include - - long SSL_CTX_set_mode(SSL_CTX *ctx, long mode); - long SSL_set_mode(SSL *ssl, long mode); - - long SSL_CTX_get_mode(SSL_CTX *ctx); - long SSL_get_mode(SSL *ssl); - -=head1 DESCRIPTION - -SSL_CTX_set_mode() adds the mode set via bitmask in B to B. -Options already set before are not cleared. - -SSL_set_mode() adds the mode set via bitmask in B to B. -Options already set before are not cleared. - -SSL_CTX_get_mode() returns the mode set for B. - -SSL_get_mode() returns the mode set for B. - -=head1 NOTES - -The following mode changes are available: - -=over 4 - -=item SSL_MODE_ENABLE_PARTIAL_WRITE - -Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success -when just a single record has been written). When not set (the default), -SSL_write() will only report success once the complete chunk was written. -Once SSL_write() returns with r, r bytes have been successfully written -and the next call to SSL_write() must only send the n-r bytes left, -imitating the behaviour of write(). - -=item SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER - -Make it possible to retry SSL_write() with changed buffer location -(the buffer contents must stay the same). This is not the default to avoid -the misconception that non-blocking SSL_write() behaves like -non-blocking write(). - -=item SSL_MODE_AUTO_RETRY - -Never bother the application with retries if the transport is blocking. -If a renegotiation take place during normal operation, a -L or L would return -with -1 and indicate the need to retry with SSL_ERROR_WANT_READ. -In a non-blocking environment applications must be prepared to handle -incomplete read/write operations. -In a blocking environment, applications are not always prepared to -deal with read/write operations returning without success report. The -flag SSL_MODE_AUTO_RETRY will cause read/write operations to only -return after the handshake and successful completion. - -=item SSL_MODE_RELEASE_BUFFERS - -When we no longer need a read buffer or a write buffer for a given SSL, -then release the memory we were using to hold it. -Using this flag can -save around 34k per idle SSL connection. -This flag has no effect on SSL v2 connections, or on DTLS connections. - -=item SSL_MODE_SEND_FALLBACK_SCSV - -Send TLS_FALLBACK_SCSV in the ClientHello. -To be set only by applications that reconnect with a downgraded protocol -version; see draft-ietf-tls-downgrade-scsv-00 for details. - -DO NOT ENABLE THIS if your application attempts a normal handshake. -Only use this in explicit fallback retries, following the guidance -in draft-ietf-tls-downgrade-scsv-00. - -=item SSL_MODE_ASYNC - -Enable asynchronous processing. TLS I/O operations may indicate a retry with -SSL_ERROR_WANT_ASYNC with this mode set if an asynchronous capable engine is -used to perform cryptographic operations. See L. - -=back - -=head1 RETURN VALUES - -SSL_CTX_set_mode() and SSL_set_mode() return the new mode bitmask -after adding B. - -SSL_CTX_get_mode() and SSL_get_mode() return the current bitmask. - -=head1 SEE ALSO - -L, L, L, L - -=head1 HISTORY - -SSL_MODE_ASYNC was first added to OpenSSL 1.1.0. - -=head1 COPYRIGHT - -Copyright 2001-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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_set_msg_callback.pod b/doc/ssl/SSL_CTX_set_msg_callback.pod deleted file mode 100644 index 9546e751..00000000 --- a/doc/ssl/SSL_CTX_set_msg_callback.pod +++ /dev/null @@ -1,103 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_set_msg_callback, SSL_CTX_set_msg_callback_arg, SSL_set_msg_callback, SSL_set_msg_callback_arg - install callback for observing protocol messages - -=head1 SYNOPSIS - - #include - - 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)); - void SSL_CTX_set_msg_callback_arg(SSL_CTX *ctx, void *arg); - - 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)); - void SSL_set_msg_callback_arg(SSL *ssl, void *arg); - -=head1 DESCRIPTION - -SSL_CTX_set_msg_callback() or SSL_set_msg_callback() can be used to -define a message callback function I for observing all SSL/TLS -protocol messages (such as handshake messages) that are received or -sent. SSL_CTX_set_msg_callback_arg() and SSL_set_msg_callback_arg() -can be used to set argument I to the callback function, which is -available for arbitrary application use. - -SSL_CTX_set_msg_callback() and SSL_CTX_set_msg_callback_arg() specify -default settings that will be copied to new B objects by -L. SSL_set_msg_callback() and -SSL_set_msg_callback_arg() modify the actual settings of an B -object. Using a B<0> pointer for I disables the message callback. - -When I is called by the SSL/TLS library for a protocol message, -the function arguments have the following meaning: - -=over 4 - -=item I - -This flag is B<0> when a protocol message has been received and B<1> -when a protocol message has been sent. - -=item I - -The protocol version according to which the protocol message is -interpreted by the library. Currently, this is one of -B, B and B (for SSL 2.0, SSL -3.0 and TLS 1.0, respectively). - -=item I - -In the case of SSL 2.0, this is always B<0>. In the case of SSL 3.0 -or TLS 1.0, this is one of the B values defined in the -protocol specification (B, B, -B; but never B because the -callback will only be called for protocol messages). - -=item I, I - -I points to a buffer containing the protocol message, which -consists of I bytes. The buffer is no longer valid after the -callback function has returned. - -=item I - -The B object that received or sent the message. - -=item I - -The user-defined argument optionally defined by -SSL_CTX_set_msg_callback_arg() or SSL_set_msg_callback_arg(). - -=back - -=head1 NOTES - -Protocol messages are passed to the callback function after decryption -and fragment collection where applicable. (Thus record boundaries are -not visible.) - -If processing a received protocol message results in an error, -the callback function may not be called. For example, the callback -function will never see messages that are considered too large to be -processed. - -Due to automatic protocol version negotiation, I is not -necessarily the protocol version used by the sender of the message: If -a TLS 1.0 ClientHello message is received by an SSL 3.0-only server, -I will be B. - -=head1 SEE ALSO - -L, L - -=head1 COPYRIGHT - -Copyright 2001-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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_set_psk_client_callback.pod b/doc/ssl/SSL_CTX_set_psk_client_callback.pod deleted file mode 100644 index a4175081..00000000 --- a/doc/ssl/SSL_CTX_set_psk_client_callback.pod +++ /dev/null @@ -1,63 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_set_psk_client_callback, SSL_set_psk_client_callback - set PSK client callback - -=head1 SYNOPSIS - - #include - - void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, - unsigned int (*callback)(SSL *ssl, const char *hint, - char *identity, unsigned int max_identity_len, - unsigned char *psk, unsigned int max_psk_len)); - void SSL_set_psk_client_callback(SSL *ssl, - unsigned int (*callback)(SSL *ssl, const char *hint, - char *identity, unsigned int max_identity_len, - unsigned char *psk, unsigned int max_psk_len)); - - -=head1 DESCRIPTION - -A client application must provide a callback function which is called -when the client is sending the ClientKeyExchange message to the server. - -The purpose of the callback function is to select the PSK identity and -the pre-shared key to use during the connection setup phase. - -The callback is set using functions SSL_CTX_set_psk_client_callback() -or SSL_set_psk_client_callback(). The callback function is given the -connection in parameter B, a B-terminated PSK identity hint -sent by the server in parameter B, a buffer B of -length B bytes where the resulting -B-terminated identity is to be stored, and a buffer B of -length B bytes where the resulting pre-shared key is to -be stored. - -=head1 NOTES - -Note that parameter B given to the callback may be B. - -=head1 RETURN VALUES - -Return values from the client callback are interpreted as follows: - -On success (callback found a PSK identity and a pre-shared key to use) -the length (> 0) of B in bytes is returned. - -Otherwise or on errors callback should return 0. In this case -the connection setup fails. - -=head1 COPYRIGHT - -Copyright 2006-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 -L. - -Copyright 2005 Nokia. - -=cut diff --git a/doc/ssl/SSL_CTX_set_security_level.pod b/doc/ssl/SSL_CTX_set_security_level.pod deleted file mode 100644 index 577b3937..00000000 --- a/doc/ssl/SSL_CTX_set_security_level.pod +++ /dev/null @@ -1,169 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_set_security_level, SSL_set_security_level, SSL_CTX_get_security_level, SSL_get_security_level, SSL_CTX_set_security_callback, SSL_set_security_callback, SSL_CTX_get_security_callback, SSL_get_security_callback, SSL_CTX_set0_security_ex_data, SSL_set0_security_ex_data, SSL_CTX_get0_security_ex_data, SSL_get0_security_ex_data - SSL/TLS security framework - -=head1 SYNOPSIS - - #include - - void SSL_CTX_set_security_level(SSL_CTX *ctx, int level); - void SSL_set_security_level(SSL *s, int level); - - int SSL_CTX_get_security_level(const SSL_CTX *ctx); - int SSL_get_security_level(const SSL *s); - - void SSL_CTX_set_security_callback(SSL_CTX *ctx, - int (*cb)(SSL *s, SSL_CTX *ctx, int op, int bits, int nid, - void *other, void *ex)); - - void SSL_set_security_callback(SSL *s, - int (*cb)(SSL *s, SSL_CTX *ctx, int op, int bits, int nid, - void *other, void *ex)); - - int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx))(SSL *s, SSL_CTX *ctx, int op, int bits, int nid, void *other, void *ex); - int (*SSL_get_security_callback(const SSL *s))(SSL *s, SSL_CTX *ctx, int op, int bits, int nid, void *other, void *ex); - - void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex); - void SSL_set0_security_ex_data(SSL *s, void *ex); - - void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx); - void *SSL_get0_security_ex_data(const SSL *s); - -=head1 DESCRIPTION - -The functions SSL_CTX_set_security_level() and SSL_set_security_level() set -the security level to B. If not set the library default security level -is used. - -The functions SSL_CTX_get_security_level() and SSL_get_security_level() -retrieve the current security level. - -SSL_CTX_set_security_callback(), SSL_set_security_callback(), -SSL_CTX_get_security_callback() and SSL_get_security_callback() get or set -the security callback associated with B or B. If not set a default -security callback is used. The meaning of the parameters and the behaviour -of the default callbacks is described below. - -SSL_CTX_set0_security_ex_data(), SSL_set0_security_ex_data(), -SSL_CTX_get0_security_ex_data() and SSL_get0_security_ex_data() set the -extra data pointer passed to the B parameter of the callback. This -value is passed to the callback verbatim and can be set to any convenient -application specific value. - -=head1 DEFAULT CALLBACK BEHAVIOUR - -If an application doesn't set its own security callback the default -callback is used. It is intended to provide sane defaults. The meaning -of each level is described below. - -=over 4 - -=item B - -Everything is permitted. This retains compatibility with previous versions of -OpenSSL. - -=item B - -The security level corresponds to a minimum of 80 bits of security. Any -parameters offering below 80 bits of security are excluded. As a result RSA, -DSA and DH keys shorter than 1024 bits and ECC keys shorter than 160 bits -are prohibited. All export ciphersuites are prohibited since they all offer -less than 80 bits of security. SSL version 2 is prohibited. Any ciphersuite -using MD5 for the MAC is also prohibited. - -=item B - -Security level set to 112 bits of security. As a result RSA, DSA and DH keys -shorter than 2048 bits and ECC keys shorter than 224 bits are prohibited. -In addition to the level 1 exclusions any ciphersuite using RC4 is also -prohibited. SSL version 3 is also not allowed. Compression is disabled. - -=item B - -Security level set to 128 bits of security. As a result RSA, DSA and DH keys -shorter than 3072 bits and ECC keys shorter than 256 bits are prohibited. -In addition to the level 2 exclusions ciphersuites not offering forward -secrecy are prohibited. TLS versions below 1.1 are not permitted. Session -tickets are disabled. - -=item B - -Security level set to 192 bits of security. As a result RSA, DSA and DH keys -shorter than 7680 bits and ECC keys shorter than 384 bits are prohibited. -Ciphersuites using SHA1 for the MAC are prohibited. TLS versions below 1.2 are -not permitted. - -=item B - -Security level set to 256 bits of security. As a result RSA, DSA and DH keys -shorter than 15360 bits and ECC keys shorter than 512 bits are prohibited. - -=back - -=head1 APPLICATION DEFINED SECURITY CALLBACKS - -I - -=head1 NOTES - -B at this time setting the security level higher than 1 for -general internet use is likely to cause B interoperability -issues and is not recommended. This is because the B algorithm -is very widely used in certificates and will be rejected at levels -higher than 1 because it only offers 80 bits of security. - -The default security level can be configured when OpenSSL is compiled by -setting B<-DOPENSSL_TLS_SECURITY_LEVEL=level>. If not set then 1 is used. - -The security framework disables or reject parameters inconsistent with the -set security level. In the past this was difficult as applications had to set -a number of distinct parameters (supported ciphers, supported curves supported -signature algorithms) to achieve this end and some cases (DH parameter size -for example) could not be checked at all. - -By setting an appropriate security level much of this complexity can be -avoided. - -The bits of security limits affect all relevant parameters including -ciphersuite encryption algorithms, supported ECC curves, supported -signature algorithms, DH parameter sizes, certificate key sizes and -signature algorithms. This limit applies no matter what other custom -settings an application has set: so if the ciphersuite is set to B -then only ciphersuites consistent with the security level are permissible. - -See SP800-57 for how the security limits are related to individual -algorithms. - -Some security levels require large key sizes for non-ECC public key -algorithms which can severely degrade performance. For example 256 bits -of security requires the use of RSA keys of at least 15360 bits in size. - -Some restrictions can be gracefully handled: for example ciphersuites -offering insufficient security are not sent by the client and will not -be selected by the server. Other restrictions such as the peer certificate -key size or the DH parameter size will abort the handshake with a fatal -alert. - -Attempts to set certificates or parameters with insufficient security are -also blocked. For example trying to set a certificate using a 512 bit RSA -key using SSL_CTX_use_certificate() at level 1. Applications which do not -check the return values for errors will misbehave: for example it might -appear that a certificate is not set at all because it had been rejected. - -=head1 HISTORY - -These functions were first added to OpenSSL 1.1.0 - -=head1 COPYRIGHT - -Copyright 2014-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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_set_split_send_fragment.pod b/doc/ssl/SSL_CTX_set_split_send_fragment.pod deleted file mode 100644 index accf5af2..00000000 --- a/doc/ssl/SSL_CTX_set_split_send_fragment.pod +++ /dev/null @@ -1,132 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_set_max_send_fragment, SSL_set_max_send_fragment, -SSL_CTX_set_split_send_fragment, SSL_set_split_send_fragment, -SSL_CTX_set_max_pipelines, SSL_set_max_pipelines, -SSL_CTX_set_default_read_buffer_len, SSL_set_default_read_buffer_len - Control -fragment sizes and pipelining operations - -=head1 SYNOPSIS - - #include - - long SSL_CTX_set_max_send_fragment(SSL_CTX *ctx, long); - long SSL_set_max_send_fragment(SSL *ssl, long m); - - long SSL_CTX_set_max_pipelines(SSL_CTX *ctx, long m); - long SSL_set_max_pipelines(SSL_CTX *ssl, long m); - - long SSL_CTX_set_split_send_fragment(SSL_CTX *ctx, long m); - long SSL_set_split_send_fragment(SSL *ssl, long m); - - void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len); - void SSL_set_default_read_buffer_len(SSL *s, size_t len); - -=head1 DESCRIPTION - -Some engines are able to process multiple simultaneous crypto operations. This -capability could be utilised to parallelise the processing of a single -connection. For example a single write can be split into multiple records and -each one encrypted independently and in parallel. Note: this will only work in -TLS1.1+. There is no support in SSLv3, TLSv1.0 or DTLS (any version). This -capability is known as "pipelining" within OpenSSL. - -In order to benefit from the pipelining capability. You need to have an engine -that provides ciphers that support this. The OpenSSL "dasync" engine provides -AES128-SHA based ciphers that have this capability. However these are for -development and test purposes only. - -SSL_CTX_set_max_send_fragment() and SSL_set_max_send_fragment() set the -B parameter for SSL_CTX and SSL objects respectively. This -value restricts the amount of plaintext bytes that will be sent in any one -SSL/TLS record. By default its value is SSL3_RT_MAX_PLAIN_LENGTH (16384). These -functions will only accept a value in the range 512 - SSL3_RT_MAX_PLAIN_LENGTH. - -SSL_CTX_set_max_pipelines() and SSL_set_max_pipelines() set the maximum number -of pipelines that will be used at any one time. This value applies to both -"read" pipelining and "write" pipelining. By default only one pipeline will be -used (i.e. normal non-parallel operation). The number of pipelines set must be -in the range 1 - SSL_MAX_PIPELINES (32). Setting this to a value > 1 will also -automatically turn on "read_ahead" (see L). This is -explained further below. OpenSSL will only every use more than one pipeline if -a ciphersuite is negotiated that uses a pipeline capable cipher provided by an -engine. - -Pipelining operates slightly differently for reading encrypted data compared to -writing encrypted data. SSL_CTX_set_split_send_fragment() and -SSL_set_split_send_fragment() define how data is split up into pipelines when -writing encrypted data. The number of pipelines used will be determined by the -amount of data provided to the SSL_write() call divided by -B. - -For example if B is set to 2000 and B is 4 -then: - -SSL_write called with 0-2000 bytes == 1 pipeline used - -SSL_write called with 2001-4000 bytes == 2 pipelines used - -SSL_write called with 4001-6000 bytes == 3 pipelines used - -SSL_write called with 6001+ bytes == 4 pipelines used - -B must always be less than or equal to -B. By default it is set to be equal to B. -This will mean that the same number of records will always be created as would -have been created in the non-parallel case, although the data will be -apportioned differently. In the parallel case data will be spread equally -between the pipelines. - -Read pipelining is controlled in a slightly different way than with write -pipelining. While reading we are constrained by the number of records that the -peer (and the network) can provide to us in one go. The more records we can get -in one go the more opportunity we have to parallelise the processing. As noted -above when setting B to a value greater than one, B -is automatically set. The B parameter causes OpenSSL to attempt to -read as much data into the read buffer as the network can provide and will fit -into the buffer. Without this set data is read into the read buffer one record -at a time. The more data that can be read, the more opportunity there is for -parallelising the processing at the cost of increased memory overhead per -connection. Setting B can impact the behaviour of the SSL_pending() -function (see L). - -The SSL_CTX_set_default_read_buffer_len() and SSL_set_default_read_buffer_len() -functions control the size of the read buffer that will be used. The B -parameter sets the size of the buffer. The value will only be used if it is -greater than the default that would have been used anyway. The normal default -value depends on a number of factors but it will be at least -SSL3_RT_MAX_PLAIN_LENGTH + SSL3_RT_MAX_ENCRYPTED_OVERHEAD (16704) bytes. - -=head1 RETURN VALUES - -All non-void functions return 1 on success and 0 on failure. - -=head1 NOTES - -With the exception of SSL_CTX_set_default_read_buffer_len() and -SSL_set_default_read_buffer_len() all these functions are implemented using -macros. - -=head1 HISTORY - -The SSL_CTX_set_max_pipelines(), SSL_set_max_pipelines(), -SSL_CTX_set_split_send_fragment(), SSL_set_split_send_fragment(), -SSL_CTX_set_default_read_buffer_len() and SSL_set_default_read_buffer_len() -functions were added in OpenSSL 1.1.0. - -=head1 SEE ALSO - -L, L - -=head1 COPYRIGHT - -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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_set_tlsext_ticket_key_cb.pod b/doc/ssl/SSL_CTX_set_tlsext_ticket_key_cb.pod deleted file mode 100644 index 34d8ce9a..00000000 --- a/doc/ssl/SSL_CTX_set_tlsext_ticket_key_cb.pod +++ /dev/null @@ -1,198 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_set_tlsext_ticket_key_cb - set a callback for session ticket processing - -=head1 SYNOPSIS - - #include - - long SSL_CTX_set_tlsext_ticket_key_cb(SSL_CTX sslctx, - int (*cb)(SSL *s, unsigned char key_name[16], - unsigned char iv[EVP_MAX_IV_LENGTH], - EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)); - -=head1 DESCRIPTION - -SSL_CTX_set_tlsext_ticket_key_cb() sets a callback function I for handling -session tickets for the ssl context I. Session tickets, defined in -RFC5077 provide an enhanced session resumption capability where the server -implementation is not required to maintain per session state. It only applies -to TLS and there is no SSLv3 implementation. - -The callback function I will be called for every client instigated TLS -session when session ticket extension is presented in the TLS hello -message. It is the responsibility of this function to create or retrieve the -cryptographic parameters and to maintain their state. - -The OpenSSL library uses your callback function to help implement a common TLS -ticket construction state according to RFC5077 Section 4 such that per session -state is unnecessary and a small set of cryptographic variables needs to be -maintained by the callback function implementation. - -In order to reuse a session, a TLS client must send the a session ticket -extension to the server. The client can only send exactly one session ticket. -The server, through the callback function, either agrees to reuse the session -ticket information or it starts a full TLS handshake to create a new session -ticket. - -Before the callback function is started I and I have been -initialised with EVP_CIPHER_CTX_init and HMAC_CTX_init respectively. - -For new sessions tickets, when the client doesn't present a session ticket, or -an attempted retrieval of the ticket failed, or a renew option was indicated, -the callback function will be called with I equal to 1. The OpenSSL -library expects that the function will set an arbitrary I, initialize -I, and set the cipher context I and the hash context I. - -The I is 16 characters long and is used as a key identifier. - -The I length is the length of the IV of the corresponding cipher. The -maximum IV length is B bytes defined in B. - -The initialization vector I should be a random value. The cipher context -I should use the initialisation vector I. The cipher context can be -set using L. The hmac context can be set using -L. - -When the client presents a session ticket, the callback function with be called -with I set to 0 indicating that the I function should retrieve a set -of parameters. In this case I and I have already been parsed out of -the session ticket. The OpenSSL library expects that the I will be used -to retrieve a cryptographic parameters and that the cryptographic context -I will be set with the retrieved parameters and the initialization vector -I. using a function like L. The I needs to be -set using L. - -If the I is still valid but a renewal of the ticket is required the -callback function should return 2. The library will call the callback again -with an argument of enc equal to 1 to set the new ticket. - -The return value of the I function is used by OpenSSL to determine what -further processing will occur. The following return values have meaning: - -=over 4 - -=item Z<>2 - -This indicates that the I and I have been set and the session can -continue on those parameters. Additionally it indicates that the session -ticket is in a renewal period and should be replaced. The OpenSSL library will -call I again with an enc argument of 1 to set the new ticket (see RFC5077 -3.3 paragraph 2). - -=item Z<>1 - -This indicates that the I and I have been set and the session can -continue on those parameters. - -=item Z<>0 - -This indicates that it was not possible to set/retrieve a session ticket and -the SSL/TLS session will continue by negotiating a set of cryptographic -parameters or using the alternate SSL/TLS resumption mechanism, session ids. - -If called with enc equal to 0 the library will call the I again to get -a new set of parameters. - -=item less than 0 - -This indicates an error. - -=back - -=head1 NOTES - -Session resumption shortcuts the TLS so that the client certificate -negotiation don't occur. It makes up for this by storing client certificate -an all other negotiated state information encrypted within the ticket. In a -resumed session the applications will have all this state information available -exactly as if a full negotiation had occurred. - -If an attacker can obtain the key used to encrypt a session ticket, they can -obtain the master secret for any ticket using that key and decrypt any traffic -using that session: even if the ciphersuite supports forward secrecy. As -a result applications may wish to use multiple keys and avoid using long term -keys stored in files. - -Applications can use longer keys to maintain a consistent level of security. -For example if a ciphersuite uses 256 bit ciphers but only a 128 bit ticket key -the overall security is only 128 bits because breaking the ticket key will -enable an attacker to obtain the session keys. - -=head1 EXAMPLES - -Reference Implementation: - SSL_CTX_set_tlsext_ticket_key_cb(SSL, ssl_tlsext_ticket_key_cb); - .... - - static int ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16], unsigned char *iv, EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc) - { - if (enc) { /* create new session */ - if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) ) { - return -1; /* insufficient random */ - } - - key = currentkey(); /* something that you need to implement */ - if ( !key ) { - /* current key doesn't exist or isn't valid */ - key = createkey(); /* something that you need to implement. - * createkey needs to initialise, a name, - * an aes_key, a hmac_key and optionally - * an expire time. */ - if ( !key ) { /* key couldn't be created */ - return 0; - } - } - memcpy(key_name, key->name, 16); - - EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key->aes_key, iv); - HMAC_Init_ex(&hctx, key->hmac_key, 16, EVP_sha256(), NULL); - - return 1; - - } else { /* retrieve session */ - key = findkey(name); - - if (!key || key->expire < now() ) { - return 0; - } - - HMAC_Init_ex(&hctx, key->hmac_key, 16, EVP_sha256(), NULL); - EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key->aes_key, iv ); - - if (key->expire < ( now() - RENEW_TIME ) ) { - /* return 2 - this session will get a new ticket even though the current is still valid */ - return 2; - } - return 1; - - } - } - - - -=head1 RETURN VALUES - -returns 0 to indicate the callback function was set. - -=head1 SEE ALSO - -L, L, -L, -L, -L, -L, -L, - -=head1 COPYRIGHT - -Copyright 2014-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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_set_verify.pod b/doc/ssl/SSL_CTX_set_verify.pod deleted file mode 100644 index 79934989..00000000 --- a/doc/ssl/SSL_CTX_set_verify.pod +++ /dev/null @@ -1,307 +0,0 @@ -=pod - -=head1 NAME - -SSL_get_ex_data_X509_STORE_CTX_idx, -SSL_CTX_set_verify, SSL_set_verify, -SSL_CTX_set_verify_depth, SSL_set_verify_depth, -SSL_verify_cb -- set peer certificate verification parameters - -=head1 SYNOPSIS - - #include - - void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, SSL_verify_cb verify_callback); - void SSL_set_verify(SSL *s, int mode, SSL_verify_cb verify_callback); - SSL_get_ex_data_X509_STORE_CTX_idx(void); - - void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth); - void SSL_set_verify_depth(SSL *s, int depth); - - - typedef int (*SSL_verify_cb)(int preverify_ok, X509_STORE_CTX *x509_ctx); - -=head1 DESCRIPTION - -SSL_CTX_set_verify() sets the verification flags for B to be B and -specifies the B function to be used. If no callback function -shall be specified, the NULL pointer can be used for B. - -SSL_set_verify() sets the verification flags for B to be B and -specifies the B function to be used. If no callback function -shall be specified, the NULL pointer can be used for B. In -this case last B set specifically for this B remains. If -no special B was set before, the default callback for the underlying -B is used, that was valid at the time B was created with -L. Within the callback function, -B can be called to get the data index -of the current SSL object that is doing the verification. - -SSL_CTX_set_verify_depth() sets the maximum B for the certificate chain -verification that shall be allowed for B. - -SSL_set_verify_depth() sets the maximum B for the certificate chain -verification that shall be allowed for B. - -=head1 NOTES - -The verification of certificates can be controlled by a set of logically -or'ed B flags: - -=over 4 - -=item SSL_VERIFY_NONE - -B the server will not send a client certificate request to the -client, so the client will not send a certificate. - -B if not using an anonymous cipher (by default disabled), the -server will send a certificate which will be checked. The result of the -certificate verification process can be checked after the TLS/SSL handshake -using the L function. -The handshake will be continued regardless of the verification result. - -=item SSL_VERIFY_PEER - -B the server sends a client certificate request to the client. -The certificate returned (if any) is checked. If the verification process -fails, the TLS/SSL handshake is -immediately terminated with an alert message containing the reason for -the verification failure. -The behaviour can be controlled by the additional -SSL_VERIFY_FAIL_IF_NO_PEER_CERT and SSL_VERIFY_CLIENT_ONCE flags. - -B the server certificate is verified. If the verification process -fails, the TLS/SSL handshake is -immediately terminated with an alert message containing the reason for -the verification failure. If no server certificate is sent, because an -anonymous cipher is used, SSL_VERIFY_PEER is ignored. - -=item SSL_VERIFY_FAIL_IF_NO_PEER_CERT - -B if the client did not return a certificate, the TLS/SSL -handshake is immediately terminated with a "handshake failure" alert. -This flag must be used together with SSL_VERIFY_PEER. - -B ignored - -=item SSL_VERIFY_CLIENT_ONCE - -B only request a client certificate on the initial TLS/SSL -handshake. Do not ask for a client certificate again in case of a -renegotiation. This flag must be used together with SSL_VERIFY_PEER. - -B ignored - -=back - -If the B is SSL_VERIFY_NONE none of the other flags may be set. - -The actual verification procedure is performed either using the built-in -verification procedure or using another application provided verification -function set with -L. -The following descriptions apply in the case of the built-in procedure. An -application provided procedure also has access to the verify depth information -and the verify_callback() function, but the way this information is used -may be different. - -SSL_CTX_set_verify_depth() and SSL_set_verify_depth() set a limit on the -number of certificates between the end-entity and trust-anchor certificates. -Neither the -end-entity nor the trust-anchor certificates count against B. If the -certificate chain needed to reach a trusted issuer is longer than B, -X509_V_ERR_CERT_CHAIN_TOO_LONG will be issued. -The depth count is "level 0:peer certificate", "level 1: CA certificate", -"level 2: higher level CA certificate", and so on. Setting the maximum -depth to 2 allows the levels 0, 1, 2 and 3 (0 being the end-entity and 3 the -trust-anchor). -The default depth limit is 100, -allowing for the peer certificate, at most 100 intermediate CA certificates and -a final trust anchor certificate. - -The B function is used to control the behaviour when the -SSL_VERIFY_PEER flag is set. It must be supplied by the application and -receives two arguments: B indicates, whether the verification of -the certificate in question was passed (preverify_ok=1) or not -(preverify_ok=0). B is a pointer to the complete context used -for the certificate chain verification. - -The certificate chain is checked starting with the deepest nesting level -(the root CA certificate) and worked upward to the peer's certificate. -At each level signatures and issuer attributes are checked. Whenever -a verification error is found, the error number is stored in B -and B is called with B=0. By applying -X509_CTX_store_* functions B can locate the certificate -in question and perform additional steps (see EXAMPLES). If no error is -found for a certificate, B is called with B=1 -before advancing to the next level. - -The return value of B controls the strategy of the further -verification process. If B returns 0, the verification -process is immediately stopped with "verification failed" state. If -SSL_VERIFY_PEER is set, a verification failure alert is sent to the peer and -the TLS/SSL handshake is terminated. If B returns 1, -the verification process is continued. If B always returns -1, the TLS/SSL handshake will not be terminated with respect to verification -failures and the connection will be established. The calling process can -however retrieve the error code of the last verification error using -L or by maintaining its -own error storage managed by B. - -If no B is specified, the default callback will be used. -Its return value is identical to B, so that any verification -failure will lead to a termination of the TLS/SSL handshake with an -alert message, if SSL_VERIFY_PEER is set. - -=head1 BUGS - -In client mode, it is not checked whether the SSL_VERIFY_PEER flag -is set, but whether any flags are set. This can lead to -unexpected behaviour if SSL_VERIFY_PEER and other flags are not used as -required. - -=head1 RETURN VALUES - -The SSL*_set_verify*() functions do not provide diagnostic information. - -=head1 EXAMPLES - -The following code sequence realizes an example B function -that will always continue the TLS/SSL handshake regardless of verification -failure, if wished. The callback realizes a verification depth limit with -more informational output. - -All verification errors are printed; information about the certificate chain -is printed on request. -The example is realized for a server that does allow but not require client -certificates. - -The example makes use of the ex_data technique to store application data -into/retrieve application data from the SSL structure -(see L, -L). - - ... - typedef struct { - int verbose_mode; - int verify_depth; - int always_continue; - } mydata_t; - int mydata_index; - ... - static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) - { - char buf[256]; - X509 *err_cert; - int err, depth; - SSL *ssl; - mydata_t *mydata; - - err_cert = X509_STORE_CTX_get_current_cert(ctx); - err = X509_STORE_CTX_get_error(ctx); - depth = X509_STORE_CTX_get_error_depth(ctx); - - /* - * Retrieve the pointer to the SSL of the connection currently treated - * and the application specific data stored into the SSL object. - */ - ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); - mydata = SSL_get_ex_data(ssl, mydata_index); - - X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256); - - /* - * Catch a too long certificate chain. The depth limit set using - * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so - * that whenever the "depth>verify_depth" condition is met, we - * have violated the limit and want to log this error condition. - * We must do it here, because the CHAIN_TOO_LONG error would not - * be found explicitly; only errors introduced by cutting off the - * additional certificates would be logged. - */ - if (depth > mydata->verify_depth) { - preverify_ok = 0; - err = X509_V_ERR_CERT_CHAIN_TOO_LONG; - X509_STORE_CTX_set_error(ctx, err); - } - if (!preverify_ok) { - printf("verify error:num=%d:%s:depth=%d:%s\n", err, - X509_verify_cert_error_string(err), depth, buf); - } - else if (mydata->verbose_mode) - { - printf("depth=%d:%s\n", depth, buf); - } - - /* - * At this point, err contains the last verification error. We can use - * it for something special - */ - if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) - { - X509_NAME_oneline(X509_get_issuer_name(err_cert), buf, 256); - printf("issuer= %s\n", buf); - } - - if (mydata->always_continue) - return 1; - else - return preverify_ok; - } - ... - - mydata_t mydata; - - ... - mydata_index = SSL_get_ex_new_index(0, "mydata index", NULL, NULL, NULL); - - ... - SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE, - verify_callback); - - /* - * Let the verify_callback catch the verify_depth error so that we get - * an appropriate error in the logfile. - */ - SSL_CTX_set_verify_depth(verify_depth + 1); - - /* - * Set up the SSL specific data into "mydata" and store it into th SSL - * structure. - */ - mydata.verify_depth = verify_depth; ... - SSL_set_ex_data(ssl, mydata_index, &mydata); - - ... - SSL_accept(ssl); /* check of success left out for clarity */ - if (peer = SSL_get_peer_certificate(ssl)) - { - if (SSL_get_verify_result(ssl) == X509_V_OK) - { - /* The client sent a certificate which verified OK */ - } - } - -=head1 SEE ALSO - -L, L, -L, -L, -L, -L, -L, -L, -L - -=head1 COPYRIGHT - -Copyright 2000-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 -L. - -=cut diff --git a/doc/ssl/SSL_CTX_use_psk_identity_hint.pod b/doc/ssl/SSL_CTX_use_psk_identity_hint.pod deleted file mode 100644 index 753074a7..00000000 --- a/doc/ssl/SSL_CTX_use_psk_identity_hint.pod +++ /dev/null @@ -1,87 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_use_psk_identity_hint, SSL_use_psk_identity_hint, -SSL_CTX_set_psk_server_callback, SSL_set_psk_server_callback - set PSK -identity hint to use - -=head1 SYNOPSIS - - #include - - int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *hint); - int SSL_use_psk_identity_hint(SSL *ssl, const char *hint); - - void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, - unsigned int (*callback)(SSL *ssl, const char *identity, - unsigned char *psk, int max_psk_len)); - void SSL_set_psk_server_callback(SSL *ssl, - unsigned int (*callback)(SSL *ssl, const char *identity, - unsigned char *psk, int max_psk_len)); - - -=head1 DESCRIPTION - -SSL_CTX_use_psk_identity_hint() sets the given B-terminated PSK -identity hint B to SSL context object -B. SSL_use_psk_identity_hint() sets the given B-terminated -PSK identity hint B to SSL connection object B. If B -is B the current hint from B or B is deleted. - -In the case where PSK identity hint is B, the server -does not send the ServerKeyExchange message to the client. - -A server application must provide a callback function which is called -when the server receives the ClientKeyExchange message from the -client. The purpose of the callback function is to validate the -received PSK identity and to fetch the pre-shared key used during the -connection setup phase. The callback is set using functions -SSL_CTX_set_psk_server_callback() or -SSL_set_psk_server_callback(). The callback function is given the -connection in parameter B, B-terminated PSK identity sent -by the client in parameter B, and a buffer B of length -B bytes where the pre-shared key is to be stored. - - -=head1 RETURN VALUES - -SSL_CTX_use_psk_identity_hint() and SSL_use_psk_identity_hint() return -1 on success, 0 otherwise. - -Return values from the server callback are interpreted as follows: - -=over 4 - -=item Z<>0 - -PSK identity was not found. An "unknown_psk_identity" alert message -will be sent and the connection setup fails. - -=item E0 - -PSK identity was found and the server callback has provided the PSK -successfully in parameter B. Return value is the length of -B in bytes. It is an error to return a value greater than -B. - -If the PSK identity was not found but the callback instructs the -protocol to continue anyway, the callback must provide some random -data to B and return the length of the random data, so the -connection will fail with decryption_error before it will be finished -completely. - -=back - -=head1 COPYRIGHT - -Copyright 2006-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 -L. - -Copyright 2005 Nokia. - -=cut diff --git a/doc/ssl/SSL_CTX_use_serverinfo.pod b/doc/ssl/SSL_CTX_use_serverinfo.pod deleted file mode 100644 index bd496ff8..00000000 --- a/doc/ssl/SSL_CTX_use_serverinfo.pod +++ /dev/null @@ -1,56 +0,0 @@ -=pod - -=head1 NAME - -SSL_CTX_use_serverinfo, SSL_CTX_use_serverinfo_file - use serverinfo extension - -=head1 SYNOPSIS - - #include - - int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, - size_t serverinfo_length); - - int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file); - -=head1 DESCRIPTION - -These functions load "serverinfo" TLS ServerHello Extensions into the SSL_CTX. -A "serverinfo" extension is returned in response to an empty ClientHello -Extension. - -SSL_CTX_use_serverinfo() loads one or more serverinfo extensions from -a byte array into B. The extensions must be concatenated into a -sequence of bytes. Each extension must consist of a 2-byte Extension Type, -a 2-byte length, and then length bytes of extension_data. - -SSL_CTX_use_serverinfo_file() loads one or more serverinfo extensions from -B into B. The extensions must be in PEM format. Each extension -must consist of a 2-byte Extension Type, a 2-byte length, and then length -bytes of extension_data. Each PEM extension name must begin with the phrase -"BEGIN SERVERINFO FOR ". - -If more than one certificate (RSA/DSA) is installed using -SSL_CTX_use_certificate(), the serverinfo extension will be loaded into the -last certificate installed. If e.g. the last item was a RSA certificate, the -loaded serverinfo extension data will be loaded for that certificate. To -use the serverinfo extension for multiple certificates, -SSL_CTX_use_serverinfo() needs to be called multiple times, once B -each time a certificate is loaded. - -=head1 RETURN VALUES - -On success, the functions return 1. -On failure, the functions return 0. Check out the error stack to find out -the reason. - -=head1 COPYRIGHT - -Copyright 2013-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 -L. - -=cut diff --git a/doc/ssl/SSL_SESSION_get0_cipher.pod b/doc/ssl/SSL_SESSION_get0_cipher.pod deleted file mode 100644 index fdd36edc..00000000 --- a/doc/ssl/SSL_SESSION_get0_cipher.pod +++ /dev/null @@ -1,42 +0,0 @@ -=pod - -=head1 NAME - -SSL_SESSION_get0_cipher - retrieve the SSL cipher associated with a session - -=head1 SYNOPSIS - - #include - - const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSSION *s); - -=head1 DESCRIPTION - -SSL_SESSION_get0_cipher() retrieves the cipher that was used by the -connection when the session was created, or NULL if it cannot be determined. - -The value returned is a pointer to an object maintained within B and -should not be released. - -=head1 SEE ALSO - -L, -L, -L, -L, -L - -=head1 HISTORY - -SSL_SESSION_get0_cipher() was first added to OpenSSL 1.1.0 - -=head1 COPYRIGHT - -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 -L. - -=cut diff --git a/doc/ssl/SSL_SESSION_get0_hostname.pod b/doc/ssl/SSL_SESSION_get0_hostname.pod deleted file mode 100644 index 6fb12bec..00000000 --- a/doc/ssl/SSL_SESSION_get0_hostname.pod +++ /dev/null @@ -1,37 +0,0 @@ -=pod - -=head1 NAME - -SSL_SESSION_get0_hostname - retrieve the SNI hostname associated with a session - -=head1 SYNOPSIS - - #include - - const char *SSL_SESSION_get0_hostname(const SSL_SESSSION *s); - -=head1 DESCRIPTION - -SSL_SESSION_get0_hostname() retrieves the SNI value that was sent by the -client when the session was created, or NULL if no value was sent. - -The value returned is a pointer to memory maintained within B and -should not be free'd. - -=head1 SEE ALSO - -L, -L, -L, -L - -=head1 COPYRIGHT - -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 -L. - -=cut diff --git a/doc/ssl/SSL_SESSION_get_protocol_version.pod b/doc/ssl/SSL_SESSION_get_protocol_version.pod deleted file mode 100644 index a033fdd9..00000000 --- a/doc/ssl/SSL_SESSION_get_protocol_version.pod +++ /dev/null @@ -1,44 +0,0 @@ -=pod - -=head1 NAME - -SSL_SESSION_get_protocol_version - retrieve session protocol version - -=head1 SYNOPSIS - - #include - - int SSL_SESSION_get_protocol_version(const SSL_SESSION *s); - -=head1 DESCRIPTION - -SSL_SESSION_get_protocol_version() returns the protocol version number used -by session B. - -=head1 RETURN VALUES - -SSL_SESSION_get_protocol_version() returns a number indicating the protocol -version used for the session; this number matches the constants I -B or B. - -Note that the SSL_SESSION_get_protocol_version() function -does B perform a null check on the provided session B pointer. - -=head1 SEE ALSO - -L - -=head1 HISTORY - -SSL_SESSION_get_protocol_version() was first added to OpenSSL 1.1.0 - -=head1 COPYRIGHT - -Copyright 2001-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 -L. - -=cut diff --git a/doc/ssl/SSL_export_keying_material.pod b/doc/ssl/SSL_export_keying_material.pod deleted file mode 100644 index ccb99ec9..00000000 --- a/doc/ssl/SSL_export_keying_material.pod +++ /dev/null @@ -1,61 +0,0 @@ -=pod - -=head1 NAME - -SSL_export_keying_material - obtain keying material for application use - -=head1 SYNOPSIS - - #include - - 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); - -=head1 DESCRIPTION - -During the creation of a TLS or DTLS connection shared keying material is -established between the two endpoints. The function SSL_export_keying_material() -enables an application to use some of this keying material for its own purposes -in accordance with RFC5705. - -An application may need to securely establish the context within which this -keying material will be used. For example this may include identifiers for the -application session, application algorithms or parameters, or the lifetime of -the context. The context value is left to the application but must be the same -on both sides of the communication. - -For a given SSL connection B, B bytes of data will be written to -B. The application specific context should be supplied in the location -pointed to by B and should be B bytes long. Provision of -a context is optional. If the context should be omitted entirely then -B should be set to 0. Otherwise it should be any other value. If -B is 0 then the values of B and B are ignored. -Note that a zero length context is treated differently to no context at all, and -will result in different keying material being returned. - -An application specific label should be provided in the location pointed to by -B

- statements with prefix P. Default: 'openssl/' (without - the quotes, naturally) - NOTE: not used any more because our include directory - structure has changed. + -debug Verbose output debugging on stderr. - -debug Turn on debugging verbose output on stderr. + -internal Generate code that is to be built as part of OpenSSL itself. + Also scans internal list of files. - -rebuild Rebuild all header and C source files, irrespective of the - fact if any error or function codes have been added/removed. - Default: only update files for libraries which saw change - (of course, this requires '-write' as well, or no - files will be touched!) + -module M Only useful with -internal! + Only write files for library module M. Whether files are + actually written or not depends on other options, such as + -rebuild. + Note: this option is cumulative. If not given at all, all + internal modules will be considered. - -recurse scan a preconfigured set of directories / files for error and - function codes: - (, , , ) - When this option is NOT specified, the filelist is taken from - the commandline instead. Here, wildcards may be embedded. (Be - sure to escape those to prevent the shell from expanding them - for you when you wish mkerr.pl to do so instead.) - Default: take file list to scan from the command line. + -nowrite Do not write the header/source files, even if changed. - -reindex Discard the numeric values previously assigned to the error - and function codes as extracted from the scanned header files; - instead renumber all of them starting from 100. (Note that - the numbers assigned through 'R' records in the config file - remain intact.) - Default: keep previously assigned numbers. (You are warned - when collisions are detected.) + -rebuild Rebuild all header and C source files, even if there + were no changes. - -nostatic Generates a different source code, where these additional - functions are generated for each library specified in the - config file: - void ERR_load__strings(void); - void ERR_unload__strings(void); - void ERR__error(int f, int r, char *fn, int ln); - #define err(f,r) ERR__error(f,r,OPENSSL_FILE,OPENSSL_LINE) - while the code facilitates the use of these in an environment - where the error support routines are dynamically loaded at - runtime. - Default: 'static' code generation. + -reindex Ignore previously assigned values (except for R records in + the config file) and renumber everything starting at 100. - -staticloader Prefix generated functions with the 'static' scope modifier. - Default: don't write any scope modifier prefix. + -static Make the load/unload functions static. - -unref Print out unreferenced function and reason codes. + -unref List all unreferenced function and reason codes on stderr; + implies -nowrite. - -write Actually (over)write the generated code to the header and C - source files as assigned to each library through the config - file. - Default: don't write. + -help Show this help text. - -help / -h / -? / --help Show this help text. - - ... Additional arguments are added to the file list to scan, - assuming '-recurse' was NOT specified on the command line. + ... Additional arguments are added to the file list to scan, + if '-internal' was NOT specified on the command line. EOF - exit 1; - } else { - last; - } } -if($recurse) { - @source = ( , , , ) +while ( @ARGV ) { + my $arg = $ARGV[0]; + last unless $arg =~ /-.*/; + $arg = $1 if $arg =~ /-(-.*)/; + if ( $arg eq "-conf" ) { + $config = $ARGV[1]; + shift @ARGV; + } elsif ( $arg eq "-debug" ) { + $debug = 1; + $unref = 1; + } elsif ( $arg eq "-internal" ) { + $internal = 1; + } elsif ( $arg eq "-nowrite" ) { + $nowrite = 1; + } elsif ( $arg eq "-rebuild" ) { + $rebuild = 1; + } elsif ( $arg eq "-reindex" ) { + $reindex = 1; + } elsif ( $arg eq "-static" ) { + $static = 1; + } elsif ( $arg eq "-unref" ) { + $unref = 1; + $nowrite = 1; + } elsif ( $arg eq "-module" ) { + shift @ARGV; + $modules{uc $ARGV[0]} = 1; + } elsif ( $arg =~ /-*h(elp)?/ ) { + &help(); + exit; + } elsif ( $arg =~ /-.*/ ) { + die "Unknown option $arg; use -h for help.\n"; + } + shift @ARGV; +} + +my @source; +if ( $internal ) { + die "Cannot mix -internal and -static\n" if $static; + die "Extra parameters given.\n" if @ARGV; + @source = ( glob('crypto/*.c'), glob('crypto/*/*.c'), + glob('ssl/*.c'), glob('ssl/*/*.c') ); } else { - @source = @ARGV; + die "-module isn't useful without -internal\n" if scalar keys %modules > 0; + @source = @ARGV; } -# Read in the config file +# Data parsed out of the config and state files. +my %hinc; # lib -> header +my %libinc; # header -> lib +my %cskip; # error_file -> lib +my %errorfile; # lib -> error file name +my %fmax; # lib -> max assigned function code +my %rmax; # lib -> max assigned reason code +my %fassigned; # lib -> colon-separated list of assigned function codes +my %rassigned; # lib -> colon-separated list of assigned reason codes +my %fnew; # lib -> count of new function codes +my %rnew; # lib -> count of new reason codes +my %rextra; # "extra" reason code -> lib +my %rcodes; # reason-name -> value +my %ftrans; # old name -> #define-friendly name (all caps) +my %fcodes; # function-name -> value +my $statefile; # state file with assigned reason and function codes +my %strings; # define -> text -open(IN, "<$config") || die "Can't open config file $config"; - -# Parse config file - -while() -{ - if(/^L\s+(\S+)\s+(\S+)\s+(\S+)/) { - $hinc{$1} = $2; - $libinc{$2} = $1; - $cskip{$3} = $1; - if($3 ne "NONE") { - $csrc{$1} = $3; - $fmax{$1} = 100; - $rmax{$1} = 100; - $fassigned{$1} = ":"; - $rassigned{$1} = ":"; - $fnew{$1} = 0; - $rnew{$1} = 0; - } - } elsif (/^F\s+(\S+)/) { - # Add extra function with $1 - } elsif (/^R\s+(\S+)\s+(\S+)/) { - $rextra{$1} = $2; - $rcodes{$1} = $2; - } +# Read and parse the config file +open(IN, "$config") || die "Can't open config file $config, $!,"; +while ( ) { + next if /^#/ || /^$/; + if ( /^L\s+(\S+)\s+(\S+)\s+(\S+)/ ) { + my $lib = $1; + my $hdr = $2; + my $err = $3; + $hinc{$lib} = $hdr; + $libinc{$hdr} = $lib; + $cskip{$err} = $lib; + next if $err eq 'NONE'; + $errorfile{$lib} = $err; + $fmax{$lib} = 100; + $rmax{$lib} = 100; + $fassigned{$lib} = ":"; + $rassigned{$lib} = ":"; + $fnew{$lib} = 0; + $rnew{$lib} = 0; + } elsif ( /^R\s+(\S+)\s+(\S+)/ ) { + $rextra{$1} = $2; + $rcodes{$1} = $2; + } elsif ( /^S\s+(\S+)/ ) { + $statefile = $1; + } else { + die "Illegal config line $_\n"; + } } - close IN; -# Scan each header file in turn and make a list of error codes -# and function names - -while (($hdr, $lib) = each %libinc) -{ - next if($hdr eq "NONE"); - print STDERR "Scanning header file $hdr\n" if $debug; - my $line = "", $def= "", $linenr = 0, $gotfile = 0, $cpp = 0; - if (open(IN, "<$hdr")) { - $gotfile = 1; - while() { - $linenr++; - print STDERR "line: $linenr\r" if $debug; - - last if(/BEGIN\s+ERROR\s+CODES/); - if ($line ne '') { - $_ = $line . $_; - $line = ''; - } - - if (/\\$/) { - $line = $_; - next; - } - - if(/\/\*/) { - if (not /\*\//) { # multiline comment... - $line = $_; # ... just accumulate - next; - } else { - s/\/\*.*?\*\///gs; # wipe it - } - } - - if ($cpp) { - $cpp++ if /^#\s*if/; - $cpp-- if /^#\s*endif/; - next; - } - $cpp = 1 if /^#.*ifdef.*cplusplus/; # skip "C" declaration - - next if (/^\#/); # skip preprocessor directives - - s/{[^{}]*}//gs; # ignore {} blocks - - if (/\{|\/\*/) { # Add a } so editor works... - $line = $_; - } else { - $def .= $_; - } - } - } - - print STDERR " \r" if $debug; - $defnr = 0; - # Delete any DECLARE_ macros - $def =~ s/DECLARE_\w+\([\w,\s]+\)//gs; - foreach (split /;/, $def) { - $defnr++; - print STDERR "def: $defnr\r" if $debug; - - # The goal is to collect function names from function declarations. - - s/^[\n\s]*//g; - s/[\n\s]*$//g; - - # Skip over recognized non-function declarations - next if(/typedef\W/ or /DECLARE_STACK_OF/ or /TYPEDEF_.*_OF/); - - # Remove STACK_OF(foo) - s/STACK_OF\(\w+\)/void/; - - # Reduce argument lists to empty () - # fold round brackets recursively: (t(*v)(t),t) -> (t{}{},t) -> {} - while(/\(.*\)/s) { - s/\([^\(\)]+\)/\{\}/gs; - s/\(\s*\*\s*(\w+)\s*\{\}\s*\)/$1/gs; #(*f{}) -> f - } - # pretend as we didn't use curly braces: {} -> () - s/\{\}/\(\)/gs; - - if (/(\w+)\s*\(\).*/s) { # first token prior [first] () is - my $name = $1; # a function name! - $name =~ tr/[a-z]/[A-Z]/; - $ftrans{$name} = $1; - } elsif (/[\(\)]/ and not (/=/)) { - print STDERR "Header $hdr: cannot parse: $_;\n"; - } - } - - print STDERR " \r" if $debug; - - next if $reindex; - - # Scan function and reason codes and store them: keep a note of the - # maximum code used. - - if ($gotfile) { - while() { - if(/^\#\s*define\s+(\S+)\s+(\S+)/) { - $name = $1; - $code = $2; - next if $name =~ /^${lib}err/; - unless($name =~ /^${lib}_([RF])_(\w+)$/) { - print STDERR "Invalid error code $name\n"; - next; - } - if($1 eq "R") { - $rcodes{$name} = $code; - if ($rassigned{$lib} =~ /:$code:/) { - print STDERR "!! ERROR: $lib reason code $code assigned twice (collision at $name)\n"; - ++$errcount; - } - $rassigned{$lib} .= "$code:"; - if(!(exists $rextra{$name}) && - ($code > $rmax{$lib}) ) { - $rmax{$lib} = $code; - } - } else { - if ($fassigned{$lib} =~ /:$code:/) { - print STDERR "!! ERROR: $lib function code $code assigned twice (collision at $name)\n"; - ++$errcount; - } - $fassigned{$lib} .= "$code:"; - if($code > $fmax{$lib}) { - $fmax{$lib} = $code; - } - $fcodes{$name} = $code; - } - } - } - } - - if ($debug) { - if (defined($fmax{$lib})) { - print STDERR "Max function code fmax" . "{" . "$lib" . "} = $fmax{$lib}\n"; - $fassigned{$lib} =~ m/^:(.*):$/; - @fassigned = sort {$a <=> $b} split(":", $1); - print STDERR " @fassigned\n"; - } - if (defined($rmax{$lib})) { - print STDERR "Max reason code rmax" . "{" . "$lib" . "} = $rmax{$lib}\n"; - $rassigned{$lib} =~ m/^:(.*):$/; - @rassigned = sort {$a <=> $b} split(":", $1); - print STDERR " @rassigned\n"; - } - } - - if ($lib eq "SSL") { - if ($rmax{$lib} >= 1000) { - print STDERR "!! ERROR: SSL error codes 1000+ are reserved for alerts.\n"; - print STDERR "!! Any new alerts must be added to $config.\n"; - ++$errcount; - print STDERR "\n"; - } - } - close IN; +if ( ! $statefile ) { + $statefile = $config; + $statefile =~ s/.ec/.txt/; } +# The statefile has all the previous assignments. +&phase("Reading state"); +my $skippedstate = 0; +if ( ! $reindex && $statefile ) { + open(STATE, "<$statefile") || die "Can't open $statefile, $!"; + + # Scan function and reason codes and store them: keep a note of the + # maximum code used. + while ( ) { + next if /^#/ || /^$/; + my $name; + my $code; + if ( /^(.+):(\d+):\\$/ ) { + $name = $1; + $code = $2; + my $next = ; + $next =~ s/^\s*(.*)\s*$/$1/; + die "Duplicate define $name" if exists $strings{$name}; + $strings{$name} = $next; + } elsif ( /^(\S+):(\d+):(.*)$/ ) { + $name = $1; + $code = $2; + die "Duplicate define $name" if exists $strings{$name}; + $strings{$name} = $3; + } else { + die "Bad line in $statefile:\n$_\n"; + } + my $lib = $name; + $lib =~ s/^((?:OSSL_|OPENSSL_)?[^_]{2,}).*$/$1/; + $lib = "SSL" if $lib =~ /TLS/; + if ( !defined $errorfile{$lib} ) { + print "Skipping $_"; + $skippedstate++; + next; + } + if ( $name =~ /^(?:OSSL_|OPENSSL_)?[A-Z0-9]{2,}_R_/ ) { + die "$lib reason code $code collision at $name\n" + if $rassigned{$lib} =~ /:$code:/; + $rassigned{$lib} .= "$code:"; + if ( !exists $rextra{$name} ) { + $rmax{$lib} = $code if $code > $rmax{$lib}; + } + $rcodes{$name} = $code; + } elsif ( $name =~ /^(?:OSSL_|OPENSSL_)?[A-Z0-9]{2,}_F_/ ) { + die "$lib function code $code collision at $name\n" + if $fassigned{$lib} =~ /:$code:/; + $fassigned{$lib} .= "$code:"; + $fmax{$lib} = $code if $code > $fmax{$lib}; + $fcodes{$name} = $code; + } else { + die "Bad line in $statefile:\n$_\n"; + } + } + close(STATE); + + if ( $debug ) { + foreach my $lib ( sort keys %rmax ) { + print STDERR "Reason codes for ${lib}:\n"; + if ( $rassigned{$lib} =~ m/^:(.*):$/ ) { + my @rassigned = sort { $a <=> $b } split( ":", $1 ); + print STDERR " ", join(' ', @rassigned), "\n"; + } else { + print STDERR " --none--\n"; + } + } + print STDERR "\n"; + foreach my $lib ( sort keys %fmax ) { + print STDERR "Function codes for ${lib}:\n"; + if ( $fassigned{$lib} =~ m/^:(.*):$/ ) { + my @fassigned = sort { $a <=> $b } split( ":", $1 ); + print STDERR " ", join(' ', @fassigned), "\n"; + } else { + print STDERR " --none--\n"; + } + } + } +} + +# Scan each header file and make a list of error codes +# and function names +&phase("Scanning headers"); +while ( ( my $hdr, my $lib ) = each %libinc ) { + next if $hdr eq "NONE"; + print STDERR " ." if $debug; + my $line = ""; + my $def = ""; + my $linenr = 0; + my $cpp = 0; + + open(IN, "<$hdr") || die "Can't open $hdr, $!,"; + while ( ) { + $linenr++; + + if ( $line ne '' ) { + $_ = $line . $_; + $line = ''; + } + + if ( /\\$/ ) { + $line = $_; + next; + } + + if ( /\/\*/ ) { + if ( not /\*\// ) { # multiline comment... + $line = $_; # ... just accumulate + next; + } else { + s/\/\*.*?\*\///gs; # wipe it + } + } + + if ( $cpp ) { + $cpp++ if /^#\s*if/; + $cpp-- if /^#\s*endif/; + next; + } + $cpp = 1 if /^#.*ifdef.*cplusplus/; # skip "C" declaration + + next if /^\#/; # skip preprocessor directives + + s/{[^{}]*}//gs; # ignore {} blocks + + if ( /\{|\/\*/ ) { # Add a so editor works... + $line = $_; + } else { + $def .= $_; + } + } + + # Delete any DECLARE_ macros + my $defnr = 0; + $def =~ s/DECLARE_\w+\([\w,\s]+\)//gs; + foreach ( split /;/, $def ) { + $defnr++; + # The goal is to collect function names from function declarations. + + s/^[\n\s]*//g; + s/[\n\s]*$//g; + + # Skip over recognized non-function declarations + next if /typedef\W/ or /DECLARE_STACK_OF/ or /TYPEDEF_.*_OF/; + + # Remove STACK_OF(foo) + s/STACK_OF\(\w+\)/void/; + + # Reduce argument lists to empty () + # fold round brackets recursively: (t(*v)(t),t) -> (t{}{},t) -> {} + while ( /\(.*\)/s ) { + s/\([^\(\)]+\)/\{\}/gs; + s/\(\s*\*\s*(\w+)\s*\{\}\s*\)/$1/gs; #(*f{}) -> f + } + + # pretend as we didn't use curly braces: {} -> () + s/\{\}/\(\)/gs; + + # Last token just before the first () is a function name. + if ( /(\w+)\s*\(\).*/s ) { + my $name = $1; + $name =~ tr/[a-z]/[A-Z]/; + $ftrans{$name} = $1; + } elsif ( /[\(\)]/ and not(/=/) ) { + print STDERR "Header $hdr: cannot parse: $_;\n"; + } + } + + next if $reindex; + + if ( $lib eq "SSL" && $rmax{$lib} >= 1000 ) { + print STDERR "SSL error codes 1000+ are reserved for alerts.\n"; + print STDERR "Any new alerts must be added to $config.\n"; + $errors++; + } + close IN; +} +print STDERR "\n" if $debug; + # Scan each C source file and look for function and reason codes # This is done by looking for strings that "look like" function or # reason codes: basically anything consisting of all upper case and # numerics which has _F_ or _R_ in it and which has the name of an -# error library at the start. This seems to work fine except for the +# error library at the start. This seems to work fine except for the # oddly named structure BIO_F_CTX which needs to be ignored. # If a code doesn't exist in list compiled from headers then mark it # with the value "X" as a place holder to give it a value later. -# Store all function and reason codes found in %ufcodes and %urcodes +# Store all function and reason codes found in %usedfuncs and %usedreasons # so all those unreferenced can be printed out. +&phase("Scanning source"); +my %usedfuncs; +my %usedreasons; +foreach my $file ( @source ) { + # Don't parse the error source file. + next if exists $cskip{$file}; + open( IN, "<$file" ) || die "Can't open $file, $!,"; + my $func; + my $linenr = 0; + print STDERR "$file:\n" if $debug; + while ( ) { + # skip obsoleted source files entirely! + last if /^#error\s+obsolete/; + $linenr++; + if ( !/;$/ && /^\**([a-zA-Z_].*[\s*])?([A-Za-z_0-9]+)\(.*([),]|$)/ ) { + /^([^()]*(\([^()]*\)[^()]*)*)\(/; + $1 =~ /([A-Za-z_0-9]*)$/; + $func = $1; + } -foreach $file (@source) { - # Don't parse the error source file. - next if exists $cskip{$file}; - print STDERR "File loaded: ".$file."\r" if $debug; - open(IN, "<$file") || die "Can't open source file $file\n"; - my $func; - my $linenr = 0; - while() { - # skip obsoleted source files entirely! - last if(/^#error\s+obsolete/); - $linenr++; - if (!/;$/ && /^\**([a-zA-Z_].*[\s*])?([A-Za-z_0-9]+)\(.*([),]|$)/) - { - /^([^()]*(\([^()]*\)[^()]*)*)\(/; - $1 =~ /([A-Za-z_0-9]*)$/; - $func = $1; - } - - if(/(([A-Z0-9]+)_F_([A-Z0-9_]+))/) { - next unless exists $csrc{$2}; - next if($1 eq "BIO_F_BUFFER_CTX"); - $ufcodes{$1} = 1; - if(!exists $fcodes{$1}) { - $fcodes{$1} = "X"; - $fnew{$2}++; - } - $ftrans{$3} = $func unless exists $ftrans{$3}; - if (uc $func ne $3) { - print STDERR "ERROR: mismatch $file:$linenr $func:$3\n"; - $errcount++; + if ( /(((?:OSSL_|OPENSSL_)?[A-Z0-9]{2,})_F_([A-Z0-9_]+))/ ) { + next unless exists $errorfile{$2}; + next if $1 eq "BIO_F_BUFFER_CTX"; + $usedfuncs{$1} = 1; + if ( !exists $fcodes{$1} ) { + print STDERR " New function $1\n" if $debug; + $fcodes{$1} = "X"; + $fnew{$2}++; } - print STDERR "Function: $1\t= $fcodes{$1} (lib: $2, name: $3)\n" if $debug; - } - if(/(([A-Z0-9]+)_R_[A-Z0-9_]+)/) { - next unless exists $csrc{$2}; - $urcodes{$1} = 1; - if(!exists $rcodes{$1}) { - $rcodes{$1} = "X"; - $rnew{$2}++; - } - print STDERR "Reason: $1\t= $rcodes{$1} (lib: $2)\n" if $debug; - } - } - close IN; + $ftrans{$3} = $func unless exists $ftrans{$3}; + if ( uc($func) ne $3 ) { + print STDERR "ERROR: mismatch $file:$linenr $func:$3\n"; + $errors++; + } + print STDERR " Function $1 = $fcodes{$1}\n" + if $debug; + } + if ( /(((?:OSSL_|OPENSSL_)?[A-Z0-9]{2,})_R_[A-Z0-9_]+)/ ) { + next unless exists $errorfile{$2}; + $usedreasons{$1} = 1; + if ( !exists $rcodes{$1} ) { + print STDERR " New reason $1\n" if $debug; + $rcodes{$1} = "X"; + $rnew{$2}++; + } + print STDERR " Reason $1 = $rcodes{$1}\n" if $debug; + } + } + close IN; } -print STDERR " \n" if $debug; +print STDERR "\n" if $debug; # Now process each library in turn. +&phase("Writing files"); +my $newstate = 0; +foreach my $lib ( keys %errorfile ) { + if ( ! $fnew{$lib} && ! $rnew{$lib} ) { + next unless $rebuild; + } + next if scalar keys %modules > 0 && !$modules{$lib}; + next if $nowrite; + print STDERR "$lib: $fnew{$lib} new functions\n" if $fnew{$lib}; + print STDERR "$lib: $rnew{$lib} new reasons\n" if $rnew{$lib}; + $newstate = 1; -foreach $lib (keys %csrc) -{ - my $hfile = $hinc{$lib}; - my $cfile = $csrc{$lib}; - if(!$fnew{$lib} && !$rnew{$lib}) { - next unless $rebuild; - } else { - print STDERR "$lib:\t\t$fnew{$lib} New Functions,"; - print STDERR " $rnew{$lib} New Reasons.\n"; - next unless $dowrite; - } + # If we get here then we have some new error codes so we + # need to rebuild the header file and C file. - # If we get here then we have some new error codes so we - # need to rebuild the header file and C file. + # Make a sorted list of error and reason codes for later use. + my @function = sort grep( /^${lib}_/, keys %fcodes ); + my @reasons = sort grep( /^${lib}_/, keys %rcodes ); - # Make a sorted list of error and reason codes for later use. + # indent level for innermost preprocessor lines + my $indent = " "; - my @function = sort grep(/^${lib}_/,keys %fcodes); - my @reasons = sort grep(/^${lib}_/,keys %rcodes); + # Rewrite the header file - # Rewrite the header file - - $cpp = 0; - $cplusplus = 0; - if (open(IN, "<$hfile")) { - # Copy across the old file - while() { - $cplusplus = $cpp if /^#.*ifdef.*cplusplus/; - $cpp++ if /^#\s*if/; - $cpp-- if /^#\s*endif/; - push @out, $_; - last if (/BEGIN ERROR CODES/); - } - close IN; - } else { - $cpp = 1; - $cplusplus = 1; - push @out, -"/*\n", -" * Copyright 1995-$YEAR The OpenSSL Project Authors. All Rights Reserved.\n", -" *\n", -" * Licensed under the OpenSSL license (the \"License\"). You may not use\n", -" * this file except in compliance with the License. You can obtain a copy\n", -" * in the file LICENSE in the source distribution or at\n", -" * https://www.openssl.org/source/license.html\n", -" */\n", -"\n", -"#ifndef HEADER_${lib}_ERR_H\n", -"# define HEADER_${lib}_ERR_H\n", -"\n", -"# ifdef __cplusplus\n", -"extern \"C\" {\n", -"# endif\n", -"\n", -"/* BEGIN ERROR CODES */\n"; - } - open (OUT, ">$hfile") || die "Can't Open File $hfile for writing\n"; - - print OUT @out; - undef @out; - print OUT <<"EOF"; + my $hfile = $hinc{$lib}; + $hfile =~ s/.h$/err.h/ if $internal; + open( OUT, ">$hfile" ) || die "Can't write to $hfile, $!,"; + print OUT <<"EOF"; /* - * 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. + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-$YEAR 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 */ -EOF - if($static) { - print OUT <<"EOF"; -${staticloader}int ERR_load_${lib}_strings(void); +#ifndef HEADER_${lib}ERR_H +# define HEADER_${lib}ERR_H EOF - } else { - print OUT <<"EOF"; -${staticloader}int ERR_load_${lib}_strings(void); -${staticloader}void ERR_unload_${lib}_strings(void); -${staticloader}void ERR_${lib}_error(int function, int reason, char *file, int line); -# define ${lib}err(f,r) ERR_${lib}_error((f),(r),OPENSSL_FILE,OPENSSL_LINE) + if ( $internal ) { + # Declare the load function because the generate C file + # includes "fooerr.h" not "foo.h" + if ($lib ne "SSL" && $lib ne "ASYNC" + && grep { $lib eq uc $_ } @disablables) { + print OUT <<"EOF"; +# include + +# ifndef OPENSSL_NO_${lib} EOF - } - print OUT <<"EOF"; -/* Error codes for the $lib functions. */ - -/* Function codes. */ + $indent = " "; + } + print OUT <<"EOF"; +#${indent}ifdef __cplusplus +extern \"C\" +#${indent}endif +int ERR_load_${lib}_strings(void); EOF - - foreach $i (@function) { - $z=48 - length($i); - if($fcodes{$i} eq "X") { - $fassigned{$lib} =~ m/^:([^:]*):/; - $findcode = $1; - if (!defined($findcode)) { - $findcode = $fmax{$lib}; - } - while ($fassigned{$lib} =~ m/:$findcode:/) { - $findcode++; - } - $fcodes{$i} = $findcode; - $fassigned{$lib} .= "$findcode:"; - print STDERR "New Function code $i\n" if $debug; - } - printf OUT "# define $i%s $fcodes{$i}\n"," " x $z; - } - - print OUT "\n/* Reason codes. */\n"; - - foreach $i (@reasons) { - $z=48 - length($i); - if($rcodes{$i} eq "X") { - $rassigned{$lib} =~ m/^:([^:]*):/; - $findcode = $1; - if (!defined($findcode)) { - $findcode = $rmax{$lib}; - } - while ($rassigned{$lib} =~ m/:$findcode:/) { - $findcode++; - } - $rcodes{$i} = $findcode; - $rassigned{$lib} .= "$findcode:"; - print STDERR "New Reason code $i\n" if $debug; - } - printf OUT "# define $i%s $rcodes{$i}\n"," " x $z; - } - print OUT <<"EOF"; + } else { + print OUT <<"EOF"; +# define ${lib}err(f, r) ERR_${lib}_error((f), (r), OPENSSL_FILE, OPENSSL_LINE) EOF - do { - if ($cplusplus == $cpp) { - print OUT "#", " "x$cpp, "ifdef __cplusplus\n"; - print OUT "}\n"; - print OUT "#", " "x$cpp, "endif\n"; - } - if ($cpp-- > 0) { - print OUT "#", " "x$cpp, "endif\n"; - } - } while ($cpp); - close OUT; + if ( ! $static ) { + print OUT <<"EOF"; - # Rewrite the C source file containing the error details. +# ifdef __cplusplus +extern \"C\" { +# endif +int ERR_load_${lib}_strings(void); +void ERR_unload_${lib}_strings(void); +void ERR_${lib}_error(int function, int reason, char *file, int line); +# ifdef __cplusplus +} +# endif +EOF + } + } - # First, read any existing reason string definitions: - my %err_reason_strings; - if (open(IN,"<$cfile")) { - my $line = ""; - while () { - s|\R$||; # Better chomp - $_ = $line . $_; - $line = ""; - if (/{ERR_(FUNC|REASON)\(/) { - if (/\b(${lib}_R_\w*)\b.*\"(.*)\"/) { - $err_reason_strings{$1} = $2; - } elsif (/\b${lib}_F_(\w*)\b.*\"(.*)\"/) { - if (!exists $ftrans{$1} && ($1 ne $2)) { - print STDERR "WARNING: Mismatched function string $2\n"; - $ftrans{$1} = $2; - } - } else { - $line = $_; - } - } - } - close(IN); - } + print OUT "\n/*\n * $lib function codes.\n */\n"; + foreach my $i ( @function ) { + my $z = 48 - length($i); + $z = 0 if $z < 0; + if ( $fcodes{$i} eq "X" ) { + $fassigned{$lib} =~ m/^:([^:]*):/; + my $findcode = $1; + $findcode = $fmax{$lib} if !defined $findcode; + while ( $fassigned{$lib} =~ m/:$findcode:/ ) { + $findcode++; + } + $fcodes{$i} = $findcode; + $fassigned{$lib} .= "$findcode:"; + print STDERR "New Function code $i\n" if $debug; + } + printf OUT "#${indent}define $i%s $fcodes{$i}\n", " " x $z; + } + print OUT "\n/*\n * $lib reason codes.\n */\n"; + foreach my $i ( @reasons ) { + my $z = 48 - length($i); + $z = 0 if $z < 0; + if ( $rcodes{$i} eq "X" ) { + $rassigned{$lib} =~ m/^:([^:]*):/; + my $findcode = $1; + $findcode = $rmax{$lib} if !defined $findcode; + while ( $rassigned{$lib} =~ m/:$findcode:/ ) { + $findcode++; + } + $rcodes{$i} = $findcode; + $rassigned{$lib} .= "$findcode:"; + print STDERR "New Reason code $i\n" if $debug; + } + printf OUT "#${indent}define $i%s $rcodes{$i}\n", " " x $z; + } + print OUT "\n"; - my $hincf; - if($static) { - $hincf = $hfile; - $hincf =~ s|.*include/||; - if ($hincf =~ m|^openssl/|) { - $hincf = "<${hincf}>"; - } else { - $hincf = "\"${hincf}\""; - } - } else { - $hincf = "\"$hfile\""; - } + while (length($indent) > 0) { + $indent = substr $indent, 0, -1; + print OUT "#${indent}endif\n"; + } - # If static we know the error code at compile time so use it - # in error definitions. + # Rewrite the C source file containing the error details. - if ($static) - { - $pack_errcode = "ERR_LIB_${lib}"; - $load_errcode = "0"; - } - else - { - $pack_errcode = "0"; - $load_errcode = "ERR_LIB_${lib}"; - } + # First, read any existing reason string definitions: + my $cfile = $errorfile{$lib}; + my $pack_lib = $internal ? "ERR_LIB_${lib}" : "0"; + my $hincf = $hfile; + $hincf =~ s|.*include/||; + if ( $hincf =~ m|^openssl/| ) { + $hincf = "<${hincf}>"; + } else { + $hincf = "\"${hincf}\""; + } + open( OUT, ">$cfile" ) + || die "Can't open $cfile for writing, $!, stopped"; - open (OUT,">$cfile") || die "Can't open $cfile for writing"; + my $const = $internal ? 'const ' : ''; - print OUT <<"EOF"; + print OUT <<"EOF"; /* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-$YEAR The OpenSSL Project Authors. All Rights Reserved. @@ -595,177 +567,187 @@ EOF * https://www.openssl.org/source/license.html */ -#include #include #include $hincf -/* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR -# define ERR_FUNC(func) ERR_PACK($pack_errcode,func,0) -# define ERR_REASON(reason) ERR_PACK($pack_errcode,0,reason) - -static ERR_STRING_DATA ${lib}_str_functs[] = { +static ${const}ERR_STRING_DATA ${lib}_str_functs[] = { EOF - # Add each function code: if a function name is found then use it. - foreach $i (@function) { - my $fn; - $i =~ /^${lib}_F_(\S+)$/; - $fn = $1; - if(exists $ftrans{$fn}) { - $fn = $ftrans{$fn}; - } -# print OUT "{ERR_PACK($pack_errcode,$i,0),\t\"$fn\"},\n"; - if(length($i) + length($fn) > 57) { - print OUT " {ERR_FUNC($i),\n \"$fn\"},\n"; - } else { - print OUT " {ERR_FUNC($i), \"$fn\"},\n"; - } - } - print OUT <<"EOF"; + + # Add each function code: if a function name is found then use it. + foreach my $i ( @function ) { + my $fn; + if ( exists $strings{$i} and $strings{$i} ne '' ) { + $fn = $strings{$i}; + $fn = "" if $fn eq '*'; + } else { + $i =~ /^${lib}_F_(\S+)$/; + $fn = $1; + $fn = $ftrans{$fn} if exists $ftrans{$fn}; + $strings{$i} = $fn; + } + my $short = " {ERR_PACK($pack_lib, $i, 0), \"$fn\"},"; + if ( length($short) <= 80 ) { + print OUT "$short\n"; + } else { + print OUT " {ERR_PACK($pack_lib, $i, 0),\n \"$fn\"},\n"; + } + } + print OUT <<"EOF"; {0, NULL} }; -static ERR_STRING_DATA ${lib}_str_reasons[] = { +static ${const}ERR_STRING_DATA ${lib}_str_reasons[] = { EOF - # Add each reason code. - foreach $i (@reasons) { - my $rn; - my $rstr = "ERR_REASON($i)"; - if (exists $err_reason_strings{$i}) { - $rn = $err_reason_strings{$i}; - } else { - $i =~ /^${lib}_R_(\S+)$/; - $rn = $1; - $rn =~ tr/_[A-Z]/ [a-z]/; - } - if(length($i) + length($rn) > 55) { - print OUT " {${rstr},\n \"$rn\"},\n"; - } else { - print OUT " {${rstr}, \"$rn\"},\n"; - } - } -if($static) { - print OUT <<"EOF"; + + # Add each reason code. + foreach my $i ( @reasons ) { + my $rn; + if ( exists $strings{$i} ) { + $rn = $strings{$i}; + $rn = "" if $rn eq '*'; + } else { + $i =~ /^${lib}_R_(\S+)$/; + $rn = $1; + $rn =~ tr/_[A-Z]/ [a-z]/; + $strings{$i} = $rn; + } + my $short = " {ERR_PACK($pack_lib, 0, $i), \"$rn\"},"; + if ( length($short) <= 80 ) { + print OUT "$short\n"; + } else { + print OUT " {ERR_PACK($pack_lib, 0, $i),\n \"$rn\"},\n"; + } + } + print OUT <<"EOF"; {0, NULL} }; #endif +EOF + if ( $internal ) { + print OUT <<"EOF"; -${staticloader}int ERR_load_${lib}_strings(void) +int ERR_load_${lib}_strings(void) { #ifndef OPENSSL_NO_ERR - if (ERR_func_error_string(${lib}_str_functs[0].error) == NULL) { - ERR_load_strings($load_errcode, ${lib}_str_functs); - ERR_load_strings($load_errcode, ${lib}_str_reasons); + ERR_load_strings_const(${lib}_str_functs); + ERR_load_strings_const(${lib}_str_reasons); } #endif return 1; } EOF -} else { - print OUT <<"EOF"; - {0, NULL} -}; + } else { + my $st = $static ? "static " : ""; + print OUT <<"EOF"; -#endif +static int lib_code = 0; +static int error_loaded = 0; -#ifdef ${lib}_LIB_NAME -static ERR_STRING_DATA ${lib}_lib_name[] = { - {0, ${lib}_LIB_NAME}, - {0, NULL} -}; -#endif - -static int ${lib}_lib_error_code = 0; -static int ${lib}_error_init = 1; - -${staticloader}int ERR_load_${lib}_strings(void) +${st}int ERR_load_${lib}_strings(void) { - if (${lib}_lib_error_code == 0) - ${lib}_lib_error_code = ERR_get_next_error_library(); + if (lib_code == 0) + lib_code = ERR_get_next_error_library(); - if (${lib}_error_init) { - ${lib}_error_init = 0; + if (!error_loaded) { #ifndef OPENSSL_NO_ERR - ERR_load_strings(${lib}_lib_error_code, ${lib}_str_functs); - ERR_load_strings(${lib}_lib_error_code, ${lib}_str_reasons); -#endif - -#ifdef ${lib}_LIB_NAME - ${lib}_lib_name->error = ERR_PACK(${lib}_lib_error_code, 0, 0); - ERR_load_strings(0, ${lib}_lib_name); + ERR_load_strings(lib_code, ${lib}_str_functs); + ERR_load_strings(lib_code, ${lib}_str_reasons); #endif + error_loaded = 1; } return 1; } -${staticloader}void ERR_unload_${lib}_strings(void) +${st}void ERR_unload_${lib}_strings(void) { - if (${lib}_error_init == 0) { + if (error_loaded) { #ifndef OPENSSL_NO_ERR - ERR_unload_strings(${lib}_lib_error_code, ${lib}_str_functs); - ERR_unload_strings(${lib}_lib_error_code, ${lib}_str_reasons); + ERR_unload_strings(lib_code, ${lib}_str_functs); + ERR_unload_strings(lib_code, ${lib}_str_reasons); #endif - -#ifdef ${lib}_LIB_NAME - ERR_unload_strings(0, ${lib}_lib_name); -#endif - ${lib}_error_init = 1; + error_loaded = 0; } } -${staticloader}void ERR_${lib}_error(int function, int reason, char *file, int line) +${st}void ERR_${lib}_error(int function, int reason, char *file, int line) { - if (${lib}_lib_error_code == 0) - ${lib}_lib_error_code = ERR_get_next_error_library(); - ERR_PUT_error(${lib}_lib_error_code, function, reason, file, line); + if (lib_code == 0) + lib_code = ERR_get_next_error_library(); + ERR_PUT_error(lib_code, function, reason, file, line); } EOF + } + + close OUT; } - close OUT; - undef %err_reason_strings; -} - -if($debug && %notrans) { - print STDERR "The following function codes were not translated:\n"; - foreach(sort keys %notrans) - { - print STDERR "$_\n"; - } -} - +&phase("Ending"); # Make a list of unreferenced function and reason codes - -foreach (keys %fcodes) { - push (@funref, $_) unless exists $ufcodes{$_}; +if ( $unref ) { + my @funref; + foreach ( keys %fcodes ) { + push( @funref, $_ ) unless exists $usedfuncs{$_}; + } + my @runref; + foreach ( keys %rcodes ) { + push( @runref, $_ ) unless exists $usedreasons{$_}; + } + if ( @funref ) { + print STDERR "The following function codes were not referenced:\n"; + foreach ( sort @funref ) { + print STDERR " $_\n"; + } + } + if ( @runref ) { + print STDERR "The following reason codes were not referenced:\n"; + foreach ( sort @runref ) { + print STDERR " $_\n"; + } + } } -foreach (keys %rcodes) { - push (@runref, $_) unless exists $urcodes{$_}; -} - -if($unref && @funref) { - print STDERR "The following function codes were not referenced:\n"; - foreach(sort @funref) - { - print STDERR "$_\n"; - } -} - -if($unref && @runref) { - print STDERR "The following reason codes were not referenced:\n"; - foreach(sort @runref) - { - print STDERR "$_\n"; - } -} - -if($errcount) { - print STDERR "There were errors, failing...\n\n"; - exit $errcount; +die "Found $errors errors, quitting" if $errors; + +# Update the state file +if ( $newstate ) { + open(OUT, ">$statefile.new") + || die "Can't write $statefile.new, $!"; + print OUT <<"EOF"; +# Copyright 1999-$YEAR 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 +EOF + print OUT "\n# Function codes\n"; + foreach my $i ( sort keys %fcodes ) { + my $short = "$i:$fcodes{$i}:"; + my $t = exists $strings{$i} ? $strings{$i} : ""; + $t = "\\\n\t" . $t if length($short) + length($t) > 80; + print OUT "$short$t\n"; + } + print OUT "\n#Reason codes\n"; + foreach my $i ( sort keys %rcodes ) { + my $short = "$i:$rcodes{$i}:"; + my $t = exists $strings{$i} ? "$strings{$i}" : ""; + $t = "\\\n\t" . $t if length($short) + length($t) > 80; + print OUT "$short$t\n" if !exists $rextra{$i}; + } + close(OUT); + if ( $skippedstate ) { + print "Skipped state, leaving update in $statefile.new"; + } else { + rename "$statefile", "$statefile.old" + || die "Can't backup $statefile to $statefile.old, $!"; + rename "$statefile.new", "$statefile" + || die "Can't rename $statefile to $statefile.new, $!"; + } } +exit; diff --git a/util/mkrc.pl b/util/mkrc.pl index c177349c..b98a6946 100755 --- a/util/mkrc.pl +++ b/util/mkrc.pl @@ -6,36 +6,45 @@ # in the file LICENSE in the source distribution or at # https://www.openssl.org/source/license.html +use strict; +use warnings; use lib "."; use configdata; use File::Spec::Functions; -my $versionfile = catfile($config{sourcedir},"include/openssl/opensslv.h"); +my $versionfile = catfile( $config{sourcedir}, "include/openssl/opensslv.h" ); + +my ( $ver, $v1, $v2, $v3, $v4, $beta, $version ); open FD, $versionfile or die "Couldn't open include/openssl/opensslv.h: $!\n"; -while() { +while () { if (/OPENSSL_VERSION_NUMBER\s+(0x[0-9a-f]+)/i) { - $ver = hex($1); - $v1 = ($ver>>28); - $v2 = ($ver>>20)&0xff; - $v3 = ($ver>>12)&0xff; - $v4 = ($ver>> 4)&0xff; - $beta = $ver&0xf; - $version = "$v1.$v2.$v3"; - if ($beta==0xf) { $version .= chr(ord('a')+$v4-1) if ($v4); } - elsif ($beta==0){ $version .= "-dev"; } - else { $version .= "-beta$beta"; } - last; + $ver = hex($1); + $v1 = ( $ver >> 28 ); + $v2 = ( $ver >> 20 ) & 0xff; + $v3 = ( $ver >> 12 ) & 0xff; + $v4 = ( $ver >> 4 ) & 0xff; + $beta = $ver & 0xf; + $version = "$v1.$v2.$v3"; + if ( $beta == 0xf ) { + $version .= chr( ord('a') + $v4 - 1 ) if ($v4); + } elsif ( $beta == 0 ) { + $version .= "-dev"; + } else { + $version .= "-beta$beta"; + } + last; } } close(FD); -$filename = $ARGV[0]; $filename =~ /(.*)\.([^.]+)$/; -$basename = $1; -$extname = $2; +my $filename = $ARGV[0]; +$filename =~ /(.*)\.([^.]+)$/; +my $basename = $1; +my $extname = $2; -if ($extname =~ /dll/i) { $description = "OpenSSL shared library"; } -else { $description = "OpenSSL application"; } +my $description = "OpenSSL application"; +$description = "OpenSSL shared library" if $extname =~ /dll/i; print <<___; #include diff --git a/util/openssl-format-source b/util/openssl-format-source index 3dcc128a..2655e9c4 100755 --- a/util/openssl-format-source +++ b/util/openssl-format-source @@ -111,7 +111,7 @@ do # the process-comments options and then undo that marking, and then # finally re-run indent without process-comments so the marked-to- # be-ignored comments we did automatically end up getting moved - # into the right possition within the code as indent leaves marked + # into the right position within the code as indent leaves marked # comments entirely untouched - we appear to have no way to avoid # the double processing and get the desired output cat "$j" | \ diff --git a/util/openssl-update-copyright b/util/openssl-update-copyright new file mode 100755 index 00000000..c432f846 --- /dev/null +++ b/util/openssl-update-copyright @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# +# Copyright 2018 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 + + +myname="$(basename $0)" + +this_year="$(date '+%Y')" +some_year="[12][0-9][0-9][0-9]" +year_range="(${some_year})(-${some_year})?" + +copyright_owner="The OpenSSL Project" +copyright="Copyright .*${year_range} .*${copyright_owner}" + +# sed_script: +# for all lines that contain ${copyright} : { +# replace years yyyy-zzzz (or year yyyy) by yyyy-${this_year} +# replace repeated years yyyy-yyyy by yyyy +# } +sed_script="/${copyright}/{ s/${year_range}/\1-${this_year}/ ; s/(${some_year})-\1/\1/ }" + +function usage() { + cat >&2 <& 2 + usage + exit 1 + ;; + *) + if [ -f "$arg" ]; then + sed -E -i "${sed_script}" "$arg" + elif [ -d "$arg" ]; then + find "$arg" -name '.[a-z]*' -prune -o -type f -exec sed -E -i "${sed_script}" {} + + else + echo "$arg: no such file or directory" >&2 + fi + ;; + esac +done diff --git a/util/perl/OpenSSL/Test.pm b/util/perl/OpenSSL/Test.pm index 5de7b58e..ad77896c 100644 --- a/util/perl/OpenSSL/Test.pm +++ b/util/perl/OpenSSL/Test.pm @@ -16,8 +16,8 @@ use Exporter; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = "0.8"; @ISA = qw(Exporter); -@EXPORT = (@Test::More::EXPORT, qw(setup indir app fuzz perlapp test perltest - run)); +@EXPORT = (@Test::More::EXPORT, qw(setup run indir cmd app fuzz test + perlapp perltest subtest)); @EXPORT_OK = (@Test::More::EXPORT_OK, qw(bldtop_dir bldtop_file srctop_dir srctop_file data_file @@ -65,6 +65,7 @@ use File::Spec::Functions qw/file_name_is_absolute curdir canonpath splitdir use File::Path 2.00 qw/rmtree mkpath/; use File::Basename; +my $level = 0; # The name of the test. This is set by setup() and is used in the other # functions to verify that setup() has been used. @@ -91,9 +92,9 @@ my %hooks = ( # exit_checker is used by run() directly after completion of a command. # it receives the exit code from that command and is expected to return - # 1 (for success) or 0 (for failure). This is the value that will be - # returned by run(). - # NOTE: When run() gets the option 'capture => 1', this hook is ignored. + # 1 (for success) or 0 (for failure). This is the status value that run() + # will give back (through the |statusvar| reference and as returned value + # when capture => 1 doesn't apply). exit_checker => sub { return shift == 0 ? 1 : 0 }, ); @@ -101,21 +102,6 @@ my %hooks = ( # Debug flag, to be set manually when needed my $debug = 0; -# Declare some utility functions that are defined at the end -sub bldtop_file; -sub bldtop_dir; -sub srctop_file; -sub srctop_dir; -sub quotify; - -# Declare some private functions that are defined at the end -sub __env; -sub __cwd; -sub __apps_file; -sub __results_file; -sub __fixup_cmd; -sub __build_cmd; - =head2 Main functions The following functions are exported by default when using C. @@ -225,25 +211,18 @@ sub indir { =over 4 -=item B +=item B -=item B +This functions build up a platform dependent command based on the +input. It takes a reference to a list that is the executable or +script and its arguments, and some additional options (described +further on). Where necessary, the command will be wrapped in a +suitable environment to make sure the correct shared libraries are +used (currently only on Unix). -Both of these functions take a reference to a list that is a command and -its arguments, and some additional options (described further on). +It returns a CODEREF to be used by C, C or C. -C expects to find the given command (the first item in the given list -reference) as an executable in C<$BIN_D> (if defined, otherwise C<$TOP/apps> -or C<$BLDTOP/apps>). - -C expects to find the given command (the first item in the given list -reference) as an executable in C<$TEST_D> (if defined, otherwise C<$TOP/test> -or C<$BLDTOP/test>). - -Both return a CODEREF to be used by C, C or C. - -The options that both C and C can take are in the form of hash -values: +The options that C can take are in the form of hash values: =over 4 @@ -259,21 +238,42 @@ string PATH, I, if the value is C, C or similar. =back +=item B + +=item B + +Both of these are specific applications of C, with just a couple +of small difference: + +C expects to find the given command (the first item in the given list +reference) as an executable in C<$BIN_D> (if defined, otherwise C<$TOP/apps> +or C<$BLDTOP/apps>). + +C expects to find the given command (the first item in the given list +reference) as an executable in C<$TEST_D> (if defined, otherwise C<$TOP/test> +or C<$BLDTOP/test>). + +Also, for both C and C, the command may be prefixed with +the content of the environment variable C<$EXE_SHELL>, which is useful +in case OpenSSL has been cross compiled. + =item B =item B -Both these functions function the same way as B and B, except -that they expect the command to be a perl script. Also, they support one -more option: +These are also specific applications of C, where the interpreter +is predefined to be C, and they expect the script to be +interpreted to reside in the same location as C and C. + +C and C will also take the following option: =over 4 =item B ARRAYref> -The array reference is a set of arguments for perl rather than the script. -Take care so that none of them can be seen as a script! Flags and their -eventual arguments only! +The array reference is a set of arguments for the interpreter rather +than the script. Take care so that none of them can be seen as a +script! Flags and their eventual arguments only! =back @@ -284,54 +284,114 @@ An example: =back +=begin comment + +One might wonder over the complexity of C, C, C, ... +with all the lazy evaluations and all that. The reason for this is that +we want to make sure the directory in which those programs are found are +correct at the time these commands are used. Consider the following code +snippet: + + my $cmd = app(["openssl", ...]); + + indir "foo", sub { + ok(run($cmd), "Testing foo") + }; + +If there wasn't this lazy evaluation, the directory where C is +found would be incorrect at the time C is called, because it was +calculated before we moved into the directory "foo". + +=end comment + =cut +sub cmd { + my $cmd = shift; + my %opts = @_; + return sub { + my $num = shift; + # Make a copy to not destroy the caller's array + my @cmdargs = ( @$cmd ); + my @prog = __wrap_cmd(shift @cmdargs, $opts{exe_shell} // ()); + + return __decorate_cmd($num, [ @prog, quotify(@cmdargs) ], + %opts); + } +} + sub app { my $cmd = shift; my %opts = @_; - return sub { my $num = shift; - return __build_cmd($num, \&__apps_file, $cmd, %opts); } + return sub { + my @cmdargs = ( @{$cmd} ); + my @prog = __fixup_prg(__apps_file(shift @cmdargs, __exeext())); + return cmd([ @prog, @cmdargs ], + exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift); + } } sub fuzz { my $cmd = shift; my %opts = @_; - return sub { my $num = shift; - return __build_cmd($num, \&__fuzz_file, $cmd, %opts); } + return sub { + my @cmdargs = ( @{$cmd} ); + my @prog = __fixup_prg(__fuzz_file(shift @cmdargs, __exeext())); + return cmd([ @prog, @cmdargs ], + exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift); + } } sub test { my $cmd = shift; my %opts = @_; - return sub { my $num = shift; - return __build_cmd($num, \&__test_file, $cmd, %opts); } + return sub { + my @cmdargs = ( @{$cmd} ); + my @prog = __fixup_prg(__test_file(shift @cmdargs, __exeext())); + return cmd([ @prog, @cmdargs ], + exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift); + } } sub perlapp { my $cmd = shift; my %opts = @_; - return sub { my $num = shift; - return __build_cmd($num, \&__perlapps_file, $cmd, %opts); } + return sub { + my @interpreter_args = defined $opts{interpreter_args} ? + @{$opts{interpreter_args}} : (); + my @interpreter = __fixup_prg($^X); + my @cmdargs = ( @{$cmd} ); + my @prog = __apps_file(shift @cmdargs, undef); + return cmd([ @interpreter, @interpreter_args, + @prog, @cmdargs ], %opts) -> (shift); + } } sub perltest { my $cmd = shift; my %opts = @_; - return sub { my $num = shift; - return __build_cmd($num, \&__perltest_file, $cmd, %opts); } + return sub { + my @interpreter_args = defined $opts{interpreter_args} ? + @{$opts{interpreter_args}} : (); + my @interpreter = __fixup_prg($^X); + my @cmdargs = ( @{$cmd} ); + my @prog = __test_file(shift @cmdargs, undef); + return cmd([ @interpreter, @interpreter_args, + @prog, @cmdargs ], %opts) -> (shift); + } } =over 4 =item B -This CODEREF is expected to be the value return by C or C, -anything else will most likely cause an error unless you know what you're -doing. +CODEREF is expected to be the value return by C or any of its +derivatives, anything else will most likely cause an error unless you +know what you're doing. C executes the command returned by CODEREF and return either the -resulting output (if the option C is set true) or a boolean indicating -if the command succeeded or not. +resulting output (if the option C is set true) or a boolean +indicating if the command succeeded or not. The options that C can take are in the form of hash values: @@ -344,6 +404,18 @@ return the resulting output as an array of lines. If false or not given, the command will be executed with C, and C will return 1 if the command was successful or 0 if it wasn't. +=item B EXPR> + +If specified, EXPR will be used as a string to prefix the output from the +command. This is useful if the output contains lines starting with C +or C that can disturb Test::Harness. + +=item B VARREF> + +If used, B must be a reference to a scalar variable. It will be +assigned a boolean indicating if the command succeeded or not. This is +particularly useful together with B. + =back For further discussion on what is considered a successful command or not, see @@ -368,6 +440,9 @@ sub run { my $r = 0; my $e = 0; + die "OpenSSL::Test::run(): statusvar value not a scalar reference" + if $opts{statusvar} && ref($opts{statusvar}) ne "SCALAR"; + # In non-verbose, we want to shut up the command interpreter, in case # it has something to complain about. On VMS, it might complain both # on stdout and stderr @@ -380,17 +455,35 @@ sub run { open STDERR, ">", devnull(); } + $ENV{HARNESS_OSSL_LEVEL} = $level + 1; + # The dance we do with $? is the same dance the Unix shells appear to # do. For example, a program that gets aborted (and therefore signals # SIGABRT = 6) will appear to exit with the code 134. We mimic this # to make it easier to compare with a manual run of the command. - if ($opts{capture}) { - @r = `$prefix$cmd`; - $e = ($? & 0x7f) ? ($? & 0x7f)|0x80 : ($? >> 8); + if ($opts{capture} || defined($opts{prefix})) { + my $pipe; + local $_; + + open($pipe, '-|', "$prefix$cmd") or die "Can't start command: $!"; + while(<$pipe>) { + my $l = ($opts{prefix} // "") . $_; + if ($opts{capture}) { + push @r, $l; + } else { + print STDOUT $l; + } + } + close $pipe; } else { + $ENV{HARNESS_OSSL_PREFIX} = "# "; system("$prefix$cmd"); - $e = ($? & 0x7f) ? ($? & 0x7f)|0x80 : ($? >> 8); - $r = $hooks{exit_checker}->($e); + delete $ENV{HARNESS_OSSL_PREFIX}; + } + $e = ($? & 0x7f) ? ($? & 0x7f)|0x80 : ($? >> 8); + $r = $hooks{exit_checker}->($e); + if ($opts{statusvar}) { + ${$opts{statusvar}} = $r; } if ($ENV{HARNESS_ACTIVE} && !$ENV{HARNESS_VERBOSE}) { @@ -570,7 +663,7 @@ sub pipe { =item B -C will temporarly install hooks given by the HASHREF and then execute +C will temporarily install hooks given by the HASHREF and then execute the given CODEREF. Hooks are usually expected to have a coderef as value. The currently available hoosk are: @@ -616,7 +709,7 @@ sub with { C takes a CODEREF from C or C and simply returns the command as a string. -C takes some additiona options OPTS that affect the string returned: +C takes some additional options OPTS that affect the string returned: =over 4 @@ -754,6 +847,14 @@ sub __env { $end_with_bailout = $ENV{STOPTEST} ? 1 : 0; }; +# __srctop_file and __srctop_dir are helpers to build file and directory +# names on top of the source directory. They depend on $SRCTOP, and +# therefore on the proper use of setup() and when needed, indir(). +# __bldtop_file and __bldtop_dir do the same thing but relative to $BLDTOP. +# __srctop_file and __bldtop_file take the same kind of argument as +# File::Spec::Functions::catfile. +# Similarly, __srctop_dir and __bldtop_dir take the same kind of argument +# as File::Spec::Functions::catdir sub __srctop_file { BAIL_OUT("Must run setup() first") if (! $test_name); @@ -780,6 +881,9 @@ sub __bldtop_dir { return catdir($directories{BLDTOP},@_); } +# __exeext is a function that returns the platform dependent file extension +# for executable binaries, or the value of the environment variable $EXE_EXT +# if that one is defined. sub __exeext { my $ext = ""; if ($^O eq "VMS" ) { # VMS @@ -790,51 +894,45 @@ sub __exeext { return $ENV{"EXE_EXT"} || $ext; } +# __test_file, __apps_file and __fuzz_file return the full path to a file +# relative to the test/, apps/ or fuzz/ directory in the build tree or the +# source tree, depending on where the file is found. Note that when looking +# in the build tree, the file name with an added extension is looked for, if +# an extension is given. The intent is to look for executable binaries (in +# the build tree) or possibly scripts (in the source tree). +# These functions all take the same arguments as File::Spec::Functions::catfile, +# *plus* a mandatory extension argument. This extension argument can be undef, +# and is ignored in such a case. sub __test_file { BAIL_OUT("Must run setup() first") if (! $test_name); + my $e = pop || ""; my $f = pop; - my $out = catfile($directories{BLDTEST},@_,$f . __exeext()); - $out = catfile($directories{SRCTEST},@_,$f) unless -x $out; - return $out; -} - -sub __perltest_file { - BAIL_OUT("Must run setup() first") if (! $test_name); - - my $f = pop; - my $out = catfile($directories{BLDTEST},@_,$f); + my $out = catfile($directories{BLDTEST},@_,$f . $e); $out = catfile($directories{SRCTEST},@_,$f) unless -f $out; - return ($^X, $out); + return $out; } sub __apps_file { BAIL_OUT("Must run setup() first") if (! $test_name); + my $e = pop || ""; my $f = pop; - my $out = catfile($directories{BLDAPPS},@_,$f . __exeext()); - $out = catfile($directories{SRCAPPS},@_,$f) unless -x $out; + my $out = catfile($directories{BLDAPPS},@_,$f . $e); + $out = catfile($directories{SRCAPPS},@_,$f) unless -f $out; return $out; } sub __fuzz_file { BAIL_OUT("Must run setup() first") if (! $test_name); + my $e = pop || ""; my $f = pop; - my $out = catfile($directories{BLDFUZZ},@_,$f . __exeext()); - $out = catfile($directories{SRCFUZZ},@_,$f) unless -x $out; + my $out = catfile($directories{BLDFUZZ},@_,$f . $e); + $out = catfile($directories{SRCFUZZ},@_,$f) unless -f $out; return $out; } -sub __perlapps_file { - BAIL_OUT("Must run setup() first") if (! $test_name); - - my $f = pop; - my $out = catfile($directories{BLDAPPS},@_,$f); - $out = catfile($directories{SRCAPPS},@_,$f) unless -f $out; - return ($^X, $out); -} - sub __data_file { BAIL_OUT("Must run setup() first") if (! $test_name); @@ -849,6 +947,16 @@ sub __results_file { return catfile($directories{RESULTS},@_,$f); } +# __cwd DIR +# __cwd DIR, OPTS +# +# __cwd changes directory to DIR (string) and changes all the relative +# entries in %directories accordingly. OPTS is an optional series of +# hash style arguments to alter __cwd's behavior: +# +# create = 0|1 The directory we move to is created if 1, not if 0. +# cleanup = 0|1 The directory we move from is removed if 1, not if 0. + sub __cwd { my $dir = catdir(shift); my %opts = @_; @@ -910,7 +1018,7 @@ sub __cwd { } # We put back new values carefully. Doing the obvious - # %directories = ( %tmp_irectories ) + # %directories = ( %tmp_directories ) # will clear out any value that happens to be an absolute path foreach (keys %tmp_directories) { $directories{$_} = $tmp_directories{$_}; @@ -937,28 +1045,46 @@ sub __cwd { return $reverse; } -sub __fixup_cmd { - my $prog = shift; +# __wrap_cmd CMD +# __wrap_cmd CMD, EXE_SHELL +# +# __wrap_cmd "wraps" CMD (string) with a beginning command that makes sure +# the command gets executed with an appropriate environment. If EXE_SHELL +# is given, it is used as the beginning command. +# +# __wrap_cmd returns a list that should be used to build up a larger list +# of command tokens, or be joined together like this: +# +# join(" ", __wrap_cmd($cmd)) +sub __wrap_cmd { + my $cmd = shift; my $exe_shell = shift; - my $prefix = __bldtop_file("util", "shlib_wrap.sh")." "; + my @prefix = ( __bldtop_file("util", "shlib_wrap.sh") ); - if (defined($exe_shell)) { - $prefix = "$exe_shell "; - } elsif ($^O eq "VMS" ) { # VMS - $prefix = ($prog =~ /^(?:[\$a-z0-9_]+:)?[<\[]/i ? "mcr " : "mcr []"); - } elsif ($^O eq "MSWin32") { # Windows - $prefix = ""; + if(defined($exe_shell)) { + @prefix = ( $exe_shell ); + } elsif ($^O eq "VMS" || $^O eq "MSWin32") { + # VMS and Windows don't use any wrapper script for the moment + @prefix = (); } - # We test both with and without extension. The reason - # is that we might be passed a complete file spec, with - # extension. - if ( ! -x $prog ) { - my $prog = "$prog"; - if ( ! -x $prog ) { - $prog = undef; - } + return (@prefix, $cmd); +} + +# __fixup_prg PROG +# +# __fixup_prg does whatever fixup is needed to execute an executable binary +# given by PROG (string). +# +# __fixup_prg returns a string with the possibly prefixed program path spec. +sub __fixup_prg { + my $prog = shift; + + my $prefix = ""; + + if ($^O eq "VMS" ) { + $prefix = ($prog =~ /^(?:[\$a-z0-9_]+:)?[<\[]/i ? "mcr " : "mcr []"); } if (defined($prog)) { @@ -974,45 +1100,25 @@ sub __fixup_cmd { return undef; } -sub __build_cmd { +# __decorate_cmd NUM, CMDARRAYREF +# +# __decorate_cmd takes a command number NUM and a command token array +# CMDARRAYREF, builds up a command string from them and decorates it +# with necessary redirections. +# __decorate_cmd returns a list of two strings, one with the command +# string to actually be used, the other to be displayed for the user. +# The reason these strings might differ is that we redirect stderr to +# the null device unless we're verbose and unless the user has +# explicitly specified a stderr redirection. +sub __decorate_cmd { BAIL_OUT("Must run setup() first") if (! $test_name); my $num = shift; - my $path_builder = shift; - # Make a copy to not destroy the caller's array - my @cmdarray = ( @{$_[0]} ); shift; + my $cmd = shift; my %opts = @_; - # We do a little dance, as $path_builder might return a list of - # more than one. If so, only the first is to be considered a - # program to fix up, the rest is part of the arguments. This - # happens for perl scripts, where $path_builder will return - # a list of two, $^X and the script name. - # Also, if $path_builder returned more than one, we don't apply - # the EXE_SHELL environment variable. - my @prog = ($path_builder->(shift @cmdarray)); - my $first = shift @prog; - my $exe_shell = @prog ? undef : $ENV{EXE_SHELL}; - my $cmd = __fixup_cmd($first, $exe_shell); - if (@prog) { - if ( ! -f $prog[0] ) { - print STDERR "$prog[0] not found\n"; - $cmd = undef; - } - } - my @args = (@prog, @cmdarray); - if (defined($opts{interpreter_args})) { - unshift @args, @{$opts{interpreter_args}}; - } - - return () if !$cmd; - - my $arg_str = ""; + my $cmdstr = join(" ", @$cmd); my $null = devnull(); - - - $arg_str = " ".join(" ", quotify @args) if @args; - my $fileornull = sub { $_[0] ? $_[0] : $null; }; my $stdin = ""; my $stdout = ""; @@ -1022,19 +1128,19 @@ sub __build_cmd { $stdout= " > ".$fileornull->($opts{stdout}) if exists($opts{stdout}); $stderr=" 2> ".$fileornull->($opts{stderr}) if exists($opts{stderr}); - my $display_cmd = "$cmd$arg_str$stdin$stdout$stderr"; + my $display_cmd = "$cmdstr$stdin$stdout$stderr"; $stderr=" 2> ".$null unless $stderr || !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE}; - $cmd .= "$arg_str$stdin$stdout$stderr"; + $cmdstr .= "$stdin$stdout$stderr"; if ($debug) { - print STDERR "DEBUG[__build_cmd]: \$cmd = \"$cmd\"\n"; - print STDERR "DEBUG[__build_cmd]: \$display_cmd = \"$display_cmd\"\n"; + print STDERR "DEBUG[__decorate_cmd]: \$cmdstr = \"$cmdstr\"\n"; + print STDERR "DEBUG[__decorate_cmd]: \$display_cmd = \"$display_cmd\"\n"; } - return ($cmd, $display_cmd); + return ($cmdstr, $display_cmd); } =head1 SEE ALSO @@ -1043,9 +1149,18 @@ L, L =head1 AUTHORS -Richard Levitte Elevitte@openssl.orgE with assitance and +Richard Levitte Elevitte@openssl.orgE with assistance and inspiration from Andy Polyakov Eappro@openssl.org. =cut +no warnings 'redefine'; +sub subtest { + $level++; + + Test::More::subtest @_; + + $level--; +}; + 1; diff --git a/util/perl/OpenSSL/Util/Pod.pm b/util/perl/OpenSSL/Util/Pod.pm index 5c0af959..9f76fbf1 100644 --- a/util/perl/OpenSSL/Util/Pod.pm +++ b/util/perl/OpenSSL/Util/Pod.pm @@ -53,11 +53,8 @@ The additional hash is for extra parameters: =item B
N> -The value MUST be a number, and will be the default man section number -to be used with the given .pod file. This number can be altered if -the .pod file has a line like this: - - =for comment openssl_manual_section: 4 +The value MUST be a number, and will be the man section number +to be used with the given .pod file. =item B 0|1> @@ -109,12 +106,6 @@ sub extract_pod_info { my %podinfo = ( section => $defaults{section}); while(<$input>) { s|\R$||; - if (m|^=for\s+comment\s+openssl_manual_section:\s*([0-9])\s*$|) { - print STDERR "DEBUG: Found man section number $1\n" - if $defaults{debug}; - $podinfo{section} = $1; - } - # Stop reading when we have reached past the NAME section. last if (m|^=head1| && defined $podinfo{lastsect} diff --git a/util/perl/TLSProxy/Certificate.pm b/util/perl/TLSProxy/Certificate.pm new file mode 100644 index 00000000..d3bf7f21 --- /dev/null +++ b/util/perl/TLSProxy/Certificate.pm @@ -0,0 +1,219 @@ +# 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 + +use strict; + +package TLSProxy::Certificate; + +use vars '@ISA'; +push @ISA, 'TLSProxy::Message'; + +sub new +{ + my $class = shift; + my ($server, + $data, + $records, + $startoffset, + $message_frag_lens) = @_; + + my $self = $class->SUPER::new( + $server, + TLSProxy::Message::MT_CERTIFICATE, + $data, + $records, + $startoffset, + $message_frag_lens); + + $self->{first_certificate} = ""; + $self->{extension_data} = ""; + $self->{remaining_certdata} = ""; + + return $self; +} + +sub parse +{ + my $self = shift; + + if (TLSProxy::Proxy->is_tls13()) { + my $context_len = unpack('C', $self->data); + my $context = substr($self->data, 1, $context_len); + + my $remdata = substr($self->data, 1 + $context_len); + + my ($hicertlistlen, $certlistlen) = unpack('Cn', $remdata); + $certlistlen += ($hicertlistlen << 16); + + $remdata = substr($remdata, 3); + + die "Invalid Certificate List length" + if length($remdata) != $certlistlen; + + my ($hicertlen, $certlen) = unpack('Cn', $remdata); + $certlen += ($hicertlen << 16); + + die "Certificate too long" if ($certlen + 3) > $certlistlen; + + $remdata = substr($remdata, 3); + + my $certdata = substr($remdata, 0, $certlen); + + $remdata = substr($remdata, $certlen); + + my $extensions_len = unpack('n', $remdata); + $remdata = substr($remdata, 2); + + die "Extensions too long" + if ($certlen + 3 + $extensions_len + 2) > $certlistlen; + + my $extension_data = ""; + if ($extensions_len != 0) { + $extension_data = substr($remdata, 0, $extensions_len); + + if (length($extension_data) != $extensions_len) { + die "Invalid extension length\n"; + } + } + my %extensions = (); + while (length($extension_data) >= 4) { + my ($type, $size) = unpack("nn", $extension_data); + my $extdata = substr($extension_data, 4, $size); + $extension_data = substr($extension_data, 4 + $size); + $extensions{$type} = $extdata; + } + $remdata = substr($remdata, $extensions_len); + + $self->context($context); + $self->first_certificate($certdata); + $self->extension_data(\%extensions); + $self->remaining_certdata($remdata); + + print " Context:".$context."\n"; + print " Certificate List Len:".$certlistlen."\n"; + print " Certificate Len:".$certlen."\n"; + print " Extensions Len:".$extensions_len."\n"; + } else { + my ($hicertlistlen, $certlistlen) = unpack('Cn', $self->data); + $certlistlen += ($hicertlistlen << 16); + + my $remdata = substr($self->data, 3); + + die "Invalid Certificate List length" + if length($remdata) != $certlistlen; + + my ($hicertlen, $certlen) = unpack('Cn', $remdata); + $certlen += ($hicertlen << 16); + + die "Certificate too long" if ($certlen + 3) > $certlistlen; + + $remdata = substr($remdata, 3); + + my $certdata = substr($remdata, 0, $certlen); + + $remdata = substr($remdata, $certlen); + + $self->first_certificate($certdata); + $self->remaining_certdata($remdata); + + print " Certificate List Len:".$certlistlen."\n"; + print " Certificate Len:".$certlen."\n"; + } +} + +#Reconstruct the on-the-wire message data following changes +sub set_message_contents +{ + my $self = shift; + my $data; + my $extensions = ""; + + if (TLSProxy::Proxy->is_tls13()) { + foreach my $key (keys %{$self->extension_data}) { + my $extdata = ${$self->extension_data}{$key}; + $extensions .= pack("n", $key); + $extensions .= pack("n", length($extdata)); + $extensions .= $extdata; + if ($key == TLSProxy::Message::EXT_DUPLICATE_EXTENSION) { + $extensions .= pack("n", $key); + $extensions .= pack("n", length($extdata)); + $extensions .= $extdata; + } + } + $data = pack('C', length($self->context())); + $data .= $self->context; + my $certlen = length($self->first_certificate); + my $certlistlen = $certlen + length($extensions) + + length($self->remaining_certdata); + my $hi = $certlistlen >> 16; + $certlistlen = $certlistlen & 0xffff; + $data .= pack('Cn', $hi, $certlistlen); + $hi = $certlen >> 16; + $certlen = $certlen & 0xffff; + $data .= pack('Cn', $hi, $certlen); + $data .= pack('n', length($extensions)); + $data .= $extensions; + $data .= $self->remaining_certdata(); + $self->data($data); + } else { + my $certlen = length($self->first_certificate); + my $certlistlen = $certlen + length($self->remaining_certdata); + my $hi = $certlistlen >> 16; + $certlistlen = $certlistlen & 0xffff; + $data .= pack('Cn', $hi, $certlistlen); + $hi = $certlen >> 16; + $certlen = $certlen & 0xffff; + $data .= pack('Cn', $hi, $certlen); + $data .= $self->remaining_certdata(); + $self->data($data); + } +} + +#Read/write accessors +sub context +{ + my $self = shift; + if (@_) { + $self->{context} = shift; + } + return $self->{context}; +} +sub first_certificate +{ + my $self = shift; + if (@_) { + $self->{first_certificate} = shift; + } + return $self->{first_certificate}; +} +sub remaining_certdata +{ + my $self = shift; + if (@_) { + $self->{remaining_certdata} = shift; + } + return $self->{remaining_certdata}; +} +sub extension_data +{ + my $self = shift; + if (@_) { + $self->{extension_data} = shift; + } + return $self->{extension_data}; +} +sub set_extension +{ + my ($self, $ext_type, $ext_data) = @_; + $self->{extension_data}{$ext_type} = $ext_data; +} +sub delete_extension +{ + my ($self, $ext_type) = @_; + delete $self->{extension_data}{$ext_type}; +} +1; diff --git a/util/perl/TLSProxy/CertificateVerify.pm b/util/perl/TLSProxy/CertificateVerify.pm new file mode 100644 index 00000000..8bf969fb --- /dev/null +++ b/util/perl/TLSProxy/CertificateVerify.pm @@ -0,0 +1,96 @@ +# 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 + +use strict; + +package TLSProxy::CertificateVerify; + +use vars '@ISA'; +push @ISA, 'TLSProxy::Message'; + +sub new +{ + my $class = shift; + my ($server, + $data, + $records, + $startoffset, + $message_frag_lens) = @_; + + my $self = $class->SUPER::new( + $server, + TLSProxy::Message::MT_CERTIFICATE_VERIFY, + $data, + $records, + $startoffset, + $message_frag_lens); + + $self->{sigalg} = -1; + $self->{signature} = ""; + + return $self; +} + +sub parse +{ + my $self = shift; + + my $sigalg = -1; + my $remdata = $self->data; + my $record = ${$self->records}[0]; + + if (TLSProxy::Proxy->is_tls13() + || $record->version() == TLSProxy::Record::VERS_TLS_1_2) { + $sigalg = unpack('n', $remdata); + $remdata = substr($remdata, 2); + } + + my $siglen = unpack('n', substr($remdata, 0, 2)); + my $sig = substr($remdata, 2); + + die "Invalid CertificateVerify signature length" if length($sig) != $siglen; + + print " SigAlg:".$sigalg."\n"; + print " Signature Len:".$siglen."\n"; + + $self->sigalg($sigalg); + $self->signature($sig); +} + +#Reconstruct the on-the-wire message data following changes +sub set_message_contents +{ + my $self = shift; + my $data = ""; + my $sig = $self->signature(); + my $olddata = $self->data(); + + $data .= pack("n", $self->sigalg()) if ($self->sigalg() != -1); + $data .= pack("n", length($sig)); + $data .= $sig; + + $self->data($data); +} + +#Read/write accessors +sub sigalg +{ + my $self = shift; + if (@_) { + $self->{sigalg} = shift; + } + return $self->{sigalg}; +} +sub signature +{ + my $self = shift; + if (@_) { + $self->{signature} = shift; + } + return $self->{signature}; +} +1; diff --git a/util/perl/TLSProxy/ClientHello.pm b/util/perl/TLSProxy/ClientHello.pm index ec739d29..2ae9d6f5 100644 --- a/util/perl/TLSProxy/ClientHello.pm +++ b/util/perl/TLSProxy/ClientHello.pm @@ -114,6 +114,24 @@ sub process_extensions } } +sub extension_contents +{ + my $self = shift; + my $key = shift; + my $extension = ""; + + my $extdata = ${$self->extension_data}{$key}; + $extension .= pack("n", $key); + $extension .= pack("n", length($extdata)); + $extension .= $extdata; + if ($key == TLSProxy::Message::EXT_DUPLICATE_EXTENSION) { + $extension .= pack("n", $key); + $extension .= pack("n", length($extdata)); + $extension .= $extdata; + } + return $extension; +} + #Reconstruct the on-the-wire message data following changes sub set_message_contents { @@ -131,15 +149,16 @@ sub set_message_contents $data .= pack("C*", @{$self->comp_meths}); foreach my $key (keys %{$self->extension_data}) { - my $extdata = ${$self->extension_data}{$key}; - $extensions .= pack("n", $key); - $extensions .= pack("n", length($extdata)); - $extensions .= $extdata; - if ($key == TLSProxy::Message::EXT_DUPLICATE_EXTENSION) { - $extensions .= pack("n", $key); - $extensions .= pack("n", length($extdata)); - $extensions .= $extdata; - } + next if ($key == TLSProxy::Message::EXT_PSK); + $extensions .= $self->extension_contents($key); + } + #PSK extension always goes last... + if (defined ${$self->extension_data}{TLSProxy::Message::EXT_PSK}) { + $extensions .= $self->extension_contents(TLSProxy::Message::EXT_PSK); + } + #unless we have EXT_FORCE_LAST + if (defined ${$self->extension_data}{TLSProxy::Message::EXT_FORCE_LAST}) { + $extensions .= $self->extension_contents(TLSProxy::Message::EXT_FORCE_LAST); } $data .= pack('n', length($extensions)); diff --git a/util/perl/TLSProxy/EncryptedExtensions.pm b/util/perl/TLSProxy/EncryptedExtensions.pm new file mode 100644 index 00000000..81242e29 --- /dev/null +++ b/util/perl/TLSProxy/EncryptedExtensions.pm @@ -0,0 +1,115 @@ +# 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 + +use strict; + +package TLSProxy::EncryptedExtensions; + +use vars '@ISA'; +push @ISA, 'TLSProxy::Message'; + +sub new +{ + my $class = shift; + my ($server, + $data, + $records, + $startoffset, + $message_frag_lens) = @_; + + my $self = $class->SUPER::new( + $server, + TLSProxy::Message::MT_ENCRYPTED_EXTENSIONS, + $data, + $records, + $startoffset, + $message_frag_lens); + + $self->{extension_data} = ""; + + return $self; +} + +sub parse +{ + my $self = shift; + + my $extensions_len = unpack('n', $self->data); + if (!defined $extensions_len) { + $extensions_len = 0; + } + + my $extension_data; + if ($extensions_len != 0) { + $extension_data = substr($self->data, 2); + + if (length($extension_data) != $extensions_len) { + die "Invalid extension length\n"; + } + } else { + if (length($self->data) != 2) { + die "Invalid extension length\n"; + } + $extension_data = ""; + } + my %extensions = (); + while (length($extension_data) >= 4) { + my ($type, $size) = unpack("nn", $extension_data); + my $extdata = substr($extension_data, 4, $size); + $extension_data = substr($extension_data, 4 + $size); + $extensions{$type} = $extdata; + } + + $self->extension_data(\%extensions); + + print " Extensions Len:".$extensions_len."\n"; +} + +#Reconstruct the on-the-wire message data following changes +sub set_message_contents +{ + my $self = shift; + my $data; + my $extensions = ""; + + foreach my $key (keys %{$self->extension_data}) { + my $extdata = ${$self->extension_data}{$key}; + $extensions .= pack("n", $key); + $extensions .= pack("n", length($extdata)); + $extensions .= $extdata; + if ($key == TLSProxy::Message::EXT_DUPLICATE_EXTENSION) { + $extensions .= pack("n", $key); + $extensions .= pack("n", length($extdata)); + $extensions .= $extdata; + } + } + + $data = pack('n', length($extensions)); + $data .= $extensions; + $self->data($data); +} + +#Read/write accessors +sub extension_data +{ + my $self = shift; + if (@_) { + $self->{extension_data} = shift; + } + return $self->{extension_data}; +} +sub set_extension +{ + my ($self, $ext_type, $ext_data) = @_; + $self->{extension_data}{$ext_type} = $ext_data; +} +sub delete_extension +{ + my ($self, $ext_type) = @_; + delete $self->{extension_data}{$ext_type}; +} +1; diff --git a/util/perl/TLSProxy/Message.pm b/util/perl/TLSProxy/Message.pm index 0821bded..68179d91 100644 --- a/util/perl/TLSProxy/Message.pm +++ b/util/perl/TLSProxy/Message.pm @@ -1,4 +1,4 @@ -# Copyright 2016 The OpenSSL Project Authors. All Rights Reserved. +# Copyright 2016-2018 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 @@ -17,6 +17,7 @@ use constant { MT_CLIENT_HELLO => 1, MT_SERVER_HELLO => 2, MT_NEW_SESSION_TICKET => 4, + MT_ENCRYPTED_EXTENSIONS => 8, MT_CERTIFICATE => 11, MT_SERVER_KEY_EXCHANGE => 12, MT_CERTIFICATE_REQUEST => 13, @@ -46,6 +47,7 @@ my %message_type = ( MT_CLIENT_HELLO, "ClientHello", MT_SERVER_HELLO, "ServerHello", MT_NEW_SESSION_TICKET, "NewSessionTicket", + MT_ENCRYPTED_EXTENSIONS, "EncryptedExtensions", MT_CERTIFICATE, "Certificate", MT_SERVER_KEY_EXCHANGE, "ServerKeyExchange", MT_CERTIFICATE_REQUEST, "CertificateRequest", @@ -58,13 +60,70 @@ my %message_type = ( ); use constant { + EXT_SERVER_NAME => 0, + EXT_MAX_FRAGMENT_LENGTH => 1, EXT_STATUS_REQUEST => 5, + EXT_SUPPORTED_GROUPS => 10, + EXT_EC_POINT_FORMATS => 11, + EXT_SRP => 12, + EXT_SIG_ALGS => 13, + EXT_USE_SRTP => 14, + EXT_ALPN => 16, + EXT_SCT => 18, + EXT_PADDING => 21, EXT_ENCRYPT_THEN_MAC => 22, EXT_EXTENDED_MASTER_SECRET => 23, EXT_SESSION_TICKET => 35, - # This extension does not exist and isn't recognised by OpenSSL. - # We use it to test handling of duplicate extensions. - EXT_DUPLICATE_EXTENSION => 1234 + EXT_KEY_SHARE => 51, + EXT_PSK => 41, + EXT_SUPPORTED_VERSIONS => 43, + EXT_COOKIE => 44, + EXT_PSK_KEX_MODES => 45, + EXT_POST_HANDSHAKE_AUTH => 49, + EXT_SIG_ALGS_CERT => 50, + EXT_RENEGOTIATE => 65281, + EXT_NPN => 13172, + # This extension is an unofficial extension only ever written by OpenSSL + # (i.e. not read), and even then only when enabled. We use it to test + # handling of duplicate extensions. + EXT_DUPLICATE_EXTENSION => 0xfde8, + EXT_UNKNOWN => 0xfffe, + #Unknown extension that should appear last + EXT_FORCE_LAST => 0xffff +}; + +# SignatureScheme of TLS 1.3, from +# https://tools.ietf.org/html/draft-ietf-tls-tls13-20#appendix-B.3.1.3 +# TODO(TLS1.3) update link to IANA registry after publication +# We have to manually grab the SHA224 equivalents from the old registry +use constant { + SIG_ALG_RSA_PKCS1_SHA256 => 0x0401, + SIG_ALG_RSA_PKCS1_SHA384 => 0x0501, + SIG_ALG_RSA_PKCS1_SHA512 => 0x0601, + SIG_ALG_ECDSA_SECP256R1_SHA256 => 0x0403, + SIG_ALG_ECDSA_SECP384R1_SHA384 => 0x0503, + SIG_ALG_ECDSA_SECP521R1_SHA512 => 0x0603, + SIG_ALG_RSA_PSS_SHA256 => 0x0804, + SIG_ALG_RSA_PSS_SHA384 => 0x0805, + SIG_ALG_RSA_PSS_SHA512 => 0x0806, + SIG_ALG_ED25519 => 0x0807, + SIG_ALG_ED448 => 0x0808, + SIG_ALG_RSA_PKCS1_SHA1 => 0x0201, + SIG_ALG_ECDSA_SHA1 => 0x0203, + SIG_ALG_DSA_SHA1 => 0x0202, + SIG_ALG_DSA_SHA256 => 0x0402, + SIG_ALG_DSA_SHA384 => 0x0502, + SIG_ALG_DSA_SHA512 => 0x0602, + OSSL_SIG_ALG_RSA_PKCS1_SHA224 => 0x0301, + OSSL_SIG_ALG_DSA_SHA224 => 0x0302, + OSSL_SIG_ALG_ECDSA_SHA224 => 0x0303 +}; + +use constant { + CIPHER_DHE_RSA_AES_128_SHA => 0x0033, + CIPHER_ADH_AES_128_SHA => 0x0034, + CIPHER_TLS13_AES_128_GCM_SHA256 => 0x1301, + CIPHER_TLS13_AES_256_GCM_SHA384 => 0x1302 }; my $payload = ""; @@ -77,6 +136,7 @@ my $end = 0; my @message_rec_list = (); my @message_frag_lens = (); my $ciphersuite = 0; +my $successondata = 0; sub clear { @@ -86,6 +146,7 @@ sub clear $server = 0; $success = 0; $end = 0; + $successondata = 0; @message_rec_list = (); @message_frag_lens = (); } @@ -111,10 +172,12 @@ sub get_messages #We can't handle this yet die "CCS received before message data complete\n"; } - if ($server) { - TLSProxy::Record->server_ccs_seen(1); - } else { - TLSProxy::Record->client_ccs_seen(1); + if (!TLSProxy::Proxy->is_tls13()) { + if ($server) { + TLSProxy::Record->server_encrypting(1); + } else { + TLSProxy::Record->client_encrypting(1); + } } } elsif ($record->content_type == TLSProxy::Record::RT_HANDSHAKE) { if ($record->len == 0 || $record->len_real == 0) { @@ -197,6 +260,11 @@ sub get_messages } elsif ($record->content_type == TLSProxy::Record::RT_APPLICATION_DATA) { print " [ENCRYPTED APPLICATION DATA]\n"; print " [".$record->decrypt_data."]\n"; + + if ($successondata) { + $success = 1; + $end = 1; + } } elsif ($record->content_type == TLSProxy::Record::RT_ALERT) { my ($alertlev, $alertdesc) = unpack('CC', $record->decrypt_data); #A CloseNotify from the client indicates we have finished successfully @@ -239,6 +307,33 @@ sub create_message [@message_frag_lens] ); $message->parse(); + } elsif ($mt == MT_ENCRYPTED_EXTENSIONS) { + $message = TLSProxy::EncryptedExtensions->new( + $server, + $data, + [@message_rec_list], + $startoffset, + [@message_frag_lens] + ); + $message->parse(); + } elsif ($mt == MT_CERTIFICATE) { + $message = TLSProxy::Certificate->new( + $server, + $data, + [@message_rec_list], + $startoffset, + [@message_frag_lens] + ); + $message->parse(); + } elsif ($mt == MT_CERTIFICATE_VERIFY) { + $message = TLSProxy::CertificateVerify->new( + $server, + $data, + [@message_rec_list], + $startoffset, + [@message_frag_lens] + ); + $message->parse(); } elsif ($mt == MT_SERVER_KEY_EXCHANGE) { $message = TLSProxy::ServerKeyExchange->new( $server, @@ -319,7 +414,7 @@ sub ciphersuite } #Update all the underlying records with the modified data from this message -#Note: Does not currently support re-encrypting +#Note: Only supports re-encrypting for TLSv1.3 sub repack { my $self = shift; @@ -362,8 +457,14 @@ sub repack # use an explicit override field instead.) $rec->decrypt_len(length($rec->decrypt_data)); $rec->len($rec->len + length($msgdata) - $old_length); - # Don't support re-encryption. - $rec->data($rec->decrypt_data); + # Only support re-encryption for TLSv1.3. + if (TLSProxy::Proxy->is_tls13() && $rec->encrypted()) { + #Add content type (1 byte) and 16 tag bytes + $rec->data($rec->decrypt_data + .pack("C", TLSProxy::Record::RT_HANDSHAKE).("\0"x16)); + } else { + $rec->data($rec->decrypt_data); + } #Update the fragment len in case we changed it above ${$self->message_frag_lens}[0] = length($msgdata) @@ -452,5 +553,12 @@ sub encoded_length my $self = shift; return TLS_MESSAGE_HEADER_LENGTH + length($self->data); } - +sub successondata +{ + my $class = shift; + if (@_) { + $successondata = shift; + } + return $successondata; +} 1; diff --git a/util/perl/TLSProxy/Proxy.pm b/util/perl/TLSProxy/Proxy.pm index de143626..0b722c11 100644 --- a/util/perl/TLSProxy/Proxy.pm +++ b/util/perl/TLSProxy/Proxy.pm @@ -17,6 +17,9 @@ use TLSProxy::Record; use TLSProxy::Message; use TLSProxy::ClientHello; use TLSProxy::ServerHello; +use TLSProxy::EncryptedExtensions; +use TLSProxy::Certificate; +use TLSProxy::CertificateVerify; use TLSProxy::ServerKeyExchange; use TLSProxy::NewSessionTicket; use Time::HiRes qw/usleep/; @@ -24,6 +27,9 @@ use Time::HiRes qw/usleep/; my $have_IPv6 = 0; my $IP_factory; +my $is_tls13 = 0; +my $ciphersuite = undef; + sub new { my $class = shift; @@ -45,16 +51,15 @@ sub new serverpid => 0, clientpid => 0, reneg => 0, + sessionfile => undef, #Public read execute => $execute, cert => $cert, debug => $debug, cipherc => "", - ciphers => "AES128-SHA", - flight => -1, - direction => -1, - partial => ["", ""], + ciphers => "AES128-SHA:TLS13-AES-128-GCM-SHA256", + flight => 0, record_list => [], message_list => [], }; @@ -130,13 +135,14 @@ sub clearClient my $self = shift; $self->{cipherc} = ""; - $self->{flight} = -1; - $self->{direction} = -1; - $self->{partial} = ["", ""]; + $self->{flight} = 0; $self->{record_list} = []; $self->{message_list} = []; $self->{clientflags} = ""; + $self->{sessionfile} = undef; $self->{clientpid} = 0; + $is_tls13 = 0; + $ciphersuite = undef; TLSProxy::Message->clear(); TLSProxy::Record->clear(); @@ -147,7 +153,7 @@ sub clear my $self = shift; $self->clearClient; - $self->{ciphers} = "AES128-SHA"; + $self->{ciphers} = "AES128-SHA:TLS13-AES-128-GCM-SHA256"; $self->{serverflags} = ""; $self->{serverconnects} = 1; $self->{serverpid} = 0; @@ -182,9 +188,10 @@ sub start $pid = fork(); if ($pid == 0) { my $execcmd = $self->execute - ." s_server -max_protocol TLSv1.2 -no_comp -rev -engine ossltest -accept " + ." s_server -no_comp -rev -engine ossltest -accept " .($self->server_port) - ." -cert ".$self->cert." -naccept ".$self->serverconnects; + ." -cert ".$self->cert." -cert2 ".$self->cert + ." -naccept ".$self->serverconnects; unless ($self->supports_IPv6) { $execcmd .= " -4"; } @@ -219,7 +226,7 @@ sub clientstart $echostr = "test"; } my $execcmd = "echo ".$echostr." | ".$self->execute - ." s_client -max_protocol TLSv1.2 -engine ossltest -connect " + ." s_client -engine ossltest -connect " .($self->proxy_addr).":".($self->proxy_port); unless ($self->supports_IPv6) { $execcmd .= " -4"; @@ -230,6 +237,9 @@ sub clientstart if ($self->clientflags ne "") { $execcmd .= " ".$self->clientflags; } + if (defined $self->sessionfile) { + $execcmd .= " -ign_eof"; + } if ($self->debug) { print STDERR "Client command: $execcmd\n"; } @@ -286,24 +296,35 @@ sub clientstart #Wait for either the server socket or the client socket to become readable my @ready; + my $ctr = 0; local $SIG{PIPE} = "IGNORE"; - while(!(TLSProxy::Message->end) && (@ready = $sel->can_read)) { + while( (!(TLSProxy::Message->end) + || (defined $self->sessionfile() + && (-s $self->sessionfile()) == 0)) + && $ctr < 10) { + if (!(@ready = $sel->can_read(1))) { + $ctr++; + next; + } foreach my $hand (@ready) { if ($hand == $server_sock) { $server_sock->sysread($indata, 16384) or goto END; $indata = $self->process_packet(1, $indata); $client_sock->syswrite($indata); + $ctr = 0; } elsif ($hand == $client_sock) { $client_sock->sysread($indata, 16384) or goto END; $indata = $self->process_packet(0, $indata); $server_sock->syswrite($indata); + $ctr = 0; } else { - print "Err\n"; - goto END; + die "Unexpected handle"; } } } + die "No progress made" if $ctr >= 10; + END: print "Connection closed\n"; if($server_sock) { @@ -348,38 +369,34 @@ sub process_packet print "Received client packet\n"; } - if ($self->{direction} != $server) { - $self->{flight} = $self->{flight} + 1; - $self->{direction} = $server; - } - print "Packet length = ".length($packet)."\n"; print "Processing flight ".$self->flight."\n"; #Return contains the list of record found in the packet followed by the - #list of messages in those records and any partial message - my @ret = TLSProxy::Record->get_records($server, $self->flight, $self->{partial}[$server].$packet); - $self->{partial}[$server] = $ret[2]; + #list of messages in those records + my @ret = TLSProxy::Record->get_records($server, $self->flight, $packet); push @{$self->record_list}, @{$ret[0]}; push @{$self->{message_list}}, @{$ret[1]}; print "\n"; - if (scalar(@{$ret[0]}) == 0 or length($ret[2]) != 0) { - return ""; - } - #Finished parsing. Call user provided filter here - if (defined $self->filter) { + if(defined $self->filter) { $self->filter->($self); } #Reconstruct the packet $packet = ""; foreach my $record (@{$self->record_list}) { - $packet .= $record->reconstruct_record(); + #We only replay the records for the current flight + if ($record->flight != $self->flight) { + next; + } + $packet .= $record->reconstruct_record($server); } + $self->{flight} = $self->{flight} + 1; + print "Forwarded packet length = ".length($packet)."\n\n"; return $packet; @@ -442,7 +459,7 @@ sub server_addr { my $self = shift; if (@_) { - $self->{server_addr} = shift; + $self->{server_addr} = shift; } return $self->{server_addr}; } @@ -450,7 +467,7 @@ sub server_port { my $self = shift; if (@_) { - $self->{server_port} = shift; + $self->{server_port} = shift; } return $self->{server_port}; } @@ -458,7 +475,7 @@ sub filter { my $self = shift; if (@_) { - $self->{filter} = shift; + $self->{filter} = shift; } return $self->{filter}; } @@ -466,7 +483,7 @@ sub cipherc { my $self = shift; if (@_) { - $self->{cipherc} = shift; + $self->{cipherc} = shift; } return $self->{cipherc}; } @@ -474,7 +491,7 @@ sub ciphers { my $self = shift; if (@_) { - $self->{ciphers} = shift; + $self->{ciphers} = shift; } return $self->{ciphers}; } @@ -482,7 +499,7 @@ sub serverflags { my $self = shift; if (@_) { - $self->{serverflags} = shift; + $self->{serverflags} = shift; } return $self->{serverflags}; } @@ -490,7 +507,7 @@ sub clientflags { my $self = shift; if (@_) { - $self->{clientflags} = shift; + $self->{clientflags} = shift; } return $self->{clientflags}; } @@ -498,7 +515,7 @@ sub serverconnects { my $self = shift; if (@_) { - $self->{serverconnects} = shift; + $self->{serverconnects} = shift; } return $self->{serverconnects}; } @@ -518,7 +535,7 @@ sub serverpid { my $self = shift; if (@_) { - $self->{serverpid} = shift; + $self->{serverpid} = shift; } return $self->{serverpid}; } @@ -541,13 +558,47 @@ sub fill_known_data return $ret; } +sub is_tls13 +{ + my $class = shift; + if (@_) { + $is_tls13 = shift; + } + return $is_tls13; +} + sub reneg { my $self = shift; if (@_) { - $self->{reneg} = shift; + $self->{reneg} = shift; } return $self->{reneg}; } +#Setting a sessionfile means that the client will not close until the given +#file exists. This is useful in TLSv1.3 where otherwise s_client will close +#immediately at the end of the handshake, but before the session has been +#received from the server. A side effect of this is that s_client never sends +#a close_notify, so instead we consider success to be when it sends application +#data over the connection. +sub sessionfile +{ + my $self = shift; + if (@_) { + $self->{sessionfile} = shift; + TLSProxy::Message->successondata(1); + } + return $self->{sessionfile}; +} + +sub ciphersuite +{ + my $class = shift; + if (@_) { + $ciphersuite = shift; + } + return $ciphersuite; +} + 1; diff --git a/util/perl/TLSProxy/Record.pm b/util/perl/TLSProxy/Record.pm index 786ba0c7..773f759a 100644 --- a/util/perl/TLSProxy/Record.pm +++ b/util/perl/TLSProxy/Record.pm @@ -11,8 +11,8 @@ use TLSProxy::Proxy; package TLSProxy::Record; -my $server_ccs_seen = 0; -my $client_ccs_seen = 0; +my $server_encrypting = 0; +my $client_encrypting = 0; my $etm = 0; use constant TLS_RECORD_HEADER_LENGTH => 5; @@ -35,12 +35,14 @@ my %record_type = ( ); use constant { - VERS_TLS_1_3 => 772, - VERS_TLS_1_2 => 771, - VERS_TLS_1_1 => 770, - VERS_TLS_1_0 => 769, - VERS_SSL_3_0 => 768, - VERS_SSL_LT_3_0 => 767 + VERS_TLS_1_4 => 0x0305, + VERS_TLS_1_3_DRAFT => 0x7f17, + VERS_TLS_1_3 => 0x0304, + VERS_TLS_1_2 => 0x0303, + VERS_TLS_1_1 => 0x0302, + VERS_TLS_1_0 => 0x0301, + VERS_SSL_3_0 => 0x0300, + VERS_SSL_LT_3_0 => 0x02ff }; my %tls_version = ( @@ -59,7 +61,6 @@ sub get_records my $server = shift; my $flight = shift; my $packet = shift; - my $partial = ""; my @record_list = (); my @message_list = (); my $data; @@ -78,10 +79,8 @@ sub get_records print " (client -> server)\n"; } #Get the record header - if (length($packet) < TLS_RECORD_HEADER_LENGTH - || length($packet) < 5 + unpack("n", substr($packet, 3, 2))) { + if (length($packet) < TLS_RECORD_HEADER_LENGTH) { print "Partial data : ".length($packet)." bytes\n"; - $partial = $packet; $packet = ""; } else { ($content_type, $version, $len) = unpack('CnnC*', $packet); @@ -110,12 +109,20 @@ sub get_records substr($packet, TLS_RECORD_HEADER_LENGTH, $len_real) ); - if (($server && $server_ccs_seen) - || (!$server && $client_ccs_seen)) { - if ($etm) { - $record->decryptETM(); - } else { - $record->decrypt(); + if ($content_type != RT_CCS) { + if (($server && $server_encrypting) + || (!$server && $client_encrypting)) { + if (!TLSProxy::Proxy->is_tls13() && $etm) { + $record->decryptETM(); + } else { + $record->decrypt(); + } + $record->encrypted(1); + + if (TLSProxy::Proxy->is_tls13()) { + print " Inner content type: " + .$record_type{$record->content_type()}."\n"; + } } } @@ -130,31 +137,31 @@ sub get_records } } - return (\@record_list, \@message_list, $partial); + return (\@record_list, \@message_list); } sub clear { - $server_ccs_seen = 0; - $client_ccs_seen = 0; + $server_encrypting = 0; + $client_encrypting = 0; } #Class level accessors -sub server_ccs_seen +sub server_encrypting { my $class = shift; if (@_) { - $server_ccs_seen = shift; + $server_encrypting = shift; } - return $server_ccs_seen; + return $server_encrypting; } -sub client_ccs_seen +sub client_encrypting { my $class = shift; if (@_) { - $client_ccs_seen = shift; + $client_encrypting= shift; } - return $client_ccs_seen; + return $client_encrypting; } #Enable/Disable Encrypt-then-MAC sub etm @@ -190,7 +197,8 @@ sub new data => $data, decrypt_data => $decrypt_data, orig_decrypt_data => $decrypt_data, - sent => 0 + encrypted => 0, + outer_content_type => RT_APPLICATION_DATA }; return bless $self, $class; @@ -227,22 +235,44 @@ sub decryptETM sub decrypt() { my ($self) = shift; - + my $mactaglen = 20; my $data = $self->data; - if($self->version >= VERS_TLS_1_1()) { - #TLS1.1+ has an explicit IV. Throw it away + #Throw away any IVs + if (TLSProxy::Proxy->is_tls13()) { + #A TLS1.3 client, when processing the server's initial flight, could + #respond with either an encrypted or an unencrypted alert. + if ($self->content_type() == RT_ALERT) { + #TODO(TLS1.3): Eventually it is sufficient just to check the record + #content type. If an alert is encrypted it will have a record + #content type of application data. However we haven't done the + #record layer changes yet, so it's a bit more complicated. For now + #we will additionally check if the data length is 2 (1 byte for + #alert level, 1 byte for alert description). If it is, then this is + #an unencrypted alert, so don't try to decrypt + return $data if (length($data) == 2); + } + $mactaglen = 16; + } elsif ($self->version >= VERS_TLS_1_1()) { + #16 bytes for a standard IV $data = substr($data, 16); + + #Find out what the padding byte is + my $padval = unpack("C", substr($data, length($data) - 1)); + + #Throw away the padding + $data = substr($data, 0, length($data) - ($padval + 1)); } - #Find out what the padding byte is - my $padval = unpack("C", substr($data, length($data) - 1)); + #Throw away the MAC or TAG + $data = substr($data, 0, length($data) - $mactaglen); - #Throw away the padding - $data = substr($data, 0, length($data) - ($padval + 1)); - - #Throw away the MAC (assumes MAC is 20 bytes for now. FIXME) - $data = substr($data, 0, length($data) - 20); + if (TLSProxy::Proxy->is_tls13()) { + #Get the content type + my $content_type = unpack("C", substr($data, length($data) - 1)); + $self->content_type($content_type); + $data = substr($data, 0, length($data) - 1); + } $self->decrypt_data($data); $self->decrypt_len(length($data)); @@ -254,17 +284,20 @@ sub decrypt() sub reconstruct_record { my $self = shift; + my $server = shift; my $data; - if ($self->{sent}) { - return ""; - } - $self->{sent} = 1; - if ($self->sslv2) { $data = pack('n', $self->len | 0x8000); } else { - $data = pack('Cnn', $self->content_type, $self->version, $self->len); + if (TLSProxy::Proxy->is_tls13() && $self->encrypted) { + $data = pack('Cnn', $self->outer_content_type, $self->version, + $self->len); + } else { + $data = pack('Cnn', $self->content_type, $self->version, + $self->len); + } + } $data .= $self->data; @@ -277,16 +310,6 @@ sub flight my $self = shift; return $self->{flight}; } -sub content_type -{ - my $self = shift; - return $self->{content_type}; -} -sub version -{ - my $self = shift; - return $self->{version}; -} sub sslv2 { my $self = shift; @@ -336,4 +359,36 @@ sub len } return $self->{len}; } +sub version +{ + my $self = shift; + if (@_) { + $self->{version} = shift; + } + return $self->{version}; +} +sub content_type +{ + my $self = shift; + if (@_) { + $self->{content_type} = shift; + } + return $self->{content_type}; +} +sub encrypted +{ + my $self = shift; + if (@_) { + $self->{encrypted} = shift; + } + return $self->{encrypted}; +} +sub outer_content_type +{ + my $self = shift; + if (@_) { + $self->{outer_content_type} = shift; + } + return $self->{outer_content_type}; +} 1; diff --git a/util/perl/TLSProxy/ServerHello.pm b/util/perl/TLSProxy/ServerHello.pm index 79a8be9a..934eaf4d 100644 --- a/util/perl/TLSProxy/ServerHello.pm +++ b/util/perl/TLSProxy/ServerHello.pm @@ -12,6 +12,11 @@ package TLSProxy::ServerHello; use vars '@ISA'; push @ISA, 'TLSProxy::Message'; +my $hrrrandom = pack("C*", 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 0xBE, + 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, 0xC2, 0xA2, + 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 0x07, 0x9E, 0x09, + 0xE2, 0xC8, 0xA8, 0x33, 0x9C); + sub new { my $class = shift; @@ -45,16 +50,23 @@ sub parse my $self = shift; my $ptr = 2; my ($server_version) = unpack('n', $self->data); + my $neg_version = $server_version; + my $random = substr($self->data, $ptr, 32); $ptr += 32; - my $session_id_len = unpack('C', substr($self->data, $ptr)); + my $session_id_len = 0; + my $session = ""; + $session_id_len = unpack('C', substr($self->data, $ptr)); $ptr++; - my $session = substr($self->data, $ptr, $session_id_len); + $session = substr($self->data, $ptr, $session_id_len); $ptr += $session_id_len; + my $ciphersuite = unpack('n', substr($self->data, $ptr)); $ptr += 2; - my $comp_meth = unpack('C', substr($self->data, $ptr)); + my $comp_meth = 0; + $comp_meth = unpack('C', substr($self->data, $ptr)); $ptr++; + my $extensions_len = unpack('n', substr($self->data, $ptr)); if (!defined $extensions_len) { $extensions_len = 0; @@ -82,6 +94,20 @@ sub parse my $extdata = substr($extension_data, 4, $size); $extension_data = substr($extension_data, 4 + $size); $extensions{$type} = $extdata; + if ($type == TLSProxy::Message::EXT_SUPPORTED_VERSIONS) { + $neg_version = unpack('n', $extdata); + } + } + + if ($random eq $hrrrandom) { + TLSProxy::Proxy->is_tls13(1); + # TODO(TLS1.3): Replace this reference to draft version before release + } elsif ($neg_version == TLSProxy::Record::VERS_TLS_1_3_DRAFT) { + $neg_version = TLSProxy::Record::VERS_TLS_1_3; + TLSProxy::Proxy->is_tls13(1); + + TLSProxy::Record->server_encrypting(1); + TLSProxy::Record->client_encrypting(1); } $self->server_version($server_version); @@ -89,11 +115,13 @@ sub parse $self->session_id_len($session_id_len); $self->session($session); $self->ciphersuite($ciphersuite); + TLSProxy::Proxy->ciphersuite($ciphersuite); $self->comp_meth($comp_meth); $self->extension_data(\%extensions); $self->process_data(); + print " Server Version:".$server_version."\n"; print " Session ID Len:".$session_id_len."\n"; print " Ciphersuite:".$ciphersuite."\n"; @@ -145,9 +173,9 @@ sub server_version { my $self = shift; if (@_) { - $self->{client_version} = shift; + $self->{server_version} = shift; } - return $self->{client_version}; + return $self->{server_version}; } sub random { diff --git a/util/perl/TLSProxy/ServerKeyExchange.pm b/util/perl/TLSProxy/ServerKeyExchange.pm index 6e5b4cdc..cb4cc7c7 100644 --- a/util/perl/TLSProxy/ServerKeyExchange.pm +++ b/util/perl/TLSProxy/ServerKeyExchange.pm @@ -33,6 +33,7 @@ sub new $self->{p} = ""; $self->{g} = ""; $self->{pub_key} = ""; + $self->{sigalg} = -1; $self->{sig} = ""; return $self; @@ -41,10 +42,13 @@ sub new sub parse { my $self = shift; + my $sigalg = -1; - #Minimal SKE parsing. Only supports DHE at the moment (if its not DHE - #the parsing data will be trash...which is ok as long as we don't try to - #use it) + #Minimal SKE parsing. Only supports one known DHE ciphersuite at the moment + return if TLSProxy::Proxy->ciphersuite() + != TLSProxy::Message::CIPHER_ADH_AES_128_SHA + && TLSProxy::Proxy->ciphersuite() + != TLSProxy::Message::CIPHER_DHE_RSA_AES_128_SHA; my $p_len = unpack('n', $self->data); my $ptr = 2; @@ -62,18 +66,28 @@ sub parse $ptr += $pub_key_len; #We assume its signed - my $sig_len = unpack('n', substr($self->data, $ptr)); + my $record = ${$self->records}[0]; + + if (TLSProxy::Proxy->is_tls13() + || $record->version() == TLSProxy::Record::VERS_TLS_1_2) { + $sigalg = unpack('n', substr($self->data, $ptr)); + $ptr += 2; + } my $sig = ""; - if (defined $sig_len) { - $ptr += 2; - $sig = substr($self->data, $ptr, $sig_len); - $ptr += $sig_len; + if (defined $sigalg) { + my $sig_len = unpack('n', substr($self->data, $ptr)); + if (defined $sig_len) { + $ptr += 2; + $sig = substr($self->data, $ptr, $sig_len); + $ptr += $sig_len; + } } $self->p($p); $self->g($g); $self->pub_key($pub_key); - $self->sig($sig); + $self->sigalg($sigalg) if defined $sigalg; + $self->signature($sig); } @@ -89,9 +103,10 @@ sub set_message_contents $data .= $self->g; $data .= pack('n', length($self->pub_key)); $data .= $self->pub_key; - if (length($self->sig) > 0) { - $data .= pack('n', length($self->sig)); - $data .= $self->sig; + $data .= pack('n', $self->sigalg) if ($self->sigalg != -1); + if (length($self->signature) > 0) { + $data .= pack('n', length($self->signature)); + $data .= $self->signature; } $self->data($data); @@ -123,7 +138,15 @@ sub pub_key } return $self->{pub_key}; } -sub sig +sub sigalg +{ + my $self = shift; + if (@_) { + $self->{sigalg} = shift; + } + return $self->{sigalg}; +} +sub signature { my $self = shift; if (@_) { diff --git a/util/perl/checkhandshake.pm b/util/perl/checkhandshake.pm new file mode 100644 index 00000000..c53b96d5 --- /dev/null +++ b/util/perl/checkhandshake.pm @@ -0,0 +1,228 @@ +#! /usr/bin/env perl +# Copyright 2015-2018 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 + +package checkhandshake; + +use OpenSSL::Test qw/:DEFAULT cmdstr srctop_file srctop_dir bldtop_dir/; +use OpenSSL::Test::Utils; +use TLSProxy::Proxy; + +use Exporter; +our @ISA = 'Exporter'; +our @EXPORT = qw(@handmessages @extensions checkhandshake); + +use constant { + DEFAULT_HANDSHAKE => 1, + OCSP_HANDSHAKE => 2, + RESUME_HANDSHAKE => 4, + CLIENT_AUTH_HANDSHAKE => 8, + RENEG_HANDSHAKE => 16, + NPN_HANDSHAKE => 32, + EC_HANDSHAKE => 64, + HRR_HANDSHAKE => 128, + HRR_RESUME_HANDSHAKE => 256, + + ALL_HANDSHAKES => 511 +}; + +use constant { + #DEFAULT also includes SESSION_TICKET_SRV_EXTENSION and SERVER_NAME_CLI + DEFAULT_EXTENSIONS => 0x00000007, + SESSION_TICKET_SRV_EXTENSION => 0x00000002, + SERVER_NAME_CLI_EXTENSION => 0x00000004, + SERVER_NAME_SRV_EXTENSION => 0x00000008, + STATUS_REQUEST_CLI_EXTENSION => 0x00000010, + STATUS_REQUEST_SRV_EXTENSION => 0x00000020, + ALPN_CLI_EXTENSION => 0x00000040, + ALPN_SRV_EXTENSION => 0x00000080, + SCT_CLI_EXTENSION => 0x00000100, + SCT_SRV_EXTENSION => 0x00000200, + RENEGOTIATE_CLI_EXTENSION => 0x00000400, + NPN_CLI_EXTENSION => 0x00000800, + NPN_SRV_EXTENSION => 0x00001000, + SRP_CLI_EXTENSION => 0x00002000, + #Client side for ec point formats is a default extension + EC_POINT_FORMAT_SRV_EXTENSION => 0x00004000, + PSK_CLI_EXTENSION => 0x00008000, + PSK_SRV_EXTENSION => 0x00010000, + KEY_SHARE_SRV_EXTENSION => 0x00020000, + PSK_KEX_MODES_EXTENSION => 0x00040000, + KEY_SHARE_HRR_EXTENSION => 0x00080000, + SUPPORTED_GROUPS_SRV_EXTENSION => 0x00100000, + POST_HANDSHAKE_AUTH_CLI_EXTENSION => 0x00200000 +}; + +our @handmessages = (); +our @extensions = (); + +sub checkhandshake($$$$) +{ + my ($proxy, $handtype, $exttype, $testname) = @_; + + subtest $testname => sub { + my $loop = 0; + my $numtests; + my $extcount; + my $clienthelloseen = 0; + + my $lastmt = 0; + my $numsh = 0; + if (TLSProxy::Proxy::is_tls13()) { + #How many ServerHellos are we expecting? + for ($numtests = 0; $handmessages[$loop][1] != 0; $loop++) { + next if (($handmessages[$loop][1] & $handtype) == 0); + $numsh++ if ($lastmt != TLSProxy::Message::MT_SERVER_HELLO + && $handmessages[$loop][0] == TLSProxy::Message::MT_SERVER_HELLO); + $lastmt = $handmessages[$loop][0]; + } + } + + #First count the number of tests + my $nextmess = 0; + my $message = undef; + my $chnum = 0; + my $shnum = 0; + if (!TLSProxy::Proxy::is_tls13()) { + # In non-TLSv1.3 we always treat reneg CH and SH like the first CH + # and SH + $chnum = 1; + $shnum = 1; + } + #If we're only expecting one ServerHello out of two then we skip the + #first ServerHello in the list completely + $shnum++ if ($numsh == 1 && TLSProxy::Proxy::is_tls13()); + $loop = 0; + for ($numtests = 0; $handmessages[$loop][1] != 0; $loop++) { + next if (($handmessages[$loop][1] & $handtype) == 0); + if (scalar @{$proxy->message_list} > $nextmess) { + $message = ${$proxy->message_list}[$nextmess]; + $nextmess++; + } else { + $message = undef; + } + $numtests++; + + next if (!defined $message); + if (TLSProxy::Proxy::is_tls13()) { + $chnum++ if $message->mt() == TLSProxy::Message::MT_CLIENT_HELLO; + $shnum++ if $message->mt() == TLSProxy::Message::MT_SERVER_HELLO; + } + next if ($message->mt() != TLSProxy::Message::MT_CLIENT_HELLO + && $message->mt() != TLSProxy::Message::MT_SERVER_HELLO + && $message->mt() != + TLSProxy::Message::MT_ENCRYPTED_EXTENSIONS + && $message->mt() != TLSProxy::Message::MT_CERTIFICATE); + + next if $message->mt() == TLSProxy::Message::MT_CERTIFICATE + && !TLSProxy::Proxy::is_tls13(); + + my $extchnum = 1; + my $extshnum = 1; + for (my $extloop = 0; + $extensions[$extloop][2] != 0; + $extloop++) { + $extchnum = 2 if $extensions[$extloop][0] != TLSProxy::Message::MT_CLIENT_HELLO + && TLSProxy::Proxy::is_tls13(); + $extshnum = 2 if $extensions[$extloop][0] != TLSProxy::Message::MT_SERVER_HELLO + && $extchnum == 2; + next if $extensions[$extloop][0] == TLSProxy::Message::MT_CLIENT_HELLO + && $extchnum != $chnum; + next if $extensions[$extloop][0] == TLSProxy::Message::MT_SERVER_HELLO + && $extshnum != $shnum; + next if ($message->mt() != $extensions[$extloop][0]); + $numtests++; + } + $numtests++; + } + + plan tests => $numtests; + + $nextmess = 0; + $message = undef; + if (TLSProxy::Proxy::is_tls13()) { + $chnum = 0; + $shnum = 0; + } else { + # In non-TLSv1.3 we always treat reneg CH and SH like the first CH + # and SH + $chnum = 1; + $shnum = 1; + } + #If we're only expecting one ServerHello out of two then we skip the + #first ServerHello in the list completely + $shnum++ if ($numsh == 1 && TLSProxy::Proxy::is_tls13()); + for ($loop = 0; $handmessages[$loop][1] != 0; $loop++) { + next if (($handmessages[$loop][1] & $handtype) == 0); + if (scalar @{$proxy->message_list} > $nextmess) { + $message = ${$proxy->message_list}[$nextmess]; + $nextmess++; + } else { + $message = undef; + } + if (!defined $message) { + fail("Message type check. Got nothing, expected " + .$handmessages[$loop][0]); + next; + } else { + ok($message->mt == $handmessages[$loop][0], + "Message type check. Got ".$message->mt + .", expected ".$handmessages[$loop][0]); + } + if (TLSProxy::Proxy::is_tls13()) { + $chnum++ if $message->mt() == TLSProxy::Message::MT_CLIENT_HELLO; + $shnum++ if $message->mt() == TLSProxy::Message::MT_SERVER_HELLO; + } + + next if ($message->mt() != TLSProxy::Message::MT_CLIENT_HELLO + && $message->mt() != TLSProxy::Message::MT_SERVER_HELLO + && $message->mt() != + TLSProxy::Message::MT_ENCRYPTED_EXTENSIONS + && $message->mt() != TLSProxy::Message::MT_CERTIFICATE); + + next if $message->mt() == TLSProxy::Message::MT_CERTIFICATE + && !TLSProxy::Proxy::is_tls13(); + + if ($message->mt() == TLSProxy::Message::MT_CLIENT_HELLO) { + #Add renegotiate extension we will expect if renegotiating + $exttype |= RENEGOTIATE_CLI_EXTENSION + if ($clienthelloseen && !TLSProxy::Proxy::is_tls13()); + $clienthelloseen = 1; + } + #Now check that we saw the extensions we expected + my $msgexts = $message->extension_data(); + my $extchnum = 1; + my $extshnum = 1; + for (my $extloop = 0, $extcount = 0; $extensions[$extloop][2] != 0; + $extloop++) { + #In TLSv1.3 we can have two ClientHellos if there has been a + #HelloRetryRequest, and they may have different extensions. Skip + #if these are extensions for a different ClientHello + $extchnum = 2 if $extensions[$extloop][0] != TLSProxy::Message::MT_CLIENT_HELLO + && TLSProxy::Proxy::is_tls13(); + $extshnum = 2 if $extensions[$extloop][0] != TLSProxy::Message::MT_SERVER_HELLO + && $extchnum == 2; + next if $extensions[$extloop][0] == TLSProxy::Message::MT_CLIENT_HELLO + && $extchnum != $chnum; + next if $extensions[$extloop][0] == TLSProxy::Message::MT_SERVER_HELLO + && $extshnum != $shnum; + next if ($message->mt() != $extensions[$extloop][0]); + ok (($extensions[$extloop][2] & $exttype) == 0 + || defined ($msgexts->{$extensions[$extloop][1]}), + "Extension presence check (Message: ".$message->mt() + ." Extension: ".($extensions[$extloop][2] & $exttype).", " + .$extloop.")"); + $extcount++ if (($extensions[$extloop][2] & $exttype) != 0); + } + ok($extcount == keys %$msgexts, "Extensions count mismatch (" + .$extcount.", ".(keys %$msgexts) + .")"); + } + } +} + +1; diff --git a/util/point.sh b/util/point.sh deleted file mode 100755 index da39899c..00000000 --- a/util/point.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh - -rm -f "$2" -if test "$OSTYPE" = msdosdjgpp || test "x$PLATFORM" = xmingw ; then - cp "$1" "$2" -else - ln -s "$1" "$2" -fi -echo "$2 => $1" - diff --git a/util/private.num b/util/private.num new file mode 100644 index 00000000..c106e608 --- /dev/null +++ b/util/private.num @@ -0,0 +1,384 @@ +# This isn't a library ".num" file but is a list of documented items +# that don't appear in lib*.num -- because they are define's, in +# assembly language, etc. +# +OPENSSL_ia32cap environment +OPENSSL_MALLOC_FD environment +OPENSSL_MALLOC_FAILURES environment +OPENSSL_instrument_bus assembler +OPENSSL_instrument_bus2 assembler +# +ADMISSION_SYNTAX datatype +ADMISSIONS datatype +ASN1_STRING_TABLE datatype +BIO_ADDR datatype +BIO_ADDRINFO datatype +BIO_callback_fn datatype +BIO_callback_fn_ex datatype +BIO_hostserv_priorities datatype +BIO_lookup_type datatype +CRYPTO_EX_dup datatype +CRYPTO_EX_free datatype +CRYPTO_EX_new datatype +DTLS_timer_cb datatype +EVP_PKEY_gen_cb datatype +EVP_PKEY_METHOD datatype +EVP_PKEY_ASN1_METHOD datatype +GEN_SESSION_CB datatype +OPENSSL_Applink external +NAMING_AUTHORITY datatype +OSSL_STORE_CTX datatype +OSSL_STORE_INFO datatype +OSSL_STORE_LOADER datatype +OSSL_STORE_LOADER_CTX datatype +OSSL_STORE_SEARCH datatype +OSSL_STORE_close_fn datatype +OSSL_STORE_ctrl_fn datatype +OSSL_STORE_expect_fn datatype +OSSL_STORE_find_fn datatype +OSSL_STORE_eof_fn datatype +OSSL_STORE_error_fn datatype +OSSL_STORE_load_fn datatype +OSSL_STORE_open_fn datatype +OSSL_STORE_post_process_info_fn datatype +PROFESSION_INFO datatype +PROFESSION_INFOS datatype +RAND_poll_cb datatype +SSL_CTX_keylog_cb_func datatype +SSL_client_hello_cb_fn datatype +SSL_psk_client_cb_func datatype +SSL_psk_find_session_cb_func datatype +SSL_psk_server_cb_func datatype +SSL_psk_use_session_cb_func datatype +SSL_verify_cb datatype +UI datatype +UI_METHOD datatype +UI_STRING datatype +UI_string_types datatype +UI_string_types datatype +X509_STORE_CTX_cert_crl_fn datatype +X509_STORE_CTX_check_crl_fn datatype +X509_STORE_CTX_check_issued_fn datatype +X509_STORE_CTX_check_policy_fn datatype +X509_STORE_CTX_check_revocation_fn datatype +X509_STORE_CTX_cleanup_fn datatype +X509_STORE_CTX_get_crl_fn datatype +X509_STORE_CTX_get_issuer_fn datatype +X509_STORE_CTX_lookup_certs_fn datatype +X509_STORE_CTX_lookup_crls_fn datatype +X509_STORE_CTX_verify_cb datatype +X509_STORE_CTX_verify_fn datatype +X509_STORE_set_verify_cb_func datatype +bio_info_cb datatype +BIO_info_cb datatype +custom_ext_add_cb datatype +custom_ext_free_cb datatype +custom_ext_parse_cb datatype +pem_password_cb datatype +ssl_ct_validation_cb datatype +# +BIO_append_filename define +BIO_destroy_bio_pair define +BIO_do_accept define +BIO_do_connect define +BIO_do_handshake define +BIO_eof define +BIO_flush define +BIO_get_accept_name define +BIO_get_accept_port define +BIO_get_bind_mode define +BIO_get_buffer_num_lines define +BIO_get_cipher_ctx define +BIO_get_cipher_status define +BIO_get_close define +BIO_get_conn_address define +BIO_get_conn_hostname define +BIO_get_conn_port define +BIO_get_fd define +BIO_get_fp define +BIO_get_info_callback define +BIO_get_md define +BIO_get_md_ctx define +BIO_get_mem_data define +BIO_get_mem_ptr define +BIO_get_num_renegotiates define +BIO_get_read_request define +BIO_get_ssl define +BIO_get_write_buf_size define +BIO_get_write_guarantee define +BIO_make_bio_pair define +BIO_pending define +BIO_read_filename define +BIO_reset define +BIO_retry_type define +BIO_rw_filename define +BIO_seek define +BIO_set_accept_bios define +BIO_set_accept_name define +BIO_set_accept_port define +BIO_set_bind_mode define +BIO_set_buffer_read_data define +BIO_set_buffer_size define +BIO_set_close define +BIO_set_conn_address define +BIO_set_conn_hostname define +BIO_set_conn_port define +BIO_set_fd define +BIO_set_fp define +BIO_set_info_callback define +BIO_set_md define +BIO_set_mem_buf define +BIO_set_mem_eof_return define +BIO_set_nbio define +BIO_set_nbio_accept define +BIO_set_read_buffer_size define +BIO_set_ssl define +BIO_set_ssl_mode define +BIO_set_ssl_renegotiate_bytes define +BIO_set_ssl_renegotiate_timeout define +BIO_set_write_buf_size define +BIO_set_write_buffer_size define +BIO_should_io_special define +BIO_should_read define +BIO_should_retry define +BIO_should_write define +BIO_shutdown_wr define +BIO_tell define +BIO_wpending define +BIO_write_filename define +BN_mod define +BN_num_bytes define +BN_one define +BN_zero define deprecated 0.9.8 +CONF_modules_free define deprecated 1.1.0 +DES_ecb2_encrypt define +DES_ede2_cbc_encrypt define +DES_ede2_cfb64_encrypt define +DES_ede2_ofb64_encrypt define +DTLS_get_link_min_mtu define +DTLS_set_link_mtu define +ENGINE_cleanup define deprecated 1.1.0 +ERR_FATAL_ERROR define +ERR_GET_FUNC define +ERR_GET_LIB define +ERR_GET_REASON define +ERR_PACK define +ERR_free_strings define deprecated 1.1.0 +ERR_load_crypto_strings define deprecated 1.1.0 +EVP_DigestSignUpdate define +EVP_DigestVerifyUpdate define +EVP_MD_CTX_block_size define +EVP_MD_CTX_size define +EVP_MD_CTX_type define +EVP_OpenUpdate define +EVP_PKEY_CTX_add1_hkdf_info define +EVP_PKEY_CTX_add1_tls1_prf_seed define +EVP_PKEY_CTX_hkdf_mode define +EVP_PKEY_CTX_set1_hkdf_key define +EVP_PKEY_CTX_set1_hkdf_salt define +EVP_PKEY_CTX_set1_tls1_prf_secret define +EVP_PKEY_CTX_set_dh_paramgen_generator define +EVP_PKEY_CTX_set_dh_paramgen_prime_len define +EVP_PKEY_CTX_set_dh_pad define +EVP_PKEY_CTX_set_dh_nid define +EVP_PKEY_CTX_set_dsa_paramgen_bits define +EVP_PKEY_CTX_set_ec_param_enc define +EVP_PKEY_CTX_set_ec_paramgen_curve_nid define +EVP_PKEY_CTX_set_hkdf_md define +EVP_PKEY_CTX_set_rsa_keygen_pubexp define +EVP_PKEY_CTX_set_rsa_padding define +EVP_PKEY_CTX_set_rsa_pss_saltlen define +EVP_PKEY_CTX_set_signature_md define +EVP_PKEY_CTX_set_tls1_prf_md define +EVP_PKEY_assign_DH define +EVP_PKEY_assign_DSA define +EVP_PKEY_assign_EC_KEY define +EVP_PKEY_assign_RSA define +EVP_SealUpdate define +EVP_SignInit define +EVP_SignInit_ex define +EVP_SignUpdate define +EVP_VerifyInit define +EVP_VerifyInit_ex define +EVP_VerifyUpdate define +EVP_bf_cfb define +EVP_cast5_cfb define +EVP_cleanup define deprecated 1.1.0 +EVP_get_digestbynid define +EVP_get_digestbyobj define +EVP_idea_cfb define +EVP_rc2_cfb define +EVP_rc5_32_12_16_cfb define +EVP_seed_cfb define +EVP_sm4_cfb define +OBJ_cleanup define deprecated 1.1.0 +OPENSSL_VERSION_NUMBER define +OPENSSL_clear_free define +OPENSSL_clear_realloc define +OPENSSL_free define +OPENSSL_malloc define +OPENSSL_malloc_init define +OPENSSL_mem_debug_pop define +OPENSSL_mem_debug_push define +OPENSSL_memdup define +OPENSSL_no_config define deprecated 1.1.0 +OPENSSL_realloc define +OPENSSL_secure_actual_size define +OPENSSL_secure_clear_free define +OPENSSL_secure_free define +OPENSSL_secure_malloc define +OPENSSL_secure_zalloc define +OPENSSL_strdup define +OPENSSL_strndup define +OPENSSL_zalloc define +OpenSSL_add_all_algorithms define deprecated 1.1.0 +OpenSSL_add_all_ciphers define deprecated 1.1.0 +OpenSSL_add_all_digests define deprecated 1.1.0 +OpenSSL_add_ssl_algorithms define +PEM_FLAG_EAY_COMPATIBLE define +PEM_FLAG_ONLY_B64 define +PEM_FLAG_SECURE define +RAND_cleanup define deprecated 1.1.0 +EVP_PKEY_CTX_set_rsa_keygen_bits define +SSL_COMP_free_compression_methods define deprecated 1.1.0 +SSL_CTX_add0_chain_cert define +SSL_CTX_add1_chain_cert define +SSL_CTX_add_extra_chain_cert define +SSL_CTX_build_cert_chain define +SSL_CTX_clear_chain_certs define +SSL_CTX_clear_extra_chain_certs define +SSL_CTX_clear_mode define +SSL_CTX_disable_ct define +SSL_CTX_get0_chain_certs define +SSL_CTX_get_default_read_ahead define +SSL_CTX_get_max_cert_list define +SSL_CTX_get_max_proto_version define +SSL_CTX_get_min_proto_version define +SSL_CTX_get_mode define +SSL_CTX_get_read_ahead define +SSL_CTX_get_session_cache_mode define +SSL_CTX_get_tlsext_status_arg define +SSL_CTX_get_tlsext_status_cb define +SSL_CTX_get_tlsext_status_type define +SSL_CTX_select_current_cert define +SSL_CTX_sess_accept define +SSL_CTX_sess_accept_good define +SSL_CTX_sess_accept_renegotiate define +SSL_CTX_sess_cache_full define +SSL_CTX_sess_cb_hits define +SSL_CTX_sess_connect define +SSL_CTX_sess_connect_good define +SSL_CTX_sess_connect_renegotiate define +SSL_CTX_sess_get_cache_size define +SSL_CTX_sess_hits define +SSL_CTX_sess_misses define +SSL_CTX_sess_number define +SSL_CTX_sess_set_cache_size define +SSL_CTX_sess_timeouts define +SSL_CTX_set0_chain define +SSL_CTX_set0_chain_cert_store define +SSL_CTX_set0_verify_cert_store define +SSL_CTX_set1_chain define +SSL_CTX_set1_chain_cert_store define +SSL_CTX_set1_client_sigalgs define +SSL_CTX_set1_client_sigalgs_list define +SSL_CTX_set1_curves define +SSL_CTX_set1_curves_list define +SSL_CTX_set1_groups define +SSL_CTX_set1_groups_list define +SSL_CTX_set1_sigalgs define +SSL_CTX_set1_sigalgs_list define +SSL_CTX_set1_verify_cert_store define +SSL_CTX_set_current_cert define +SSL_CTX_set_max_cert_list define +SSL_CTX_set_max_pipelines define +SSL_CTX_set_max_proto_version define +SSL_CTX_set_max_send_fragment define +SSL_CTX_set_min_proto_version define +SSL_CTX_set_mode define +SSL_CTX_set_msg_callback_arg define +SSL_CTX_set_read_ahead define +SSL_CTX_set_session_cache_mode define +SSL_CTX_set_split_send_fragment define +SSL_CTX_set_tlsext_servername_arg define +SSL_CTX_set_tlsext_servername_callback define +SSL_CTX_set_tlsext_status_arg define +SSL_CTX_set_tlsext_status_cb define +SSL_CTX_set_tlsext_status_type define +SSL_CTX_set_tlsext_ticket_key_cb define +SSL_CTX_set_tmp_dh define +SSL_add0_chain_cert define +SSL_add1_chain_cert define +SSL_build_cert_chain define +SSL_clear_chain_certs define +SSL_clear_mode define +SSL_disable_ct define +SSL_get0_chain_certs define +SSL_get0_session define +SSL_get1_curves define +SSL_get1_groups define +SSL_get_cipher define +SSL_get_cipher_bits define +SSL_get_cipher_name define +SSL_get_cipher_version define +SSL_get_extms_support define +SSL_get_max_cert_list define +SSL_get_max_proto_version define +SSL_get_min_proto_version define +SSL_get_mode define +SSL_get_peer_signature_nid define +SSL_get_secure_renegotiation_support define +SSL_get_server_tmp_key define +SSL_get_shared_curve define +SSL_get_shared_group define +SSL_get_time define +SSL_get_timeout define +SSL_get_tlsext_status_ocsp_resp define +SSL_get_tlsext_status_type define +SSL_in_accept_init define +SSL_in_connect_init define +SSL_library_init define +SSL_load_error_strings define deprecated 1.1.0 +SSL_select_current_cert define +SSL_set0_chain define +SSL_set0_chain_cert_store define +SSL_set0_verify_cert_store define +SSL_set1_chain define +SSL_set1_chain_cert_store define +SSL_set1_client_sigalgs define +SSL_set1_client_sigalgs_list define +SSL_set1_curves define +SSL_set1_curves_list define +SSL_set1_groups define +SSL_set1_groups_list define +SSL_set1_sigalgs define +SSL_set1_sigalgs_list define +SSL_set1_verify_cert_store define +SSL_set_current_cert define +SSL_set_max_cert_list define +SSL_set_max_pipelines define +SSL_set_max_proto_version define +SSL_set_max_send_fragment define +SSL_set_min_proto_version define +SSL_set_mode define +SSL_set_msg_callback_arg define +SSL_set_mtu define +SSL_set_split_send_fragment define +SSL_set_time define +SSL_set_timeout define +SSL_set_tlsext_host_name define +SSL_set_tlsext_status_ocsp_resp define +SSL_set_tlsext_status_type define +SSL_set_tmp_dh define +SSL_want_async define +SSL_want_async_job define +SSL_want_client_hello_cb define +SSL_want_nothing define +SSL_want_read define +SSL_want_write define +SSL_want_x509_lookup define +SSLv23_client_method define +SSLv23_method define +SSLv23_server_method define +X509_STORE_set_lookup_crls_cb define +X509_STORE_set_verify_func define diff --git a/util/process_docs.pl b/util/process_docs.pl index e084df78..2b7f3227 100755 --- a/util/process_docs.pl +++ b/util/process_docs.pl @@ -30,11 +30,10 @@ use OpenSSL::Util::Pod; my %options = (); GetOptions(\%options, 'sourcedir=s', # Source directory - 'subdir=s%', # Subdirectories to look through, + 'section=i@', # Subdirectories to look through, # with associated section numbers 'destdir=s', # Destination directory #'in=s@', # Explicit files to process (ignores sourcedir) - #'section=i', # Default section used for --in files 'type=s', # The result type, 'man' or 'html' 'suffix:s', # Suffix to add to the extension. # Only used with type=man @@ -43,15 +42,13 @@ GetOptions(\%options, 'debug|D+', ); -unless ($options{subdir}) { - $options{subdir} = { apps => '1', - crypto => '3', - ssl => '3' }; +unless ($options{section}) { + $options{section} = [ 1, 3, 5, 7 ]; } unless ($options{sourcedir}) { $options{sourcedir} = catdir($config{sourcedir}, "doc"); } -pod2usage(1) unless ( defined $options{subdir} +pod2usage(1) unless ( defined $options{section} && defined $options{sourcedir} && defined $options{destdir} && defined $options{type} @@ -70,8 +67,8 @@ if ($options{debug}) { if defined $options{type}; print STDERR "DEBUG: --suffix = $options{suffix}\n" if defined $options{suffix}; - foreach (keys %{$options{subdir}}) { - print STDERR "DEBUG: --subdir = $_=$options{subdir}->{$_}\n"; + foreach (sort @{$options{section}}) { + print STDERR "DEBUG: --section = $_\n"; } print STDERR "DEBUG: --remove = $options{remove}\n" if defined $options{remove}; @@ -83,8 +80,8 @@ if ($options{debug}) { my $symlink_exists = eval { symlink("",""); 1 }; -foreach my $subdir (keys %{$options{subdir}}) { - my $section = $options{subdir}->{$subdir}; +foreach my $section (sort @{$options{section}}) { + my $subdir = "man$section"; my $podsourcedir = catfile($options{sourcedir}, $subdir); my $podglob = catfile($podsourcedir, "*.pod"); @@ -101,7 +98,7 @@ foreach my $subdir (keys %{$options{subdir}}) { my $suffix = { man => ".$podinfo{section}".($options{suffix} // ""), html => ".html" } -> {$options{type}}; my $generate = { man => "pod2man --name=$name --section=$podinfo{section} --center=OpenSSL --release=$config{version} \"$podpath\"", - html => "pod2html \"--podroot=$options{sourcedir}\" --htmldir=$updir --podpath=apps:crypto:ssl \"--infile=$podpath\" \"--title=$podname\"" + html => "pod2html \"--podroot=$options{sourcedir}\" --htmldir=$updir --podpath=man1:man3:man5:man7 \"--infile=$podpath\" \"--title=$podname\"" } -> {$options{type}}; my $output_dir = catdir($options{destdir}, "man$podinfo{section}"); my $output_file = $podname . $suffix; @@ -113,7 +110,7 @@ foreach my $subdir (keys %{$options{subdir}}) { if $options{debug}; unless ($options{"dry-run"}) { @output = `$generate`; - map { s|href="http://man\.he\.net/(man\d/[^"]+)(?:\.html)?"|href="../$1.html|g; } @output + map { s|href="http://man\.he\.net/(man\d/[^"]+)(?:\.html)?"|href="../$1.html"|g; } @output if $options{type} eq "html"; } print STDERR "DEBUG: Done processing\n" if $options{debug}; diff --git a/util/selftest.pl b/util/selftest.pl deleted file mode 100644 index d1d11593..00000000 --- a/util/selftest.pl +++ /dev/null @@ -1,207 +0,0 @@ -#! /usr/bin/env perl -# Copyright 2000-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 - -# Run the test suite and generate a report - -if (! -f "Configure") { - print "Please run perl util/selftest.pl in the OpenSSL directory.\n"; - exit 1; -} - -my $report="testlog"; -my $os="??"; -my $version="??"; -my $platform0="??"; -my $platform="??"; -my $options="??"; -my $last="??"; -my $ok=0; -my $cc="cc"; -my $cversion="??"; -my $sep="-----------------------------------------------------------------------------\n"; -my $not_our_fault="\nPlease ask your system administrator/vendor for more information.\n[Problems with your operating system setup should not be reported\nto the OpenSSL project.]\n"; - -open(OUT,">$report") or die; - -print OUT "OpenSSL self-test report:\n\n"; - -$uname=`uname -a`; -$uname="??\n" if $uname eq ""; - -$c=`sh config -t`; -foreach $_ (split("\n",$c)) { - $os=$1 if (/Operating system: (.*)$/); - $platform0=$1 if (/Configuring for (.*)$/); -} - -system "sh config" if (! -f "Makefile"); - -if (open(IN,") { - $version=$1 if (/^VERSION=(.*)$/); - $platform=$1 if (/^PLATFORM=(.*)$/); - $options=$1 if (/^OPTIONS=(.*)$/); - $cc=$1 if (/^CC= *(.*)$/); - } - close(IN); -} else { - print OUT "Error running config!\n"; -} - -$cversion=`$cc -v 2>&1`; -$cversion=`$cc -V 2>&1` if $cversion =~ "[Uu]sage"; -$cversion=`$cc -V |head -1` if $cversion =~ "Error"; -$cversion=`$cc --version` if $cversion eq ""; -$cversion =~ s/Reading specs.*\n//; -$cversion =~ s/usage.*\n//; -$cversion =~ s|\R$||; - -if (open(IN,") { - if (/\*\) (.{0,55})/ && !/applies to/) { - $last=$1; - last; - } - } - close(IN); -} - -print OUT "OpenSSL version: $version\n"; -print OUT "Last change: $last...\n"; -print OUT "Options: $options\n" if $options ne ""; -print OUT "OS (uname): $uname"; -print OUT "OS (config): $os\n"; -print OUT "Target (default): $platform0\n"; -print OUT "Target: $platform\n"; -print OUT "Compiler: $cversion\n"; -print OUT "\n"; - -print "Checking compiler...\n"; -if (open(TEST,">cctest.c")) { - print TEST "#include \n#include \n#include \nmain(){printf(\"Hello world\\n\");}\n"; - close(TEST); - system("$cc -o cctest cctest.c"); - if (`./cctest` !~ /Hello world/) { - print OUT "Compiler doesn't work.\n"; - print OUT $not_our_fault; - goto err; - } - system("ar r cctest.a /dev/null"); - if (not -f "cctest.a") { - print OUT "Check your archive tool (ar).\n"; - print OUT $not_our_fault; - goto err; - } -} else { - print OUT "Can't create cctest.c\n"; -} -if (open(TEST,">cctest.c")) { - print TEST "#include \n#include \n#include \nmain(){printf(OPENSSL_VERSION_TEXT);}\n"; - close(TEST); - system("$cc -o cctest -Iinclude cctest.c"); - $cctest = `./cctest`; - if ($cctest !~ /OpenSSL $version/) { - if ($cctest =~ /OpenSSL/) { - print OUT "#include uses headers from different OpenSSL version!\n"; - } else { - print OUT "Can't compile test program!\n"; - } - print OUT $not_our_fault; - goto err; - } -} else { - print OUT "Can't create cctest.c\n"; -} - -print "Running make...\n"; -if (system("make 2>&1 | tee make.log") > 255) { - - print OUT "make failed!\n"; - if (open(IN,") { - print OUT; - } - close(IN); - print OUT $sep; - } else { - print OUT "make.log not found!\n"; - } - goto err; -} - -# Not sure why this is here. The tests themselves can detect if their -# particular feature isn't included, and should therefore skip themselves. -# To skip *all* tests just because one algorithm isn't included is like -# shooting mosquito with an elephant gun... -# -- Richard Levitte, inspired by problem report 1089 -# -#$_=$options; -#s/no-asm//; -#s/no-shared//; -#s/no-krb5//; -#if (/no-/) -#{ -# print OUT "Test skipped.\n"; -# goto err; -#} - -print "Running make test...\n"; -if (system("make test 2>&1 | tee maketest.log") > 255) - { - print OUT "make test failed!\n"; -} else { - $ok=1; -} - -if ($ok and open(IN,") { - $ok=2 if /^platform: $platform/; - } - close(IN); -} - -if ($ok != 2) { - print OUT "Failure!\n"; - if (open(IN,") { - print OUT; - } - close(IN); - print OUT $sep; - } else { - print OUT "make.log not found!\n"; - } - if (open(IN,") { - print OUT; - } - close(IN); - print OUT $sep; - } else { - print OUT "maketest.log not found!\n"; - } -} else { - print OUT "Test passed.\n"; -} -err: -close(OUT); - -print "\n"; -open(IN,"<$report") or die; -while () { - if (/$sep/) { - print "[...]\n"; - last; - } - print; -} -print "\nTest report in file $report\n"; - -die if $ok != 2; diff --git a/util/shlib_wrap.sh.in b/util/shlib_wrap.sh.in index 6c115ba7..27a1e513 100755 --- a/util/shlib_wrap.sh.in +++ b/util/shlib_wrap.sh.in @@ -1,25 +1,5 @@ #!/bin/sh -# To test this OpenSSL version's applications against another version's -# shared libraries, simply set -# -# OPENSSL_REGRESSION=/path/to/other/OpenSSL/build/tree -if [ -n "$OPENSSL_REGRESSION" ]; then - shlibwrap="$OPENSSL_REGRESSION/util/shlib_wrap.sh" - if [ -x "$shlibwrap" ]; then - # We clear OPENSSL_REGRESSION to avoid a loop, should the shlib_wrap.sh - # we exec also support that mechanism... - OPENSSL_REGRESSION= exec "$shlibwrap" "$@" - else - if [ -f "$shlibwrap" ]; then - echo "Not permitted to run $shlibwrap" >&2 - else - echo "No $shlibwrap, perhaps OPENSSL_REGRESSION isn't properly set?" >&2 - fi - exit 1 - fi -fi - [ $# -ne 0 ] || set -x # debug mode without arguments:-) THERE="`echo $0 | sed -e 's|[^/]*$||' 2>/dev/null`.." diff --git a/util/su-filter.pl b/util/su-filter.pl index 5996f582..389c7c35 100644 --- a/util/su-filter.pl +++ b/util/su-filter.pl @@ -108,7 +108,7 @@ sub structureData { if($inbrace) { if($item eq "}") { $inbrace --; - + if(!$inbrace) { $substruc = structureData($dataitem); $dataitem = $substruc;

- * The Whirlpool algorithm was developed by - * Paulo S. L. M. Barreto and - * Vincent Rijmen. - * * See * P.S.L.M. Barreto, V. Rijmen, * ``The Whirlpool hashing function,'' diff --git a/crypto/whrlpool/wp_dgst.c b/crypto/whrlpool/wp_dgst.c index 6d925517..1ac29803 100644 --- a/crypto/whrlpool/wp_dgst.c +++ b/crypto/whrlpool/wp_dgst.c @@ -10,14 +10,6 @@ /** * The Whirlpool hashing function. * - *